-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathElement.cs
More file actions
4065 lines (3668 loc) · 201 KB
/
Element.cs
File metadata and controls
4065 lines (3668 loc) · 201 KB
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
using System.Diagnostics.CodeAnalysis;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Text;
using Windows.UI.Text;
using WinUI = Microsoft.UI.Xaml.Controls;
using WinPrim = Microsoft.UI.Xaml.Controls.Primitives;
using WinShapes = Microsoft.UI.Xaml.Shapes;
namespace Microsoft.UI.Reactor.Core;
// ════════════════════════════════════════════════════════════════════════
// Base types
// ════════════════════════════════════════════════════════════════════════
/// <summary>
/// A lightweight, immutable description of a UI node (the "virtual DOM").
/// Elements are cheap to create and diff — they never touch real controls directly.
/// </summary>
// <snippet:element-record>
public abstract record Element
{
/// <summary>
/// Optional key for stable identity across re-renders (like React's key prop).
/// When set, the reconciler uses it to match elements across list reorderings.
/// </summary>
public string? Key { get; init; }
/// <summary>
/// Layout modifiers (margin, padding, size, alignment, etc.) applied to this element.
/// Set via fluent extension methods: Text("hi").Margin(10).Width(200)
/// Modifiers are stored inline so the concrete element type is preserved through chaining.
/// </summary>
public ElementModifiers? Modifiers { get; init; }
// </snippet:element-record>
/// <summary>
/// Outer margin shim that routes to <see cref="Modifiers"/>. Lets
/// <c>el with { Margin = new Thickness(8) }</c> work directly on a record
/// initializer (where extension methods are not visible). Identical
/// semantics to <c>.Margin(...)</c>.
/// </summary>
public Thickness? Margin
{
get => Modifiers?.Margin;
init => Modifiers = Modifiers is null
? new ElementModifiers { Margin = value }
: Modifiers with { Margin = value };
}
/// <summary>
/// Inner padding shim that routes to <see cref="Modifiers"/>. Lets
/// <c>el with { Padding = new Thickness(8) }</c> work directly on a record
/// initializer (where extension methods are not visible). Identical
/// semantics to <c>.Padding(...)</c>.
/// </summary>
public Thickness? Padding
{
get => Modifiers?.Padding;
init => Modifiers = Modifiers is null
? new ElementModifiers { Padding = value }
: Modifiers with { Padding = value };
}
/// <summary>
/// Attached properties from parent containers (Grid.Row, Canvas.Left, etc.).
/// Set via fluent extension methods: Text("hi").Grid(row: 1, column: 2)
/// Stored as a type-keyed dictionary so each provider defines its own data record.
/// </summary>
public IReadOnlyDictionary<Type, object>? Attached { get; init; }
/// <summary>
/// Implicit transitions (opacity, scale, rotation, translation, background).
/// Set via fluent extension methods: Rectangle().WithOpacityTransition()
/// Applied by the reconciler after mount/update, so they are always present when
/// property values are set via .Set() callbacks.
/// </summary>
public ImplicitTransitions? ImplicitTransitions { get; init; }
/// <summary>
/// Theme transitions (children, item container).
/// Set via fluent extension methods: VStack(children).WithThemeTransitions(...)
/// </summary>
public ThemeTransitions? ThemeTransitions { get; init; }
/// <summary>
/// Theme-resource bindings for brush properties (Background, Foreground, BorderBrush).
/// When set, the reconciler resolves from WinUI theme resources instead of using local values.
/// Set via fluent extension methods: Text("hi").Background(Theme.Accent)
/// </summary>
public IReadOnlyDictionary<string, ThemeRef>? ThemeBindings { get; init; }
/// <summary>
/// Composition-layer layout animation configuration.
/// When set, the reconciler attaches implicit animations to the element's Visual
/// so that layout-driven position (and optionally size) changes animate smoothly.
/// Set via fluent extension methods: Border(child).LayoutAnimation()
/// </summary>
public LayoutAnimationConfig? LayoutAnimation { get; init; }
/// <summary>
/// Compositor property animation configuration (.Animate() modifier).
/// When set, the reconciler creates ImplicitAnimationCollection entries on the
/// element's Visual for Opacity/Scale/Rotation/Offset/CenterPoint.
/// </summary>
public Microsoft.UI.Reactor.Animation.AnimationConfig? AnimationConfig { get; init; }
/// <summary>
/// Element enter/exit transition configuration (.Transition() modifier).
/// When set, the reconciler animates mount (enter) and unmount (exit) with
/// compositor animations, deferring removal until exit animation completes.
/// </summary>
public Microsoft.UI.Reactor.Animation.ElementTransition? ElementTransition { get; init; }
/// <summary>
/// Interaction states configuration (.InteractionStates() modifier).
/// When set, the reconciler registers pointer event handlers that drive
/// zero-reconcile visual state transitions (hover, pressed, focused).
/// </summary>
public Microsoft.UI.Reactor.Animation.InteractionStatesConfig? InteractionStates { get; init; }
/// <summary>
/// Stagger configuration for container children (.Stagger() modifier).
/// When set, child animations (enter, layout, property) have incrementing
/// DelayTime = childIndex * staggerDelay.
/// </summary>
public Microsoft.UI.Reactor.Animation.StaggerConfig? StaggerConfig { get; init; }
/// <summary>
/// Keyframe animation definitions (.Keyframes() modifier).
/// Trigger-based: plays when the trigger value changes between renders.
/// </summary>
public Microsoft.UI.Reactor.Animation.KeyframeEntry[]? KeyframeAnimations { get; init; }
/// <summary>
/// Scroll-linked expression animation configuration (.ScrollLinked() modifier).
/// Expression animations run on the compositor, driven by ScrollViewer position.
/// </summary>
public Microsoft.UI.Reactor.Animation.ScrollAnimationConfig? ScrollAnimation { get; init; }
/// <summary>
/// Connected animation key for cross-container transitions.
/// When set, the reconciler automatically captures a visual snapshot on unmount
/// (via ConnectedAnimationService.PrepareToAnimate) and starts the animation on
/// mount if a prepared animation with the same key exists.
/// Set via fluent extension method: Border(child).ConnectedAnimation("hero")
/// </summary>
public string? ConnectedAnimationKey { get; init; }
/// <summary>
/// Per-control resource overrides (lightweight styling). When set, the reconciler
/// injects these into <see cref="FrameworkElement.Resources"/> so that the control's
/// VisualStateManager picks them up for hover/pressed/disabled states.
/// Set via fluent extension: <c>Button("Go").Resources(r => r.Set("ButtonBackground", "#0078D4"))</c>
/// </summary>
public Microsoft.UI.Reactor.Elements.ResourceOverrides? ResourceOverrides { get; init; }
/// <summary>
/// Context values provided to this element's subtree via .Provide().
/// The reconciler pushes these onto the context scope when entering
/// this element's subtree and pops them when leaving.
/// </summary>
public IReadOnlyDictionary<ContextBase, object?>? ContextValues { get; init; }
/// <summary>
/// Gets the attached property data of the specified type, or null if not set.
/// </summary>
internal T? GetAttached<T>() where T : class =>
Attached is not null && Attached.TryGetValue(typeof(T), out var val) ? (T)val : null;
/// <summary>
/// Returns a copy of this element with the given attached property data set.
/// Used by Grid/Canvas/RelativePanel extension methods.
/// </summary>
internal Element SetAttached(object data)
{
var dict = Attached is not null
? new Dictionary<Type, object>(Attached)
: new Dictionary<Type, object>();
dict[data.GetType()] = data;
return this with { Attached = dict };
}
/// <summary>
/// Convenience: implicitly convert a string to a TextBlockElement.
/// Allows writing: VStack("Hello", "World") instead of VStack(Text("Hello"), Text("World"))
/// </summary>
public static implicit operator Element(string text) => new TextBlockElement(text);
// ════════════════════════════════════════════════════════════════════════
// Fast structural comparison for reconciler short-circuit
// ════════════════════════════════════════════════════════════════════════
/// <summary>
/// True if this element exposes any non-null event-handler delegate (OnClick,
/// OnChanged, etc.). Two roles:
///
/// 1. When the reconciler takes a skip fast-path, it must still refresh the
/// control's Tag so the event trampoline dispatches into the current
/// render's closure rather than a stale one. Handler-free elements don't
/// need the Tag refresh — their controls never fire into Reactor code.
///
/// 2. Callback *presence* is part of the skip invariant: when
/// <c>oldEl.HasCallbacks != newEl.HasCallbacks</c>, skipping is unsafe
/// because <see cref="ShallowEquals"/> intentionally ignores delegate
/// identity — a null→non-null transition wouldn't trigger the lazy-wire
/// path in UpdateXxx, so the WinRT event would never be subscribed.
/// The skip fast-paths therefore guard on this equality.
///
/// Override on each callback-bearing leaf.
/// </summary>
internal virtual bool HasCallbacks => false;
/// <summary>
/// Returns true if two elements are structurally identical AND the child can be
/// completely skipped during reconciliation (no need to call Update at all).
/// This is stricter than ShallowEquals: elements with ThemeBindings must still
/// go through Update so bindings can be re-evaluated against the current theme,
/// and a change in callback *presence* must run Update so the lazy-wire path
/// can subscribe to the WinRT event on a null→non-null transition.
/// IMPORTANT: keep in sync with the ShallowEquals fast-path in Reconciler.Update().
/// </summary>
internal static bool CanSkipUpdate(Element oldEl, Element newEl)
=> ShallowEquals(oldEl, newEl)
&& newEl.ThemeBindings is null
&& oldEl.HasCallbacks == newEl.HasCallbacks;
/// <summary>
/// Fast structural comparison that avoids the pitfalls of record Equals
/// (Dictionary reference equality, Action[] reference equality, delegate equality).
/// Returns true only when the two elements are provably identical for rendering purposes.
/// Conservative: returns false for unknown element types.
/// </summary>
internal static bool ShallowEquals(Element a, Element b)
{
if (ReferenceEquals(a, b)) return true;
if (a.GetType() != b.GetType()) return false;
if (!ModifiersEqual(a.Modifiers, b.Modifiers)) return false;
if (!AttachedEqual(a.Attached, b.Attached)) return false;
if (!ThemeBindingsEqual(a.ThemeBindings, b.ThemeBindings)) return false;
if (!ContextValuesEqual(a.ContextValues, b.ContextValues)) return false;
return (a, b) switch
{
(TextBlockElement ta, TextBlockElement tb) =>
ta.Content == tb.Content
&& ta.FontSize == tb.FontSize
&& ta.Weight == tb.Weight
&& ta.FontStyle == tb.FontStyle
&& ta.HorizontalAlignment == tb.HorizontalAlignment
&& ReferenceEquals(ta.Setters, tb.Setters),
// Callbacks (OnClick, OnChanged, etc.) are intentionally not compared:
// dispatch goes through the Tag trampoline, and the Update.cs skip path
// refreshes Tag when HasCallbacks is true. So identity of the delegate
// on the element is irrelevant to dispatch correctness — only presence
// mattered historically (and presence is still captured by HasCallbacks).
(ButtonElement ba, ButtonElement bb) =>
ba.Label == bb.Label
&& ba.IsEnabled == bb.IsEnabled
&& ba.ContentElement is null && bb.ContentElement is null
&& ReferenceEquals(ba.Setters, bb.Setters),
(HyperlinkButtonElement ha, HyperlinkButtonElement hb) =>
ha.Content == hb.Content
&& ha.NavigateUri == hb.NavigateUri
&& ReferenceEquals(ha.Setters, hb.Setters),
(RepeatButtonElement ra, RepeatButtonElement rb) =>
ra.Label == rb.Label
&& ra.Delay == rb.Delay
&& ra.Interval == rb.Interval
&& ReferenceEquals(ra.Setters, rb.Setters),
(ToggleButtonElement ta, ToggleButtonElement tb) =>
ta.Label == tb.Label
&& ta.IsChecked == tb.IsChecked
&& ReferenceEquals(ta.Setters, tb.Setters),
(SliderElement sa, SliderElement sb) =>
sa.Value == sb.Value
&& sa.Min == sb.Min
&& sa.Max == sb.Max
&& sa.StepFrequency == sb.StepFrequency
&& sa.Header == sb.Header
&& ReferenceEquals(sa.Setters, sb.Setters),
(ToggleSwitchElement ta, ToggleSwitchElement tb) =>
ta.IsOn == tb.IsOn
&& ta.OnContent == tb.OnContent
&& ta.OffContent == tb.OffContent
&& ta.Header == tb.Header
&& ReferenceEquals(ta.Setters, tb.Setters),
(CheckBoxElement ca, CheckBoxElement cb) =>
ca.IsChecked == cb.IsChecked
&& ca.Label == cb.Label
&& ca.IsThreeState == cb.IsThreeState
&& ca.CheckedState == cb.CheckedState
&& ReferenceEquals(ca.Setters, cb.Setters),
(RadioButtonElement ra, RadioButtonElement rb) =>
ra.Label == rb.Label
&& ra.IsChecked == rb.IsChecked
&& ra.GroupName == rb.GroupName
&& ReferenceEquals(ra.Setters, rb.Setters),
(ComboBoxElement ca, ComboBoxElement cb) =>
ReferenceEquals(ca.Items, cb.Items)
&& ca.SelectedIndex == cb.SelectedIndex
&& ca.PlaceholderText == cb.PlaceholderText
&& ca.Header == cb.Header
&& ca.IsEditable == cb.IsEditable
&& ReferenceEquals(ca.ItemElements, cb.ItemElements)
&& ReferenceEquals(ca.Setters, cb.Setters),
(TextBoxElement ta, TextBoxElement tb) =>
ta.Value == tb.Value
&& ta.PlaceholderText == tb.PlaceholderText
&& ta.Header == tb.Header
&& ta.IsReadOnly == tb.IsReadOnly
&& ta.AcceptsReturn == tb.AcceptsReturn
&& ta.TextWrapping == tb.TextWrapping
&& ta.SelectionStart == tb.SelectionStart
&& ta.SelectionLength == tb.SelectionLength
&& ReferenceEquals(ta.Setters, tb.Setters),
(NumberBoxElement na, NumberBoxElement nb) =>
na.Value == nb.Value
&& na.Minimum == nb.Minimum
&& na.Maximum == nb.Maximum
&& na.SmallChange == nb.SmallChange
&& na.LargeChange == nb.LargeChange
&& na.Header == nb.Header
&& na.PlaceholderText == nb.PlaceholderText
&& na.SpinButtonPlacement == nb.SpinButtonPlacement
&& ReferenceEquals(na.Setters, nb.Setters),
(PasswordBoxElement pa, PasswordBoxElement pb) =>
pa.Password == pb.Password
&& pa.PlaceholderText == pb.PlaceholderText
&& ReferenceEquals(pa.Setters, pb.Setters),
(ProgressElement pa, ProgressElement pb) =>
pa.Value == pb.Value
&& pa.Minimum == pb.Minimum
&& pa.Maximum == pb.Maximum
&& pa.ShowError == pb.ShowError
&& pa.ShowPaused == pb.ShowPaused
&& ReferenceEquals(pa.Setters, pb.Setters),
(ProgressRingElement pa, ProgressRingElement pb) =>
pa.Value == pb.Value
&& pa.Minimum == pb.Minimum
&& pa.Maximum == pb.Maximum
&& pa.IsActive == pb.IsActive
&& ReferenceEquals(pa.Setters, pb.Setters),
(ImageElement ia, ImageElement ib) =>
ia.Source == ib.Source
&& ReferenceEquals(ia.Setters, ib.Setters),
(RectangleElement ra, RectangleElement rb) =>
ReferenceEquals(ra.Setters, rb.Setters),
(EllipseElement ea, EllipseElement eb) =>
ReferenceEquals(ea.Setters, eb.Setters),
// Chart primitives — emitted in bulk by D3Charts. Without these arms,
// every Path/Line in a chart falls through to UpdatePath/UpdateLine on
// every parent render even when chart data is unchanged, so D3Charts.Brush
// re-allocations cause every WinUI Path/Line property to be reassigned.
(PathElement pa, PathElement pb) =>
string.Equals(pa.PathDataString, pb.PathDataString, StringComparison.Ordinal)
&& (pa.PathDataString is not null || ReferenceEquals(pa.Data, pb.Data))
&& BrushesEqual(pa.Fill, pb.Fill)
&& BrushesEqual(pa.Stroke, pb.Stroke)
&& pa.StrokeThickness == pb.StrokeThickness
&& ReferenceEquals(pa.StrokeDashArray, pb.StrokeDashArray)
&& TransformsEqual(pa.RenderTransform, pb.RenderTransform)
&& pa.Setters.Length == 0 && pb.Setters.Length == 0,
(LineElement la, LineElement lb) =>
la.X1 == lb.X1 && la.Y1 == lb.Y1 && la.X2 == lb.X2 && la.Y2 == lb.Y2
&& BrushesEqual(la.Stroke, lb.Stroke)
&& la.StrokeThickness == lb.StrokeThickness
&& la.Setters.Length == 0 && lb.Setters.Length == 0,
(RichTextBlockElement ra, RichTextBlockElement rb) =>
ra.Text == rb.Text
&& ra.FontSize == rb.FontSize
&& ra.IsTextSelectionEnabled == rb.IsTextSelectionEnabled
&& ra.TextWrapping == rb.TextWrapping
&& ParagraphsEqual(ra.Paragraphs, rb.Paragraphs)
&& ReferenceEquals(ra.Setters, rb.Setters),
// Container elements: compare own props + children by reference.
// Same children reference = truly unchanged subtree = safe to skip entirely.
// Different children reference = fall through to UpdateXxx which recurses.
(StackElement sa, StackElement sb) =>
sa.Orientation == sb.Orientation
&& sa.Spacing == sb.Spacing
&& sa.HorizontalAlignment == sb.HorizontalAlignment
&& sa.VerticalAlignment == sb.VerticalAlignment
&& ReferenceEquals(sa.Children, sb.Children)
&& ReferenceEquals(sa.Setters, sb.Setters),
(BorderElement ba, BorderElement bb) =>
BrushesEqual(ba.Background, bb.Background)
&& BrushesEqual(ba.BorderBrush, bb.BorderBrush)
&& ba.CornerRadius == bb.CornerRadius
&& ba.BorderThickness == bb.BorderThickness
&& ReferenceEquals(ba.Child, bb.Child)
&& ReferenceEquals(ba.Setters, bb.Setters),
// ItemContainer is the ItemsView item-root wrapper. Selection
// state is framework-driven (so the Reactor element's
// IsSelected stays at its declared default across re-renders
// unless the user explicitly drives it), making this skip
// path the common case during selection-triggered reconciles.
(ItemContainerElement ica, ItemContainerElement icb) =>
ica.IsSelected == icb.IsSelected
&& ReferenceEquals(ica.Child, icb.Child)
&& ReferenceEquals(ica.Setters, icb.Setters),
(GridElement ga, GridElement gb) =>
ga.RowSpacing == gb.RowSpacing
&& ga.ColumnSpacing == gb.ColumnSpacing
&& ReferenceEquals(ga.Definition, gb.Definition)
&& ReferenceEquals(ga.Children, gb.Children)
&& ReferenceEquals(ga.Setters, gb.Setters),
(ScrollViewerElement sva, ScrollViewerElement svb) =>
sva.Orientation == svb.Orientation
&& sva.HorizontalScrollBarVisibility == svb.HorizontalScrollBarVisibility
&& sva.VerticalScrollBarVisibility == svb.VerticalScrollBarVisibility
&& sva.HorizontalScrollMode == svb.HorizontalScrollMode
&& sva.VerticalScrollMode == svb.VerticalScrollMode
&& sva.ZoomMode == svb.ZoomMode
&& ReferenceEquals(sva.Child, svb.Child)
&& ReferenceEquals(sva.Setters, svb.Setters),
(ScrollViewElement sva, ScrollViewElement svb) =>
sva.ContentOrientation == svb.ContentOrientation
&& sva.HorizontalScrollBarVisibility == svb.HorizontalScrollBarVisibility
&& sva.VerticalScrollBarVisibility == svb.VerticalScrollBarVisibility
&& sva.HorizontalScrollMode == svb.HorizontalScrollMode
&& sva.VerticalScrollMode == svb.VerticalScrollMode
&& sva.ZoomMode == svb.ZoomMode
&& sva.MinZoomFactor == svb.MinZoomFactor
&& sva.MaxZoomFactor == svb.MaxZoomFactor
&& sva.HorizontalAnchorRatio == svb.HorizontalAnchorRatio
&& sva.VerticalAnchorRatio == svb.VerticalAnchorRatio
&& ReferenceEquals(sva.Child, svb.Child)
&& ReferenceEquals(sva.Setters, svb.Setters),
(FlexElement fa, FlexElement fb) =>
fa.Direction == fb.Direction
&& fa.JustifyContent == fb.JustifyContent
&& fa.AlignItems == fb.AlignItems
&& fa.AlignContent == fb.AlignContent
&& fa.Wrap == fb.Wrap
&& fa.ColumnGap == fb.ColumnGap
&& fa.RowGap == fb.RowGap
&& fa.FlexPadding == fb.FlexPadding
&& ReferenceEquals(fa.Children, fb.Children)
&& ReferenceEquals(fa.Setters, fb.Setters),
(CanvasElement ca, CanvasElement cb) =>
ca.Width == cb.Width
&& ca.Height == cb.Height
&& BrushesEqual(ca.Background, cb.Background)
&& ReferenceEquals(ca.Children, cb.Children)
&& ReferenceEquals(ca.ChartData, cb.ChartData)
&& ReferenceEquals(ca.CustomPalette, cb.CustomPalette)
&& ca.IsColorOnly == cb.IsColorOnly
&& ca.IsRawColors == cb.IsRawColors
&& ca.IsInteractive == cb.IsInteractive
&& ca.IsKeyboardDisabled == cb.IsKeyboardDisabled
&& ca.IsTightHitTest == cb.IsTightHitTest
&& ca.IsAnnounceEveryFrame == cb.IsAnnounceEveryFrame
&& ca.CustomFocusColor == cb.CustomFocusColor
&& ca.Setters.Length == 0 && cb.Setters.Length == 0,
(EmptyElement, EmptyElement) => true,
// ErrorBoundary contains delegates — always update
(ErrorBoundaryElement, ErrorBoundaryElement) => false,
// Conservative: unknown element types always update
_ => false,
};
}
/// <summary>
/// Like ShallowEquals but for container types, ignores child/children references.
/// Returns true when the element's own WinUI-mapped properties are unchanged,
/// meaning the only reason Update was entered is to recurse into children.
/// Used by the highlight overlay to avoid marking containers yellow when only
/// their children changed (the children themselves will be individually captured).
/// Conservative: returns false for unknown/non-container types (assume props changed).
/// </summary>
internal static bool OwnPropsEqual(Element a, Element b)
{
if (ReferenceEquals(a, b)) return true;
if (a.GetType() != b.GetType()) return false;
return (a, b) switch
{
// Container types: same checks as ShallowEquals minus Children/Child refs
(StackElement sa, StackElement sb) =>
sa.Orientation == sb.Orientation
&& sa.Spacing == sb.Spacing
&& sa.HorizontalAlignment == sb.HorizontalAlignment
&& sa.VerticalAlignment == sb.VerticalAlignment
&& ReferenceEquals(sa.Setters, sb.Setters),
(Core.GridElement ga, Core.GridElement gb) =>
ga.RowSpacing == gb.RowSpacing
&& ga.ColumnSpacing == gb.ColumnSpacing
&& ReferenceEquals(ga.Definition, gb.Definition)
&& ReferenceEquals(ga.Setters, gb.Setters),
(BorderElement ba, BorderElement bb) =>
BrushesEqual(ba.Background, bb.Background)
&& BrushesEqual(ba.BorderBrush, bb.BorderBrush)
&& ba.CornerRadius == bb.CornerRadius
&& ba.Padding == bb.Padding
&& ba.BorderThickness == bb.BorderThickness
&& ReferenceEquals(ba.Setters, bb.Setters),
// ItemContainer: own props (excluding Child) match when
// IsSelected and Setters agree. The reconcile-highlight gate
// checks this to avoid marking every realized item yellow
// when the only changes are inside the user-supplied subtree.
(ItemContainerElement ica, ItemContainerElement icb) =>
ica.IsSelected == icb.IsSelected
&& ReferenceEquals(ica.Setters, icb.Setters),
(ScrollViewerElement sva, ScrollViewerElement svb) =>
sva.Orientation == svb.Orientation
&& sva.HorizontalScrollBarVisibility == svb.HorizontalScrollBarVisibility
&& sva.VerticalScrollBarVisibility == svb.VerticalScrollBarVisibility
&& sva.HorizontalScrollMode == svb.HorizontalScrollMode
&& sva.VerticalScrollMode == svb.VerticalScrollMode
&& sva.ZoomMode == svb.ZoomMode
&& ReferenceEquals(sva.Setters, svb.Setters),
(ScrollViewElement sva, ScrollViewElement svb) =>
sva.ContentOrientation == svb.ContentOrientation
&& sva.HorizontalScrollBarVisibility == svb.HorizontalScrollBarVisibility
&& sva.VerticalScrollBarVisibility == svb.VerticalScrollBarVisibility
&& sva.HorizontalScrollMode == svb.HorizontalScrollMode
&& sva.VerticalScrollMode == svb.VerticalScrollMode
&& sva.ZoomMode == svb.ZoomMode
&& sva.MinZoomFactor == svb.MinZoomFactor
&& sva.MaxZoomFactor == svb.MaxZoomFactor
&& sva.HorizontalAnchorRatio == svb.HorizontalAnchorRatio
&& sva.VerticalAnchorRatio == svb.VerticalAnchorRatio
&& ReferenceEquals(sva.Setters, svb.Setters),
(FlexElement fa, FlexElement fb) =>
fa.Direction == fb.Direction
&& fa.JustifyContent == fb.JustifyContent
&& fa.AlignItems == fb.AlignItems
&& fa.AlignContent == fb.AlignContent
&& fa.Wrap == fb.Wrap
&& fa.ColumnGap == fb.ColumnGap
&& fa.RowGap == fb.RowGap
&& fa.FlexPadding == fb.FlexPadding
&& ReferenceEquals(fa.Setters, fb.Setters),
(CanvasElement ca, CanvasElement cb) =>
ReferenceEquals(ca.Setters, cb.Setters),
(WrapGridElement wa, WrapGridElement wb) =>
wa.Orientation == wb.Orientation
&& wa.ItemWidth == wb.ItemWidth
&& wa.ItemHeight == wb.ItemHeight
&& wa.MaximumRowsOrColumns == wb.MaximumRowsOrColumns
&& ReferenceEquals(wa.Setters, wb.Setters),
(RelativePanelElement ra, RelativePanelElement rb) =>
ReferenceEquals(ra.Setters, rb.Setters),
(ViewboxElement va, ViewboxElement vb) =>
ReferenceEquals(va.Setters, vb.Setters),
// Structural wrappers that only contain children
(NavigationHostElement, NavigationHostElement) => true,
(CommandHostElement, CommandHostElement) => true,
(PopupElement pa, PopupElement pb) =>
pa.IsOpen == pb.IsOpen
&& pa.IsLightDismissEnabled == pb.IsLightDismissEnabled,
// TitleBar: own-props check (ignore Content/RightHeader slots which
// recurse as children). Without this, TitleBar flashes yellow on
// every reconcile even when only descendants changed.
(TitleBarElement ta, TitleBarElement tb) =>
ta.Title == tb.Title
&& ta.Subtitle == tb.Subtitle
&& ta.IsBackButtonVisible == tb.IsBackButtonVisible
&& ta.IsBackButtonEnabled == tb.IsBackButtonEnabled
&& ta.IsPaneToggleButtonVisible == tb.IsPaneToggleButtonVisible
&& ReferenceEquals(ta.Setters, tb.Setters),
// Pure composition wrappers — they never write their own WinUI
// properties; their rendered output is diffed separately. Returning
// true here prevents the overlay from flashing the entire content
// block every time the component re-renders.
(ComponentElement, ComponentElement) => true,
(FuncElement, FuncElement) => true,
(MemoElement, MemoElement) => true,
(ModifiedElement, ModifiedElement) => true,
(GroupElement, GroupElement) => true,
(ErrorBoundaryElement, ErrorBoundaryElement) => true,
// MenuFlyout attaches a flyout to its Target but doesn't have its
// own WinUI props that change across renders.
(MenuFlyoutElement, MenuFlyoutElement) => true,
(ContentFlyoutElement, ContentFlyoutElement) => true,
(MenuFlyoutContentElement, MenuFlyoutContentElement) => true,
(FlyoutElement, FlyoutElement) => true,
// Collection-style elements: compare own props only (SelectedIndex,
// mode flags, header). Item/children arrays are compared separately
// in ShallowEquals via ReferenceEquals — a fresh items array does
// NOT mean own props changed, so the highlight overlay should not
// light up the ComboBox/ListView/etc. when only the authored items
// projection allocated a new array.
(ComboBoxElement ca, ComboBoxElement cb) =>
ca.SelectedIndex == cb.SelectedIndex
&& ca.PlaceholderText == cb.PlaceholderText
&& ca.Header == cb.Header
&& ca.IsEditable == cb.IsEditable
&& ReferenceEquals(ca.Setters, cb.Setters),
(ListViewElement la, ListViewElement lb) =>
la.SelectedIndex == lb.SelectedIndex
&& la.SelectionMode == lb.SelectionMode
&& la.Header == lb.Header
&& ReferenceEquals(la.Setters, lb.Setters),
(GridViewElement ga, GridViewElement gb) =>
ga.SelectedIndex == gb.SelectedIndex
&& ga.SelectionMode == gb.SelectionMode
&& ga.Header == gb.Header
&& ReferenceEquals(ga.Setters, gb.Setters),
(FlipViewElement fa, FlipViewElement fb) =>
fa.SelectedIndex == fb.SelectedIndex
&& ReferenceEquals(fa.Setters, fb.Setters),
(PivotElement pa, PivotElement pb) =>
pa.SelectedIndex == pb.SelectedIndex
&& pa.Title == pb.Title
&& ReferenceEquals(pa.Setters, pb.Setters),
(TabViewElement ta, TabViewElement tb) =>
ta.SelectedIndex == tb.SelectedIndex
&& ta.IsAddTabButtonVisible == tb.IsAddTabButtonVisible
&& ReferenceEquals(ta.Setters, tb.Setters),
(TreeViewElement ta, TreeViewElement tb) =>
ta.SelectionMode == tb.SelectionMode
&& ta.CanDragItems == tb.CanDragItems
&& ta.AllowDrop == tb.AllowDrop
&& ta.CanReorderItems == tb.CanReorderItems
&& ReferenceEquals(ta.Setters, tb.Setters),
(SelectorBarElement sa, SelectorBarElement sb) =>
sa.SelectedIndex == sb.SelectedIndex
&& ReferenceEquals(sa.Setters, sb.Setters),
(ListBoxElement la, ListBoxElement lb) =>
la.SelectedIndex == lb.SelectedIndex
&& ReferenceEquals(la.Setters, lb.Setters),
(RadioButtonsElement ra, RadioButtonsElement rb) =>
ra.SelectedIndex == rb.SelectedIndex
&& ra.Header == rb.Header
&& ReferenceEquals(ra.Setters, rb.Setters),
(BreadcrumbBarElement ba, BreadcrumbBarElement bb) =>
ReferenceEquals(ba.Setters, bb.Setters),
// Templated (data-driven) collections: own props are the WinUI
// properties UpdateTemplatedXxx writes back. Items + ViewBuilder
// are not own props — they drive child reconcile but don't write
// properties on the parent control. Without this case, the typed
// ListView<T>/GridView<T>/FlipView<T> falls through to false and
// the highlight overlay flashes the whole list on every parent
// re-render (because OwnPropsEqual returning false is the gate
// for ReconcileHighlightOverlay's "modified" tag).
(TemplatedListElementBase ta, TemplatedListElementBase tb) =>
ta.GetSelectedIndex() == tb.GetSelectedIndex()
&& ta.GetSelectionMode() == tb.GetSelectionMode()
&& ta.GetHeader() == tb.GetHeader()
&& ta.GetIsItemClickEnabled() == tb.GetIsItemClickEnabled()
&& !ta.HasSetters && !tb.HasSetters,
// Typed TreeView<T>: Items/selectors/ViewBuilder are factory inputs
// (they drive child reconcile, not parent control properties), so
// own-prop equality compares only the WinUI properties the update
// path writes back — same rationale as the templated collections.
(TemplatedTreeViewElementBase ta, TemplatedTreeViewElementBase tb) =>
ta.SelectionMode == tb.SelectionMode
&& ta.CanDragItems == tb.CanDragItems
&& ta.AllowDrop == tb.AllowDrop
&& ta.CanReorderItems == tb.CanReorderItems
&& ReferenceEquals(ta.SettersErased, tb.SettersErased),
// Lazy (virtualized) stacks: same rationale — Items/ViewBuilder
// are factory inputs, not control properties.
(LazyStackElementBase la, LazyStackElementBase lb) =>
la.Orientation == lb.Orientation
&& la.Spacing == lb.Spacing
&& la.EstimatedItemSize == lb.EstimatedItemSize
&& ReferenceEquals(la.ScrollViewerSetters, lb.ScrollViewerSetters)
&& ReferenceEquals(la.RepeaterSetters, lb.RepeaterSetters),
// Spec 045 §2.1 / §2.3 — docking elements use closures for
// their callbacks (OnDelta, OnHover, etc.) that are freshly
// captured on every parent render. The closures don't touch
// the realized WinUI control's visible properties — only
// structural fields (Direction, Mode) do — so for the
// highlight overlay's purposes these are "equal" when the
// structural fields match. Without these arms, every parent
// re-render flashes the splitter handles + drop overlay
// yellow even though nothing visible changed.
(Microsoft.UI.Reactor.Docking.Native.DockSplitterElement da,
Microsoft.UI.Reactor.Docking.Native.DockSplitterElement db) =>
da.Direction == db.Direction,
(Microsoft.UI.Reactor.Docking.Native.DockDropTargetOverlayElement oa,
Microsoft.UI.Reactor.Docking.Native.DockDropTargetOverlayElement ob) =>
oa.Mode == ob.Mode,
// Non-container / leaf types: return false → always captured
_ => false,
};
}
/// <summary>
/// Structural comparison of RichTextParagraph arrays.
/// Compares each paragraph's inlines using record equality.
/// </summary>
private static bool ParagraphsEqual(RichTextParagraph[]? a, RichTextParagraph[]? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null || b is null) return false;
if (a.Length != b.Length) return false;
for (int i = 0; i < a.Length; i++)
{
if (!ParagraphEqual(a[i], b[i])) return false;
}
return true;
}
/// <summary>
/// Structural comparison of a single RichTextParagraph (inline-by-inline record equality).
/// </summary>
internal static bool ParagraphEqual(RichTextParagraph a, RichTextParagraph b)
{
if (ReferenceEquals(a, b)) return true;
var ai = a.Inlines;
var bi = b.Inlines;
if (ai.Length != bi.Length) return false;
for (int j = 0; j < ai.Length; j++)
{
if (!ai[j].Equals(bi[j])) return false;
}
return true;
}
/// <summary>
/// Structural brush comparison. BrushHelper.Parse caches the parsed Color
/// but returns a fresh SolidColorBrush instance on every call (Brushes have
/// thread affinity), so ReferenceEquals always fails for ".Background("#x")"
/// style fluent chains. Unwrap the underlying Color for the common
/// SolidColorBrush case and fall back to ReferenceEquals for everything else.
/// </summary>
private static bool BrushesEqual(Brush? a, Brush? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null || b is null) return false;
if (a is SolidColorBrush sa && b is SolidColorBrush sb)
return sa.Color == sb.Color && sa.Opacity == sb.Opacity;
return false;
}
/// <summary>
/// Structural transform comparison. D3PathTranslated allocates a fresh
/// TranslateTransform on every render even when X/Y match, so reference
/// equality always fails for the common chart case. Unwrap TranslateTransform
/// and fall back to ReferenceEquals for everything else.
/// </summary>
private static bool TransformsEqual(Transform? a, Transform? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null || b is null) return false;
if (a is TranslateTransform ta && b is TranslateTransform tb)
return ta.X == tb.X && ta.Y == tb.Y;
return false;
}
private static bool FontFamiliesEqual(Microsoft.UI.Xaml.Media.FontFamily? a, Microsoft.UI.Xaml.Media.FontFamily? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null || b is null) return false;
return a.Source == b.Source;
}
/// <summary>
/// Compare two ElementModifiers for rendering equivalence.
/// Brushes and FontFamily are compared structurally because fluent helpers
/// (<c>.Background("#color")</c>, <c>.FontFamily("Segoe UI")</c>) allocate
/// fresh instances on every render even when the underlying values match.
/// Ignores OnMountAction (only runs at mount time, not during update).
/// </summary>
internal static bool ModifiersEqual(ElementModifiers? a, ElementModifiers? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null || b is null) return false;
return a.Margin == b.Margin
&& a.Padding == b.Padding
&& a.Width == b.Width
&& a.Height == b.Height
&& a.MinWidth == b.MinWidth
&& a.MinHeight == b.MinHeight
&& a.MaxWidth == b.MaxWidth
&& a.MaxHeight == b.MaxHeight
&& a.HorizontalAlignment == b.HorizontalAlignment
&& a.VerticalAlignment == b.VerticalAlignment
&& a.Opacity == b.Opacity
&& a.IsVisible == b.IsVisible
&& a.IsEnabled == b.IsEnabled
&& a.CornerRadius == b.CornerRadius
&& a.BorderThickness == b.BorderThickness
&& a.ElementSoundMode == b.ElementSoundMode
&& a.ToolTip == b.ToolTip
&& a.AutomationName == b.AutomationName
&& a.AutomationId == b.AutomationId
&& BrushesEqual(a.Background, b.Background)
&& BrushesEqual(a.Foreground, b.Foreground)
&& BrushesEqual(a.BorderBrush, b.BorderBrush)
&& a.FontSize == b.FontSize
&& a.FontWeight == b.FontWeight
&& FontFamiliesEqual(a.FontFamily, b.FontFamily)
// Skip OnMountAction — only runs at mount time
// Skip event handlers — delegate comparison is unreliable, conservative false
&& a.OnSizeChanged is null && b.OnSizeChanged is null
&& a.OnPointerPressed is null && b.OnPointerPressed is null
&& a.OnPointerMoved is null && b.OnPointerMoved is null
&& a.OnPointerReleased is null && b.OnPointerReleased is null
&& a.OnTapped is null && b.OnTapped is null
&& a.OnKeyDown is null && b.OnKeyDown is null
// Skip RichToolTip, AttachedFlyout, ContextFlyout — rare, conservative false
&& a.RichToolTip is null && b.RichToolTip is null
&& a.AttachedFlyout is null && b.AttachedFlyout is null
&& a.ContextFlyout is null && b.ContextFlyout is null
// Accessibility Tier 1
&& a.HeadingLevel == b.HeadingLevel
&& a.IsTabStop == b.IsTabStop
&& a.TabIndex == b.TabIndex
&& a.AccessKey == b.AccessKey
// Accessibility Tier 2/3. AccessibilityModifiers is a record of
// scalar/string fields, but every fluent helper (.AccessibilityView,
// .LiveRegion, .ItemStatus, …) allocates a fresh instance per render
// — so reference equality always fails for elements that set any
// accessibility modifier, even when the values are unchanged.
// Falsely missing this match cascades into the reconcile-highlight
// overlay, which paints those elements as "modified" every render.
// Use record value-equality instead.
&& AccessibilityEqual(a.Accessibility, b.Accessibility);
}
private static bool AccessibilityEqual(AccessibilityModifiers? a, AccessibilityModifiers? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null || b is null) return false;
return a.Equals(b);
}
/// <summary>
/// Compare two Attached property dictionaries by content.
/// Common case: both have a single GridAttached entry (a record with structural equality).
/// </summary>
internal static bool AttachedEqual(IReadOnlyDictionary<Type, object>? a, IReadOnlyDictionary<Type, object>? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null && b is null) return true;
if (a is null || b is null) return false;
if (a.Count != b.Count) return false;
foreach (var (key, valA) in a)
{
if (!b.TryGetValue(key, out var valB)) return false;
if (!Equals(valA, valB)) return false; // GridAttached is a record — Equals works
}
return true;
}
internal static bool ThemeBindingsEqual(IReadOnlyDictionary<string, ThemeRef>? a, IReadOnlyDictionary<string, ThemeRef>? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null && b is null) return true;
if (a is null || b is null) return false;
if (a.Count != b.Count) return false;
foreach (var (key, valA) in a)
{
if (!b.TryGetValue(key, out var valB)) return false;
if (valA.ResourceKey != valB.ResourceKey) return false;
}
return true;
}
internal static bool ContextValuesEqual(IReadOnlyDictionary<ContextBase, object?>? a, IReadOnlyDictionary<ContextBase, object?>? b)
{
if (ReferenceEquals(a, b)) return true;
if (a is null && b is null) return true;
if (a is null || b is null) return false;
if (a.Count != b.Count) return false;
foreach (var (key, valA) in a)
{
if (!b.TryGetValue(key, out var valB)) return false;
if (!Equals(valA, valB)) return false;
}
return true;
}
}
/// <summary>
/// An element that renders nothing (used for conditional rendering).
/// </summary>
public record EmptyElement : Element
{
public static readonly EmptyElement Instance = new();
}
/// <summary>
/// A transparent grouping element (like React's Fragment). Does not introduce
/// any layout container — its children are flattened into the parent.
/// Produced by <c>ForEach</c> and <c>Group()</c> in the DSL.
/// </summary>
public record GroupElement(Element[] Children) : Element;
/// <summary>
/// Catches render errors in its child subtree and displays fallback UI.
/// Like React's ErrorBoundary — catches errors during rendering, not event handlers.
/// When the ErrorBoundary re-renders, it retries the child (error recovery).
/// </summary>
public record ErrorBoundaryElement(Element Child, Func<Exception, Element> Fallback) : Element;
/// <summary>
/// Wraps any element with layout modifiers (margin, alignment, size, etc.).
/// Kept for backward compatibility. New code stores modifiers inline on Element.Modifiers.
/// </summary>
public record ModifiedElement(Element Inner, ElementModifiers WrappedModifiers) : Element;
/// <summary>
/// Wraps a Component class so it can participate in the element tree.
/// Created automatically by Component<T>() factory method.
/// </summary>
public record ComponentElement(
[property: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
Type ComponentType,
object? Props = null) : Element
{
// Factory creates the component instance without reflection. Stored as a field
// so it does not participate in record equality (two ComponentElements for the
// same Type/Props are equal regardless of factory identity).
internal Func<Component>? _factory;
internal Component CreateInstance() =>
_factory is not null ? _factory() : (Component)Activator.CreateInstance(ComponentType)!;
}
/// <summary>
/// Strongly-typed <see cref="ComponentElement"/> that exposes <see cref="Props"/>
/// as <typeparamref name="TProps"/> instead of <c>object?</c>, so callers can use
/// a record <c>with</c>-expression to produce a modified copy of the element
/// with updated props:
/// <code>
/// var grid = DataGrid<Foo>(source, columns);
/// var taller = grid with { Props = grid.Props with { RowHeight = 60 } };
/// </code>
/// The typed <see cref="Props"/> is a thin view over the base
/// <see cref="ComponentElement.Props"/> slot — there is no second storage field,
/// so the reconciler (which reads <c>base.Props</c>) always sees the same value
/// as the typed accessor on the cloned record.
/// </summary>
public record ComponentElement<TProps> : ComponentElement
{
public ComponentElement(