diff --git a/CHANGELOG.md b/CHANGELOG.md index 83fc428ab7..ebeb00e467 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -165,6 +165,32 @@ Conventions for contributors: page helper that wraps the content in `ScrollView`, matching the control pages and Home. +- **Controls registered with `Reconciler.RegisterType` now carry their element tag, so + keyed lists of them keep their place and their `unmount` callback runs** (spec 047 + §14, PR #1301). The reconciler records each control's element on the control and reads + it back in several places, but it left a registered type's control to its own + callbacks, which only `XamlInterop` tagged. A keyed registered-type child that survived + a re-render was therefore neither moved nor patched: a `Grid` of them that grew or + reordered showed stale content at another child's row and column. The `unmount` + callback never ran, keyed or not, so the docking host's cleanup (closing its floating + windows, unregistering from `DockHostRegistry`) never ran either, and the guide's + `editor.Dispose()` example never disposed anything. The docking cleanup now runs, but + it covers only the host's latest `DockManager` element, so a window floated under an + earlier element still outlives the host; that is a separate docking bug. A + `.Ref(...)` on a registered type kept pointing at the removed control, which the pool + could already have handed to another element. The reconciler now tags these controls + wherever it reads the tag itself: when the element is keyed or carries callbacks, + extras or a reference modifier, and always when the registration has an `unmount` + callback. A control already tagged for an element of another type, such as one the + callback got from `Reconciler.Mount`, keeps that tag. An `update` callback that + returns the control it was handed now counts as patching it, where the child + reconcilers used to unmount it. Unmounting a replaced control also no longer clears a + `.Ref(...)` that has already moved to its replacement. Because `unmount` now runs, it + replaces the reconciler's walk over the control's children, as it always has for + `XamlInterop`: a registration that mounts children through the reconciler and + supplies `unmount` has to unmount them there. Calling `UnmountChild` on the control + itself from `unmount` walks its children once rather than calling `unmount` again. + - **Apps that reference only `Microsoft.UI.Reactor` are framework-dependent again** (regression from #822). The package now depends on `Microsoft.WindowsAppSDK.Runtime`; without it the Windows App SDK silently diff --git a/docs/_pipeline/templates/extending-reactor-controls.md.dt b/docs/_pipeline/templates/extending-reactor-controls.md.dt index 0151ed3e50..a8bd1917cd 100644 --- a/docs/_pipeline/templates/extending-reactor-controls.md.dt +++ b/docs/_pipeline/templates/extending-reactor-controls.md.dt @@ -522,10 +522,28 @@ callback that runs before the first render: `RegisterType` takes **inline** mount/update/unmount delegates, so a one-off control needs no `IElementHandler` class at all; `unmount` is optional. Returning `null` from `update` means "I patched the existing -control" — return a different `UIElement` only when you genuinely -replaced it. If you *do* have a handler class, `RegisterHandler` takes -an **instance** of it instead. This is the shape Reactor's own docking -natives and the Monaco sample use. +control", and so does returning the control you were handed — return a +different `UIElement` only when you genuinely replaced it. If you *do* +have a handler class, `RegisterHandler` takes an **instance** of it +instead. This is the shape Reactor's own docking natives and the Monaco +sample use. + +Reactor records the element on the control that `mount` or `update` +returns wherever Reactor itself reads it back — keyed reordering, the +`unmount` lookup and `.Ref(...)` cleanup — so the delegates don't call +`Reconciler.SetElementTag` for those. If your own code reads the element +back with `Reconciler.GetElementTag`, from an event handler for example, +keep tagging the control yourself. Return a control your registration +owns: a control Reactor already mounted for another kind of element +keeps that element's identity, so to wrap built-in elements write a +component instead. `unmount` runs when Reactor unmounts the control, +*instead of* Reactor's own walk over the control's children. If your +delegates mount child elements through the reconciler, unmount them +there too (`r.UnmountChild(child)`); without an `unmount` delegate, +Reactor walks the children itself. One gap remains: a control that +`update` replaced inside a single-content parent such as `Border` is +swapped out without `unmount`, so don't rely on it for a control your +`update` replaces. A library that wants eager setup ships an ordinary `public static void UseAcme(Reconciler reconciler)` over one of these — diff --git a/docs/guide/extending-reactor-controls.md b/docs/guide/extending-reactor-controls.md index a42c7f32e0..b46d712786 100644 --- a/docs/guide/extending-reactor-controls.md +++ b/docs/guide/extending-reactor-controls.md @@ -675,10 +675,28 @@ ReactorApp.Run("Monaco Editor", configure: host => `RegisterType` takes **inline** mount/update/unmount delegates, so a one-off control needs no `IElementHandler` class at all; `unmount` is optional. Returning `null` from `update` means "I patched the existing -control" — return a different `UIElement` only when you genuinely -replaced it. If you *do* have a handler class, `RegisterHandler` takes -an **instance** of it instead. This is the shape Reactor's own docking -natives and the Monaco sample use. +control", and so does returning the control you were handed — return a +different `UIElement` only when you genuinely replaced it. If you *do* +have a handler class, `RegisterHandler` takes an **instance** of it +instead. This is the shape Reactor's own docking natives and the Monaco +sample use. + +Reactor records the element on the control that `mount` or `update` +returns wherever Reactor itself reads it back — keyed reordering, the +`unmount` lookup and `.Ref(...)` cleanup — so the delegates don't call +`Reconciler.SetElementTag` for those. If your own code reads the element +back with `Reconciler.GetElementTag`, from an event handler for example, +keep tagging the control yourself. Return a control your registration +owns: a control Reactor already mounted for another kind of element +keeps that element's identity, so to wrap built-in elements write a +component instead. `unmount` runs when Reactor unmounts the control, +*instead of* Reactor's own walk over the control's children. If your +delegates mount child elements through the reconciler, unmount them +there too (`r.UnmountChild(child)`); without an `unmount` delegate, +Reactor walks the children itself. One gap remains: a control that +`update` replaced inside a single-content parent such as `Border` is +swapped out without `unmount`, so don't rely on it for a control your +`update` replaces. A library that wants eager setup ships an ordinary `public static void UseAcme(Reconciler reconciler)` over one of these — diff --git a/src/Reactor/Core/Reconciler.cs b/src/Reactor/Core/Reconciler.cs index 928af21dda..239d7f048b 100644 --- a/src/Reactor/Core/Reconciler.cs +++ b/src/Reactor/Core/Reconciler.cs @@ -919,6 +919,37 @@ private static void WithdrawAttachedValidation(UIElement control) /// The mount and update handlers receive the Reconciler instance so they can /// recursively mount/update/unmount child elements without capturing external state. /// + /// The reconciler records the element on the control it gets back from mount or + /// update (the element tag) wherever it reads the tag back itself: keyed + /// reconciliation, the unmount lookup, .Ref(...) cleanup and exit + /// transitions. The callbacks don't call for those. Code of your + /// own that reads the element back with , such + /// as an event handler, still tags the control itself. The tag lives on a + /// . may be declared as + /// , but in WinUI 3 is its only + /// subclass, so every control a registration returns is tagged the same way. + /// + /// mount and update are expected to return a control the registration owns. + /// The tag holds one element, so a control that already carries the tag of an element of + /// another type (registration is by exact type, so a derived type counts), for example one + /// mount got from for a child element, keeps that tag: + /// overwriting it would silence that element's own callbacks (the collision issue #942 + /// tracks for target-wrapping decorators). The registration's key, ref, transitions and + /// unmount are not tracked for such a control. To wrap built-in elements, compose + /// them in a component instead. + /// + /// update returns null after patching the control in place; returning the control + /// it was handed means the same. Return a different control only when you replaced it. + /// + /// unmount runs when the reconciler unmounts the control, in place of its own walk + /// over the control's children: a child the callbacks mounted through the reconciler has to + /// be torn down there, for example with . Calling + /// on the control itself from unmount walks its children + /// once rather than calling unmount again. Without an unmount callback the + /// reconciler walks the control's children itself. Not every path that drops a control + /// unmounts it yet: a control that update replaced inside a single-content parent, + /// such as a Border, is swapped out without unmount. + /// /// Not part of the REACTOR_V1_PREVIEW surface — this is the legacy /// type-registry path, public since before Spec 047. The §13 Q17 hardening /// (throw on duplicate, no base-class fallback, no open generics) tightens @@ -1517,16 +1548,44 @@ public TypeRegistration( public bool HasUnmount => _unmount is not null; public UIElement Mount(Element element, Action requestRerender, Reconciler reconciler) - => _mount(reconciler, (TElement)element, requestRerender); + { + var control = _mount(reconciler, (TElement)element, requestRerender); + TagControl(control, element); + return control; + } public UIElement? Update(Element oldEl, Element newEl, UIElement control, Action requestRerender, Reconciler reconciler) { // Guard against control type mismatch (e.g., recycled from pool or element type changed at this position). // If the existing control isn't our expected type, force a fresh mount instead of crashing. - if (control is not TControl typedControl || oldEl is not TElement typedOldEl) - return _mount(reconciler, (TElement)newEl, requestRerender); - - return _update(reconciler, typedOldEl, (TElement)newEl, typedControl, requestRerender); + var result = control is not TControl typedControl || oldEl is not TElement typedOldEl + ? _mount(reconciler, (TElement)newEl, requestRerender) + : _update(reconciler, typedOldEl, (TElement)newEl, typedControl, requestRerender); + + // Returning the control it was handed means the callback patched it in place, the + // same as returning null. The child reconcilers read any non-null result as a + // replacement and unmount the control they hold, which would run this registration's + // unmount callback against a control that stays mounted. A second managed wrapper + // for the same native control counts too. + if (result is not null && IsSameControl(result, control)) + result = null; + + TagControl(result ?? control, newEl); + return result; + } + + // True when an update result is the control it was handed, possibly through a second + // managed wrapper. Every wrapper for a native object reads the same ReactorState, so + // the handed-in control gets one if it has none and the result is checked for it. That + // allocation happens only when the callback returned a different wrapper, which is + // almost always a genuine replacement, and it lands on the old control. + private static bool IsSameControl(UIElement result, UIElement control) + { + if (ReferenceEquals(result, control)) return true; + if (result is not FrameworkElement resultFe || control is not FrameworkElement controlFe) + return false; + var state = GetOrCreateReactorState(controlFe); + return ReferenceEquals(resultFe.GetValue(ReactorAttached.StateProperty), state); } public void Unmount(UIElement control, Reconciler reconciler) @@ -1534,6 +1593,31 @@ public void Unmount(UIElement control, Reconciler reconciler) if (control is TControl typedControl) _unmount?.Invoke(reconciler, typedControl); } + + // The reconciler tags the control so the callbacks don't have to. The keyed-middle + // reconcile finds a surviving child by the key on its tag, the unmount path finds this + // registration's unmount callback through it, and .Ref(...) cleanup reads it too. + // Same allocation gate as SetElementTagIfNeeded, so an unkeyed, extras-free leaf gets + // no ReactorState, except that a registration with an unmount callback always tags: + // that lookup goes through the tag whatever the element carries. + private void TagControl(UIElement control, Element element) + { + // The tag lives on FrameworkElement, UIElement's only subclass in WinUI 3, so a + // TControl declared as UIElement still arrives here as a FrameworkElement. + if (control is not FrameworkElement fe) return; + if (fe.GetValue(ReactorAttached.StateProperty) is ReactorState state) + { + // The callback returned a control the reconciler mounted for an element of + // another type, such as a child's. That element's own event trampolines and + // unmount read the tag, so it keeps it. Registration is by exact type, so a + // derived element type is another type here too. + if (state.Element is { } owner && owner.GetType() != typeof(TElement)) return; + state.Element = element; + return; + } + if (HasUnmount || NeedsTag(element)) + fe.SetValue(ReactorAttached.StateProperty, new ReactorState { Element = element }); + } } // @@ -2290,10 +2374,13 @@ private void UnmountRecursive(UIElement control) } // Check registered type unmount handlers via the attached element - if (control is FrameworkElement fe && GetElementTag(fe) is Element tagEl - && _typeRegistry.TryGetValue(tagEl.GetType(), out var reg) && reg.HasUnmount) + if (control is FrameworkElement fe && TryGetReactorState(fe, out var regState) + && regState.Element is Element tagEl + && _typeRegistry.TryGetValue(tagEl.GetType(), out var reg) && reg.HasUnmount + && TryBeginRegisteredUnmount(regState)) { - reg.Unmount(control, this); + try { reg.Unmount(control, this); } + finally { EndRegisteredUnmount(regState); } return; } @@ -2312,10 +2399,35 @@ private void UnmountRecursive(UIElement control) private static void CleanupReferenceStateForUnmount(FrameworkElement control, Element? element) { - element?.Modifiers?.Ref?.SetCurrent(null); + // Clear the producer ref only while it still names this control. When an update + // replaces a control, ApplyModifiers points the element's ref at the replacement + // before the caller unmounts the old control, and the ref must keep it. + if (element?.Modifiers?.Ref is { } producerRef && producerRef.Current is { } current + && IsSameNativeElement(current, control)) + producerRef.SetCurrent(null); TeardownReferenceEdges(control); } + // Two managed wrappers can front one native element (see ReactorAttached.StateProperty), so + // identity falls back to the ReactorState that lives on the native object. When b carries no + // ReactorState there is nothing native to compare, and only the same wrapper matches. + private static bool IsSameNativeElement(FrameworkElement a, FrameworkElement b) => + ReferenceEquals(a, b) + || (b.GetValue(ReactorAttached.StateProperty) is ReactorState state + && ReferenceEquals(a.GetValue(ReactorAttached.StateProperty), state)); + + // Controls whose RegisterType unmount callback is running, by the ReactorState on the native + // control so a second managed wrapper for it is recognized too. A callback that tears its own + // control down through the reconciler (UnmountChild on the control it was handed, to reach + // the children it mounted) re-enters the unmount path for that control; the re-entrant call + // takes the default walk over the children instead of calling the callback again. + private HashSet? _registeredUnmountsRunning; + + private bool TryBeginRegisteredUnmount(ReactorState state) => + (_registeredUnmountsRunning ??= new HashSet(ReferenceEqualityComparer.Instance)).Add(state); + + private void EndRegisteredUnmount(ReactorState state) => _registeredUnmountsRunning?.Remove(state); + private static void ForEachReactorChildControl(UIElement control, Action visit) => ForEachReactorChildControl(control, child => { visit(child); return true; }); @@ -2665,10 +2777,13 @@ private void UnmountAndCollect(UIElement control, List toPool) } } - if (control is FrameworkElement fe && GetElementTag(fe) is Element tagEl - && _typeRegistry.TryGetValue(tagEl.GetType(), out var reg) && reg.HasUnmount) + if (control is FrameworkElement fe && TryGetReactorState(fe, out var regState) + && regState.Element is Element tagEl + && _typeRegistry.TryGetValue(tagEl.GetType(), out var reg) && reg.HasUnmount + && TryBeginRegisteredUnmount(regState)) { - reg.Unmount(control, this); + try { reg.Unmount(control, this); } + finally { EndRegisteredUnmount(regState); } // Collect this control for pooling, but do NOT recurse into children — // they were created outside Reactor's tree and must not be pooled. // (Mirrors UnmountRecursive which returns early in this case.) diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/NativeDockingReliabilityFixture.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/NativeDockingReliabilityFixture.cs index 4d032abb9c..e4b6cccff3 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/NativeDockingReliabilityFixture.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/NativeDockingReliabilityFixture.cs @@ -460,44 +460,22 @@ public override async Task RunAsync() // contract: DockingNativeInterop's unmount lambda // iterates DockFloatingTracker.SnapshotFor(managerEl) // and calls Close + UnregisterFor on each floating - // window. In the headless self-test harness this path - // is intermittently observable — the reconcile-driven - // unmount lambda does not always fire when - // host.Mount(Func) replaces the root (ReactorHost.Mount - // resets the func context per spec §F#15). We poll the - // tracker for several render cycles to give the unmount - // path a chance, then fall back to an explicit close. - // Either path is sufficient to exercise the - // Closed → UnregisterFor wire; the spec-§2.25 contract - // proper is verified by the Appium-tier self-tests. + // window. This used to be skipped as "intermittently + // observable in the headless harness", but the lambda + // never ran at all: the reconciler did not tag controls + // mounted through RegisterType, so the unmount path could + // not find the registration. It is deterministic now. host.Mount(_ => TextBlock("host-unmounted")); - await Harness.Render(); - - bool unmountClearedTracker = false; - for (int i = 0; i < 8; i++) - { - if (DockFloatingTracker.SnapshotFor(managerEl).Count == 0) - { - unmountClearedTracker = true; - break; - } - await Harness.Render(); - } + bool unmountClearedTracker = await Harness.WaitFor( + () => DockFloatingTracker.SnapshotFor(managerEl).Count == 0, maxPasses: 8); + H.Check("Reliability_FloatOutlive_TrackerClearedByUnmount", unmountClearedTracker); - if (unmountClearedTracker) - { - H.Check("Reliability_FloatOutlive_TrackerClearedByUnmount", true); - } - else - { - H.Skip("Reliability_FloatOutlive_TrackerClearedByUnmount", - "Host swap did not drain the docking unmount lambda in the headless harness " + - "(see ReactorHost.Mount(Func) review finding). " + - "Falling back to explicit close to exercise the rest of the chain."); + // Close it by hand if the host did not, so a failure here + // doesn't leak the window into later fixtures. + if (!unmountClearedTracker) floating?.Close(); - for (int i = 0; i < 8 && !closedFired; i++) - await Harness.Render(); - } + for (int i = 0; i < 8 && !closedFired; i++) + await Harness.Render(); H.Check("Reliability_FloatOutlive_PerHostTrackerClearedEventually", DockFloatingTracker.SnapshotFor(managerEl).Count == 0); diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ReconcilerBigCoverageFixtures.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ReconcilerBigCoverageFixtures.cs index 262bc4fe22..37ca9da2ad 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ReconcilerBigCoverageFixtures.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ReconcilerBigCoverageFixtures.cs @@ -1367,11 +1367,9 @@ public override async Task RunAsync() H.ClickButton("CustomPhase"); await Harness.Render(); H.Check("CustomReg_Replaced", H.FindText("custom-replaced") is not null); - // The unmount callback is invoked through the registered TypeRegistration's - // Unmount path; if the framework chose a different teardown (e.g. unmount - // via parent), the variable may not increment — keep the test green. - _ = unmountCount; - H.Check("CustomReg_TypeRegistered", true); + // Swapping the slot to a TextBlock unmounts the widget through UnmountRecursive, + // which finds the registration's unmount callback through the element tag. + H.Check("CustomReg_UnmountCallbackRan", unmountCount == 1); } } diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/RegisterTypeElementTagFixtures.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/RegisterTypeElementTagFixtures.cs new file mode 100644 index 0000000000..ff87a7c4de --- /dev/null +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/RegisterTypeElementTagFixtures.cs @@ -0,0 +1,1022 @@ +using Microsoft.UI.Reactor.AppTests.Host.SelfTest; +using Microsoft.UI.Reactor.Core; +using Microsoft.UI.Reactor.Hosting; +using Microsoft.UI.Reactor.Input; +using Microsoft.UI.Xaml; +using static Microsoft.UI.Reactor.Factories; +using ReactorTransition = Microsoft.UI.Reactor.Animation.Transition; +using WinXC = Microsoft.UI.Xaml.Controls; + +namespace Microsoft.UI.Reactor.AppTests.Host.SelfTest.Fixtures; + +/// +/// A control mounted through the per-host Reconciler.RegisterType must carry its element +/// tag (ReactorAttached.StateProperty → ReactorState.Element) whenever something +/// reads it back, without the registration's callbacks calling Reconciler.SetElementTag +/// themselves. None of the registrations below tag by hand. +/// +/// Four readers depend on the tag. ChildReconciler.ReconcileKeyedMiddle finds a +/// surviving keyed child by the key on its tag; an untagged survivor is neither moved nor +/// patched, so after a grow or a reorder the control keeps stale content while the Grid assigns +/// it another child's cell. UnmountRecursive / UnmountAndCollect find a +/// registration's unmount callback through the tag, so without it the callback never ran. +/// CleanupReferenceStateForUnmount clears a .Ref(...) through the tag, so without +/// it the ref kept pointing at the removed control. RemoveChildWithExitTransition reads a +/// .Transition(...) exit animation from the tag, so without it the control was removed +/// without one. +/// +/// The reconciler used to tag only the V1 arm and the composition wrappers. The +/// registered-type arm left tagging to the author, which in-tree only XamlInterop did. +/// These fixtures cover each reader, both unmount paths, both update outcomes (patched in place +/// and replaced), and the allocation gate: an unkeyed control whose registration has no +/// unmount is still not tagged unless it carries an extra. Others pin what tagging must +/// not do: clear a ref that has already moved to a replacement, or retag a control that an +/// element of another type owns. One more pins that an unmount callback can unmount its +/// own control through the reconciler without calling itself again. +/// +internal static class RegisterTypeElementTagFixtures +{ + // ── Keyed children: grow a Grid, then reverse it ──────────────────── + + private sealed record CellElement(int Row, int Column, int Generation) : Element; + + private readonly record struct Cell(UIElement Control, int GridRow, int GridColumn, string? Text); + + private static string CellLabel(CellElement cell) => $"{cell.Row},{cell.Column}@{cell.Generation}"; + + /// + /// Mounts a 3×3 Grid of keyed registered-type cells, grows it to 4×5 and then reverses the + /// child order, the same shape as KeyedWrapperChildrenFixtures. Row 0 stays put as the + /// keyed prefix; rows 1 and 2 survive in the keyed middle at new indices. After each step + /// every cell's text must name its own Grid cell at the current generation, and every + /// survivor must still be the control that was mounted for it. + /// + internal sealed class KeyedGridGrowAndReverse(Harness h) : SelfTestFixtureBase(h) + { + private const string Name = "RegisterTypeTag_KeyedGrid"; + + private readonly Dictionary<(int Row, int Column), int> _mounts = new(); + + public override async Task RunAsync() + { + var host = H.CreateHost(); + // No unmount callback, so only the key can be the reason this control is tagged. + host.Reconciler.RegisterType( + mount: (_, cell, _) => + { + _mounts[(cell.Row, cell.Column)] = _mounts.GetValueOrDefault((cell.Row, cell.Column)) + 1; + return new WinXC.TextBlock { Text = CellLabel(cell) }; + }, + update: (_, _, cell, text, _) => + { + text.Text = CellLabel(cell); + return null; + }); + + host.Mount(ctx => + { + var (step, setStep) = ctx.UseState(0); + var (rows, columns) = step == 0 ? (3, 3) : (4, 5); + var cells = new List(rows * columns); + for (int r = 0; r < rows; r++) + for (int c = 0; c < columns; c++) + cells.Add(new CellElement(r, c, step).Grid(row: r, column: c).WithKey($"cell-{r}-{c}")); + if (step == 2) + cells.Reverse(); + + return VStack( + Button("RTT Grow", () => setStep(1)), + Button("RTT Reverse", () => setStep(2)), + Grid(Tracks(columns), Tracks(rows), cells.ToArray()).AutomationId("rtt_grid")); + }); + + await Harness.Render(); + var mounted = Snapshot(); + Verify("Mount", mounted, rows: 3, columns: 3, generation: 0); + + H.ClickButton("RTT Grow"); + await Harness.Render(); + var grown = Snapshot(); + Verify("Grow", grown, rows: 4, columns: 5, generation: 1); + CheckSurvivorsKeptTheirControl("Grow", mounted, grown); + + H.ClickButton("RTT Reverse"); + await Harness.Render(); + var reversed = Snapshot(); + Verify("Reverse", reversed, rows: 4, columns: 5, generation: 2); + CheckSurvivorsKeptTheirControl("Reverse", grown, reversed); + } + + private static GridSize[] Tracks(int count) + { + var tracks = new GridSize[count]; + for (int i = 0; i < count; i++) tracks[i] = GridSize.Px(40); + return tracks; + } + + private List Snapshot() + { + var grid = H.FindControl(g => + Microsoft.UI.Xaml.Automation.AutomationProperties.GetAutomationId(g) == "rtt_grid"); + var cells = new List(); + if (grid is null) return cells; + foreach (var child in grid.Children) + { + cells.Add(new Cell( + child, + WinXC.Grid.GetRow((FrameworkElement)child), + WinXC.Grid.GetColumn((FrameworkElement)child), + (child as WinXC.TextBlock)?.Text)); + } + return cells; + } + + private static bool TryParse(string? text, out int row, out int column, out int generation) + { + row = column = generation = -1; + if (text is null) return false; + var at = text.IndexOf('@'); + var comma = text.IndexOf(','); + return comma > 0 && at > comma + && int.TryParse(text[..comma], out row) + && int.TryParse(text[(comma + 1)..at], out column) + && int.TryParse(text[(at + 1)..], out generation); + } + + private void Verify(string step, List cells, int rows, int columns, int generation) + { + H.Check($"{Name}_{step}_ChildCount", cells.Count == rows * columns, + $"expected {rows * columns} children, found {cells.Count}"); + + var misplaced = new List(); + var stale = new List(); + for (int i = 0; i < cells.Count; i++) + { + var cell = cells[i]; + var at = $"child {i} '{cell.Text}' at ({cell.GridRow},{cell.GridColumn})"; + if (!TryParse(cell.Text, out var row, out var column, out var shown)) + { + misplaced.Add(at); + continue; + } + if (row != cell.GridRow || column != cell.GridColumn) + misplaced.Add(at); + if (shown != generation) + stale.Add(at); + } + + H.Check($"{Name}_{step}_ContentMatchesGridCell", cells.Count > 0 && misplaced.Count == 0, + $"{misplaced.Count} of {cells.Count} children show another cell's content: {Summarize(misplaced)}"); + H.Check($"{Name}_{step}_ContentIsCurrent", cells.Count > 0 && stale.Count == 0, + $"{stale.Count} of {cells.Count} children still show an older generation than {generation}: {Summarize(stale)}"); + } + + private void CheckSurvivorsKeptTheirControl(string step, List before, List after) + { + static Dictionary<(int, int), UIElement> ByCell(List cells) + { + var shown = cells + .Select(c => (c.Control, Parsed: TryParse(c.Text, out var row, out var column, out _), Row: row, Column: column)) + .Where(c => c.Parsed); + // Indexer writes, not ToDictionary: two controls showing one cell must not throw + // here, because Verify has already failed the step for it. + var map = new Dictionary<(int, int), UIElement>(); + foreach (var s in shown) + map[(s.Row, s.Column)] = s.Control; + return map; + } + + var was = ByCell(before); + var now = ByCell(after); + int survivors = 0; + var remounted = new List(); + foreach (var (cell, control) in was) + { + if (!now.TryGetValue(cell, out var current)) continue; + survivors++; + if (!ReferenceEquals(control, current) || _mounts.GetValueOrDefault(cell) != 1) + remounted.Add($"({cell.Item1},{cell.Item2}) x{_mounts.GetValueOrDefault(cell)}"); + } + + H.Check($"{Name}_{step}_SurvivorsKeptTheirControl", survivors == was.Count && remounted.Count == 0, + $"{survivors} of {was.Count} cells survived; remounted: {Summarize(remounted)}"); + } + + private static string Summarize(List items) => + items.Count == 0 ? "none" : string.Join("; ", items.Take(6)) + (items.Count > 6 ? "; ..." : ""); + } + + // ── Unmount callback ──────────────────────────────────────────────── + + private sealed record ProbeElement(string Label) : Element; + + /// + /// Registers as a Border around a TextBlock, the shape of the + /// docking host, with an unmount callback that records the control it was handed. + /// + internal abstract class UnmountProbeFixture(Harness h) : SelfTestFixtureBase(h) + { + /// Every control a callback created, mount first, in creation order. + protected List Created { get; } = new(); + + protected List Unmounted { get; } = new(); + + /// + /// How the registration's update callback answers when the label changes: + /// null (patched in place), the same control, or a new control. + /// + protected virtual UpdateResult OnRename => UpdateResult.PatchInPlace; + + protected enum UpdateResult { PatchInPlace, SameControl, NewControl } + + protected ReactorHost CreateHost() + { + var host = H.CreateHost(); + host.Reconciler.RegisterType( + mount: (_, probe, _) => Create(probe.Label), + update: (_, oldProbe, newProbe, border, _) => + { + if (oldProbe.Label == newProbe.Label) return null; + switch (OnRename) + { + case UpdateResult.NewControl: + return Create(newProbe.Label); + case UpdateResult.SameControl: + ((WinXC.TextBlock)border.Child).Text = newProbe.Label; + return border; + default: + ((WinXC.TextBlock)border.Child).Text = newProbe.Label; + return null; + } + }, + unmount: (_, border) => Unmounted.Add(border)); + return host; + } + + private WinXC.Border Create(string label) + { + var border = new WinXC.Border { Child = new WinXC.TextBlock { Text = label } }; + Created.Add(border); + return border; + } + + /// The Border hosting the TextBlock that shows , if mounted. + protected WinXC.Border? FindProbe(string label) => + H.FindText(label)?.Parent as WinXC.Border; + + protected static string Describe(List controls, List created) => + controls.Count == 0 + ? "none" + : string.Join(", ", controls.Select(c => created.IndexOf(c) is var i and >= 0 ? $"#{i}" : "foreign")); + } + + /// + /// Renames an unkeyed probe (an in-place update) and then removes it from its panel, which + /// tears it down through RemoveChildWithExitTransition → UnmountAndCollect. + /// Unkeyed and callback-free, the element fails every NeedsTag test, so only the + /// registration's unmount callback can be the reason it is tagged. + /// + internal sealed class UnkeyedRemoved(Harness h) : UnmountProbeFixture(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Unmount_UnkeyedRemoved"; + var host = CreateHost(); + host.Mount(ctx => + { + var (label, setLabel) = ctx.UseState("rtt-unkeyed-a"); + var (show, setShow) = ctx.UseState(true); + var children = new List + { + Button("RTT Rename", () => setLabel("rtt-unkeyed-b")), + Button("RTT Remove", () => setShow(false)), + }; + if (show) children.Add(new ProbeElement(label)); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + H.Check($"{Name}_Mounted", Created.Count == 1 && FindProbe("rtt-unkeyed-a") is { } first + && ReferenceEquals(first, Created[0]), $"created {Created.Count}"); + + H.ClickButton("RTT Rename"); + H.Check($"{Name}_Renamed", await Harness.WaitFor(() => FindProbe("rtt-unkeyed-b") is not null)); + H.Check($"{Name}_UpdatedInPlace", Created.Count == 1 && ReferenceEquals(FindProbe("rtt-unkeyed-b"), Created[0]), + $"created {Created.Count}"); + H.Check($"{Name}_NotUnmountedByUpdate", Unmounted.Count == 0, + $"unmounted: {Describe(Unmounted, Created)}"); + + H.ClickButton("RTT Remove"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => FindProbe("rtt-unkeyed-b") is null)); + H.Check($"{Name}_UnmountCallbackRanOnce", + Unmounted.Count == 1 && ReferenceEquals(Unmounted[0], Created[0]), + $"unmount callback saw: {Describe(Unmounted, Created)}; expected #0 exactly once"); + } + } + + /// + /// A keyed probe removed from a keyed panel. The key alone qualifies it for a tag. + /// + internal sealed class KeyedRemoved(Harness h) : UnmountProbeFixture(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Unmount_KeyedRemoved"; + var host = CreateHost(); + host.Mount(ctx => + { + var (show, setShow) = ctx.UseState(true); + var children = new List + { + Button("RTT Remove keyed", () => setShow(false)).WithKey("remove"), + TextBlock("rtt-keyed-sibling").WithKey("sibling"), + }; + if (show) children.Insert(1, new ProbeElement("rtt-keyed").WithKey("probe")); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + H.Check($"{Name}_Mounted", Created.Count == 1 && ReferenceEquals(FindProbe("rtt-keyed"), Created[0]), + $"created {Created.Count}"); + + H.ClickButton("RTT Remove keyed"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => FindProbe("rtt-keyed") is null)); + H.Check($"{Name}_SiblingKept", H.FindText("rtt-keyed-sibling") is not null); + H.Check($"{Name}_UnmountCallbackRanOnce", + Unmounted.Count == 1 && ReferenceEquals(Unmounted[0], Created[0]), + $"unmount callback saw: {Describe(Unmounted, Created)}; expected #0 exactly once"); + } + } + + /// + /// The probe's slot switches to another element type, so the positional reconcile mounts + /// the replacement and tears the probe down through UnmountRecursive. + /// + internal sealed class ReplacedByOtherType(Harness h) : UnmountProbeFixture(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Unmount_ReplacedByOtherType"; + var host = CreateHost(); + host.Mount(ctx => + { + var (swapped, setSwapped) = ctx.UseState(false); + return VStack( + Button("RTT Swap", () => setSwapped(true)), + swapped ? (Element)TextBlock("rtt-replacement") : new ProbeElement("rtt-replaced")); + }); + + await Harness.Render(); + H.Check($"{Name}_Mounted", Created.Count == 1 && ReferenceEquals(FindProbe("rtt-replaced"), Created[0]), + $"created {Created.Count}"); + + H.ClickButton("RTT Swap"); + H.Check($"{Name}_Swapped", await Harness.WaitFor(() => H.FindText("rtt-replacement") is not null + && FindProbe("rtt-replaced") is null)); + H.Check($"{Name}_UnmountCallbackRanOnce", + Unmounted.Count == 1 && ReferenceEquals(Unmounted[0], Created[0]), + $"unmount callback saw: {Describe(Unmounted, Created)}; expected #0 exactly once"); + } + } + + /// + /// The probe is the host's root and the root is replaced, which is how an app swaps a whole + /// scene: Reconcile → ReconcileImperative → Unmount. + /// + internal sealed class RootReplaced(Harness h) : UnmountProbeFixture(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Unmount_RootReplaced"; + var host = CreateHost(); + host.Mount(_ => new ProbeElement("rtt-root")); + await Harness.Render(); + H.Check($"{Name}_Mounted", Created.Count == 1 && ReferenceEquals(FindProbe("rtt-root"), Created[0]), + $"created {Created.Count}"); + + host.Mount(_ => TextBlock("rtt-root-replaced")); + H.Check($"{Name}_Swapped", await Harness.WaitFor(() => H.FindText("rtt-root-replaced") is not null)); + H.Check($"{Name}_UnmountCallbackRanOnce", + Unmounted.Count == 1 && ReferenceEquals(Unmounted[0], Created[0]), + $"unmount callback saw: {Describe(Unmounted, Created)}; expected #0 exactly once"); + } + } + + private sealed record ContainerElement : Element; + + private sealed record DeclaredUIElementElement(string Label) : Element; + + /// + /// RegisterType lets TControl be declared as . The tag + /// lives on , which in WinUI 3 every UIElement is, so such a + /// registration is tagged and gets its unmount like any other. + /// + internal sealed class DeclaredUIElementControl(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_DeclaredUIElementControl"; + UIElement? mounted = null; + var unmounted = new List(); + var host = H.CreateHost(); + host.Reconciler.RegisterType( + mount: (_, el, _) => + { + UIElement text = new WinXC.TextBlock { Text = el.Label }; + mounted = text; + return text; + }, + update: (_, _, el, control, _) => + { + ((WinXC.TextBlock)control).Text = el.Label; + return null; + }, + unmount: (_, control) => unmounted.Add(control)); + host.Mount(ctx => + { + var (show, setShow) = ctx.UseState(true); + var children = new List { Button("RTT Remove declared", () => setShow(false)) }; + if (show) children.Add(new DeclaredUIElementElement("rtt-declared-uielement")); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + H.Check($"{Name}_Tagged", + mounted is FrameworkElement fe && Reconciler.GetElementTag(fe) is DeclaredUIElementElement, + $"mounted {mounted?.GetType().Name ?? "nothing"}, tag {(mounted is FrameworkElement f ? Reconciler.GetElementTag(f)?.GetType().Name ?? "null" : "n/a")}"); + + H.ClickButton("RTT Remove declared"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => H.FindText("rtt-declared-uielement") is null)); + H.Check($"{Name}_UnmountCallbackRanOnce", unmounted.Count == 1 && ReferenceEquals(unmounted[0], mounted), + $"unmount callback ran {unmounted.Count} times"); + } + } + + private sealed class ContainedProbe : Component + { + public static int Cleanups; + + public override Element Render() + { + UseEffect(() => { return () => { Cleanups++; }; }); + return TextBlock("rtt-contained-child"); + } + } + + /// + /// A registration mounts a child through the reconciler into its own Border, and its + /// unmount tears that child down by unmounting the Border itself. That re-enters the + /// unmount path for the same control, which must walk the Border's children once instead + /// of calling unmount again, recursively and without end. + /// + internal sealed class UnmountCallbackUnmountsItsControl(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Unmount_CallbackUnmountsItsControl"; + ContainedProbe.Cleanups = 0; + int unmounts = 0; + var host = H.CreateHost(); + host.Reconciler.RegisterType( + mount: (r, _, rerender) => new WinXC.Border { Child = r.Mount(Component(), rerender)! }, + update: (_, _, _, _, _) => null, + unmount: (r, border) => + { + unmounts++; + r.UnmountChild(border); + }); + host.Mount(ctx => + { + var (show, setShow) = ctx.UseState(true); + var children = new List { Button("RTT Remove container", () => setShow(false)) }; + if (show) children.Add(new ContainerElement()); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + H.Check($"{Name}_Mounted", H.FindText("rtt-contained-child") is not null); + + H.ClickButton("RTT Remove container"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => H.FindText("rtt-contained-child") is null)); + H.Check($"{Name}_UnmountCallbackRanOnce", unmounts == 1, $"unmount callback ran {unmounts} times"); + H.Check($"{Name}_ChildCleanedUpOnce", ContainedProbe.Cleanups == 1, + $"the contained component's effect cleanup ran {ContainedProbe.Cleanups} times"); + } + } + + /// + /// An update callback that returns the control it was given, instead of null, patched + /// that control in place. The child reconcilers read any non-null result as a replacement + /// and unmount the control they hold, so without normalizing the result the now-reachable + /// unmount callback would run against a control that stays mounted. + /// + internal sealed class UpdateReturnsSameControl(Harness h) : UnmountProbeFixture(h) + { + protected override UpdateResult OnRename => UpdateResult.SameControl; + + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Update_SameControlStaysMounted"; + var host = CreateHost(); + host.Mount(ctx => + { + var (label, setLabel) = ctx.UseState("rtt-same-a"); + var (show, setShow) = ctx.UseState(true); + var children = new List + { + Button("RTT Rename same", () => setLabel("rtt-same-b")), + Button("RTT Remove same", () => setShow(false)), + }; + if (show) children.Add(new ProbeElement(label)); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + H.Check($"{Name}_Mounted", Created.Count == 1 && ReferenceEquals(FindProbe("rtt-same-a"), Created[0]), + $"created {Created.Count}"); + + H.ClickButton("RTT Rename same"); + H.Check($"{Name}_Renamed", await Harness.WaitFor(() => FindProbe("rtt-same-b") is not null)); + H.Check($"{Name}_StillTheSameControl", ReferenceEquals(FindProbe("rtt-same-b"), Created[0])); + H.Check($"{Name}_NotUnmountedByUpdate", Unmounted.Count == 0, + $"unmount callback ran for a control that is still mounted: {Describe(Unmounted, Created)}"); + + H.ClickButton("RTT Remove same"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => FindProbe("rtt-same-b") is null)); + H.Check($"{Name}_UnmountCallbackRanOnce", + Unmounted.Count == 1 && ReferenceEquals(Unmounted[0], Created[0]), + $"unmount callback saw: {Describe(Unmounted, Created)}; expected #0 exactly once"); + } + } + + /// + /// An update callback that returns a new control replaces the old one. The old control + /// is unmounted at once; the replacement, which the callback built rather than + /// mount, has to be tagged too, or its own unmount never runs. + /// + internal sealed class UpdateReturnsReplacement(Harness h) : UnmountProbeFixture(h) + { + protected override UpdateResult OnRename => UpdateResult.NewControl; + + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Update_ReplacementUnmountedLater"; + var host = CreateHost(); + host.Mount(ctx => + { + var (label, setLabel) = ctx.UseState("rtt-new-a"); + var (show, setShow) = ctx.UseState(true); + var children = new List + { + Button("RTT Rename new", () => setLabel("rtt-new-b")), + Button("RTT Remove new", () => setShow(false)), + }; + if (show) children.Add(new ProbeElement(label)); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + H.Check($"{Name}_Mounted", Created.Count == 1 && ReferenceEquals(FindProbe("rtt-new-a"), Created[0]), + $"created {Created.Count}"); + + H.ClickButton("RTT Rename new"); + H.Check($"{Name}_Renamed", await Harness.WaitFor(() => FindProbe("rtt-new-b") is not null)); + H.Check($"{Name}_ReplacementInstalled", Created.Count == 2 && ReferenceEquals(FindProbe("rtt-new-b"), Created[1]), + $"created {Created.Count}"); + H.Check($"{Name}_ReplacedControlUnmounted", + Unmounted.Count == 1 && ReferenceEquals(Unmounted[0], Created[0]), + $"unmount callback saw: {Describe(Unmounted, Created)}; expected #0"); + + H.ClickButton("RTT Remove new"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => FindProbe("rtt-new-b") is null)); + H.Check($"{Name}_ReplacementUnmounted", + Unmounted.Count == 2 && ReferenceEquals(Unmounted[1], Created[1]), + $"unmount callback saw: {Describe(Unmounted, Created)}; expected #0 then #1"); + } + } + + // ── .Ref(...) on a registered type ────────────────────────────────── + + private sealed record PlainElement(string Label) : Element; + + /// + /// ElementRef.Current is documented to go null when the referenced element unmounts + /// without a replacement. The unmount path clears it through the element tag, and the + /// registration has no unmount, so the reference modifier is the only reason to tag. + /// + internal sealed class RefClearedOnUnmount(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Ref_ClearedOnUnmount"; + WinXC.TextBlock? mounted = null; + var target = new ElementRef(); + var host = H.CreateHost(); + host.Reconciler.RegisterType( + mount: (_, plain, _) => + { + var text = new WinXC.TextBlock { Text = plain.Label }; + mounted = text; + return text; + }, + update: (_, _, plain, text, _) => + { + text.Text = plain.Label; + return null; + }); + host.Mount(ctx => + { + var (show, setShow) = ctx.UseState(true); + var children = new List { Button("RTT Remove ref", () => setShow(false)) }; + if (show) children.Add(new PlainElement("rtt-ref-target").Ref(target)); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + H.Check($"{Name}_RefSetOnMount", mounted is not null && ReferenceEquals(target.Current, mounted)); + + H.ClickButton("RTT Remove ref"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => H.FindText("rtt-ref-target") is null)); + H.Check($"{Name}_RefClearedOnUnmount", target.Current is null, + $"ref still points at a {target.Current?.GetType().Name ?? "null"} showing '{(target.Current as WinXC.TextBlock)?.Text}'"); + } + } + + /// + /// When update replaces the control, the reconciler points the element's ref at the + /// replacement before the child reconciler unmounts the old control. Now that the old + /// control is tagged, its unmount must leave a ref that has already moved on alone. + /// + internal sealed class RefFollowsReplacement(Harness h) : UnmountProbeFixture(h) + { + protected override UpdateResult OnRename => UpdateResult.NewControl; + + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_Ref_FollowsReplacement"; + var target = new ElementRef(); + var host = CreateHost(); + host.Mount(ctx => + { + var (label, setLabel) = ctx.UseState("rtt-refnew-a"); + var (show, setShow) = ctx.UseState(true); + var children = new List + { + Button("RTT Rename refnew", () => setLabel("rtt-refnew-b")), + Button("RTT Remove refnew", () => setShow(false)), + }; + if (show) children.Add(new ProbeElement(label).Ref(target)); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + H.Check($"{Name}_RefSetOnMount", Created.Count == 1 && ReferenceEquals(target.Current, Created[0]), + $"ref points at {DescribeRef(target)}"); + + H.ClickButton("RTT Rename refnew"); + H.Check($"{Name}_Renamed", await Harness.WaitFor(() => FindProbe("rtt-refnew-b") is not null)); + H.Check($"{Name}_RefFollowsReplacement", Created.Count == 2 && ReferenceEquals(target.Current, Created[1]), + $"ref points at {DescribeRef(target)}; expected #1"); + + H.ClickButton("RTT Remove refnew"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => FindProbe("rtt-refnew-b") is null)); + H.Check($"{Name}_RefClearedOnUnmount", target.Current is null, + $"ref points at {DescribeRef(target)}"); + } + + private string DescribeRef(ElementRef target) => target.Current switch + { + null => "null", + WinXC.Border border => Describe([border], Created), + var other => other.GetType().Name, + }; + } + + // ── Element extras on a registered type ───────────────────────────── + + private sealed record ExitProbeElement(string Label) : Element; + + /// + /// An element extra makes the element need its tag even when it is unkeyed and its + /// registration has no unmount: RemoveChildWithExitTransition reads the + /// .Transition(...) exit animation back from the tag when the control is removed. The + /// transition is exit-only, so nothing touches the control's composition visual before + /// removal, and playing the exit animation marks the control compositor-tainted. That taint + /// is the oracle for the removal having taken the transition path, and it doesn't depend on + /// the animation finishing: completion is ExitTransitionOnRemove's job, and issue + /// #1037 tracks its flake. + /// + internal sealed class ExitTransitionReadFromTag(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_ExitTransition_ReadFromTag"; + var exitOnly = ReactorTransition.Exit(ReactorTransition.Fade); + WinXC.TextBlock? control = null; + Element? rendered = null; + var host = H.CreateHost(); + host.Reconciler.RegisterType( + mount: (_, el, _) => + { + var text = new WinXC.TextBlock { Text = el.Label }; + control = text; + return text; + }, + update: (_, _, el, text, _) => + { + text.Text = el.Label; + return null; + }); + host.Mount(ctx => + { + var (label, setLabel) = ctx.UseState("rtt-exit-a"); + var (show, setShow) = ctx.UseState(true); + var children = new List + { + Button("RTT Rename exit", () => setLabel("rtt-exit-b")), + Button("RTT Remove exit", () => setShow(false)), + }; + if (show) children.Add(rendered = new ExitProbeElement(label).Transition(exitOnly)); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + CheckTag($"{Name}_Mount_TaggedWithCurrentElement", control, rendered); + H.Check($"{Name}_Mount_VisualUntouched", control is not null && !ElementPool.IsCompositorTainted(control)); + + H.ClickButton("RTT Rename exit"); + H.Check($"{Name}_Renamed", await Harness.WaitFor(() => control?.Text == "rtt-exit-b")); + CheckTag($"{Name}_Update_TaggedWithCurrentElement", control, rendered); + + H.ClickButton("RTT Remove exit"); + await Harness.Render(); + H.Check($"{Name}_RemovalPlayedExitTransition", control is not null && ElementPool.IsCompositorTainted(control), + "the control was removed without its exit transition"); + } + + private void CheckTag(string check, WinXC.TextBlock? control, Element? expected) + { + var tag = control is null ? null : Reconciler.GetElementTag(control); + H.Check(check, control is not null && expected is not null && ReferenceEquals(tag, expected), + control is null ? "control never mounted" : $"tag is {(tag is null ? "null" : tag.GetType().Name)}"); + } + } + + // ── A control that belongs to another element ─────────────────────── + + private sealed record DelegatingElement(string Label, Action OnClick) : Element; + + /// + /// A registration may hand back the control the reconciler mounted for another element, + /// here a Button. That control's tag belongs to the ButtonElement: its click + /// trampoline resolves the live element through it. Tagging it with the registered + /// element would silence the click, so the reconciler leaves the tag alone. The + /// registration has an unmount callback, so it would otherwise always tag. + /// + internal sealed class DelegatedControlKeepsItsTag(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_DelegatedControl_KeepsItsTag"; + int clicks = 0; + static Element Inner(DelegatingElement el) => Button(el.Label, el.OnClick); + + var host = H.CreateHost(); + host.Reconciler.RegisterType( + mount: (r, el, rerender) => r.Mount(Inner(el), rerender)!, + update: (r, oldEl, newEl, control, rerender) => r.UpdateChild(Inner(oldEl), Inner(newEl), control, rerender), + unmount: (_, _) => { }); + host.Mount(ctx => + { + var (label, setLabel) = ctx.UseState("rtt-delegated-a"); + return VStack( + Button("RTT Rename delegated", () => setLabel("rtt-delegated-b")), + new DelegatingElement(label, () => clicks++)); + }); + + await Harness.Render(); + CheckButtonTag($"{Name}_Mount_KeepsButtonTag", "rtt-delegated-a"); + H.ClickButton("rtt-delegated-a"); + H.Check($"{Name}_Mount_ClickDispatches", await Harness.WaitFor(() => clicks == 1), $"clicks: {clicks}"); + + H.ClickButton("RTT Rename delegated"); + H.Check($"{Name}_Renamed", await Harness.WaitFor(() => H.FindButton("rtt-delegated-b") is not null)); + CheckButtonTag($"{Name}_Update_KeepsButtonTag", "rtt-delegated-b"); + H.ClickButton("rtt-delegated-b"); + H.Check($"{Name}_Update_ClickDispatches", await Harness.WaitFor(() => clicks == 2), $"clicks: {clicks}"); + } + + private void CheckButtonTag(string check, string label) + { + var button = H.FindButton(label); + var tag = button is null ? null : Reconciler.GetElementTag(button); + H.Check(check, tag is ButtonElement, + button is null ? "button not mounted" : $"tag is {tag?.GetType().Name ?? "null"}"); + } + } + + private record BaseDelegatingElement(string Label) : Element; + + private sealed record DerivedOwnedElement(string Label) : BaseDelegatingElement(Label); + + /// + /// Registration is by exact element type, so a base and a derived element type can be + /// registered separately. A base registration that hands back the control it mounted for + /// the derived type must leave the derived element's tag alone: that tag is how the derived + /// registration's unmount is found, and overwriting it runs the base one instead. + /// + internal sealed class DelegatedToDerivedTypeKeepsItsTag(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + const string Name = "RegisterTypeTag_DelegatedToDerivedType_KeepsItsTag"; + int baseUnmounts = 0, derivedUnmounts = 0; + var host = H.CreateHost(); + host.Reconciler.RegisterType( + mount: (_, el, _) => new WinXC.TextBlock { Text = el.Label }, + update: (_, _, el, text, _) => + { + text.Text = el.Label; + return null; + }, + unmount: (_, _) => derivedUnmounts++); + host.Reconciler.RegisterType( + mount: (r, el, rerender) => r.Mount(new DerivedOwnedElement(el.Label), rerender)!, + update: (r, oldEl, newEl, control, rerender) => + r.UpdateChild(new DerivedOwnedElement(oldEl.Label), new DerivedOwnedElement(newEl.Label), control, rerender), + unmount: (_, _) => baseUnmounts++); + host.Mount(ctx => + { + var (label, setLabel) = ctx.UseState("rtt-derived-a"); + var (show, setShow) = ctx.UseState(true); + var children = new List + { + Button("RTT Rename derived", () => setLabel("rtt-derived-b")), + Button("RTT Remove derived", () => setShow(false)), + }; + if (show) children.Add(new BaseDelegatingElement(label)); + return VStack(children.ToArray()); + }); + + await Harness.Render(); + CheckDerivedTag($"{Name}_Mount_KeepsDerivedTag", "rtt-derived-a"); + + H.ClickButton("RTT Rename derived"); + H.Check($"{Name}_Renamed", await Harness.WaitFor(() => H.FindText("rtt-derived-b") is not null)); + CheckDerivedTag($"{Name}_Update_KeepsDerivedTag", "rtt-derived-b"); + + H.ClickButton("RTT Remove derived"); + H.Check($"{Name}_Removed", await Harness.WaitFor(() => H.FindText("rtt-derived-b") is null)); + H.Check($"{Name}_OwnerUnmountRan", derivedUnmounts == 1 && baseUnmounts == 0, + $"derived unmount ran {derivedUnmounts} times, base unmount {baseUnmounts} times"); + } + + private void CheckDerivedTag(string check, string label) + { + var text = H.FindText(label); + var tag = text is null ? null : Reconciler.GetElementTag(text); + H.Check(check, tag is DerivedOwnedElement derived && derived.Label == label, + text is null ? "control not mounted" : $"tag is {tag?.GetType().Name ?? "null"}"); + } + } + + // ── Which registered controls carry a tag ─────────────────────────── + + private sealed record SlotElement(string Slot, int Generation) : Element; + + private sealed record ManualTagElement(string Label) : Element; + + /// + /// Reads the tag directly. A keyed element and an element whose registration has an + /// unmount callback are tagged at mount and re-tagged with the new element on update. + /// An unkeyed, modifier-free element whose registration has no unmount is not tagged: + /// nothing reads it back, and a ReactorState per leaf is the allocation #468 removed. + /// That holds whether its update returns null, the control it was handed, or a + /// replacement: telling a second wrapper for the same control from a replacement allocates + /// only on the control being replaced. A registration that tags by hand, as + /// XamlInterop does, keeps working. + /// + internal sealed class TagOnlyWhereRead(Harness h) : SelfTestFixtureBase(h) + { + private const string Name = "RegisterTypeTag_TagOnlyWhereRead"; + + private readonly Dictionary _slots = new(); + private readonly Dictionary _rendered = new(); + private WinXC.Border? _probe; + private WinXC.TextBlock? _manual; + + public override async Task RunAsync() + { + var host = H.CreateHost(); + host.Reconciler.RegisterType( + mount: (_, slot, _) => + { + var text = new WinXC.TextBlock { Text = $"{slot.Slot}@{slot.Generation}" }; + _slots[slot.Slot] = text; + return text; + }, + update: (_, _, slot, text, _) => + { + var label = $"{slot.Slot}@{slot.Generation}"; + switch (slot.Slot) + { + case "same": + text.Text = label; + return text; + case "replaced": + var replacement = new WinXC.TextBlock { Text = label }; + _slots[slot.Slot] = replacement; + return replacement; + default: + text.Text = label; + return null; + } + }); + host.Reconciler.RegisterType( + mount: (_, probe, _) => + { + var border = new WinXC.Border { Child = new WinXC.TextBlock { Text = probe.Label } }; + _probe = border; + return border; + }, + update: (_, _, probe, border, _) => + { + ((WinXC.TextBlock)border.Child).Text = probe.Label; + return null; + }, + unmount: (_, _) => { }); + host.Reconciler.RegisterType( + mount: (_, el, _) => + { + var text = new WinXC.TextBlock { Text = el.Label }; + Reconciler.SetElementTag(text, el); + _manual = text; + return text; + }, + update: (_, _, el, text, _) => + { + text.Text = el.Label; + Reconciler.SetElementTag(text, el); + return null; + }); + + host.Mount(ctx => + { + var (generation, setGeneration) = ctx.UseState(0); + return VStack( + Button("RTT Rerender", () => setGeneration(1)), + Track("plain", new SlotElement("plain", generation)), + Track("same", new SlotElement("same", generation)), + Track("replaced", new SlotElement("replaced", generation)), + Track("keyed", new SlotElement("keyed", generation).WithKey("keyed")), + Track("unmount", new ProbeElement($"rtt-with-unmount@{generation}")), + Track("manual", new ManualTagElement($"rtt-manual@{generation}"))); + }); + + await Harness.Render(); + Verify("Mount"); + var sameAtMount = _slots["same"]; + var replacedAtMount = _slots["replaced"]; + + H.ClickButton("RTT Rerender"); + H.Check($"{Name}_Rerendered", await Harness.WaitFor(() => + _slots["plain"].Text == "plain@1" && _slots["same"].Text == "same@1" + && H.FindText("replaced@1") is not null && _slots["keyed"].Text == "keyed@1" + && H.FindText("rtt-with-unmount@1") is not null && _manual?.Text == "rtt-manual@1")); + H.Check($"{Name}_Update_SameControlKept", + ReferenceEquals(_slots["same"], sameAtMount) && ReferenceEquals(H.FindText("same@1"), sameAtMount)); + H.Check($"{Name}_Update_ReplacementInstalled", + !ReferenceEquals(_slots["replaced"], replacedAtMount) && ReferenceEquals(H.FindText("replaced@1"), _slots["replaced"])); + Verify("Update"); + } + + private Element Track(string slot, Element element) + { + _rendered[slot] = element; + return element; + } + + private void Verify(string step) + { + CheckNoState($"{Name}_{step}_UnkeyedWithoutUnmount_NoReactorState", _slots["plain"]); + CheckNoState($"{Name}_{step}_UnkeyedWithoutUnmount_UpdateReturnsSame_NoReactorState", _slots["same"]); + CheckNoState($"{Name}_{step}_UnkeyedWithoutUnmount_UpdateReturnsNew_NoReactorState", _slots["replaced"]); + CheckTag($"{Name}_{step}_Keyed_TaggedWithCurrentElement", _slots["keyed"], _rendered["keyed"]); + CheckTag($"{Name}_{step}_WithUnmount_TaggedWithCurrentElement", _probe, _rendered["unmount"]); + CheckTag($"{Name}_{step}_ManualTag_TaggedWithCurrentElement", _manual, _rendered["manual"]); + } + + private void CheckNoState(string check, WinXC.TextBlock control) => + H.Check(check, !Reconciler.TryGetReactorState(control, out var state), + $"allocated a ReactorState tagged with {state?.Element?.GetType().Name ?? "null"}"); + + private void CheckTag(string check, FrameworkElement? control, Element expected) + { + var tag = control is null ? null : Reconciler.GetElementTag(control); + H.Check(check, control is not null && ReferenceEquals(tag, expected), + control is null + ? "control never mounted" + : $"tag is {(tag is null ? "null" : ReferenceEquals(tag, expected) ? "current" : "a stale or foreign " + tag.GetType().Name)}"); + } + } +} diff --git a/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs b/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs index a6d3195684..67db908f33 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs @@ -422,6 +422,23 @@ internal static class SelfTestFixtureRegistry // TypeRegistration mismatch regression "Reconciler_TypeMismatch_UpdateFallback", "Reconciler_TypeMismatch_UnmountSkip", + // RegisterType controls carry their element tag without the callbacks setting it: + // keyed identity, the unmount callback, and .Ref(...) cleanup all read it back. + "RegisterTypeTag_KeyedGrid_GrowAndReverse", + "RegisterTypeTag_Unmount_UnkeyedRemoved", + "RegisterTypeTag_Unmount_KeyedRemoved", + "RegisterTypeTag_Unmount_ReplacedByOtherType", + "RegisterTypeTag_Unmount_RootReplaced", + "RegisterTypeTag_Unmount_CallbackUnmountsItsControl", + "RegisterTypeTag_DeclaredUIElementControl", + "RegisterTypeTag_Update_SameControlStaysMounted", + "RegisterTypeTag_Update_ReplacementUnmountedLater", + "RegisterTypeTag_Ref_ClearedOnUnmount", + "RegisterTypeTag_Ref_FollowsReplacement", + "RegisterTypeTag_ExitTransition_ReadFromTag", + "RegisterTypeTag_DelegatedControl_KeepsItsTag", + "RegisterTypeTag_DelegatedToDerivedType_KeepsItsTag", + "RegisterTypeTag_TagOnlyWhereRead", // Control catalog — mount/unmount every control type "ControlCatalog_MountUnmountAll", // Reconciler stress tests — target uncovered branches @@ -2352,6 +2369,22 @@ internal static string[] StaleTierDeclarations() => // TypeRegistration mismatch regression "Reconciler_TypeMismatch_UpdateFallback" => new TypeRegistrationMismatchFixtures.UpdateControlTypeMismatch(harness), "Reconciler_TypeMismatch_UnmountSkip" => new TypeRegistrationMismatchFixtures.UnmountControlTypeMismatch(harness), + // RegisterType controls carry their element tag + "RegisterTypeTag_KeyedGrid_GrowAndReverse" => new RegisterTypeElementTagFixtures.KeyedGridGrowAndReverse(harness), + "RegisterTypeTag_Unmount_UnkeyedRemoved" => new RegisterTypeElementTagFixtures.UnkeyedRemoved(harness), + "RegisterTypeTag_Unmount_KeyedRemoved" => new RegisterTypeElementTagFixtures.KeyedRemoved(harness), + "RegisterTypeTag_Unmount_ReplacedByOtherType" => new RegisterTypeElementTagFixtures.ReplacedByOtherType(harness), + "RegisterTypeTag_Unmount_RootReplaced" => new RegisterTypeElementTagFixtures.RootReplaced(harness), + "RegisterTypeTag_Unmount_CallbackUnmountsItsControl" => new RegisterTypeElementTagFixtures.UnmountCallbackUnmountsItsControl(harness), + "RegisterTypeTag_DeclaredUIElementControl" => new RegisterTypeElementTagFixtures.DeclaredUIElementControl(harness), + "RegisterTypeTag_Update_SameControlStaysMounted" => new RegisterTypeElementTagFixtures.UpdateReturnsSameControl(harness), + "RegisterTypeTag_Update_ReplacementUnmountedLater" => new RegisterTypeElementTagFixtures.UpdateReturnsReplacement(harness), + "RegisterTypeTag_Ref_ClearedOnUnmount" => new RegisterTypeElementTagFixtures.RefClearedOnUnmount(harness), + "RegisterTypeTag_Ref_FollowsReplacement" => new RegisterTypeElementTagFixtures.RefFollowsReplacement(harness), + "RegisterTypeTag_ExitTransition_ReadFromTag" => new RegisterTypeElementTagFixtures.ExitTransitionReadFromTag(harness), + "RegisterTypeTag_DelegatedControl_KeepsItsTag" => new RegisterTypeElementTagFixtures.DelegatedControlKeepsItsTag(harness), + "RegisterTypeTag_DelegatedToDerivedType_KeepsItsTag" => new RegisterTypeElementTagFixtures.DelegatedToDerivedTypeKeepsItsTag(harness), + "RegisterTypeTag_TagOnlyWhereRead" => new RegisterTypeElementTagFixtures.TagOnlyWhereRead(harness), // Control catalog "ControlCatalog_MountUnmountAll" => new ControlCatalogFixtures.MountUnmountAllControls(harness), // Reconciler stress tests