zng-app 0.18.3

Part of the zng project.
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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! Widget nodes types, [`UiNode`], [`UiVec`] and others.

use std::{any::Any, ops::ControlFlow};

mod adopt;
pub use adopt::*;

mod arc;
pub use arc::*;

mod extend;
pub use extend::*;

mod match_node;
pub use match_node::*;

mod when;
pub use when::*;

mod trace;

mod list;
pub use list::*;
use zng_app_proc_macros::widget;
use zng_layout::{context::LAYOUT, unit::PxSize};
use zng_var::{BoxAnyVarValue, ContextInitHandle, ResponseVar, response_done_var, response_var};

use crate::{
    render::{FrameBuilder, FrameUpdate},
    update::{EventUpdate, WidgetUpdates},
};

use super::{
    WIDGET, WidgetId, WidgetUpdateMode,
    info::{WidgetInfoBuilder, WidgetLayout, WidgetMeasure},
};

macro_rules! debug_warn_list {
    ($self:ident, $op:tt) => {
        #[cfg(debug_assertions)]
        {
            if $self.is_list() {
                let op = $op;
                tracing::warn!("UiNodeImpl is_list without implementing `{op}`");
            }
        }
    };
}

/// Represents an [`UiNode`] implementation.
///
/// You can use the [`match_node`] helper to quickly declare a new node from a closure, most property nodes are implemented
/// using the match helpers. For more advanced nodes you can manually implement this trait.
pub trait UiNodeImpl: Any + Send {
    /// Gets the current count of children nodes.
    fn children_len(&self) -> usize;

    /// Gets if the node represents a list of other nodes.
    ///
    /// If `true` the node provides only minimal layout implementations and expects the caller
    /// to use [`measure_list`], [`layout_list`] or direct access to child nodes for layout.
    ///
    /// If `true` the node must implement all methods that iterate over children, for better performance and if possible, parallelization.
    /// A warning is logged in debug builds if a list node did not implement one of these methods.
    ///
    /// [`measure_list`]: UiNodeImpl::measure_list
    /// [`layout_list`]: UiNodeImpl::layout_list
    fn is_list(&self) -> bool {
        false
    }

    /// Visit a child node by `index`. If the index is not valid `visitor` is not called.
    ///
    /// Nodes with many children should also implement [`for_each_child`] and [`par_each_child`] for better performance.
    ///
    /// [`for_each_child`]: UiNodeImpl::for_each_child
    /// [`par_each_child`]: UiNodeImpl::par_each_child
    fn with_child(&mut self, index: usize, visitor: &mut dyn FnMut(&mut UiNode));

    /// Call `visitor` for each child node of `self`, one at a time.
    ///
    /// The closure parameters are the child index and the child.
    fn for_each_child(&mut self, visitor: &mut dyn FnMut(usize, &mut UiNode)) {
        debug_warn_list!(self, "for_each_child");

        for i in 0..self.children_len() {
            self.with_child(i, &mut |n| visitor(i, n));
        }
    }

    /// Call `visitor` for each child node of `self`, one at a time, with control flow.
    ///
    /// The closure parameters are the child index and the child.
    fn try_for_each_child(
        &mut self,
        visitor: &mut dyn FnMut(usize, &mut UiNode) -> ControlFlow<BoxAnyVarValue>,
    ) -> ControlFlow<BoxAnyVarValue> {
        debug_warn_list!(self, "try_for_each_child");

        for i in 0..self.children_len() {
            let mut flow = ControlFlow::Continue(());
            self.with_child(i, &mut |n| flow = visitor(i, n));
            flow?;
        }
        ControlFlow::Continue(())
    }

    /// Calls `visitor` for each child node in parallel.
    ///
    /// The closure parameters are the child index and the child.
    fn par_each_child(&mut self, visitor: &(dyn Fn(usize, &mut UiNode) + Sync)) {
        debug_warn_list!(self, "par_each_child");

        for i in 0..self.children_len() {
            self.with_child(i, &mut |n| visitor(i, n));
        }
    }

    /// Calls `fold` for each child node in parallel, with fold accumulators produced by cloning `identity`, then merges the folded results
    /// using `reduce` to produce the final value also in parallel.
    ///
    /// If the `reduce` closure is [associative], an *append* like operation will produce a result in the same order as the input items.
    ///
    /// [associative]: https://en.wikipedia.org/wiki/Associative_property
    fn par_fold_reduce(
        &mut self,
        identity: BoxAnyVarValue,
        fold: &(dyn Fn(BoxAnyVarValue, usize, &mut UiNode) -> BoxAnyVarValue + Sync),
        reduce: &(dyn Fn(BoxAnyVarValue, BoxAnyVarValue) -> BoxAnyVarValue + Sync),
    ) -> BoxAnyVarValue {
        debug_warn_list!(self, "par_fold_reduce");

        let _ = reduce;
        let mut accumulator = identity;
        for i in 0..self.children_len() {
            self.with_child(i, &mut |n| {
                accumulator = fold(std::mem::replace(&mut accumulator, BoxAnyVarValue::new(())), i, n);
            });
        }
        accumulator
    }

    /// Initializes the node in a new UI context.
    ///
    /// Common init operations are subscribing to variables and events and initializing data.
    /// You can use [`WIDGET`] to subscribe events and vars, the subscriptions live until the widget is deinited.
    ///
    /// If the node is a custom widget it must request an info, layout and render updates, other nodes
    /// do not need to request any sort of update on init.
    ///
    /// Note that this method can be called again, after a [`deinit`].
    ///
    /// [`deinit`]: UiNode::deinit
    fn init(&mut self) {
        match self.children_len() {
            0 => {}
            1 => self.with_child(0, &mut |c| c.0.init()),
            _ => {
                debug_warn_list!(self, "init");
                self.for_each_child(&mut |_, n| n.0.init())
            }
        }
    }

    /// Deinitializes the node in the current UI context.
    ///
    /// Common deinit operations include dropping allocations and handlers.
    ///
    /// If the node is a custom widget it must request an info, layout and render updates, other nodes
    /// do not need to request any sort of update on deinit.
    ///
    /// Note that [`init`] can be called again after this.
    ///
    /// [`init`]: UiNode::init
    fn deinit(&mut self) {
        match self.children_len() {
            0 => {}
            1 => self.with_child(0, &mut |c| c.0.deinit()),
            _ => {
                debug_warn_list!(self, "deinit");
                self.for_each_child(&mut |_, n| n.0.deinit())
            }
        }
    }

    /// Builds widget info.
    ///
    /// This method is called every time there are structural changes in the UI tree such as a node added or removed, you
    /// can also request an info rebuild using [`WIDGET.update_info`].
    ///
    /// Only nodes in widgets that requested info rebuild and nodes in their ancestors receive this call. Other
    /// widgets reuse their info in the new info tree. The widget's latest built info is available in [`WIDGET.info`].
    ///
    /// Note that info rebuild has higher priority over event, update, layout and render, this means that if you set a variable
    /// and request info update the next info rebuild will still observe the old variable value, you can work around this issue by
    /// only requesting info rebuild after the variable updates.
    ///
    /// [`WIDGET.info`]: crate::widget::WIDGET::info
    /// [`WIDGET.update_info`]: crate::widget::WIDGET::update_info
    fn info(&mut self, info: &mut WidgetInfoBuilder) {
        match self.children_len() {
            0 => {}
            1 => self.with_child(0, &mut |c| c.0.info(info)),
            _ => {
                debug_warn_list!(self, "info");
                self.for_each_child(&mut |_, n| n.0.info(info))
            }
        }
    }

    /// Receives an event.
    ///
    /// Every call to this method is for a single update of a single event type, you can listen to events
    /// by subscribing to then on init and using the [`Event::on`] method in this method to detect the event.
    ///
    /// Note that events sent to descendant nodes also flow through this method and must be delegated. If you observe
    /// an event for a descendant before delegating to the descendant this is a ***preview*** handling, in the normal handling
    /// you delegate first, then check the event propagation.
    ///
    /// [`Event::on`]: crate::event::Event::on
    fn event(&mut self, update: &EventUpdate) {
        match self.children_len() {
            0 => {}
            1 => self.with_child(0, &mut |c| c.0.event(update)),
            _ => {
                debug_warn_list!(self, "event");
                self.for_each_child(&mut |_, n| n.0.event(update))
            }
        }
    }

    /// Receives variable and other non-event updates.
    ///
    /// Calls to this method aggregate all updates that happen in the last pass, multiple variables can be new at the same time.
    /// You can listen to variable updates by subscribing to then on init and using the [`Var::get_new`] method in this method to
    /// receive the new values.
    ///
    /// A custom update can be requested using the context [`WIDGET.update`]. Common update operations include reacting to variable
    /// changes that generate an intermediary value for layout or render, the update implementation uses [`WIDGET`] to request layout
    /// and render after updating the data. Note that for simple variables that are used directly on layout or render you can subscribe
    /// to that operation directly, skipping update.
    ///
    /// [`Var::get_new`]: zng_var::Var::get_new
    /// [`WIDGET.update`]: crate::widget::WIDGET::update
    fn update(&mut self, updates: &WidgetUpdates) {
        match self.children_len() {
            0 => {}
            1 => self.with_child(0, &mut |c| c.0.update(updates)),
            _ => {
                debug_warn_list!(self, "update");
                self.for_each_child(&mut |_, n| n.0.update(updates))
            }
        }
    }

    /// Does [`update`] and if the node is a list notifies list changes to the `observer`.
    ///
    /// [`update`]: UiNodeImpl::update
    fn update_list(&mut self, updates: &WidgetUpdates, observer: &mut dyn UiNodeListObserver) {
        if self.is_list() {
            debug_warn_list!(self, "update_list");
            let len = self.children_len();
            self.update(updates);
            if len != self.children_len() {
                observer.reset();
            }
        } else {
            self.update(updates);
        }
    }

    /// Computes the widget size given the contextual layout metrics without actually updating the widget layout.
    ///
    /// Implementers must return the same size [`layout`] returns for the given [`LayoutMetrics`], without
    /// affecting the actual widget render. Panel widgets that implement some complex layouts need to get an
    /// what the widget would be given some constraints, this value is used to inform the actual [`layout`] call.
    ///
    /// Nodes that implement [`layout`] must also implement this method, the [`LAYOUT`] context can be used to retrieve the metrics,
    /// the [`WidgetMeasure`] parameter can be used to communicate with the parent layout, such as disabling inline layout, the
    /// returned [`PxSize`] is the desired size given the parent constraints.
    ///
    /// [`layout`]: Self::layout
    /// [`LayoutMetrics`]: zng_layout::context::LayoutMetrics
    /// [`LAYOUT`]: zng_layout::context::LAYOUT
    /// [`PxSize`]: zng_layout::unit::PxSize
    #[must_use]
    fn measure(&mut self, wm: &mut WidgetMeasure) -> PxSize {
        match self.children_len() {
            0 => LAYOUT.constraints().fill_size(),
            1 => {
                let mut r = PxSize::zero();
                self.with_child(0, &mut |c| r = c.measure(wm));
                r
            }
            _ => {
                debug_warn_list!(self, "measure");
                let mut accumulator = PxSize::zero();
                self.for_each_child(&mut |_, n| accumulator = accumulator.max(n.0.measure(wm)));
                accumulator
            }
        }
    }

    /// If the node [`is_list`] measure each child and combine the size using `fold_size`.
    ///
    /// If the node is not a list, simply measures it.
    ///
    /// [`is_list`]: UiNodeImpl::is_list
    #[must_use]
    fn measure_list(
        &mut self,
        wm: &mut WidgetMeasure,
        measure: &(dyn Fn(usize, &mut UiNode, &mut WidgetMeasure) -> PxSize + Sync),
        fold_size: &(dyn Fn(PxSize, PxSize) -> PxSize + Sync),
    ) -> PxSize {
        if self.is_list() {
            match self.children_len() {
                0 => PxSize::zero(),
                1 => {
                    let mut r = PxSize::zero();
                    self.with_child(0, &mut |c| r = measure(0, c, wm));
                    r
                }
                _ => {
                    debug_warn_list!(self, "measure_list");

                    let mut accumulator = PxSize::zero();
                    self.for_each_child(&mut |i, n| {
                        let c_s = measure(i, n, wm);
                        accumulator = fold_size(accumulator, c_s)
                    });
                    accumulator
                }
            }
        } else {
            self.measure(wm)
        }
    }

    /// Computes the widget layout given the contextual layout metrics.
    ///
    /// Implementers must also implement [`measure`]. This method is called by the parent layout once the final constraints
    /// for the frame are defined, the [`LAYOUT`] context can be used to retrieve the constraints, the [`WidgetLayout`] parameter
    /// can be used to communicate layout metadata such as inline segments to the parent layout, the returned [`PxSize`] is the
    /// final size given the constraints.
    ///
    /// Only widgets and ancestors that requested layout or use metrics that changed since last layout receive this call. Other
    /// widgets reuse the last layout result.
    ///
    /// Nodes that render can also implement this operation just to observe the latest widget size, if changes are detected
    /// the [`WIDGET.render`] method can be used to request render.
    ///
    /// [`measure`]: Self::measure
    /// [`LayoutMetrics`]: zng_layout::context::LayoutMetrics
    /// [`constraints`]: zng_layout::context::LayoutMetrics::constraints
    /// [`WIDGET.render`]: crate::widget::WIDGET::render
    /// [`LAYOUT`]: zng_layout::context::LAYOUT
    /// [`PxSize`]: zng_layout::unit::PxSize
    #[must_use]
    fn layout(&mut self, wl: &mut WidgetLayout) -> PxSize {
        match self.children_len() {
            0 => LAYOUT.constraints().fill_size(),
            1 => {
                let mut r = PxSize::zero();
                self.with_child(0, &mut |c| r = c.layout(wl));
                r
            }
            _ => {
                debug_warn_list!(self, "layout");

                let mut accumulator = PxSize::zero();
                self.for_each_child(&mut |_, n| accumulator = accumulator.max(n.0.layout(wl)));
                accumulator
            }
        }
    }

    /// If the node [`is_list`] layout each child and combine the size using `fold_size`.
    ///
    /// If the node is not a list, simply layout it.
    ///
    /// [`is_list`]: UiNodeImpl::is_list
    #[must_use]
    fn layout_list(
        &mut self,
        wl: &mut WidgetLayout,
        layout: &(dyn Fn(usize, &mut UiNode, &mut WidgetLayout) -> PxSize + Sync),
        fold_size: &(dyn Fn(PxSize, PxSize) -> PxSize + Sync),
    ) -> PxSize {
        if self.is_list() {
            match self.children_len() {
                0 => PxSize::zero(),
                1 => {
                    let mut r = PxSize::zero();
                    self.with_child(0, &mut |c| r = layout(0, c, wl));
                    r
                }
                _ => {
                    debug_warn_list!(self, "layout_list");

                    let mut accumulator = PxSize::zero();
                    self.for_each_child(&mut |i, n| {
                        let c_s = layout(i, n, wl);
                        accumulator = fold_size(accumulator, c_s)
                    });
                    accumulator
                }
            }
        } else {
            self.layout(wl)
        }
    }

    /// Generates render instructions and updates transforms and hit-test areas.
    ///
    /// This method does not generate pixels immediately, it generates *display items* that are visual building block instructions
    /// for the renderer that will run after the window *display list* is built.
    ///
    /// Only widgets and ancestors that requested render receive this call, other widgets reuse the display items and transforms
    /// from the last frame.
    fn render(&mut self, frame: &mut FrameBuilder) {
        match self.children_len() {
            0 => {}
            1 => self.with_child(0, &mut |c| c.render(frame)),
            _ => {
                debug_warn_list!(self, "render");

                self.for_each_child(&mut |_, n| n.0.render(frame));
            }
        }
    }

    /// If the node [`is_list`] render each child.
    ///
    /// If the node is not a list, simply renders it.
    ///
    /// [`is_list`]: UiNodeImpl::is_list
    fn render_list(&mut self, frame: &mut FrameBuilder, render: &(dyn Fn(usize, &mut UiNode, &mut FrameBuilder) + Sync)) {
        if self.is_list() {
            match self.children_len() {
                0 => {}
                1 => self.with_child(0, &mut |n| render(0, n, frame)),
                _ => {
                    debug_warn_list!(self, "render_list");

                    self.for_each_child(&mut |i, n| render(i, n, frame));
                }
            }
        } else {
            self.render(frame);
        }
    }

    /// Updates values in the last generated frame.
    ///
    /// Some display item values and transforms can be updated directly, without needing to rebuild the display list. All [`FrameBuilder`]
    /// methods that accept a [`FrameValue<T>`] input can be bound to an ID that can be used to update that value.
    ///
    /// Only widgets and ancestors that requested render update receive this call. Note that if any other widget in the same window
    /// requests render all pending render update requests are upgraded to render requests.
    ///
    /// [`FrameValue<T>`]: crate::render::FrameValue
    fn render_update(&mut self, update: &mut FrameUpdate) {
        match self.children_len() {
            0 => {}
            1 => self.with_child(0, &mut |c| c.render_update(update)),
            _ => {
                debug_warn_list!(self, "render_update");

                self.for_each_child(&mut |_, n| n.0.render_update(update));
            }
        }
    }

    /// If the node [`is_list`] render_update each child.
    ///
    /// If the node is not a list, simply render_update it.
    ///
    /// [`is_list`]: UiNodeImpl::is_list
    fn render_update_list(&mut self, update: &mut FrameUpdate, render_update: &(dyn Fn(usize, &mut UiNode, &mut FrameUpdate) + Sync)) {
        if self.is_list() {
            match self.children_len() {
                0 => {}
                1 => self.with_child(0, &mut |n| render_update(0, n, update)),
                _ => {
                    debug_warn_list!(self, "render_update_list");

                    self.for_each_child(&mut |i, n| render_update(i, n, update));
                }
            }
        } else {
            self.render_update(update);
        }
    }

    /// Gets the node implementation as a [`WidgetUiNodeImpl`], if the node defines a widget instance scope.
    fn as_widget(&mut self) -> Option<&mut dyn WidgetUiNodeImpl> {
        None
    }
}
impl dyn UiNodeImpl {
    /// Gets if this node is a good candidate for parallelization when visiting children.
    ///
    /// List implementers should check this and [`PARALLEL_VAR`] to enable parallelization of node methods.
    ///
    /// [`PARALLEL_VAR`]: crate::widget::base::PARALLEL_VAR
    pub fn parallelize_hint(&mut self) -> bool {
        self.children_len() > 1 && self.non_parallel_count() >= MIN_PARALLEL
    }
    fn non_parallel_count(&mut self) -> usize {
        let mut count = 0;
        let _ = self.try_for_each_child(&mut |_, child| {
            let cc = child.0.non_parallel_count();
            if cc < MIN_PARALLEL {
                count += 1 + cc;
            }
            if count >= MIN_PARALLEL {
                ControlFlow::Break(BoxAnyVarValue::new(()))
            } else {
                ControlFlow::Continue(())
            }
        });
        count
    }
}
const MIN_PARALLEL: usize = 24;

/// Represents an [`UiNodeImpl`] that defines a widget instance scope.
///
/// Widget defining nodes implement this trait and [`UiNodeImpl::as_widget`].
pub trait WidgetUiNodeImpl: UiNodeImpl {
    /// Calls `visitor` with the [`WIDGET`] context of the widget instance defined by the node.
    ///
    /// If `update_mode` is [`WidgetUpdateMode::Bubble`] the update flags requested for the widget in `visitor` will be copied to the
    /// caller widget context, otherwise they are ignored.
    fn with_context(&mut self, update_mode: WidgetUpdateMode, visitor: &mut dyn FnMut());
}

/// Represents a value that can become a [`UiNode`] instance.
#[diagnostic::on_unimplemented(note = "`IntoUiNode` is implemented for all `U: UiNodeImpl`")]
pub trait IntoUiNode {
    /// Instantiate the UI node.
    fn into_node(self) -> UiNode;
}

impl<U: UiNodeImpl> IntoUiNode for U {
    #[inline(always)]
    fn into_node(self) -> UiNode {
        UiNode::new(self)
    }
}
impl IntoUiNode for UiNode {
    #[inline(always)]
    fn into_node(self) -> UiNode {
        self
    }
}
impl<U: IntoUiNode> IntoUiNode for Option<U> {
    /// Unwrap or nil.
    fn into_node(self) -> UiNode {
        self.map(IntoUiNode::into_node).unwrap_or_else(UiNode::nil)
    }
}

impl<A, B> IntoUiNode for std::iter::Chain<A, B>
where
    A: Iterator<Item = UiNode>,
    B: Iterator<Item = A::Item>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl IntoUiNode for std::iter::Empty<UiNode> {
    fn into_node(self) -> UiNode {
        ui_vec![].into_node()
    }
}
impl<I, P> IntoUiNode for std::iter::Filter<I, P>
where
    I: Iterator<Item = UiNode>,
    P: FnMut(&<I as Iterator>::Item) -> bool,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, F> IntoUiNode for std::iter::FilterMap<I, F>
where
    I: Iterator,
    F: FnMut(<I as Iterator>::Item) -> Option<UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, U, F> IntoUiNode for std::iter::FlatMap<I, U, F>
where
    I: Iterator,
    U: IntoIterator<Item = UiNode>,
    F: FnMut(I::Item) -> U,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, U> IntoUiNode for std::iter::Flatten<I>
where
    I: Iterator,
    <I as Iterator>::Item: IntoIterator<IntoIter = U, Item = <U as Iterator>::Item>,
    U: Iterator<Item = UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<F> IntoUiNode for std::iter::FromFn<F>
where
    F: FnMut() -> Option<UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, F> IntoUiNode for std::iter::Inspect<I, F>
where
    I: Iterator<Item = UiNode>,
    F: FnMut(&<I as Iterator>::Item),
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, F> IntoUiNode for std::iter::Map<I, F>
where
    I: Iterator,
    F: FnMut(I::Item) -> UiNode,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, P> IntoUiNode for std::iter::MapWhile<I, P>
where
    I: Iterator,
    P: FnMut(<I as Iterator>::Item) -> Option<UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I> IntoUiNode for std::iter::Peekable<I>
where
    I: Iterator<Item = UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I> IntoUiNode for std::iter::Rev<I>
where
    I: DoubleEndedIterator<Item = UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, St, F> IntoUiNode for std::iter::Scan<I, St, F>
where
    I: Iterator,
    F: FnMut(&mut St, <I as Iterator>::Item) -> Option<UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I> IntoUiNode for std::iter::Skip<I>
where
    I: Iterator<Item = UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, P> IntoUiNode for std::iter::SkipWhile<I, P>
where
    I: Iterator<Item = UiNode>,
    P: FnMut(&<I as Iterator>::Item) -> bool,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I> IntoUiNode for std::iter::StepBy<I>
where
    I: Iterator<Item = UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<F> IntoUiNode for std::iter::Successors<UiNode, F>
where
    F: FnMut(&UiNode) -> Option<UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I> IntoUiNode for std::iter::Take<I>
where
    I: Iterator<Item = UiNode>,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}
impl<I, P> IntoUiNode for std::iter::TakeWhile<I, P>
where
    I: Iterator<Item = UiNode>,
    P: FnMut(&<I as Iterator>::Item) -> bool,
{
    fn into_node(self) -> UiNode {
        let vec: Vec<UiNode> = self.collect();
        vec.into_node()
    }
}

/// Represents an UI tree node instance.
///
/// You can use the [`match_node`] helper to quickly declare a new node from a closure, most property nodes are implemented
/// using the match helpers. For more advanced nodes can implement the [`UiNodeImpl`] trait. Other types can be converted to nodes
/// if they implement [`IntoUiNode`].
///
/// [`match_node`]:fn@match_node
pub struct UiNode(Box<dyn UiNodeImpl>);

/// Constructors.
impl UiNode {
    /// New UI node instance from implementation.
    ///
    /// Note that [`IntoUiNode`] is implemented for all `U: UiNodeImpl` so you don't usually need to call this.
    pub fn new(implementation: impl UiNodeImpl) -> Self {
        Self(Box::new(implementation))
    }

    /// New UI node that does nothing and collapses layout.
    pub fn nil() -> Self {
        Self::new(NilUiNode)
    }
}

/// UI operations.
impl UiNode {
    /// Calls the [`UiNodeOp`].
    #[inline(always)]
    pub fn op(&mut self, op: UiNodeOp) {
        match op {
            UiNodeOp::Init => self.init(),
            UiNodeOp::Deinit => self.deinit(),
            UiNodeOp::Info { info } => self.info(info),
            UiNodeOp::Event { update } => self.event(update),
            UiNodeOp::Update { updates } => self.update(updates),
            UiNodeOp::Measure { wm, desired_size } => *desired_size = self.measure(wm),
            UiNodeOp::Layout { wl, final_size } => *final_size = self.layout(wl),
            UiNodeOp::Render { frame } => self.render(frame),
            UiNodeOp::RenderUpdate { update } => self.render_update(update),
        }
    }

    /// Initialize the node in a new UI context.
    ///
    /// See [`UiNodeImpl::init`] for more details.
    #[inline(always)]
    pub fn init(&mut self) {
        self.0.init();
    }

    /// Deinitialize the node in the current UI context.
    ///
    /// This must be called before dropping the node.
    ///
    /// After calling this you can move the node to a new context and call [`init`] again.
    ///
    /// See [`UiNodeImpl::deinit`] for more details.
    ///
    /// [`init`]: Self::init
    #[inline(always)]
    pub fn deinit(&mut self) {
        self.0.deinit();
    }

    /// Continue building widget info metadata.
    ///
    /// See [`UiNodeImpl::info`] for more details.
    #[inline(always)]
    pub fn info(&mut self, info: &mut WidgetInfoBuilder) {
        self.0.info(info);
    }

    /// Notify event update.
    ///
    /// See [`UiNodeImpl::event`] for more details.
    #[inline(always)]
    pub fn event(&mut self, update: &EventUpdate) {
        self.0.event(update);
    }

    /// Notify non-event update.
    ///
    /// See [`UiNodeImpl::update`] for more details.
    #[inline(always)]
    pub fn update(&mut self, updates: &WidgetUpdates) {
        self.0.update(updates);
    }

    /// Notify non-event update and observe list changes if the widget is a list.
    ///
    /// See [`UiNodeImpl::update_list`] for more details.
    #[inline(always)]
    pub fn update_list(&mut self, updates: &WidgetUpdates, observer: &mut impl UiNodeListObserver) {
        self.0.update_list(updates, observer);
    }

    /// Estimate node layout without actually updating the node render state.
    ///
    /// See [`UiNodeImpl::measure`] for more details.
    #[inline(always)]
    #[must_use]
    pub fn measure(&mut self, wm: &mut WidgetMeasure) -> PxSize {
        self.0.measure(wm)
    }

    /// If the node [`is_list`] measure each child and combine the size using `fold_size`.
    ///
    /// If the node is not a list, simply measures it.
    ///
    /// See [`UiNodeImpl::measure_list`] for more details.
    ///
    /// [`is_list`]: UiNode::is_list
    #[inline(always)]
    #[must_use]
    pub fn measure_list(
        &mut self,
        wm: &mut WidgetMeasure,
        measure: impl Fn(usize, &mut UiNode, &mut WidgetMeasure) -> PxSize + Sync,
        fold_size: impl Fn(PxSize, PxSize) -> PxSize + Sync,
    ) -> PxSize {
        self.0.measure_list(wm, &measure, &fold_size)
    }

    /// Update node layout.
    ///
    /// See [`UiNodeImpl::layout`] for more details.
    #[inline(always)]
    #[must_use]
    pub fn layout(&mut self, wl: &mut WidgetLayout) -> PxSize {
        self.0.layout(wl)
    }

    /// If the node [`is_list`] layout each child and combine the size using `fold_size`.
    ///
    /// If the node is not a list, simply layout it.
    ///
    /// See [`UiNodeImpl::layout_list`] for more details.
    ///
    /// [`is_list`]: UiNode::is_list
    #[inline(always)]
    #[must_use]
    pub fn layout_list(
        &mut self,
        wl: &mut WidgetLayout,
        layout: impl Fn(usize, &mut UiNode, &mut WidgetLayout) -> PxSize + Sync,
        fold_size: impl Fn(PxSize, PxSize) -> PxSize + Sync,
    ) -> PxSize {
        self.0.layout_list(wl, &layout, &fold_size)
    }

    /// Collect render instructions for a new frame.
    ///
    /// See [`UiNodeImpl::render`] for more details.
    #[inline(always)]
    pub fn render(&mut self, frame: &mut FrameBuilder) {
        self.0.render(frame)
    }

    /// If the node [`is_list`] render each child.
    ///
    /// If the node is not a list, simply renders it.
    ///
    /// See [`UiNodeImpl::render_list`] for more details.
    ///
    /// [`is_list`]: UiNode::is_list
    #[inline(always)]
    pub fn render_list(&mut self, frame: &mut FrameBuilder, render: impl Fn(usize, &mut UiNode, &mut FrameBuilder) + Sync) {
        self.0.render_list(frame, &render);
    }

    /// Collect render patches to apply to the previous frame.
    ///
    /// See [`UiNodeImpl::render_update`] for more details.
    #[inline(always)]
    pub fn render_update(&mut self, update: &mut FrameUpdate) {
        self.0.render_update(update);
    }

    /// If the node [`is_list`] render_update each child.
    ///
    /// If the node is not a list, simply render_update it.
    ///
    /// See [`UiNodeImpl::render_update_list`] for more details.
    ///
    /// [`is_list`]: UiNode::is_list
    #[inline(always)]
    pub fn render_update_list(&mut self, update: &mut FrameUpdate, render_update: impl Fn(usize, &mut UiNode, &mut FrameUpdate) + Sync) {
        self.0.render_update_list(update, &render_update);
    }
}

/// Children.
impl UiNode {
    /// Number of direct descendants of this node.
    pub fn children_len(&self) -> usize {
        self.0.children_len()
    }

    /// Call `visitor` with a exclusive reference to the child node identified by `index`.
    ///
    /// If the `index` is out of bounds the closure is not called and returns `None`.
    pub fn try_with_child<R>(&mut self, index: usize, visitor: impl FnOnce(&mut UiNode) -> R) -> Option<R> {
        let mut once = Some(visitor);
        let mut r = None;
        self.0.with_child(index, &mut |child| r = Some(once.take().unwrap()(child)));
        r
    }

    /// Call `visitor` with a exclusive reference to the child node identified by `index`.
    ///
    /// Panics if the `index` is out of bounds.
    pub fn with_child<R>(&mut self, index: usize, visitor: impl FnOnce(&mut UiNode) -> R) -> R {
        self.try_with_child(index, visitor).expect("index out of bounds")
    }

    /// Call `visitor` for each child node of `self`, one at a time.
    ///
    /// The closure parameters are the child index and the child.
    pub fn for_each_child(&mut self, mut visitor: impl FnMut(usize, &mut UiNode)) {
        self.0.for_each_child(&mut visitor);
    }

    /// Call `visitor` for each child node of `self`, one at a time, with control flow.
    ///
    /// The closure parameters are the child index and the child.
    pub fn try_for_each_child<B>(&mut self, mut visitor: impl FnMut(usize, &mut UiNode) -> ControlFlow<B>) -> ControlFlow<B>
    where
        B: zng_var::VarValue,
    {
        self.0
            .try_for_each_child(&mut move |i, n| visitor(i, n).map_break(BoxAnyVarValue::new))
            .map_break(|b| b.downcast::<B>().unwrap())
    }

    /// Calls `visitor` for each child node in parallel.
    ///
    /// The closure parameters are the child index and the child.
    pub fn par_each_child(&mut self, visitor: impl Fn(usize, &mut UiNode) + Sync) {
        self.0.par_each_child(&visitor);
    }

    /// Calls `fold` for each child node in parallel, with fold accumulators produced by cloning `identity`, then merges the folded results
    /// using `reduce` to produce the final value also in parallel.
    ///
    /// If the `reduce` closure is [associative], an *append* like operation will produce a result in the same order as the input items.
    ///
    /// [associative]: https://en.wikipedia.org/wiki/Associative_property
    pub fn par_fold_reduce<T: zng_var::VarValue>(
        &mut self,
        identity: T,
        fold: impl Fn(T, usize, &mut UiNode) -> T + Sync,
        reduce: impl Fn(T, T) -> T + Sync,
    ) -> T {
        use zng_var::BoxAnyVarValue as B;
        self.0
            .par_fold_reduce(
                B::new(identity),
                &|accumulator, index, node| {
                    let r = fold(accumulator.downcast::<T>().unwrap(), index, node);
                    B::new(r)
                },
                &|a, b| {
                    let r = reduce(a.downcast::<T>().unwrap(), b.downcast::<T>().unwrap());
                    B::new(r)
                },
            )
            .downcast::<T>()
            .unwrap()
    }
}

/// Node type.
impl UiNode {
    /// Returns some reference to implementation of type `U`, if the node instance is of that implementation.
    #[inline(always)]
    pub fn downcast_ref<U: UiNodeImpl>(&self) -> Option<&U> {
        let u: &dyn Any = &*self.0;
        u.downcast_ref::<U>()
    }

    /// Returns some mutable reference to implementation of type `U`, if the node instance is of that implementation.
    #[inline(always)]
    pub fn downcast_mut<U: UiNodeImpl>(&mut self) -> Option<&mut U> {
        let u: &mut dyn Any = &mut *self.0;
        u.downcast_mut::<U>()
    }

    /// Gets if the node is an instance of implementation `U`.
    #[inline(always)]
    pub fn is<U: UiNodeImpl>(&self) -> bool {
        self.downcast_ref::<U>().is_some()
    }

    /// Exclusive borrow the node implementation directly.
    #[inline(always)]
    pub fn as_dyn(&mut self) -> &mut dyn UiNodeImpl {
        &mut *self.0
    }

    /// Gets if the node represents a list of other nodes.
    ///
    /// If `true` the node provides only minimal layout implementations and expects the caller
    /// to use [`measure_list`], [`layout_list`] or direct access to the child nodes for layout.
    ///
    /// [`measure_list`]: Self::measure_list
    /// [`layout_list`]: Self::layout_list
    #[inline(always)]
    pub fn is_list(&self) -> bool {
        self.0.is_list()
    }

    /// Returns a node that [`is_list`].
    ///
    /// If `self` is a list returns it unchanged.
    ///
    /// If `self` is nil returns an empty list node.
    ///
    /// Otherwise returns a new list node with `self` as the single entry.
    ///
    /// [`is_list`]: Self::is_list
    pub fn into_list(self) -> UiNode {
        if self.is_list() {
            self
        } else if self.is_nil() {
            ui_vec![].into_node()
        } else {
            ui_vec![self].into_node()
        }
    }

    /// Gets if is [`nil`].
    ///
    /// [`nil`]: Self::nil
    #[inline(always)]
    pub fn is_nil(&self) -> bool {
        self.is::<NilUiNode>()
    }

    /// Access widget node methods, if the node defines a widget context.
    #[inline(always)]
    pub fn as_widget(&mut self) -> Option<WidgetUiNode<'_>> {
        self.0.as_widget().map(WidgetUiNode)
    }

    /// Returns a node that defines a widget context.
    ///
    /// If this node already defines a widget just returns it, if not wraps it in a minimal widget implementation.
    ///
    /// See also [`init_widget`] for a node that awaits until `self` is inited to verify if a new widget really needs to be declared.
    ///
    /// [`init_widget`]: Self::init_widget
    pub fn into_widget(mut self) -> UiNode {
        if self.0.as_widget().is_some() {
            self
        } else {
            into_widget!(child = self)
        }
    }

    /// Returns a node that defines a widget context or will begin defining it after [`init`].
    ///
    /// Also returns a response var that contains or will contain the widget instance ID.
    ///
    /// If `self` is already an widget node simply returns it and the ID, otherwise returns a node that wraps `self`
    /// and checks again if `self` is a widget after init, if `self` is still not a widget after init the wrapper node starts
    /// defining a minimal widget context.
    ///
    /// Some nodes like [`ArcNode::take_on_init`] can only become widgets on init, this helper is an alternative to [`into_widget`]
    /// that avoids declaring a second wrapper widget in those cases. Note that because the wrapper node needs to define a widget context
    /// after the [`init`] call the wrapped `self` node will need to be reinited inside the new widget.
    ///
    /// [`init`]: Self::init
    /// [`into_widget`]: Self::into_widget
    pub fn init_widget(mut self) -> (UiNode, ResponseVar<WidgetId>) {
        if let Some(mut wgt) = self.as_widget() {
            let id = response_done_var(wgt.id());
            (self, id)
        } else {
            let (r, id) = response_var::<WidgetId>();
            let mut first_init = Some(r);
            let wgt = match_widget(self, move |c, op| {
                if let UiNodeOp::Init = op {
                    c.init();

                    if let Some(r) = first_init.take() {
                        if let Some(mut wgt) = c.node().as_widget() {
                            r.respond(wgt.id());
                        } else {
                            // reinit inside a new widget
                            c.deinit();
                            let not_wgt = std::mem::replace(c.node(), UiNode::nil());
                            *c.node() = into_widget!(child = not_wgt);
                            c.init();

                            r.respond(c.node().as_widget().unwrap().id());
                        }
                    }
                }
            });
            (wgt, id)
        }
    }

    /// Wraps this in a node that, before delegating each method, calls a closure with
    /// the [`UiNodeMethod`], the closure can return a *span* that is dropped after the method delegation.
    ///
    /// The tracing node delegates all methods to self, but only traces the [`UiNodeMethod`] methods. If
    /// this node is an widget the `enter_mtd` closure will be called (and span dropped) in the context of the widget.
    ///
    /// You can use the [`tracing`](https://docs.rs/tracing) crate to create the span. You can also use the [`RunOnDrop`]
    /// struct to run a closure after the method executes.
    ///
    /// [`RunOnDrop`]: zng_app_context::RunOnDrop
    pub fn trace<E, S>(self, enter_mtd: E) -> UiNode
    where
        Self: Sized,
        E: FnMut(UiNodeMethod) -> S + Send + 'static,
    {
        UiNode::new(trace::TraceNode::new(self, enter_mtd))
    }
}

/// Extra [`UiNode`] methods for nodes that define a widget instance context.
///
/// See [`UiNode::as_widget`] for more details.
pub struct WidgetUiNode<'u>(&'u mut dyn WidgetUiNodeImpl);

impl<'u> WidgetUiNode<'u> {
    /// Calls `visitor` with the [`WIDGET`] context of the widget instance defined by the node.
    ///
    /// If `update_mode` is [`WidgetUpdateMode::Bubble`] the update flags requested for the widget in `visitor` will be copied to the
    /// caller widget context, otherwise they are ignored.
    #[inline(always)]
    pub fn with_context<R>(&mut self, update_mode: WidgetUpdateMode, visitor: impl FnOnce() -> R) -> R {
        let mut once = Some(visitor);
        let mut r = None;
        self.0.with_context(update_mode, &mut || r = Some(once.take().unwrap()()));
        r.unwrap()
    }

    /// Gets the widget instance ID.
    pub fn id(&mut self) -> WidgetId {
        self.with_context(WidgetUpdateMode::Ignore, || WIDGET.id())
    }
}

/// See [`UiNode::into_widget`]
#[expect(non_camel_case_types)]
#[widget($crate::widget::node::into_widget)]
struct into_widget(crate::widget::base::WidgetBase);
#[zng_app_proc_macros::property(CHILD, capture, widget_impl(into_widget))]
fn child(child: impl IntoUiNode) {}
impl into_widget {
    fn widget_intrinsic(&mut self) {
        self.widget_builder().push_build_action(|b| {
            let child = b.capture_ui_node(crate::property_id!(Self::child)).unwrap();
            b.set_child(child);
        });
    }
}

struct NilUiNode;
impl UiNodeImpl for NilUiNode {
    fn measure(&mut self, _: &mut WidgetMeasure) -> PxSize {
        PxSize::zero()
    }

    fn layout(&mut self, _: &mut WidgetLayout) -> PxSize {
        PxSize::zero()
    }

    fn children_len(&self) -> usize {
        0
    }

    fn with_child(&mut self, _: usize, _: &mut dyn FnMut(&mut UiNode)) {}
}

/// A UI node that fills the available layout space.
///
/// The space is blank, the node does nothing other then layout to fill.
pub struct FillUiNode;
impl UiNodeImpl for FillUiNode {
    fn children_len(&self) -> usize {
        0
    }

    fn with_child(&mut self, _: usize, _: &mut dyn FnMut(&mut UiNode)) {}

    // default impl is fill
}

/// Wraps `child` in a node that provides a unique [`ContextInitHandle`], refreshed every (re)init.
///
/// [`ContextInitHandle`]: zng_var::ContextInitHandle
pub fn with_new_context_init_id(child: impl IntoUiNode) -> UiNode {
    let mut id = None;

    match_node(child, move |child, op| {
        let is_deinit = matches!(op, UiNodeOp::Deinit);
        id.get_or_insert_with(ContextInitHandle::new).with_context(|| child.op(op));

        if is_deinit {
            id = None;
        }
    })
}