nsh-core 0.8.1

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
//! Components that run once ([`crate::element::Component::view`]) in the core:
//! their views are mounted with bindings, and what changes later arrives as
//! patches.
//!
//! The view is expanded once, under the component's owner; an element's
//! bound parts (a text, props or a style given as a signal or a closure)
//! become render effects. Each run of one queues a patch with the part's
//! new value; the core applies it against what it applied last (field by
//! field), so a change sends only what changed.
//! A region ([`crate::element::dynamic`], `If`, `Each`) is an effect queueing its
//! new elements; the core reconciles that region's nodes alone, in place
//! among its parent's other children. Reused nodes are diffed against the
//! latest values their bindings applied, including when replaced by static
//! elements. Patches and the events components emit are taken at the start
//! of each commit round, until none is left.

use std::{cell::RefCell, rc::Rc};

use super::{
    Core,
    components::{Classes, Expanded, Instance, NewChild, Part, Placement},
};
use crate::{
    NodeId, Op, Tag, TextEngine,
    element::{
        Attrs, BoundListConfig, ElNode, ListConfig, Owner, SharedString, StyleRefinement,
        builder::BoundAttrs,
        flow::{Region, RegionElement},
        reactive::render_effect,
    },
};

/// A change a binding of a view queued.
pub(super) enum Patch {
    /// A text's new content.
    Text {
        host: NodeId,
        id: NodeId,
        text: SharedString,
    },
    /// An element's props, the bound ones read again.
    Attrs {
        host: NodeId,
        id: NodeId,
        attrs: Box<Attrs>,
    },
    /// An element's style, the bound parts read again.
    Style {
        host: NodeId,
        id: NodeId,
        style: StyleRefinement,
    },
    /// A region's new elements.
    Region {
        region: u32,
        elements: Vec<RegionElement>,
    },
    /// A list's layout, its bound parts read again.
    Layout {
        list: NodeId,
        binding: Owner,
        config: ListConfig,
    },
    /// The styles a view gives a nested component (its host), the bound
    /// parts read again.
    Nested {
        host: NodeId,
        style: StyleRefinement,
    },
    /// The attributes a view gives a nested component (its host) besides
    /// styles, the bound parts read again.
    NestedAttrs { host: NodeId, attrs: Box<Attrs> },
    /// A list's rows, its bound count or keys read again.
    Rows {
        list: NodeId,
        binding: Owner,
        count: u32,
        keys: Option<Rc<[u64]>>,
    },
}

/// The queue the bindings of views push to.
pub(super) type Patches = Rc<RefCell<Vec<Patch>>>;

/// Deterministic work counts for the dependency's reconciliation probes.
#[cfg(test)]
#[derive(Debug, Default, Clone, Copy)]
pub(super) struct CleanupWork {
    pub(super) regions: usize,
    pub(super) scans: usize,
    pub(super) entries: usize,
}

/// What was last applied to a node with bindings.
pub(super) struct BoundNode {
    pub(super) attrs: Attrs,
    pub(super) style: StyleRefinement,
    pub(super) classes: Classes,
    /// Its text's content and raw text node.
    pub(super) text: Option<(SharedString, NodeId)>,
}

/// A region of a parent's children.
pub(super) struct RegionState {
    pub(super) host: NodeId,
    parent: NodeId,
    /// What its nodes go before.
    anchor: Anchor,
    /// Its elements, as applied.
    pub(super) children: Vec<Expanded>,
    /// The slot whose fill it is part of, in content of the nested
    /// component `parent`.
    fill: Option<&'static str>,
}

/// What a region's nodes (or a host's JS children) go before in their
/// parent.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Anchor {
    /// The end.
    End,
    Node(NodeId),
    /// The next region's first node, or what it goes before.
    Region(u32),
}

/// The bound parts of an element, taken off it before its static parts are
/// applied.
pub(super) struct Bound {
    text: Option<Rc<dyn Fn() -> SharedString>>,
    attrs: Vec<BoundAttrs>,
    /// The style with its bound parts (none when it has none).
    style: Option<StyleRefinement>,
    /// A list's layout: its static part and its bound parts.
    list: (ListConfig, Vec<BoundListConfig>),
}

impl Bound {
    /// The bound parts of `el`, if it has any (they leave it: what remains
    /// is static).
    pub(super) fn take(el: &mut ElNode) -> Option<Self> {
        if !el.is_bound() {
            return None;
        }
        Some(Self {
            text: el.bound_text.take(),
            attrs: std::mem::take(&mut el.bound_attrs),
            style: el.style.is_bound().then(|| {
                let full = std::mem::take(&mut el.style);
                el.style = full.static_part();
                full
            }),
            list: (
                el.list_config().copied().unwrap_or_default(),
                std::mem::take(&mut el.bound_list),
            ),
        })
    }
}

/// A binding's runs: the first one's value, or a patch for each later one.
///
/// A render effect runs as it is made, so its first value is read while
/// the node is being made and applied with its static parts, once; only what
/// changes later goes through the patch queue.
struct Runs<T> {
    first: Rc<RefCell<Option<T>>>,
    started: std::cell::Cell<bool>,
}

impl<T> Runs<T> {
    fn new() -> (Self, Rc<RefCell<Option<T>>>) {
        let first = Rc::new(RefCell::new(None));
        (
            Self {
                first: first.clone(),
                started: std::cell::Cell::new(false),
            },
            first,
        )
    }

    /// The value of a run: kept if it is the first, else `patch`ed.
    fn run(&self, value: T, patch: impl FnOnce(T)) {
        if self.started.replace(true) {
            patch(value);
        } else {
            *self.first.borrow_mut() = Some(value);
        }
    }
}

impl<M: TextEngine> Core<M> {
    /// Binds the bound parts of node `id` (of `host`'s view) under the
    /// current owner and puts what they read now into `el`, whose parts are
    /// then applied together; their later runs queue patches against what
    /// [`Self::keep_bound`] records.
    pub(super) fn bind_parts(&mut self, host: NodeId, id: NodeId, bound: Bound, el: &mut ElNode) {
        let patches = self.components.patches.clone();
        if let Some(text) = bound.text {
            let patches = patches.clone();
            let (runs, first) = Runs::new();
            render_effect(move || {
                runs.run(text(), |text| {
                    patches.borrow_mut().push(Patch::Text { host, id, text });
                });
            });
            if let Some(text) = first.take() {
                el.text = Some(text);
            }
        }
        if !bound.attrs.is_empty() {
            let base = el.attrs.clone();
            let parts = bound.attrs;
            let patches = patches.clone();
            let (runs, first) = Runs::new();
            render_effect(move || {
                let mut attrs = base.clone();
                for part in &parts {
                    part(&mut attrs);
                }
                runs.run(attrs, |attrs| {
                    patches.borrow_mut().push(Patch::Attrs {
                        host,
                        id,
                        attrs: Box::new(attrs),
                    });
                });
            });
            if let Some(attrs) = first.take() {
                el.attrs = attrs;
            }
        }
        if let Some(style) = bound.style {
            let (runs, first) = Runs::new();
            render_effect(move || {
                runs.run(style.resolved(), |style| {
                    patches.borrow_mut().push(Patch::Style { host, id, style });
                });
            });
            if let Some(style) = first.take() {
                el.style = style;
            }
        }
        let (base, parts) = bound.list;
        if !parts.is_empty() {
            let config = self.bind_list_layout(id, base, parts);
            if let Some(c) = el.list_config() {
                *c = config;
            }
        }
    }

    /// Records what was applied to node `id` of a view with bindings (its
    /// parts with the bindings' first values): what their patches apply
    /// against.
    pub(super) fn keep_bound(
        inst: &mut Instance,
        id: NodeId,
        attrs: &Attrs,
        style: &StyleRefinement,
        classes: Classes,
        text: Option<(SharedString, NodeId)>,
    ) {
        inst.bound.insert(
            id,
            Box::new(BoundNode {
                attrs: attrs.clone(),
                style: style.clone(),
                classes,
                text,
            }),
        );
    }

    /// Binds the styles a view gives nested component `host` under the
    /// current owner: the styles now, to apply; later changes are patches.
    pub(super) fn bind_nested_style(
        &mut self,
        host: NodeId,
        style: StyleRefinement,
    ) -> StyleRefinement {
        let patches = self.components.patches.clone();
        let (runs, first) = Runs::new();
        render_effect(move || {
            runs.run(style.resolved(), |style| {
                patches.borrow_mut().push(Patch::Nested { host, style });
            });
        });
        first.take().unwrap_or_default()
    }

    /// Binds the attributes a view gives nested component `host` (`base`
    /// with the bound `parts`) under the current owner: them now; later
    /// changes are patches.
    pub(super) fn bind_nested_attrs(
        &mut self,
        host: NodeId,
        base: Attrs,
        parts: Vec<crate::element::builder::BoundAttrs>,
    ) -> Attrs {
        let patches = self.components.patches.clone();
        let (runs, first) = Runs::new();
        let resolve = base.clone();
        render_effect(move || {
            let mut attrs = resolve.clone();
            for part in &parts {
                part(&mut attrs);
            }
            runs.run(attrs, |attrs| {
                patches.borrow_mut().push(Patch::NestedAttrs {
                    host,
                    attrs: Box::new(attrs),
                });
            });
        });
        first.take().unwrap_or(base)
    }

    /// Binds the bound parts of list `list`'s layout over `base` under the
    /// current owner: the layout now, to apply; later changes are patches.
    pub(super) fn bind_list_layout(
        &mut self,
        list: NodeId,
        base: ListConfig,
        parts: Vec<BoundListConfig>,
    ) -> ListConfig {
        let patches = self.components.patches.clone();
        let (runs, first) = Runs::new();
        render_effect(move || {
            let mut config = base;
            for part in &parts {
                part(&mut config);
            }
            runs.run(config, |config| {
                patches.borrow_mut().push(Patch::Layout {
                    list,
                    binding: Owner::current(),
                    config,
                });
            });
        });
        let config = first.take().unwrap_or(base);
        self.components.list_layouts.insert(list, config);
        config
    }

    /// Makes region `region` of `host`'s view in `parent` a binding under
    /// the current owner; returns its id (its nodes come with its first
    /// patch).
    pub(super) fn bind_region(&mut self, host: NodeId, parent: NodeId, region: Region) -> u32 {
        let id = self.components.next_region;
        self.components.next_region += 1;
        self.components.regions.insert(
            id,
            RegionState {
                host,
                parent,
                anchor: Anchor::End,
                children: Vec::new(),
                fill: self
                    .components
                    .filling
                    .filter(|&(nested, _)| nested == parent)
                    .map(|(_, name)| name),
            },
        );
        let patches = self.components.patches.clone();
        region.bind(Rc::new(move |elements| {
            patches.borrow_mut().push(Patch::Region {
                region: id,
                elements,
            });
        }));
        id
    }

    /// Sets what region `region`'s nodes go before.
    pub(super) fn set_region_anchor(&mut self, region: u32, anchor: Anchor) {
        if let Some(state) = self.components.regions.get_mut(&region) {
            state.anchor = anchor;
        }
    }

    /// The nodes of region `region` now, in order.
    pub(super) fn region_nodes(&self, region: u32) -> Vec<NodeId> {
        self.components
            .regions
            .get(&region)
            .map(|state| state.children.iter().flat_map(|e| self.placed(e)).collect())
            .unwrap_or_default()
    }

    /// The nodes an expanded element puts in its parent (a region its own).
    pub(super) fn placed(&self, e: &Expanded) -> Vec<NodeId> {
        match e.part {
            Part::Region(region) => self.region_nodes(region),
            Part::Fill(_) => e.children.iter().flat_map(|c| self.placed(c)).collect(),
            // Shown by a nested component's root, not put in a parent.
            Part::Filled(_) | Part::Tooltip => Vec::new(),
            _ => vec![e.id],
        }
    }

    /// The first node region `region` puts in its parent now, if any,
    /// without collecting the others ([`Self::region_nodes`]).
    fn first_node(&self, region: u32) -> Option<NodeId> {
        let state = self.components.regions.get(&region)?;
        // (Its host's JS children and fills: known but while its view is
        // reconciled, when its instance is out of the instances.)
        let inst = self.components.instances.get(&state.host).map(|i| &**i);
        state.children.iter().find_map(|e| self.node_of(e, inst))
    }

    /// The node an element of `inst`'s view puts first in its parent now.
    fn node_of(&self, e: &Expanded, inst: Option<&Instance>) -> Option<NodeId> {
        match e.part {
            Part::Children => inst?.js_children.first().copied(),
            Part::Filled(name) => self
                .fill_of(inst?, name)
                .and_then(|f| self.fill_nodes(f).first().copied()),
            Part::Region(region) => self.first_node(region),
            // A slot's: placed by the nested view where it places it.
            Part::Fill(_) | Part::Tooltip => None,
            _ => (e.id != 0).then_some(e.id),
        }
    }

    /// What follows the elements before `elements` (some of `inst`'s view,
    /// all in one parent): the first node among them, the first region
    /// (empty now, it may fill), or `end` past them all (what follows the
    /// region they are, or the end).
    pub(super) fn anchor_after(
        &self,
        elements: &[Expanded],
        inst: &Instance,
        end: Anchor,
    ) -> Anchor {
        elements
            .iter()
            .find_map(|e| match e.part {
                Part::Region(region) => Some(Anchor::Region(region)),
                _ => self.node_of(e, Some(inst)).map(Anchor::Node),
            })
            .unwrap_or(end)
    }

    /// Anchors each region among `out` (`inst`'s view's children, or a
    /// region's) to what follows it: past `out`'s end, `end` (a region in
    /// a region resolves to what follows the outer one, as its nodes do).
    pub(super) fn set_region_anchors(&mut self, out: &[Expanded], inst: &Instance, end: Anchor) {
        for (i, e) in out.iter().enumerate() {
            if let Part::Region(region) = e.part {
                let anchor = self.anchor_after(&out[i + 1..], inst, end);
                self.set_region_anchor(region, anchor);
            }
        }
    }

    /// The node a region's nodes go before (`None`: the end).
    pub(super) fn anchor_node(&self, anchor: Anchor) -> Option<NodeId> {
        let mut anchor = anchor;
        loop {
            match anchor {
                Anchor::End => return None,
                Anchor::Node(id) => return Some(id),
                Anchor::Region(region) => {
                    if let Some(first) = self.first_node(region) {
                        return Some(first);
                    }
                    anchor = self.components.regions.get(&region)?.anchor;
                }
            }
        }
    }

    /// Applies what the views' bindings queued and routes the events their
    /// components emitted, until nothing is left. Whether anything was.
    pub(super) fn drain_views(&mut self) -> bool {
        // `render_dirty` can release static children of recycled cells
        // between drain rounds, without reconciling a region at all.
        self.forget_released_hosts();
        let mut any = false;
        loop {
            // The insets components read, as their screens have them now.
            for host in self.components.runtime.inset_hosts() {
                let insets = self.insets_of(host);
                self.components.runtime.set_insets(host, insets);
            }
            let emits = self.components.runtime.take_emits();
            let patches = std::mem::take(&mut *self.components.patches.borrow_mut());
            if emits.is_empty() && patches.is_empty() {
                return any;
            }
            any = true;
            for (host, event) in emits {
                self.route_emit(host, event);
            }
            for patch in patches {
                self.apply_patch(patch);
            }
            // No event or next round of bindings can observe the released
            // records. Clean each affected host once, after all regions in
            // this batch have reconciled and put their instances back.
            self.forget_released_hosts();
        }
    }

    fn apply_patch(&mut self, patch: Patch) {
        // A preceding region in this batch may have released the node.
        // Keep its already queued bindings from changing a former slot's
        // JS node while host cleanup waits for this batch's boundary.
        if let Patch::Text { host, id, .. }
        | Patch::Attrs { host, id, .. }
        | Patch::Style { host, id, .. } = &patch
            && self.components.released_hosts.contains(host)
            && !self.keeps_view_node(*host, *id)
        {
            return;
        }
        match patch {
            Patch::Region { region, elements } => self.reconcile_region(region, elements),
            Patch::Rows {
                list,
                binding,
                count,
                keys,
            } => {
                // The list node can outlive the binding that queued these rows.
                if binding.is_live() {
                    self.set_list_rows(list, count, keys);
                }
            }
            Patch::NestedAttrs { host, attrs } => {
                if self.is_host(host) {
                    self.set_given(host, *attrs);
                }
            }
            Patch::Nested { host, style } => {
                if self.is_host(host) {
                    let user = (!style.is_empty()).then(|| self.components.lowered(&style));
                    self.set_user(host, user);
                }
            }
            Patch::Layout {
                list,
                binding,
                config,
            } => {
                if !binding.is_live() {
                    return;
                }
                let Some(old) = self.components.list_layouts.get_mut(&list) else {
                    return;
                };
                let old = std::mem::replace(old, config);
                let mut props = Vec::new();
                config.changes(&old, &mut props);
                for prop in props {
                    let _ = self.apply_op(Op::SetProp { id: list, prop });
                }
            }
            Patch::Text { host, id, text } => {
                let Some(inst) = self.components.instances.get_mut(&host) else {
                    return;
                };
                let Some(node) = inst.bound.get_mut(&id) else {
                    return;
                };
                match &mut node.text {
                    Some((old, raw)) if *old != text => {
                        let raw = *raw;
                        *old = text.clone();
                        let _ = self.apply_op(Op::SetText {
                            id: raw,
                            text: text.as_str().to_owned(),
                        });
                    }
                    _ => {}
                }
            }
            Patch::Attrs { host, id, attrs } => {
                // The root: what the views and components above give it
                // goes after its own.
                let cx = if id == host {
                    self.root_context_of(host)
                } else {
                    None
                };
                let Some(inst) = self.components.instances.get_mut(&host) else {
                    return;
                };
                let app = match &cx {
                    Some(cx) if cx.combined => cx.app.clone(),
                    Some(_) => inst.app_style.clone(),
                    None => None,
                };
                let Some(node) = inst.bound.get_mut(&id) else {
                    return;
                };
                let attrs = *attrs;
                let old = std::mem::replace(&mut node.attrs, attrs.clone());
                // The app's classes changed: the styles go again.
                let restyle = (attrs.class != old.class).then(|| {
                    (
                        node.style.clone(),
                        node.classes.clone(),
                        attrs.class.clone(),
                    )
                });
                let (attrs, old) = match &cx {
                    Some(cx) => {
                        let mut old = old;
                        old.set_insets(inst.root_insets_applied);
                        let old = super::components::with_host(old, &inst.root_host_applied);
                        let attrs = cx.over(attrs);
                        inst.root_insets_applied = attrs.insets();
                        inst.root_host_applied = cx.host.clone();
                        (attrs, old)
                    }
                    None => (attrs, old),
                };
                if self.components.slot_hosts.get(&id) == Some(&host)
                    || self.components.fill_holders.contains(&id)
                {
                    // An app's slot, or a node around a fill: what is not a
                    // style goes to its target (`super::slots`).
                    self.apply_slot_attrs(id, host, &attrs, &old, None);
                } else if !self.apply_target_attrs(id, &attrs, &old, app.as_ref()) {
                    self.apply_attrs_over(id, &attrs, &old, app.as_ref());
                }
                if let Some((style, classes, class)) = restyle {
                    let outer = cx.and_then(|cx| cx.user);
                    let classes =
                        self.apply_el_styles(id, &style, &style, classes, class.as_ref(), outer);
                    if let Some(node) = self
                        .components
                        .instances
                        .get_mut(&host)
                        .and_then(|i| i.bound.get_mut(&id))
                    {
                        node.classes = classes;
                    }
                }
            }
            Patch::Style { host, id, style } => {
                let user = if id == host {
                    self.root_context_of(host).and_then(|cx| cx.user)
                } else {
                    None
                };
                let Some(inst) = self.components.instances.get_mut(&host) else {
                    return;
                };
                let Some(node) = inst.bound.get_mut(&id) else {
                    return;
                };
                let old_style = std::mem::replace(&mut node.style, style.clone());
                let old_classes = node.classes.clone();
                let class = node.attrs.class.clone();
                let classes =
                    self.apply_el_styles(id, &style, &old_style, old_classes, class.as_ref(), user);
                if let Some(node) = self
                    .components
                    .instances
                    .get_mut(&host)
                    .and_then(|i| i.bound.get_mut(&id))
                {
                    node.classes = classes;
                }
            }
        }
    }

    /// Region `region`'s new elements, matched with the old ones as an
    /// element's children are (kept rows stay as they are; each element is
    /// applied under its owner), then put in place among the parent's other
    /// children, before the region's anchor.
    fn reconcile_region(&mut self, region: u32, elements: Vec<RegionElement>) {
        let Some(state) = self.components.regions.remove(&region) else {
            return;
        };
        let host = state.host;
        let Some(mut inst) = self.components.instances.remove(&host) else {
            return;
        };
        let parent = state.parent;
        // The JS children were placed by this region: placed again below.
        let old_place = inst.children_at;
        if state.children.iter().any(|e| e.part == Part::Children) {
            inst.children_at = Placement::None;
        }
        // Rows kept where they were update through their item bindings:
        // matching would only move these elements into the output
        // unchanged, as it does first of all for the elements a run starts
        // with. A list mostly changes at its end, so only what follows
        // them is matched.
        let stay = elements
            .iter()
            .zip(&state.children)
            .take_while(|(element, previous)| {
                matches!(element, RegionElement::Kept(key) if previous.key.as_ref() == Some(key))
            })
            .count();
        let mut children = state.children;
        let before = self.components.release_generation;
        let (out, placeholder) = if stay == children.len() && stay == elements.len() {
            (children, None)
        } else {
            // What a run made goes with it unapplied once a later run
            // replaced it or its row went.
            let new = elements
                .into_iter()
                .skip(stay)
                .filter(RegionElement::applies)
                .map(|element| match element {
                    RegionElement::Made { owner, element } => NewChild::Made(Some(owner), *element),
                    RegionElement::Kept(key) => NewChild::Kept(key),
                })
                .collect();
            if stay == 0 {
                self.match_children(parent, children, new, host, &mut inst)
            } else {
                let old = children.split_off(stay);
                let (rest, placeholder) = self.match_children(parent, old, new, host, &mut inst);
                children.extend(rest);
                (children, placeholder.map(|at| at + stay))
            }
        };
        #[cfg(test)]
        {
            self.components.cleanup_work.regions += 1;
        }
        // Initial population, keyed retention and reordering release
        // nothing. In particular, do not scan the growing host-wide maps
        // once for every region a large view initially populates.
        if self.components.release_generation != before {
            self.components.released_hosts.insert(host);
        }
        // The JS children's place went with what the region released.
        let gone = match inst.children_at {
            Placement::At(at, _) => at != host && !self.components.owners.contains_key(&at),
            Placement::Nested(nested, _) => !self.is_host(nested),
            _ => false,
        };
        if gone {
            inst.children_at = Placement::None;
        }
        // A nested component's content joins it as JS children do.
        let nested = parent != host && self.is_host(parent);
        let place = |after| {
            if nested {
                Placement::Nested(parent, after)
            } else {
                Placement::At(parent, after)
            }
        };
        // What it holds resolves past its end to what follows it: its
        // regions, the JS children, what fills a slot.
        self.set_region_anchors(&out, &inst, state.anchor);
        if let Some(at) = placeholder {
            inst.children_at = place(self.anchor_after(&out[at + 1..], &inst, state.anchor));
        }
        self.place_filled(&out, &mut inst, state.anchor, place);
        // In place: from the last, each before the next, from the anchor.
        let mut nodes: Vec<NodeId> = Vec::with_capacity(out.len());
        for e in &out {
            match e.part {
                Part::Children => nodes.extend_from_slice(&inst.js_children),
                Part::Filled(name) => {
                    if let Some(fill) = self.fill_of(&inst, name) {
                        nodes.extend(self.fill_nodes(fill));
                    }
                }
                Part::Region(_) | Part::Fill(_) => nodes.extend(self.placed(e)),
                // (As `placed` has it, without a list of its own for each.)
                _ => nodes.push(e.id),
            }
        }
        self.children_placed(host, &mut inst, old_place);
        self.components.instances.insert(host, inst);
        self.components.regions.insert(
            region,
            RegionState {
                host,
                parent,
                anchor: state.anchor,
                children: out,
                fill: state.fill,
            },
        );
        // Part of what fills a nested component's slot: it goes where the
        // nested view places the slot, whose prop follows; what fills this
        // view's own slots and it passes on goes there too.
        if let Some(name) = state.fill {
            if let Some(mut inst) = self.components.instances.remove(&host) {
                self.note_passed(parent, name, host, &mut inst);
                self.components.instances.insert(host, inst);
            }
            self.refill(parent, name);
            return;
        }
        // (Resolved with the host's instance back: a region after this one
        // may hold its JS children.)
        let mut before = self.anchor_node(state.anchor);
        let parent_key = self.key(parent).ok().filter(|_| !nested);
        // Where `before` is among the parent's children (their end for
        // `None`), when known.
        let mut next = parent_key.and_then(|key| {
            let children = &self.nodes[key as usize].children;
            match before {
                Some(id) => children
                    .iter()
                    .position(|&child| self.nodes[child as usize].id == id),
                None => Some(children.len()),
            }
        });
        // Already contiguous before the anchor: every precedes check below
        // would succeed, so no child needs to move.
        if let (Some(key), Some(end)) = (parent_key, next)
            && end.checked_sub(nodes.len()).is_some_and(|start| {
                self.nodes[key as usize].children[start..end]
                    .iter()
                    .zip(&nodes)
                    .all(|(&child, &id)| self.nodes[child as usize].id == id)
            })
        {
            return;
        }
        for &child in nodes.iter().rev() {
            if nested {
                if !self.nested_precedes(parent, child, before) {
                    self.join_nested_at(parent, child, before);
                }
            } else {
                // Looked for right before the node after it.
                let after = next;
                next = self.preceding(
                    parent,
                    child,
                    before,
                    after.and_then(|at| at.checked_sub(1)),
                );
                if next.is_none() {
                    let _ = self.apply_op(Op::Insert {
                        parent,
                        child,
                        before,
                    });
                    // In the place `before` had, or right before it when
                    // the child moved from before it: the node before it
                    // is looked for next to it, so a node kept after new
                    // ones is found without a search of the children.
                    next = after.and_then(|at| {
                        let children = &self.nodes[parent_key? as usize].children;
                        std::iter::once(at).chain(at.checked_sub(1)).find(|&at| {
                            children
                                .get(at)
                                .is_some_and(|&c| self.nodes[c as usize].id == child)
                        })
                    });
                }
            }
            before = Some(child);
        }
    }

    /// A region of the fill of slot `name` of the nested component hosted
    /// by `nested` changed: the nested view places the fill's nodes again,
    /// and its slot prop follows whether there are any.
    fn refill(&mut self, nested: NodeId, name: &'static str) {
        self.components.mark(nested);
        self.join_fill(nested, name, None);
        self.place_fill(nested, name);
    }

    /// Forgets what `host`'s view knew of the nodes released since: their
    /// handlers, responders and bindings.
    fn forget_released_hosts(&mut self) {
        let hosts: Vec<_> = self.components.released_hosts.drain().collect();
        for host in hosts {
            if let Some(mut inst) = self.components.instances.remove(&host) {
                self.forget_released(host, &mut inst);
                self.components.instances.insert(host, inst);
            }
        }
    }

    fn keeps_view_node(&self, host: NodeId, id: NodeId) -> bool {
        id == host
            || self.components.owners.contains_key(&id)
            || self.components.slot_hosts.get(&id) == Some(&host)
            || self.adopted_host(id) == Some(host)
    }

    fn forget_released(&mut self, host: NodeId, inst: &mut Instance) {
        #[cfg(test)]
        {
            self.components.cleanup_work.scans += 1;
            self.components.cleanup_work.entries += inst.handlers.len()
                + inst.event_handlers.len()
                + inst.responders.len()
                + inst.bound.len();
        }
        // The app's slot nodes are JS's, not the view's: they keep what the
        // view gave them while they are its slots (and so do the app's
        // elements in them that take the slots' props).
        let live = |id: &NodeId| self.keeps_view_node(host, *id);
        inst.handlers.retain_nodes(live);
        inst.event_handlers.retain(|(id, _)| live(id));
        inst.responders.retain(|(id, _)| live(id));
        inst.bound.retain(|id, _| live(id));
    }

    /// Releases the regions of `host`'s view (the host goes).
    pub(super) fn release_regions(&mut self, host: NodeId) {
        let regions: Vec<u32> = self
            .components
            .regions
            .iter()
            .filter(|(_, s)| s.host == host)
            .map(|(&id, _)| id)
            .collect();
        // Their nodes go too (a region inside another is released with it).
        for region in regions {
            self.release_region(region);
        }
    }

    /// Releases region `region`'s nodes (its placeholder goes).
    pub(super) fn release_region(&mut self, region: u32) {
        if let Some(state) = self.components.regions.remove(&region) {
            for e in state.children {
                self.release_expanded(e);
            }
        }
    }
}

/// A placeholder element for a region of `tag` (it has no node).
pub(super) fn region_placeholder(region: u32) -> Expanded {
    let mut e = Expanded::js(0, Part::Region(region));
    e.tag = Tag::View;
    e
}

#[cfg(test)]
mod size_tests {
    use super::*;

    #[test]
    fn rare_attrs_keep_element_records_compact_and_default_equal() {
        let attrs_bytes = std::mem::size_of::<Attrs>();
        let expanded_bytes = std::mem::size_of::<Expanded>();
        let bound_bytes = std::mem::size_of::<BoundNode>();
        eprintln!(
            "sizes: Attrs={attrs_bytes}B Expanded={expanded_bytes}B BoundNode={bound_bytes}B"
        );
        assert!(attrs_bytes <= 120, "Attrs grew back to {attrs_bytes} bytes");
        assert!(
            expanded_bytes <= 320,
            "Expanded grew back to {expanded_bytes} bytes"
        );
        assert!(
            bound_bytes <= 240,
            "BoundNode grew back to {bound_bytes} bytes"
        );

        let mut cleared = Attrs::default();
        cleared.rare_mut().selectable_view = true;
        assert_ne!(cleared, Attrs::default());
        cleared.rare_mut().selectable_view = false;
        assert_eq!(cleared, Attrs::default());

        let mut props = Vec::new();
        cleared.changes(&Attrs::default(), &mut props);
        assert!(props.is_empty());
    }
}