cranpose-foundation 0.29.0

Modifier-node, input, focus, text and semantics contracts for Cranpose UI
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
980
981
982
983
984
985
//! The chain of modifier nodes a layout node holds, and its reconciliation
//! with the node's modifier.

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

use super::{
    AnyModifierElement, DynModifierElement, ElementMaker, InvalidationKind, MAX_DELEGATE_DEPTH,
    ModifierChainIter, ModifierChainNodeRef, ModifierNode, ModifierNodeContext, NodeCapabilities,
    NodeMaker, NodePath, chain_node_ref::ChainPosition,
};
mod entry;
mod entry_element;
mod in_place;
mod plain;
use entry::ModifierNodeEntry;
use entry_element::EntryElement;
pub use entry_element::HeldElement;
use in_place::{InPlace, update_entry_in_place};
pub(crate) use plain::PlainWords;
pub use plain::{
    PLAIN_WORDS_MAX, PlainElement, PlainFns, PlainIntrinsic, PlainLayout, PlainLayoutFns,
    PlainValue, PrepareAt, plain_element,
};

fn visit_node_tree_mut(
    node: &mut dyn ModifierNode,
    visitor: &mut dyn FnMut(&mut dyn ModifierNode),
) {
    visitor(node);
    node.for_each_delegate_mut(&mut |child| visit_node_tree_mut(child, visitor));
}

fn nth_delegate(node: &dyn ModifierNode, target: usize) -> Option<&dyn ModifierNode> {
    let mut current = 0usize;
    let mut result: Option<&dyn ModifierNode> = None;
    node.for_each_delegate(&mut |child| {
        if result.is_none() && current == target {
            result = Some(child);
        }
        current += 1;
    });
    result
}

fn nth_delegate_mut(node: &mut dyn ModifierNode, target: usize) -> Option<&mut dyn ModifierNode> {
    let mut current = 0usize;
    let mut result: Option<&mut dyn ModifierNode> = None;
    node.for_each_delegate_mut(&mut |child| {
        if result.is_none() && current == target {
            result = Some(child);
        }
        current += 1;
    });
    result
}

fn with_node_context<F, R>(
    node: &mut dyn ModifierNode,
    context: &mut dyn ModifierNodeContext,
    f: F,
) -> R
where
    F: FnOnce(&mut dyn ModifierNode, &mut dyn ModifierNodeContext) -> R,
{
    context.push_active_capabilities(node.node_state().capabilities());
    let result = f(node, context);
    context.pop_active_capabilities();
    result
}

fn request_update_auto_invalidations(
    element: &dyn AnyModifierElement,
    context: &mut dyn ModifierNodeContext,
    capabilities: NodeCapabilities,
) {
    if let Some(kind) = element.update_invalidation_kind() {
        let capabilities = NodeCapabilities::for_invalidation(kind);
        context.push_active_capabilities(capabilities);
        context.invalidate(kind);
        context.pop_active_capabilities();
    } else if element.auto_invalidates_on_update() {
        request_auto_invalidations(context, capabilities);
    }
}

fn request_auto_invalidations(
    context: &mut dyn ModifierNodeContext,
    capabilities: NodeCapabilities,
) {
    if capabilities.is_empty() {
        return;
    }

    context.push_active_capabilities(capabilities);

    if capabilities.contains(NodeCapabilities::LAYOUT) {
        context.invalidate(InvalidationKind::Layout);
    }
    if capabilities.contains(NodeCapabilities::DRAW) {
        context.invalidate(InvalidationKind::Draw);
    }
    if capabilities.contains(NodeCapabilities::POINTER_INPUT) {
        context.invalidate(InvalidationKind::PointerInput);
    }
    if capabilities.contains(NodeCapabilities::SEMANTICS) {
        context.invalidate(InvalidationKind::Semantics);
    }
    if capabilities.contains(NodeCapabilities::FOCUS) {
        context.invalidate(InvalidationKind::Focus);
    }

    context.pop_active_capabilities();
}

fn attach_node_tree(node: &mut dyn ModifierNode, context: &mut dyn ModifierNodeContext) {
    visit_node_tree_mut(node, &mut |n| {
        if !n.node_state().is_attached() {
            n.node_state().set_attached(true);
            with_node_context(n, context, |node, ctx| node.on_attach(ctx));
        }
    });
}

fn reset_node_tree(node: &mut dyn ModifierNode) {
    visit_node_tree_mut(node, &mut |n| n.on_reset());
}

fn detach_node_tree(node: &mut dyn ModifierNode) {
    visit_node_tree_mut(node, &mut |n| {
        if n.node_state().is_attached() {
            n.on_detach();
            n.node_state().set_attached(false);
        }
    });
}

/// Chain of modifier nodes attached to a layout node.
///
/// The chain tracks ownership of modifier nodes and reuses them across
/// updates when the incoming element list still contains a node of the
/// same type. Removed nodes detach automatically so callers do not need
/// to manually manage their lifetimes.
pub struct ModifierNodeChain {
    entries: Vec<ModifierNodeEntry>,
    pub(super) aggregated_capabilities: NodeCapabilities,
    // While a node of the chain delegates: the chain's nodes in order,
    // delegates after the node that delegates to them, each with its
    // capabilities and the union of its own and those of every node after
    // it. `None` otherwise, when the entries are the order and keep the
    // unions: most chains delegate nowhere, and the list sits out of line.
    #[expect(
        clippy::box_collection,
        reason = "one word in every chain, where a vector takes three"
    )]
    delegated_order: Option<Box<Vec<(NodePath, NodeCapabilities, NodeCapabilities)>>>,
    /// Whether the chain's nodes are attached. A node that joins an attached
    /// chain attaches as it joins; one that joins a detached chain waits for
    /// [`Self::attach_nodes`].
    attached: bool,
}

/// Buffers the reconciliation of a chain reuses, held per thread rather than
/// per chain: a chain kept its own after its first reconciliation, a few
/// hundred bytes on every node of a tree.
#[derive(Default)]
struct ReconcileScratch {
    old_used: Vec<bool>,
    match_order: Vec<Option<usize>>,
    final_slots: Vec<Option<ModifierNodeEntry>>,
    elements: Vec<DynModifierElement>,
}

thread_local! {
    static RECONCILE_SCRATCH: RefCell<ReconcileScratch> =
        RefCell::default();
}

impl Default for ModifierNodeChain {
    fn default() -> Self {
        Self::new()
    }
}

struct EntryMatchQuery<'a> {
    element_type: TypeId,
    node_type: TypeId,
    key: Option<u64>,
    hash_code: u64,
    element: &'a DynModifierElement,
}

// The first old entry no element took yet that `query` may take over: one
// of its types and key, or, for an unkeyed element, an equal unkeyed one of
// its types, else any unkeyed one of its types. A chain holds a few entries,
// so a scan takes less than an index would.
fn find_match(
    entries: &[ModifierNodeEntry],
    used: &[bool],
    query: &EntryMatchQuery<'_>,
) -> Option<usize> {
    let candidates = || {
        entries
            .iter()
            .zip(used)
            .enumerate()
            .filter(|(_, (entry, used))| {
                let held = entry.held();
                !**used
                    && held.element_type() == query.element_type
                    && held.node_type() == query.node_type
            })
            .map(|(index, (entry, _))| (index, entry))
    };
    match query.key {
        Some(key) => candidates()
            .find(|(_, entry)| entry.key() == Some(key))
            .map(|(index, _)| index),
        None => {
            let mut unkeyed = candidates().filter(|(_, entry)| entry.key().is_none());
            let first = unkeyed.next()?;
            std::iter::once(first)
                .chain(unkeyed)
                .find(|(_, entry)| {
                    let held = entry.held();
                    held.hash_code() == query.hash_code && held.equals(&**query.element)
                })
                .map_or(Some(first.0), |(index, _)| Some(index))
        }
    }
}

// A new entry for `element`: its node, updated, and attached when `attach`,
// as it joins an attached chain, or its words. The flag tells whether the
// node delegates, asked while the node is borrowed for its update.
fn new_entry(
    element: &DynModifierElement,
    context: &mut dyn ModifierNodeContext,
    attach: bool,
) -> (ModifierNodeEntry, bool) {
    match element.maker() {
        ElementMaker::Plain(value) => (ModifierNodeEntry::of_plain(value), false),
        ElementMaker::Node(maker) => {
            let entry = ModifierNodeEntry::of_node(element, maker, element.capabilities());
            let delegating = entry.node().is_some_and(|node| {
                let mut node = node.borrow_mut();
                if attach {
                    attach_node_tree(&mut *node, context);
                }
                maker.update_node(&mut *node);
                delegates(&*node)
            });
            (entry, delegating)
        }
    }
}

// `new_entry` for an element that joins a chain of entries already there:
// the stages its node takes part in are invalidated.
fn fresh_entry(
    element: &DynModifierElement,
    context: &mut dyn ModifierNodeContext,
    attach: bool,
) -> ModifierNodeEntry {
    let (entry, _) = new_entry(element, context, attach);
    request_auto_invalidations(context, entry.capabilities());
    entry
}

// Whether `node` delegates to another node.
fn delegates(node: &dyn ModifierNode) -> bool {
    let mut delegates = false;
    node.for_each_delegate(&mut |_| delegates = true);
    delegates
}

/// Matches `element`, at `new_pos` of the rebuilt tail, against the old
/// entries: one of its type and key that can
/// take it is updated and marked for `new_pos`, and `None` is returned;
/// otherwise the element's new entry is, attached when `attach`.
fn reconcile_element(
    element: DynModifierElement,
    new_pos: usize,
    old_entries: &mut [ModifierNodeEntry],
    (used, match_order): (&mut [bool], &mut [Option<usize>]),
    context: &mut dyn ModifierNodeContext,
    attach: bool,
) -> Option<ModifierNodeEntry> {
    let maker = element.maker();
    let key = element.key();
    let query = EntryMatchQuery {
        element_type: element.element_type(),
        node_type: match maker {
            ElementMaker::Node(maker) => maker.node_type(),
            ElementMaker::Plain(value) => value.fns().element_type(),
        },
        key,
        // Only an unkeyed element is matched by its hash.
        hash_code: if key.is_none() {
            element.hash_code()
        } else {
            0
        },
        element: &element,
    };
    let capabilities = element.capabilities();
    let Some(idx) = find_match(old_entries, used, &query) else {
        return Some(fresh_entry(&element, context, attach));
    };
    let entry = &mut old_entries[idx];
    match (&mut *entry, maker) {
        (ModifierNodeEntry::Plain { fns, words, .. }, ElementMaker::Plain(value)) => {
            let held = &mut words[..fns.words()];
            if !value.equals_words(held) {
                value.write_words(held);
                request_update_auto_invalidations(&*element, context, capabilities);
            }
        }
        (
            ModifierNodeEntry::Node {
                element: held,
                node,
                capabilities: held_capabilities,
                ..
            },
            ElementMaker::Node(maker),
        ) if maker.can_update_node(&*node.borrow()) => {
            let same_element = held.view(node, *held_capabilities).equals(&*element);
            if !same_element || element.requires_update() {
                maker.update_node(&mut *node.borrow_mut());
                request_update_auto_invalidations(&*element, context, capabilities);
                *held = EntryElement::new(&element, maker);
            }
            *held_capabilities = capabilities;
            node.borrow().node_state().set_capabilities(capabilities);
        }
        _ => return Some(fresh_entry(&element, context, attach)),
    }

    used[idx] = true;
    match_order[idx] = Some(new_pos);
    if idx != new_pos {
        request_auto_invalidations(context, capabilities);
    }
    None
}

impl ModifierNodeChain {
    /// An attached chain: its nodes attach as they join it.
    pub fn new() -> Self {
        let mut chain = Self::detached();
        chain.attached = true;
        chain
    }

    /// A detached chain: its nodes attach at [`Self::attach_nodes`], as a
    /// layout node's do once the node has its id.
    pub fn detached() -> Self {
        Self {
            entries: Vec::new(),
            aggregated_capabilities: NodeCapabilities::empty(),
            delegated_order: None,
            attached: false,
        }
    }

    /// Detaches all nodes in the chain.
    pub fn detach_nodes(&mut self) {
        if !self.attached {
            return;
        }
        self.attached = false;
        for entry in &self.entries {
            entry.detach();
        }
    }

    /// Whether the chain's nodes are attached.
    pub fn is_attached(&self) -> bool {
        self.attached
    }

    /// Attaches all nodes in the chain.
    pub fn attach_nodes(&mut self, context: &mut dyn ModifierNodeContext) {
        if self.attached {
            return;
        }
        self.attached = true;
        for node in self.entries.iter().filter_map(ModifierNodeEntry::node) {
            attach_node_tree(&mut *node.borrow_mut(), context);
        }
    }

    /// Reconcile the chain against the provided elements, attaching newly
    /// created nodes and detaching nodes that are no longer required.
    ///
    /// This method delegates to `update_from_ref_iter` which handles the
    /// actual reconciliation logic.
    pub fn update_from_slice(
        &mut self,
        elements: &[DynModifierElement],
        context: &mut dyn ModifierNodeContext,
    ) {
        self.update_from_ref_iter(elements.iter(), context);
    }

    /// Updates in place the entries `changed` names, one bit an index, for
    /// `elements` that differ from the chain's only in those: entries and
    /// elements line up one to one, and every other entry stays as it is.
    /// `false` when they do not line up or an entry cannot take its element;
    /// a full update then reconciles the chain.
    pub fn update_entries_in_place<'a, I>(
        &mut self,
        elements: I,
        element_count: usize,
        changed: u64,
        context: &mut dyn ModifierNodeContext,
    ) -> bool
    where
        I: Iterator<Item = &'a DynModifierElement>,
    {
        if element_count != self.entries.len() {
            return false;
        }
        let mut relink = false;
        let updated = self
            .entries
            .iter_mut()
            .zip(elements)
            .enumerate()
            .filter(|&(index, _)| {
                u32::try_from(index)
                    .ok()
                    .and_then(|bit| changed.checked_shr(bit))
                    .is_some_and(|rest| rest & 1 == 1)
            })
            .map(|(_, pair)| pair)
            .all(
                |(entry, element)| match update_entry_in_place(entry, element, context) {
                    Some(outcome) => {
                        relink |= outcome == InPlace::Relink;
                        true
                    }
                    None => false,
                },
            );
        if relink {
            self.sync_chain_links();
        }
        updated
    }

    /// Asks `context` for what an update of the last node's values
    /// invalidates, by the node's capabilities, after its caller updated the
    /// node in place and left its capabilities as they were.
    pub fn invalidate_last(&self, context: &mut dyn ModifierNodeContext) {
        if let Some(entry) = self.entries.last() {
            request_auto_invalidations(context, entry.capabilities());
        }
    }

    /// Reconciles the chain against the elements that `elements` yields, without collecting them
    /// first. See `update_from_slice`.
    pub fn update_from_ref_iter<'a, I>(
        &mut self,
        elements: I,
        context: &mut dyn ModifierNodeContext,
    ) where
        I: Iterator<Item = &'a DynModifierElement>,
    {
        // No element of a chain without entries, as a new node's, can take
        // over an entry: the reconciliation's buffers stay unused.
        if self.entries.is_empty() {
            self.build(elements, context);
            return;
        }
        // Taken out for the reconciliation, so one that reconciles another
        // chain inside it works on buffers of its own.
        let mut scratch = RECONCILE_SCRATCH
            .try_with(|scratch| std::mem::take(&mut *scratch.borrow_mut()))
            .unwrap_or_default();
        self.reconcile(elements, context, &mut scratch);
        scratch.elements.clear();
        scratch.final_slots.clear();
        let _ = RECONCILE_SCRATCH.try_with(|slot| *slot.borrow_mut() = scratch);
    }

    // Makes an entry of each of `elements` for a chain that holds none, in
    // one pass, which also finds the union of their capabilities and whether
    // a node delegates. The union is invalidated once for the whole chain:
    // a node's invalidations reach every stage its chain takes part in.
    fn build<'a, I>(&mut self, elements: I, context: &mut dyn ModifierNodeContext)
    where
        I: Iterator<Item = &'a DynModifierElement>,
    {
        self.entries.reserve_exact(elements.size_hint().0);
        let mut capabilities = NodeCapabilities::empty();
        let mut delegating = false;
        for element in elements {
            let (entry, delegated) = new_entry(element, context, self.attached);
            capabilities |= entry.capabilities();
            delegating |= delegated;
            self.entries.push(entry);
        }
        request_auto_invalidations(context, capabilities);
        if delegating {
            self.order_with_delegates();
        } else {
            self.delegated_order = None;
        }
        self.link_aggregates();
    }

    fn reconcile<'a, I>(
        &mut self,
        elements: I,
        context: &mut dyn ModifierNodeContext,
        scratch: &mut ReconcileScratch,
    ) where
        I: Iterator<Item = &'a DynModifierElement>,
    {
        let old_len = self.entries.len();
        let mut fast_path_failed_at: Option<usize> = None;
        let mut elements_count = 0;
        // Entries updated where they are keep the links between them, unless
        // their capabilities or delegates change.
        let mut relink = false;

        scratch.elements.clear();

        for (idx, element) in elements.enumerate() {
            elements_count = idx + 1;
            if fast_path_failed_at.is_none() && idx < old_len {
                if let Some(outcome) =
                    update_entry_in_place(&mut self.entries[idx], element, context)
                {
                    relink |= outcome == InPlace::Relink;
                    continue;
                }
                fast_path_failed_at = Some(idx);
            }
            scratch.elements.push(element.clone());
        }

        if fast_path_failed_at.is_none() && scratch.elements.is_empty() {
            if elements_count < self.entries.len() {
                for entry in self.entries.drain(elements_count..) {
                    request_auto_invalidations(context, entry.capabilities());
                    entry.detach();
                }
                relink = true;
            }
            if relink {
                self.sync_chain_links();
            }
            return;
        }

        self.rebuild_tail(fast_path_failed_at.unwrap_or(old_len), context, scratch);
    }

    /// Rebuilds the chain from `fail_idx` for the elements in `scratch`:
    /// each takes over an old entry of its type and key, wherever it was,
    /// or gets a node of its own; old entries nothing took over detach.
    fn rebuild_tail(
        &mut self,
        fail_idx: usize,
        context: &mut dyn ModifierNodeContext,
        scratch: &mut ReconcileScratch,
    ) {
        // No old entry to take over, as for elements that join the end of a
        // chain: every element gets an entry of its own, with no query for a
        // match.
        if fail_idx == self.entries.len() {
            self.entries.reserve_exact(scratch.elements.len());
            for element in scratch.elements.drain(..) {
                self.entries
                    .push(fresh_entry(&element, context, self.attached));
            }
            self.sync_chain_links();
            return;
        }
        let mut old_entries: Vec<ModifierNodeEntry> = self.entries.drain(fail_idx..).collect();
        let processed_entries_len = self.entries.len();
        let old_len = old_entries.len();

        scratch.old_used.clear();
        scratch.old_used.resize(old_len, false);

        scratch.match_order.clear();
        scratch.match_order.resize(old_len, None);

        let new_elements_count = scratch.elements.len();
        scratch.final_slots.clear();
        scratch.final_slots.reserve(new_elements_count);

        for (new_pos, element) in scratch.elements.drain(..).enumerate() {
            let fresh = reconcile_element(
                element,
                new_pos,
                &mut old_entries,
                (&mut scratch.old_used, &mut scratch.match_order),
                context,
                self.attached,
            );
            scratch.final_slots.push(fresh);
        }

        for (i, entry) in old_entries.into_iter().enumerate() {
            match scratch.match_order[i] {
                Some(pos) if scratch.old_used[i] => scratch.final_slots[pos] = Some(entry),
                _ => {
                    request_auto_invalidations(context, entry.capabilities());
                    entry.detach();
                }
            }
        }

        // Exactly: a chain is rebuilt only when its modifiers change, and
        // most hold one to three entries, where growth would make room for
        // four.
        self.entries.reserve_exact(scratch.final_slots.len());
        for slot in scratch.final_slots.drain(..) {
            if let Some(entry) = slot {
                self.entries.push(entry);
            } else {
                log::error!("modifier reconciliation produced an empty final slot");
            }
        }

        debug_assert_eq!(
            self.entries.len(),
            processed_entries_len + new_elements_count
        );
        self.sync_chain_links();
    }

    /// Convenience wrapper that accepts any iterator of type-erased
    /// modifier elements. Elements are collected into a temporary vector
    /// before reconciliation.
    pub fn update<I>(&mut self, elements: I, context: &mut dyn ModifierNodeContext)
    where
        I: IntoIterator<Item = DynModifierElement>,
    {
        let collected: Vec<DynModifierElement> = elements.into_iter().collect();
        self.update_from_slice(&collected, context);
    }

    /// Resets all nodes in the chain. This mirrors the behaviour of
    /// Jetpack Compose's `onReset` callback.
    pub fn reset(&mut self) {
        for node in self.entries.iter().filter_map(ModifierNodeEntry::node) {
            reset_node_tree(&mut *node.borrow_mut());
        }
    }

    /// Detaches every node in the chain and clears internal storage.
    pub fn detach_all(&mut self) {
        for entry in std::mem::take(&mut self.entries) {
            entry.detach();
            if let Some(node) = entry.node() {
                node.borrow()
                    .node_state()
                    .set_capabilities(NodeCapabilities::empty());
            }
        }
        self.sync_chain_links();
    }

    /// The number of entries in the chain: its nodes and its plain elements.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the chain holds no nodes.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// The elements of the chain's nodes, one for each in chain order: those
    /// the chain was last updated from, or equal ones it kept, or the nodes
    /// that hold every value of them.
    pub fn held_elements(&self) -> impl ExactSizeIterator<Item = HeldElement<'_>> {
        self.entries.iter().map(ModifierNodeEntry::held)
    }

    /// Returns the aggregated capability mask for the entire chain.
    pub fn capabilities(&self) -> NodeCapabilities {
        self.aggregated_capabilities
    }

    /// Returns true if the chain contains at least one node with the requested capability.
    pub fn has_capability(&self, capability: NodeCapabilities) -> bool {
        self.aggregated_capabilities.contains(capability)
    }

    /// Returns the sentinel head reference for traversal.
    pub fn head(&self) -> ModifierChainNodeRef<'_> {
        self.node_ref(ChainPosition::Head)
    }

    /// Returns the sentinel tail reference for traversal.
    pub fn tail(&self) -> ModifierChainNodeRef<'_> {
        self.node_ref(ChainPosition::Tail)
    }

    /// Iterates over the chain from head to tail, skipping sentinels.
    pub fn head_to_tail(&self) -> ModifierChainIter<'_> {
        ModifierChainIter::forward(self)
    }

    /// Iterates over the chain from tail to head, skipping sentinels.
    pub fn tail_to_head(&self) -> ModifierChainIter<'_> {
        ModifierChainIter::backward(self)
    }

    /// Calls `f` for every node in insertion order.
    pub fn for_each_forward<F>(&self, mut f: F)
    where
        F: FnMut(ModifierChainNodeRef<'_>),
    {
        for node in self.head_to_tail() {
            f(node);
        }
    }

    /// Calls `f` for every node containing any capability from `mask`.
    pub fn for_each_forward_matching<F>(&self, mask: NodeCapabilities, mut f: F)
    where
        F: FnMut(ModifierChainNodeRef<'_>),
    {
        if mask.is_empty() {
            self.for_each_forward(f);
            return;
        }

        if !self.head().aggregate_child_capabilities().intersects(mask) {
            return;
        }

        for node in self.head_to_tail() {
            if node.kind_set().intersects(mask) {
                f(node);
            }
        }
    }

    /// Calls `f` for every node containing any capability from `mask`, providing the node ref.
    pub fn for_each_node_with_capability<F>(&self, mask: NodeCapabilities, mut f: F)
    where
        F: FnMut(ModifierChainNodeRef<'_>, &dyn ModifierNode),
    {
        self.for_each_forward_matching(mask, |node_ref| {
            node_ref.with_node(|node| f(node_ref.clone(), node));
        });
    }

    /// Calls `f` for every node in reverse insertion order.
    pub fn for_each_backward<F>(&self, mut f: F)
    where
        F: FnMut(ModifierChainNodeRef<'_>),
    {
        for node in self.tail_to_head() {
            f(node);
        }
    }

    /// Returns the node reference that owns `node`.
    pub fn find_node_ref(&self, node: &dyn ModifierNode) -> Option<ModifierChainNodeRef<'_>> {
        fn node_data_ptr(node: &dyn ModifierNode) -> *const () {
            node as *const dyn ModifierNode as *const ()
        }

        let target = node_data_ptr(node);
        // A node comes before its delegates, so a delegate that starts its
        // node's memory finds the node.
        (0..self.order_len())
            .find(|&index| {
                self.with_path(self.order_at(index).0, |node| node_data_ptr(node) == target)
                    .unwrap_or(false)
            })
            .map(|index| self.node_ref(ChainPosition::Node(index)))
    }

    /// Downcasts the node at `index` to the requested type.
    /// Returns a `Ref` guard that dereferences to the node type.
    pub fn node<N: ModifierNode + 'static>(&self, index: usize) -> Option<std::cell::Ref<'_, N>> {
        self.get_node_rc(index).and_then(|node| {
            std::cell::Ref::filter_map(node.borrow(), |boxed_node| {
                boxed_node.as_any().downcast_ref::<N>()
            })
            .ok()
        })
    }

    /// Downcasts the node at `index` to the requested mutable type.
    /// Returns a `RefMut` guard that dereferences to the node type.
    pub fn node_mut<N: ModifierNode + 'static>(
        &self,
        index: usize,
    ) -> Option<std::cell::RefMut<'_, N>> {
        self.get_node_rc(index).and_then(|node| {
            std::cell::RefMut::filter_map(node.borrow_mut(), |boxed_node| {
                boxed_node.as_any_mut().downcast_mut::<N>()
            })
            .ok()
        })
    }

    /// Returns the shared node at the given index, `None` for a plain
    /// element, which has none. Coordinators compare it with the node they
    /// hold and clone it only to hold a new one.
    pub fn get_node_rc(&self, index: usize) -> Option<&Rc<RefCell<dyn ModifierNode>>> {
        self.entries.get(index).and_then(ModifierNodeEntry::node)
    }

    /// The table and the words of the plain element at `index`.
    #[inline]
    pub fn plain_words(&self, index: usize) -> Option<(&'static PlainFns, &[u32])> {
        self.entries.get(index)?.plain_words()
    }

    /// How the plain element at `index` measures, with every word of its
    /// entry: the words past the element's own are zero.
    #[inline]
    pub fn plain_layout(
        &self,
        index: usize,
    ) -> Option<(Option<&'static PlainLayoutFns>, &[u32; PLAIN_WORDS_MAX])> {
        self.entries.get(index)?.plain_layout()
    }

    /// The value of the plain element at `index`, when it is an `E`.
    #[inline]
    pub fn plain<E: PlainElement>(&self, index: usize) -> Option<E> {
        self.entries.get(index)?.held().plain()
    }

    /// Returns true if the chain contains any nodes matching the given invalidation kind.
    pub fn has_nodes_for_invalidation(&self, kind: InvalidationKind) -> bool {
        self.aggregated_capabilities
            .contains(NodeCapabilities::for_invalidation(kind))
    }

    /// Visits every node mutably in insertion order together with its capability mask.
    pub fn visit_nodes_mut<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut dyn ModifierNode, NodeCapabilities),
    {
        for index in 0..self.order_len() {
            let (path, cached_caps, _agg) = self.order_at(index);
            let Some(node) = self.entries[path.entry()].node() else {
                continue;
            };
            let mut node_borrow = node.borrow_mut();
            let mut current: &mut dyn ModifierNode = &mut *node_borrow;
            for &delegate_index in path.delegates() {
                match nth_delegate_mut(current, delegate_index as usize) {
                    Some(delegate) => current = delegate,
                    None => return,
                }
            }
            f(current, cached_caps);
        }
    }

    pub(super) fn node_ref(&self, position: ChainPosition) -> ModifierChainNodeRef<'_> {
        ModifierChainNodeRef {
            chain: self,
            position,
        }
    }

    // Runs `f` on the node at `path`; `None` when a delegate of it is gone.
    pub(super) fn with_path<R>(
        &self,
        path: NodePath,
        f: impl FnOnce(&dyn ModifierNode) -> R,
    ) -> Option<R> {
        let node_borrow = self.entries[path.entry()].node()?.borrow();
        let mut current: &dyn ModifierNode = &*node_borrow;
        for &delegate_index in path.delegates() {
            current = nth_delegate(current, delegate_index as usize)?;
        }
        Some(f(current))
    }

    // How many nodes the chain's order holds, delegates included.
    pub(super) fn order_len(&self) -> usize {
        self.delegated_order
            .as_deref()
            .map_or(self.entries.len(), Vec::len)
    }

    // The node at `index` of the chain's order: its path, its capabilities
    // and the union of capabilities from it to the tail.
    pub(super) fn order_at(&self, index: usize) -> (NodePath, NodeCapabilities, NodeCapabilities) {
        match self.delegated_order.as_deref() {
            Some(order) => order[index],
            None => {
                let entry = &self.entries[index];
                (
                    NodePath::root(index),
                    entry.capabilities(),
                    entry.aggregate(),
                )
            }
        }
    }

    // Orders the nodes again and works out the union of capabilities from
    // each node to the tail.
    fn sync_chain_links(&mut self) {
        let delegating = self
            .entries
            .iter()
            .filter_map(ModifierNodeEntry::node)
            .any(|node| delegates(&*node.borrow()));
        if delegating {
            self.order_with_delegates();
        } else {
            self.delegated_order = None;
        }
        self.link_aggregates();
    }

    // Works out the union of capabilities from each node to the tail.
    fn link_aggregates(&mut self) {
        let mut aggregate = NodeCapabilities::empty();
        if let Some(order) = self.delegated_order.as_deref_mut() {
            for (_, caps, aggregate_child) in order.iter_mut().rev() {
                aggregate |= *caps;
                *aggregate_child = aggregate;
            }
        } else {
            for entry in self.entries.iter_mut().rev() {
                aggregate |= entry.capabilities();
                entry.set_aggregate(aggregate);
            }
        }
        self.aggregated_capabilities = aggregate;
    }

    // Orders the nodes of a chain of which a node delegates, each delegate
    // after the node that delegates to it.
    fn order_with_delegates(&mut self) {
        let order = self.delegated_order.get_or_insert_default();
        order.clear();
        let mut path_buf = [0usize; MAX_DELEGATE_DEPTH];
        for (index, entry) in self.entries.iter().enumerate() {
            match entry.node() {
                Some(node) => {
                    Self::enumerate_link_order(&*node.borrow(), index, &mut path_buf, 0, order);
                }
                None => order.push((
                    NodePath::root(index),
                    entry.capabilities(),
                    NodeCapabilities::empty(),
                )),
            }
        }
    }

    fn enumerate_link_order(
        node: &dyn ModifierNode,
        entry: usize,
        path_buf: &mut [usize; MAX_DELEGATE_DEPTH],
        path_len: usize,
        out: &mut Vec<(NodePath, NodeCapabilities, NodeCapabilities)>,
    ) {
        let caps = node.node_state().capabilities();
        out.push((
            NodePath::from_slice(entry, &path_buf[..path_len]),
            caps,
            NodeCapabilities::empty(),
        ));
        let mut delegate_index = 0usize;
        node.for_each_delegate(&mut |child| {
            if path_len < MAX_DELEGATE_DEPTH {
                path_buf[path_len] = delegate_index;
                Self::enumerate_link_order(child, entry, path_buf, path_len + 1, out);
            }
            delegate_index += 1;
        });
    }
}