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
use std::mem;

use zng_layout::unit::PxSize;

use crate::{
    render::{FrameBuilder, FrameUpdate},
    update::{EventUpdate, WidgetUpdates},
    widget::{
        info::{WidgetInfoBuilder, WidgetLayout, WidgetMeasure},
        ui_node, WidgetUpdateMode,
    },
};

use super::*;

/// Represents a node operation in a [`match_node`].
///
/// [`match_node`]: fn@match_node
#[non_exhaustive]
pub enum UiNodeOp<'a> {
    /// The [`UiNode::init`].
    ///
    /// Initialize 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.
    ///
    /// This operation can be called again after a [`Deinit`].
    ///
    /// [`Deinit`]: Self::Deinit
    Init,
    /// The [`UiNode::deinit`].
    ///
    /// Deinitialize the node in the current UI context.
    ///
    /// Common deinit operations include dropping allocations and handlers.
    ///
    /// [`Init`] can be called again after this.
    ///
    /// [`Init`]: Self::Init
    Deinit,
    /// The [`UiNode::info`].
    ///
    /// Build widget info.
    ///
    /// This operation 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.update_info`]: crate::widget::WIDGET::update_info
    /// [`WIDGET.info`]: crate::widget::WIDGET::info
    Info {
        /// Info builder.
        info: &'a mut WidgetInfoBuilder,
    },
    /// The [`UiNode::event`].
    ///
    /// Receive an event.
    ///
    /// Every call to this operation 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 during this operation to detect the event.
    ///
    /// Note that events sent to descendant nodes also flow through the match node and are automatically delegated if
    /// you don't manually delegate. Automatic delegation happens after the operation is handled, you can call
    /// `child.event` to manually delegate before handling.
    ///
    /// When an ancestor handles the event before the descendants this is a ***preview*** handling, so match nodes handle
    /// event operations in preview by default.
    ///
    /// [`Init`]: Self::Init
    /// [`Event::on`]: crate::event::Event::on
    Event {
        /// Event update args and targets.
        update: &'a EventUpdate,
    },
    /// The [`UiNode::update`].
    ///
    /// Receive variable and other non-event updates.
    ///
    /// Calls to this operation 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 during this operation
    /// to receive the new values.
    ///
    /// Common update operations include reacting to variable changes to generate an intermediary value
    /// for layout or render. You can use [`WIDGET`] to request layout and render. Note that for simple variables
    /// that are used directly on layout or render you can subscribe to that operation directly, skipping update.
    ///
    /// [`Init`]: Self::Init
    /// [`Var::get_new`]: zng_var::Var::get_new
    Update {
        /// Update targets
        updates: &'a WidgetUpdates,
    },
    /// The [`UiNode::measure`].
    ///
    /// Compute the widget size given the contextual layout metrics without actually updating the widget layout.
    ///
    /// Implementers must set `desired_size` to the same size [`Layout`] sets for the given [`LayoutMetrics`], without
    /// affecting the actual widget render. Panel widgets that implement some complex layouts need to get
    /// the estimated widget size for a given layout context, this value is used to inform the actual [`Layout`] call.
    ///
    /// Nodes that implement [`Layout`] must also implement this operation, the [`LAYOUT`] context can be used to retrieve the metrics,
    /// the [`WidgetMeasure`] field can be used to communicate with the parent layout, such as disabling inline layout, the
    /// [`PxSize`] field must be set to the desired size given the layout context.
    ///
    /// [`Layout`]: Self::Layout
    /// [`LayoutMetrics`]: zng_layout::context::LayoutMetrics
    /// [`LAYOUT`]: zng_layout::context::LAYOUT
    /// [`PxSize`]: zng_layout::unit::PxSize
    Measure {
        /// Measure pass state.
        wm: &'a mut WidgetMeasure,
        /// Return value, the widget's desired size after measure.
        desired_size: &'a mut PxSize,
    },
    /// The [`UiNode::layout`].
    ///
    /// Compute the widget layout given the contextual layout metrics.
    ///
    /// Implementers must also implement [`Measure`]. This operation 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`] field
    /// can be used to communicate layout metadata such as inline segments to the parent layout, the [`PxSize`] field must be
    /// set to the final size given the layout context.
    ///
    /// 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
    Layout {
        /// Layout pass state.
        wl: &'a mut WidgetLayout,
        /// Return value, the widget's final size after layout.
        final_size: &'a mut PxSize,
    },
    /// The [`UiNode::render`].
    ///
    /// Generate render instructions and update transforms and hit-test areas.
    ///
    /// This operation 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.
    Render {
        /// Frame builder.
        frame: &'a mut FrameBuilder,
    },
    /// The [`UiNode::render_update`].
    ///
    /// Update 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
    RenderUpdate {
        /// Fame updater.
        update: &'a mut FrameUpdate,
    },
}
impl<'a> UiNodeOp<'a> {
    /// Gets the operation without the associated data.
    pub fn mtd(&self) -> UiNodeOpMethod {
        match self {
            UiNodeOp::Init => UiNodeOpMethod::Init,
            UiNodeOp::Deinit => UiNodeOpMethod::Deinit,
            UiNodeOp::Info { .. } => UiNodeOpMethod::Info,
            UiNodeOp::Event { .. } => UiNodeOpMethod::Event,
            UiNodeOp::Update { .. } => UiNodeOpMethod::Update,
            UiNodeOp::Measure { .. } => UiNodeOpMethod::Measure,
            UiNodeOp::Layout { .. } => UiNodeOpMethod::Layout,
            UiNodeOp::Render { .. } => UiNodeOpMethod::Render,
            UiNodeOp::RenderUpdate { .. } => UiNodeOpMethod::RenderUpdate,
        }
    }

    /// Reborrow the op.
    pub fn reborrow(&mut self) -> UiNodeOp {
        match self {
            UiNodeOp::Init => UiNodeOp::Init,
            UiNodeOp::Deinit => UiNodeOp::Deinit,
            UiNodeOp::Info { info } => UiNodeOp::Info { info },
            UiNodeOp::Event { update } => UiNodeOp::Event { update },
            UiNodeOp::Update { updates } => UiNodeOp::Update { updates },
            UiNodeOp::Measure { wm, desired_size } => UiNodeOp::Measure { wm, desired_size },
            UiNodeOp::Layout { wl, final_size } => UiNodeOp::Layout { wl, final_size },
            UiNodeOp::Render { frame } => UiNodeOp::Render { frame },
            UiNodeOp::RenderUpdate { update } => UiNodeOp::RenderUpdate { update },
        }
    }
}
impl<'a> fmt::Debug for UiNodeOp<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Event { update } => f.debug_struct("Event").field("update", update).finish(),
            Self::Update { updates } => f.debug_struct("Update").field("updates", updates).finish(),
            op => write!(f, "{}", op.mtd()),
        }
    }
}

/// Identifies an [`UiNodeOp`] method without the associated data.
#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum UiNodeOpMethod {
    /// The [`UiNodeOp::Init`].
    Init,
    /// The [`UiNodeOp::Deinit`].
    Deinit,
    /// The [`UiNodeOp::Info`].
    Info,
    /// The [`UiNodeOp::Event`].
    Event,
    /// The [`UiNodeOp::Update`].
    Update,
    /// The [`UiNodeOp::Measure`].
    Measure,
    /// The [`UiNodeOp::Layout`].
    Layout,
    /// The [`UiNodeOp::Render`].
    Render,
    /// The [`UiNodeOp::RenderUpdate`].
    RenderUpdate,
}
impl UiNodeOpMethod {
    /// Gets an static string representing the enum variant (CamelCase).
    pub fn enum_name(self) -> &'static str {
        match self {
            UiNodeOpMethod::Init => "Init",
            UiNodeOpMethod::Deinit => "Deinit",
            UiNodeOpMethod::Info => "Info",
            UiNodeOpMethod::Event => "Event",
            UiNodeOpMethod::Update => "Update",
            UiNodeOpMethod::Measure => "Measure",
            UiNodeOpMethod::Layout => "Layout",
            UiNodeOpMethod::Render => "Render",
            UiNodeOpMethod::RenderUpdate => "RenderUpdate",
        }
    }

    /// Gets an static string representing the method name (snake_case).
    pub fn mtd_name(self) -> &'static str {
        match self {
            UiNodeOpMethod::Init => "init",
            UiNodeOpMethod::Deinit => "deinit",
            UiNodeOpMethod::Info => "info",
            UiNodeOpMethod::Event => "event",
            UiNodeOpMethod::Update => "update",
            UiNodeOpMethod::Measure => "measure",
            UiNodeOpMethod::Layout => "layout",
            UiNodeOpMethod::Render => "render",
            UiNodeOpMethod::RenderUpdate => "render_update",
        }
    }
}
impl fmt::Debug for UiNodeOpMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}
impl fmt::Display for UiNodeOpMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write!(f, "{}", self.enum_name())
        } else {
            write!(f, "{}", self.mtd_name())
        }
    }
}

/// Creates a node that is implemented as a closure that matches over [`UiNodeOp`] and delegates to another child node.
///
/// The closure node can delegate to `child`, when the `closure` itself does not delegate, the `child` methods
/// are called after the closure returns. See [`MatchNodeChild`] for more details.
///
/// This is a convenient way of declaring anonymous nodes, such as those that implement a property function. By leveraging
/// closure captures, state can be easily declared and used, without the verbosity of declaring a struct.
///
/// # Examples
///
/// The example declares a property node that implements multiple UI node operations.
///
/// ```
/// # fn main() { }
/// # use zng_app::{*, widget::{*, node::*, builder::*}};
/// # use zng_var::*;
/// # use zng_layout::context::LAYOUT;
/// #[property(LAYOUT)]
/// pub fn count_layout(child: impl UiNode, enabled: impl IntoVar<bool>) -> impl UiNode {
///     let enabled = enabled.into_var();
///     let mut layout_count = 0;
///
///     match_node(child, move |child, op| match op {
///         UiNodeOp::Init => {
///             WIDGET.sub_var(&enabled);
///         }
///         UiNodeOp::Update { .. } => {
///             if let Some(true) = enabled.get_new() {
///                 println!("layout count reset");
///                 layout_count = 0;
///             }
///         }
///         UiNodeOp::Measure { wm, desired_size } => {
///             let s = child.measure(wm);
///             *desired_size = LAYOUT.constraints().fill_size_or(s);
///         }
///         UiNodeOp::Layout { wl, final_size } => {
///             if enabled.get() {
///                 layout_count += 1;
///                 println!("layout {layout_count}");
///             }
///             let s = child.layout(wl);
///             *final_size = LAYOUT.constraints().fill_size_or(s);
///         }
///         _ => {}
///     })
/// }
/// ```
///
/// # See Also
///
/// See also [`match_node_list`] that delegates to multiple children, [`match_node_leaf`] that declares a leaf node (no child)
/// and [`match_widget`] that can extend a widget node.
///
/// Note that the child type is changed to [`BoxedUiNode`] when build with the `feature = "dyn_node"`, if you want to access the
/// child directly using [`MatchNodeChild::child`] you can use [`match_node_typed`] instead.
///
/// [`match_node_typed`]: fn@match_node_typed
/// [`match_widget`]: fn@match_widget
#[cfg(feature = "dyn_node")]
pub fn match_node<C: UiNode>(child: C, closure: impl FnMut(&mut MatchNodeChild<BoxedUiNode>, UiNodeOp) + Send + 'static) -> impl UiNode {
    #[cfg(feature = "dyn_closure")]
    let closure: Box<dyn FnMut(&mut MatchNodeChild<BoxedUiNode>, UiNodeOp) + Send> = Box::new(closure);

    match_node_impl(child.boxed(), closure)
}

/// Creates a node that is implemented as a closure that matches over [`UiNodeOp`] and delegates to another child node.
///
/// The closure node can delegate to `child`, when the `closure` itself does not delegate, the `child` methods
/// are called after the closure returns. See [`MatchNodeChild`] for more details.
///
/// This is a convenient way of declaring anonymous nodes, such as those that implement a property function. By leveraging
/// closure captures, state can be easily declared and used, without the verbosity of declaring a struct.
///
/// # Examples
///
/// The example declares a property node that implements multiple UI node operations.
///
/// ```
/// # fn main() { }
/// # use zng_app::{*, widget::{*, node::*, builder::*}};
/// # use zng_var::*;
/// # use zng_layout::context::LAYOUT;
/// #[property(LAYOUT)]
/// pub fn count_layout(child: impl UiNode, enabled: impl IntoVar<bool>) -> impl UiNode {
///     let enabled = enabled.into_var();
///     let mut layout_count = 0;
///
///     match_node(child, move |child, op| match op {
///         UiNodeOp::Init => {
///             WIDGET.sub_var(&enabled);
///         }
///         UiNodeOp::Update { .. } => {
///             if let Some(true) = enabled.get_new() {
///                 println!("layout count reset");
///                 layout_count = 0;
///             }
///         }
///         UiNodeOp::Measure { wm, desired_size } => {
///             let s = child.measure(wm);
///             *desired_size = LAYOUT.constraints().fill_size_or(s);
///         }
///         UiNodeOp::Layout { wl, final_size } => {
///             if enabled.get() {
///                 layout_count += 1;
///                 println!("layout {layout_count}");
///             }
///             let s = child.layout(wl);
///             *final_size = LAYOUT.constraints().fill_size_or(s);
///         }
///         _ => {}
///     })
/// }
/// ```
///
/// # See Also
///
/// See also [`match_node_list`] that delegates to multiple children, [`match_node_leaf`] that declares a leaf node (no child)
/// and [`match_widget`] that can extend a widget node.
///
/// Note that the child type is changed to [`BoxedUiNode`] when build with the `feature = "dyn_node"`, if you want to access the
/// child directly using [`MatchNodeChild::child`] you can use [`match_node_typed`] instead.
///
/// [`match_node_typed`]: fn@match_node_typed
/// [`match_widget`]: fn@match_widget
#[cfg(not(feature = "dyn_node"))]
pub fn match_node<C: UiNode>(child: C, closure: impl FnMut(&mut MatchNodeChild<C>, UiNodeOp) + Send + 'static) -> impl UiNode {
    match_node_typed(child, closure)
}

/// Like [`match_node`], but does not change the child type when build with `dyn_node`.
///
/// [`match_node`]: fn@match_node
pub fn match_node_typed<C: UiNode>(child: C, closure: impl FnMut(&mut MatchNodeChild<C>, UiNodeOp) + Send + 'static) -> impl UiNode {
    #[cfg(feature = "dyn_closure")]
    let closure: Box<dyn FnMut(&mut MatchNodeChild<C>, UiNodeOp) + Send> = Box::new(closure);

    match_node_impl(child, closure)
}

fn match_node_impl<C: UiNode>(child: C, closure: impl FnMut(&mut MatchNodeChild<C>, UiNodeOp) + Send + 'static) -> impl UiNode {
    #[ui_node(struct MatchNode<C: UiNode> {
        child: MatchNodeChild<C>,
        closure: impl FnMut(&mut MatchNodeChild<C>, UiNodeOp) + Send + 'static,
    })]
    impl UiNode for MatchNode {
        fn init(&mut self) {
            self.child.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Init);

            if !mem::take(&mut self.child.delegated) {
                self.child.child.init();
            }
        }

        fn deinit(&mut self) {
            self.child.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Deinit);

            if !mem::take(&mut self.child.delegated) {
                self.child.child.deinit();
            }
        }

        fn info(&mut self, info: &mut WidgetInfoBuilder) {
            self.child.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Info { info });

            if !mem::take(&mut self.child.delegated) {
                self.child.child.info(info);
            }
        }

        fn event(&mut self, update: &EventUpdate) {
            self.child.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Event { update });

            if !mem::take(&mut self.child.delegated) {
                self.child.child.event(update);
            }
        }

        fn update(&mut self, updates: &WidgetUpdates) {
            self.child.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Update { updates });

            if !mem::take(&mut self.child.delegated) {
                self.child.child.update(updates);
            }
        }

        fn measure(&mut self, wm: &mut WidgetMeasure) -> PxSize {
            self.child.delegated = false;

            let mut size = PxSize::zero();
            (self.closure)(
                &mut self.child,
                UiNodeOp::Measure {
                    wm,
                    desired_size: &mut size,
                },
            );

            if !mem::take(&mut self.child.delegated) {
                if size != PxSize::zero() {
                    // this is an error because the child will be measured if the return size is zero,
                    // flagging delegated ensure consistent behavior.
                    tracing::error!("measure changed size without flagging delegated");
                    return size;
                }

                self.child.child.measure(wm)
            } else {
                size
            }
        }

        fn layout(&mut self, wl: &mut WidgetLayout) -> PxSize {
            self.child.delegated = false;

            let mut size = PxSize::zero();
            (self.closure)(&mut self.child, UiNodeOp::Layout { wl, final_size: &mut size });

            if !mem::take(&mut self.child.delegated) {
                if size != PxSize::zero() {
                    // this is an error because the child will be layout if the return size is zero,
                    // flagging delegated ensure consistent behavior.
                    tracing::error!("layout changed size without flagging delegated");
                    return size;
                }

                self.child.child.layout(wl)
            } else {
                size
            }
        }

        fn render(&mut self, frame: &mut FrameBuilder) {
            self.child.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Render { frame });

            if !mem::take(&mut self.child.delegated) {
                self.child.child.render(frame);
            }
        }

        fn render_update(&mut self, update: &mut FrameUpdate) {
            self.child.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::RenderUpdate { update });

            if !mem::take(&mut self.child.delegated) {
                self.child.child.render_update(update);
            }
        }
    }
    MatchNode {
        child: MatchNodeChild { child, delegated: false },
        closure,
    }
}

/// Child node of [`match_node`].
///
/// When the closure does not delegate to this node the delegation happens after the closure returns.
///
/// [`match_node`]: fn@match_node
pub struct MatchNodeChild<C> {
    child: C,
    delegated: bool,
}
impl<C: UiNode> MatchNodeChild<C> {
    /// Flags the current operation as *delegated*, stopping the default delegation after the closure ends.
    ///
    /// Note that each node operation methods already flags this.
    pub fn delegated(&mut self) {
        self.delegated = true;
    }

    /// If the current operation was already delegated to the child.
    pub fn has_delegated(&self) -> bool {
        self.delegated
    }

    /// Borrow the actual child.
    ///
    /// Note that if you delegate using this reference you must call [`delegated`].
    ///
    /// **Warning:** that [`match_node`] changes the child type to [`BoxedUiNode`] when build with the `"dyn_node"` feature.
    /// To get a consistent child type use the [`BoxedUiNode`] directly or use [`match_node_typed`].
    ///
    /// [`delegated`]: Self::delegated
    /// [`match_node`]: fn@match_node
    pub fn child(&mut self) -> &mut C {
        &mut self.child
    }
}
impl<C: UiNode> UiNode for MatchNodeChild<C> {
    fn init(&mut self) {
        self.child.init();
        self.delegated = true;
    }

    fn deinit(&mut self) {
        self.child.deinit();
        self.delegated = true;
    }

    fn info(&mut self, info: &mut WidgetInfoBuilder) {
        self.child.info(info);
        self.delegated = true;
    }

    fn event(&mut self, update: &EventUpdate) {
        self.child.event(update);
        self.delegated = true;
    }

    fn update(&mut self, updates: &WidgetUpdates) {
        self.child.update(updates);
        self.delegated = true;
    }

    fn measure(&mut self, wm: &mut WidgetMeasure) -> PxSize {
        self.delegated = true;
        self.child.measure(wm)
    }

    fn layout(&mut self, wl: &mut WidgetLayout) -> PxSize {
        self.delegated = true;
        self.child.layout(wl)
    }

    fn render(&mut self, frame: &mut FrameBuilder) {
        self.child.render(frame);
        self.delegated = true;
    }

    fn render_update(&mut self, update: &mut FrameUpdate) {
        self.child.render_update(update);
        self.delegated = true;
    }

    fn is_widget(&self) -> bool {
        self.child.is_widget()
    }

    fn with_context<R, F>(&mut self, update_mode: WidgetUpdateMode, f: F) -> Option<R>
    where
        F: FnOnce() -> R,
    {
        self.child.with_context(update_mode, f)
    }
}

/// Creates a node that is implemented as a closure that matches over [`UiNodeOp`] and does not delegate to any child node.
pub fn match_node_leaf(closure: impl FnMut(UiNodeOp) + Send + 'static) -> impl UiNode {
    #[ui_node(struct MatchNodeLeaf {
        closure: impl FnMut(UiNodeOp) + Send + 'static,
    })]
    impl UiNode for MatchNodeLeaf {
        fn init(&mut self) {
            (self.closure)(UiNodeOp::Init);
        }

        fn deinit(&mut self) {
            (self.closure)(UiNodeOp::Deinit);
        }

        fn info(&mut self, info: &mut WidgetInfoBuilder) {
            (self.closure)(UiNodeOp::Info { info });
        }

        fn event(&mut self, update: &EventUpdate) {
            (self.closure)(UiNodeOp::Event { update });
        }

        fn update(&mut self, updates: &WidgetUpdates) {
            (self.closure)(UiNodeOp::Update { updates });
        }

        fn measure(&mut self, wm: &mut WidgetMeasure) -> PxSize {
            let mut size = PxSize::zero();
            (self.closure)(UiNodeOp::Measure {
                wm,
                desired_size: &mut size,
            });
            size
        }

        fn layout(&mut self, wl: &mut WidgetLayout) -> PxSize {
            let mut size = PxSize::zero();
            (self.closure)(UiNodeOp::Layout { wl, final_size: &mut size });
            size
        }

        fn render(&mut self, frame: &mut FrameBuilder) {
            (self.closure)(UiNodeOp::Render { frame });
        }

        fn render_update(&mut self, update: &mut FrameUpdate) {
            (self.closure)(UiNodeOp::RenderUpdate { update });
        }
    }
    MatchNodeLeaf { closure }
}

/// Creates a widget that is implemented as a closure that matches over [`UiNodeOp`] and delegates to another child widget.
///
/// The returned node will delegate to `child` like [`match_node`] does, and will also delegate [`UiNode::is_widget`] and
/// [`UiNode::with_context`].
///
/// Note that the `closure` itself will not run inside [`UiNode::with_context`].
///
/// Note that unlike the [`match_node`] the `W` type is always preserved, the feature `dyn_node` is ignored here.
///
/// [`match_node`]: fn@match_node
pub fn match_widget<W: UiNode>(child: W, closure: impl FnMut(&mut MatchWidgetChild<W>, UiNodeOp) + Send + 'static) -> impl UiNode {
    #[ui_node(struct MatchWidget<C: UiNode> {
        child: MatchWidgetChild<C>,
        closure: impl FnMut(&mut MatchWidgetChild<C>, UiNodeOp) + Send + 'static,
    })]
    impl UiNode for MatchWidget {
        fn is_widget(&self) -> bool {
            self.child.0.child.is_widget()
        }

        fn with_context<R, F: FnOnce() -> R>(&mut self, update_mode: WidgetUpdateMode, f: F) -> Option<R> {
            self.child.0.child.with_context(update_mode, f)
        }

        fn init(&mut self) {
            self.child.0.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Init);

            if !mem::take(&mut self.child.0.delegated) {
                self.child.0.child.init();
            }
        }

        fn deinit(&mut self) {
            self.child.0.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Deinit);

            if !mem::take(&mut self.child.0.delegated) {
                self.child.0.child.deinit();
            }
        }

        fn info(&mut self, info: &mut WidgetInfoBuilder) {
            self.child.0.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Info { info });

            if !mem::take(&mut self.child.0.delegated) {
                self.child.0.child.info(info);
            } else {
                #[cfg(debug_assertions)]
                if self
                    .child
                    .0
                    .child
                    .with_context(WidgetUpdateMode::Ignore, || {
                        WIDGET.pending_update().contains(crate::update::UpdateFlags::INFO)
                    })
                    .unwrap_or(false)
                {
                    // this is likely an error, but a child widget could have requested info again
                    tracing::warn!(target: "match_widget-pending", "pending info build after info delegated in {:?}", WIDGET.id());
                }
            }
        }

        fn event(&mut self, update: &EventUpdate) {
            self.child.0.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Event { update });

            if !mem::take(&mut self.child.0.delegated) {
                self.child.0.child.event(update);
            }
        }

        fn update(&mut self, updates: &WidgetUpdates) {
            self.child.0.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Update { updates });

            if !mem::take(&mut self.child.0.delegated) {
                self.child.0.child.update(updates);
            }
        }

        fn measure(&mut self, wm: &mut WidgetMeasure) -> PxSize {
            self.child.0.delegated = false;

            let mut size = PxSize::zero();
            (self.closure)(
                &mut self.child,
                UiNodeOp::Measure {
                    wm,
                    desired_size: &mut size,
                },
            );

            if !mem::take(&mut self.child.0.delegated) {
                if size != PxSize::zero() {
                    // this is an error because the child will be measured if the return size is zero,
                    // flagging delegated ensure consistent behavior.
                    tracing::error!("measure changed size without flagging delegated in {:?}", WIDGET.id());
                    return size;
                }

                self.child.0.child.measure(wm)
            } else {
                size
            }
        }

        fn layout(&mut self, wl: &mut WidgetLayout) -> PxSize {
            self.child.0.delegated = false;

            let mut size = PxSize::zero();
            (self.closure)(&mut self.child, UiNodeOp::Layout { wl, final_size: &mut size });

            if !mem::take(&mut self.child.0.delegated) {
                if size != PxSize::zero() {
                    // this is an error because the child will be layout if the return size is zero,
                    // flagging delegated ensure consistent behavior.
                    tracing::error!("layout changed size without flagging delegated in {:?}", WIDGET.id());
                    return size;
                }

                self.child.0.child.layout(wl)
            } else {
                #[cfg(debug_assertions)]
                if self
                    .child
                    .0
                    .child
                    .with_context(WidgetUpdateMode::Ignore, || {
                        WIDGET.pending_update().contains(crate::update::UpdateFlags::LAYOUT)
                    })
                    .unwrap_or(false)
                {
                    // this is likely an error, but a child widget could have requested layout again,
                    tracing::warn!(target: "match_widget-pending", "pending layout after layout delegated in {:?}", WIDGET.id());
                }
                size
            }
        }

        fn render(&mut self, frame: &mut FrameBuilder) {
            self.child.0.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::Render { frame });

            if !mem::take(&mut self.child.0.delegated) {
                self.child.0.child.render(frame);
            } else {
                #[cfg(debug_assertions)]
                if self
                    .child
                    .0
                    .child
                    .with_context(WidgetUpdateMode::Ignore, || {
                        WIDGET.pending_update().contains(crate::update::UpdateFlags::RENDER)
                    })
                    .unwrap_or(false)
                {
                    // this is likely an error, but a child widget could have requested render again,
                    tracing::warn!(target: "match_widget-pending", "pending render after render delegated in {:?}", WIDGET.id());
                }
            }
        }

        fn render_update(&mut self, update: &mut FrameUpdate) {
            self.child.0.delegated = false;

            (self.closure)(&mut self.child, UiNodeOp::RenderUpdate { update });

            if !mem::take(&mut self.child.0.delegated) {
                self.child.0.child.render_update(update);
            } else {
                #[cfg(debug_assertions)]
                if self
                    .child
                    .0
                    .child
                    .with_context(WidgetUpdateMode::Ignore, || {
                        WIDGET.pending_update().contains(crate::update::UpdateFlags::RENDER_UPDATE)
                    })
                    .unwrap_or(false)
                {
                    // this is likely an error, but a child widget could have requested render_update again,
                    tracing::warn!(target: "match_widget-pending", "pending render_update after render_update delegated in {:?}", WIDGET.id());
                }
            }
        }
    }
    MatchWidget {
        child: MatchWidgetChild(MatchNodeChild { child, delegated: false }),
        closure,
    }
}

/// Child node of [`match_widget`].
///
/// This node delegates like [`MatchNodeChild<C>`] plus delegates [`UiNode::is_widget`] and [`UiNode::with_context`].
///
/// [`match_widget`]: fn@match_widget
pub struct MatchWidgetChild<C>(MatchNodeChild<C>);
impl<C> MatchWidgetChild<C> {
    /// Flags the current operation as *delegated*, stopping the default delegation after the closure ends.
    ///
    /// Note that each node operation methods already flags this.
    pub fn delegated(&mut self) {
        self.0.delegated = true;
    }

    /// If the current operation was already delegated to the child.
    pub fn has_delegated(&self) -> bool {
        self.0.delegated
    }

    /// Borrow the actual child.
    ///
    /// Note that if you delegate using this reference you must call [`delegated`].
    ///
    /// [`delegated`]: Self::delegated
    /// [`match_node`]: fn@match_node
    pub fn child(&mut self) -> &mut C {
        &mut self.0.child
    }

    /// Adapter to `match_node` child type.
    ///
    /// Note that the returned node does not delegate widget methods.
    pub fn as_match_node(&mut self) -> &mut MatchNodeChild<C> {
        &mut self.0
    }
}
#[ui_node(delegate = &mut self.0)]
impl<C: UiNode> UiNode for MatchWidgetChild<C> {
    fn is_widget(&self) -> bool {
        self.0.child.is_widget()
    }

    fn with_context<R, F: FnOnce() -> R>(&mut self, update_mode: WidgetUpdateMode, f: F) -> Option<R> {
        self.0.child.with_context(update_mode, f)
    }
}

/// Creates a node that is implemented as a closure that matches over [`UiNodeOp`] and delegates to multiple children nodes in a list.
///
/// The closure node can delegate to `children`, when the `closure` itself does not delegate, the `children` methods
/// are called after the closure returns. See [`MatchNodeChildren`] for more details.
pub fn match_node_list<L: UiNodeList>(
    children: L,
    closure: impl FnMut(&mut MatchNodeChildren<L>, UiNodeOp) + Send + 'static,
) -> impl UiNode {
    #[ui_node(struct MatchNodeList<C: UiNodeList> {
        children: MatchNodeChildren<C>,
        closure: impl FnMut(&mut MatchNodeChildren<C>, UiNodeOp) + Send + 'static,
    })]
    #[allow_(zng::missing_delegate)] // false positive
    impl UiNode for MatchNodeList {
        fn init(&mut self) {
            self.children.delegated = false;

            (self.closure)(&mut self.children, UiNodeOp::Init);

            if !mem::take(&mut self.children.delegated) {
                ui_node_list_default::init_all(&mut self.children.children);
            }
        }

        fn deinit(&mut self) {
            self.children.delegated = false;

            (self.closure)(&mut self.children, UiNodeOp::Deinit);

            if !mem::take(&mut self.children.delegated) {
                ui_node_list_default::deinit_all(&mut self.children.children);
            }
        }

        fn info(&mut self, info: &mut WidgetInfoBuilder) {
            self.children.delegated = false;

            (self.closure)(&mut self.children, UiNodeOp::Info { info });

            if !mem::take(&mut self.children.delegated) {
                ui_node_list_default::info_all(&mut self.children.children, info)
            }
        }

        fn event(&mut self, update: &EventUpdate) {
            self.children.delegated = false;

            (self.closure)(&mut self.children, UiNodeOp::Event { update });

            if !mem::take(&mut self.children.delegated) {
                ui_node_list_default::event_all(&mut self.children.children, update);
            }
        }

        fn update(&mut self, updates: &WidgetUpdates) {
            self.children.delegated = false;

            (self.closure)(&mut self.children, UiNodeOp::Update { updates });

            if !mem::take(&mut self.children.delegated) {
                ui_node_list_default::update_all(&mut self.children.children, updates);
            }
        }

        fn measure(&mut self, wm: &mut WidgetMeasure) -> PxSize {
            self.children.delegated = false;

            let mut size = PxSize::zero();
            (self.closure)(
                &mut self.children,
                UiNodeOp::Measure {
                    wm,
                    desired_size: &mut size,
                },
            );

            if !mem::take(&mut self.children.delegated) {
                if size != PxSize::zero() {
                    // this is an error because the children will be measured if the return size is zero,
                    // flagging delegated ensure consistent behavior.
                    tracing::error!("measure(list) changed size without flagging delegated");
                    return size;
                }

                ui_node_list_default::measure_all(&mut self.children.children, wm)
            } else {
                size
            }
        }

        fn layout(&mut self, wl: &mut WidgetLayout) -> PxSize {
            self.children.delegated = false;

            let mut size = PxSize::zero();
            (self.closure)(&mut self.children, UiNodeOp::Layout { wl, final_size: &mut size });

            if !mem::take(&mut self.children.delegated) {
                if size != PxSize::zero() {
                    // this is an error because the children will be layout if the return size is zero,
                    // flagging delegated ensure consistent behavior.
                    tracing::error!("layout(list) changed size without flagging delegated");
                    return size;
                }
                ui_node_list_default::layout_all(&mut self.children.children, wl)
            } else {
                size
            }
        }

        fn render(&mut self, frame: &mut FrameBuilder) {
            self.children.delegated = false;

            (self.closure)(&mut self.children, UiNodeOp::Render { frame });

            if !mem::take(&mut self.children.delegated) {
                ui_node_list_default::render_all(&mut self.children.children, frame);
            }
        }

        fn render_update(&mut self, update: &mut FrameUpdate) {
            self.children.delegated = false;

            (self.closure)(&mut self.children, UiNodeOp::RenderUpdate { update });

            if !mem::take(&mut self.children.delegated) {
                ui_node_list_default::render_update_all(&mut self.children.children, update);
            }
        }
    }
    MatchNodeList {
        children: MatchNodeChildren {
            children,
            delegated: false,
        },
        closure,
    }
}

/// Children node of [`match_node_list`].
///
/// When the closure does not delegate to this list the delegation happens after the closure returns. The
/// [`UiNodeList`] methods that flag as [`delegated`] are all the `*_all` methods and the methods that access mutable
/// references to each child and the [`UiNodeList::with_node`]. You can use the [`children`] accessor to visit
/// children without flagging as delegated.
///
/// [`match_node`]: fn@match_node
/// [`delegated`]: Self::delegated
/// [`children`]: Self::children
pub struct MatchNodeChildren<L> {
    children: L,
    delegated: bool,
}
impl<L: UiNodeList> MatchNodeChildren<L> {
    /// Flags the current operation as *delegated*, stopping the default delegation after the closure ends.
    ///
    /// Note that each `*_all` method and the methods that give mutable access to children already flags this.
    pub fn delegated(&mut self) {
        self.delegated = true;
    }

    /// If the current operation was already delegated to the children.
    pub fn has_delegated(&self) -> bool {
        self.delegated
    }

    /// Reference the children.
    ///
    /// Note that if you delegate using this reference you must call [`delegated`].
    ///
    /// [`delegated`]: Self::delegated
    pub fn children(&mut self) -> &mut L {
        &mut self.children
    }
}
impl<L: UiNodeList> UiNodeList for MatchNodeChildren<L> {
    fn with_node<R, F>(&mut self, index: usize, f: F) -> R
    where
        F: FnOnce(&mut BoxedUiNode) -> R,
    {
        self.delegated = true;
        self.children.with_node(index, f)
    }

    fn for_each<F>(&mut self, f: F)
    where
        F: FnMut(usize, &mut BoxedUiNode),
    {
        self.delegated = true;
        self.children.for_each(f)
    }

    fn par_each<F>(&mut self, f: F)
    where
        F: Fn(usize, &mut BoxedUiNode) + Send + Sync,
    {
        self.delegated = true;
        self.children.par_each(f)
    }

    fn par_fold_reduce<T, I, F, R>(&mut self, identity: I, fold: F, reduce: R) -> T
    where
        T: Send + 'static,
        I: Fn() -> T + Send + Sync,
        F: Fn(T, usize, &mut BoxedUiNode) -> T + Send + Sync,
        R: Fn(T, T) -> T + Send + Sync,
    {
        self.delegated = true;
        self.children.par_fold_reduce(identity, fold, reduce)
    }

    fn len(&self) -> usize {
        self.children.len()
    }

    fn boxed(self) -> BoxedUiNodeList {
        Box::new(self)
    }

    fn drain_into(&mut self, vec: &mut Vec<BoxedUiNode>) {
        self.children.drain_into(vec)
    }

    fn init_all(&mut self) {
        self.children.init_all();
        self.delegated = true;
    }

    fn deinit_all(&mut self) {
        self.children.deinit_all();
        self.delegated = true;
    }

    fn update_all(&mut self, updates: &WidgetUpdates, observer: &mut dyn UiNodeListObserver) {
        self.children.update_all(updates, observer);
        self.delegated = true;
    }

    fn info_all(&mut self, info: &mut WidgetInfoBuilder) {
        self.children.info_all(info);
        self.delegated = true;
    }

    fn event_all(&mut self, update: &EventUpdate) {
        self.children.event_all(update);
        self.delegated = true;
    }

    fn measure_each<F, S>(&mut self, wm: &mut WidgetMeasure, measure: F, fold_size: S) -> PxSize
    where
        F: Fn(usize, &mut BoxedUiNode, &mut WidgetMeasure) -> PxSize + Send + Sync,
        S: Fn(PxSize, PxSize) -> PxSize + Send + Sync,
    {
        self.delegated = true;
        self.children.measure_each(wm, measure, fold_size)
    }

    fn layout_each<F, S>(&mut self, wl: &mut WidgetLayout, layout: F, fold_size: S) -> PxSize
    where
        F: Fn(usize, &mut BoxedUiNode, &mut WidgetLayout) -> PxSize + Send + Sync,
        S: Fn(PxSize, PxSize) -> PxSize + Send + Sync,
    {
        self.delegated = true;
        self.children.layout_each(wl, layout, fold_size)
    }

    fn render_all(&mut self, frame: &mut FrameBuilder) {
        self.children.render_all(frame);
        self.delegated = true;
    }

    fn render_update_all(&mut self, update: &mut FrameUpdate) {
        self.children.render_update_all(update);
        self.delegated = true;
    }
}