Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,24 @@ Conventions for contributors:

### Fixed

- **Unmount callbacks survive managed-wrapper collection** (spec 047 §3).
`.OnUnmount(...)` now lives in native attached state rather than a weak table
keyed by a managed wrapper, so a still-mounted control keeps its teardown callback
when WinRT projects a new wrapper before removal. Callbacks stay scoped to the host
that registered them. A wrapper that shares its control with an inner target, as
`Flyout` does, no longer erases the target's callback when the wrapper has no callback
of its own, or drops its own while the target re-registers.

- **Keyed-list diagnostics retain their native control identity** (spec 047 §3).
Duplicate/null-key warning counters now share one ledger across managed wrappers
for the same control instead of emitting a second entry after wrapper collection.

- **`AutoSuggestBox` clears stale choices when `Suggestions` becomes empty**
(spec 047 §6.1). The suggestions binding now clears the native `ItemsSource`
instead of skipping empty updates, preserving the existing control and allowing
later suggestions to repopulate it. Empty suggestions leave `ItemsSource` null,
so direct `Items.Add(...)` setters continue to work on mount.

- **Keyed children keep their own controls while siblings exit** (spec 014, feature 2).
Fading controls retained from an earlier render no longer shift keyed prefix, suffix,
removal or reorder updates onto another child's control. Live controls keep their
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -731,10 +731,12 @@ box.
bounded snapshot (newest-first, capped at 64 entries × 8 sample
keys each). Producer side is `internal Record(...)` /
`IsFirstOccurrence(...)` with dedup keyed on
(controlInstance, kind, hashed-sample-set). Per-control dedup
uses a `ConditionalWeakTable` so a torn-down control doesn't
leak; contextual fallback uses a global concurrent dictionary
for unit-test / standalone callers.
(controlInstance, kind, hashed-sample-set). Native-control dedup
lives in `ReactorState.KeyedDiagnosticLedger`, preserving counts
across managed-wrapper collection and pool reuse (#1434).
Non-native objects use a `ConditionalWeakTable`; contextual
fallback uses a global concurrent dictionary for unit-test /
standalone callers. Ledgers never reference their owning controls.
2. **`KeyedListDiff.Apply`** gained a `controlInstance` parameter
and now routes both bailout paths through `ReportBailout`,
which records into the collector *and* logs through `ILogger`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -570,9 +570,9 @@ shrink lands after V1 ships ON by default.
`!ReferenceEquals(o.QueryIcon, n.QueryIcon)` — descriptor's
OneWay path can't see the previous element ref). Same visual
result, slightly more work per pass when QueryIcon is set.
- `AutoSuggestBoxDescriptor.Suggestions` transition to empty
does not clear the previous `ItemsSource` (mirrors the legacy
mount guard's `Length > 0` gate).
- **Resolved (#1434):** `AutoSuggestBoxElement.Suggestions` now uses
ordinary `OneWay`; empty suggestions clear `ItemsSource` to null,
preserving direct `Items.Add(...)` setters on an empty mount.
- `ComboBoxElement.IsDropDownOpen` is not exposed on the element
record itself; descriptor doesn't surface it. (Legacy parity.)
- [x] **Batch 7** — `Viewbox`, `Expander`, `ScrollViewer`, `ScrollView`.
Expand Down
32 changes: 15 additions & 17 deletions src/Reactor/Core/Diagnostics/ReactorDiagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,18 +98,15 @@ public static partial class ReactorDiagnostics
// A buffered entry plus what it was recorded for: the ledger it belongs to (per control,
// or the contextual one) and its dedup key. A repeat updates only its own entry, never
// another control's entry that happens to share the label, kind and samples. Holding the
// ledger does not keep the control alive: the weak table's value never references its key.
// ledger does not keep the control alive: it never references the control or its state.
private sealed class Slot(KeyedListDiagnostic entry, ConcurrentDictionary<long, int> ledger, long dedupKey)
{
public KeyedListDiagnostic Entry = entry;
public readonly ConcurrentDictionary<long, int> Ledger = ledger;
public readonly long DedupKey = dedupKey;
}

// (control instance) → set of (kind | sample-set hash) keys already
// logged. ConditionalWeakTable so a control that's torn down doesn't
// leak its dedup state; a fresh control instance reusing the same type
// gets a fresh ledger.
// Non-native callers retain weak object identity; native ledgers live on ReactorState.
private static readonly ConditionalWeakTable<object, ConcurrentDictionary<long, int>> _seenPerControl = new();

// For diff sites that don't have a control instance (unit tests,
Expand Down Expand Up @@ -140,7 +137,7 @@ public static IReadOnlyList<KeyedListDiagnostic> RecentKeyedListWarnings
}

/// <summary>
/// Drop every captured entry and forget per-control dedup state.
/// Drop every captured entry and contextual dedup state, retaining per-control counts.
/// Tests use this between scenarios; production code never needs to call it.
/// </summary>
public static void ClearRecentKeyedListWarnings()
Expand All @@ -149,11 +146,8 @@ public static void ClearRecentKeyedListWarnings()
{
_recent.Clear();
_seenContextual.Clear();
// ConditionalWeakTable has no Clear in netstandard2.0 / .NET 10
// semantics worth depending on; entries age out naturally with
// their control instance. For test isolation, swap the field —
// but doing so during a live run would race the producer. Tests
// that absolutely need a clean slate construct fresh controls.
// Per-control ledgers retain counts for the control's lifetime.
// Tests that need a clean slate construct fresh controls.
}
}

Expand Down Expand Up @@ -192,9 +186,7 @@ internal static KeyedListDiagnostic Record(
{
// Dedup ledger lookup — per-control for live instances, global
// for context-only callers.
ConcurrentDictionary<long, int> ledger = controlInstance is not null
? _seenPerControl.GetValue(controlInstance, static _ => new ConcurrentDictionary<long, int>())
: _seenContextual;
var ledger = LedgerFor(controlInstance);

if (ledger.TryGetValue(dedupKey, out var existingCount))
{
Expand Down Expand Up @@ -265,13 +257,19 @@ internal static bool IsFirstOccurrence(
var label = controlContext ?? "<unknown>";
long dedupKey = ComputeDedupKey(kind, sampleKeys, label);

ConcurrentDictionary<long, int> ledger = controlInstance is not null
? _seenPerControl.GetValue(controlInstance, static _ => new ConcurrentDictionary<long, int>())
: _seenContextual;
var ledger = LedgerFor(controlInstance);

return !ledger.ContainsKey(dedupKey);
}

private static ConcurrentDictionary<long, int> LedgerFor(object? controlInstance)
{
if (controlInstance is null) return _seenContextual;
if (controlInstance is global::Microsoft.UI.Xaml.FrameworkElement control)
return Reconciler.GetOrCreateReactorState(control).KeyedDiagnosticLedger ??= new();
return _seenPerControl.GetValue(controlInstance, static _ => new ConcurrentDictionary<long, int>());
}

// Dedup key = kind ⊕ samples-hash ⊕ context-label hash. Folding the
// label in is what makes the global `_seenContextual` ledger distinguish
// two different controlContext values that happen to share the same
Expand Down
7 changes: 3 additions & 4 deletions src/Reactor/Core/Element.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1300,7 +1300,7 @@ internal static bool ModifiersEqual(ElementModifiers? a, ElementModifiers? b)
// new one — otherwise the shallow-skip path strands a stale ElementRef.
&& ReferenceEquals(a.Ref, b.Ref)
// Imperative teardown slot (.OnUnmount). ApplyModifiers re-registers the
// latest OnUnmountAction (Reconciler._onUnmountActions) on every non-skip
// latest OnUnmountAction (ReactorState.UnmountAction) on every non-skip
// Update, and that captured delegate is what fires at unmount — so a
// changed teardown closure must decline the skip or the stale (first-render)
// action is stranded and runs in place of the current one. Unlike
Expand Down Expand Up @@ -3874,10 +3874,9 @@ private static void ReleaseExpired(global::Microsoft.UI.Dispatching.DispatcherQu
// reused verbatim from the hand-written descriptor (shared AutoSuggestBoxEventPayload).
private static partial global::Microsoft.UI.Reactor.Core.V1Protocol.Descriptor.ControlDescriptor<AutoSuggestBoxElement, WinUI.AutoSuggestBox> Customize(
global::Microsoft.UI.Reactor.Core.V1Protocol.Descriptor.ControlDescriptor<AutoSuggestBoxElement, WinUI.AutoSuggestBox> d)
=> d.OneWayConditional(
=> d.OneWay(
get: static e => e.Suggestions,
set: static (c, v) => c.ItemsSource = v,
shouldWrite: static e => e.Suggestions.Length > 0)
set: static (c, v) => c.ItemsSource = v.Length > 0 ? v : null)
.HandCodedControlled<global::Microsoft.UI.Reactor.Core.V1Protocol.AutoSuggestBoxEventPayload, string,
global::Windows.Foundation.TypedEventHandler<WinUI.AutoSuggestBox, WinUI.AutoSuggestBoxTextChangedEventArgs>>(
get: static e => e.Text,
Expand Down
68 changes: 42 additions & 26 deletions src/Reactor/Core/Reconciler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ public sealed partial class Reconciler : IDisposable
// look up per-instance navigation state; teardown stays here (Dispose loop +
// CleanupNavigationHostNode).
internal readonly Dictionary<UIElement, NavigationHostNode> _navigationHostNodes = new();
// Per-control unmount actions (.OnUnmount). Captured at ApplyModifiers from the
// authoritative modifier set (same source .OnMount reads), so it doesn't depend
// on the tagged element's identity at teardown. Invoked + removed on unmount.
private readonly global::System.Runtime.CompilerServices.ConditionalWeakTable<FrameworkElement, Action<FrameworkElement>> _onUnmountActions = new();
// Internal so V1-owned lifecycle classes (e.g. LazyStackLifecycle) can rent
// pooled controls and pass the pool into element factories.
internal readonly ElementPool _pool = new();
Expand Down Expand Up @@ -334,11 +330,8 @@ void OnCleanupError(Exception ex)
Diagnostics.ComponentRenderControls.Registry.Forget(node.DiagnosticId, wrapper);
RunUnmountCleanups(node);
}
if (wrapper is FrameworkElement fe && _onUnmountActions.TryGetValue(fe, out var onUnmount))
{
_onUnmountActions.Remove(fe);
RunUnmountAction(onUnmount, fe);
}
if (wrapper is FrameworkElement fe)
RunUnmountAction(fe);
if (_navigationHostNodes.ContainsKey(wrapper))
CleanupNavigationHostNode(wrapper);
}
Expand All @@ -359,6 +352,7 @@ void OnCleanupError(Exception ex)
/// behaviour: the first failure escapes.
/// </summary>
private Action<Exception>? _unmountCleanupErrorSink;
private readonly object _unmountActionOwner = new();

internal IsolatedUnmountScope IsolateUnmountCleanupFailures(Action<Exception> onError)
{
Expand Down Expand Up @@ -386,8 +380,14 @@ private void RunUnmountCleanups(ComponentNode node)
}
}

private void RunUnmountAction(Action<FrameworkElement> onUnmount, FrameworkElement control)
private void RunUnmountAction(FrameworkElement control)
{
if (!TryGetReactorState(control, out var state)
|| !ReferenceEquals(state.UnmountActionOwner, _unmountActionOwner)
|| state.UnmountAction is not { } onUnmount)
return;
state.UnmountAction = null;
state.UnmountActionOwner = null;
if (_unmountCleanupErrorSink is not { } sink)
{
onUnmount(control);
Expand Down Expand Up @@ -1495,6 +1495,10 @@ internal sealed class ReactorState
public Element? Element;
internal ElementTheme? RealizationTheme;
public ModifierEventHandlerState? Modifiers;
// Native identity keeps teardown alive when WinRT replaces a collected managed wrapper.
public Action<FrameworkElement>? UnmountAction;
// Opaque identity scopes callbacks to a reconciler without retaining that reconciler.
public object? UnmountActionOwner;
// Per-native-element echo-suppress counter consumed by ChangeEchoSuppressor.
// Lives here (not in a CWT-by-RCW) so that BeginSuppress on one managed
// wrapper and ShouldSuppress on a different wrapper for the same native
Expand Down Expand Up @@ -1624,6 +1628,9 @@ internal sealed class ReactorState
/// Cleared when the component unmounts, before the wrapper can be pooled.
/// </summary>
public long ComponentDiagnosticId;

// Warning counts follow the native control's lifetime, including pool reuse.
public global::System.Collections.Concurrent.ConcurrentDictionary<long, int>? KeyedDiagnosticLedger;
}

internal static class ReactorAttached
Expand Down Expand Up @@ -2079,6 +2086,8 @@ public static void DetachReactorState(FrameworkElement fe)
if (state.ComponentDiagnosticId != 0)
Diagnostics.ComponentRenderControls.Registry.Forget(state.ComponentDiagnosticId, fe);
state.Element = null;
state.UnmountAction = null;
state.UnmountActionOwner = null;
state.Modifiers?.ClearCurrentHandlers();
state.Modifiers = null;
state.EchoSuppressCount = 0;
Expand Down Expand Up @@ -2454,6 +2463,8 @@ public void ReturnControl<T>(T control, PoolPolicy<T>? policy = null) where T :
rs.EchoSuppressScopeDepth = 0;
rs.PendingEchoMatch = null;
rs.PendingLabeledBy = null;
rs.UnmountAction = null;
rs.UnmountActionOwner = null;
ClearRefreshSnapshots(rs);
rs.Element = null;
}
Expand Down Expand Up @@ -3865,11 +3876,8 @@ private void UnmountRecursive(UIElement control)
WithdrawAttachedValidation(control);

// OnUnmountAction (.OnUnmount) — imperative teardown half of .OnMount.
if (control is FrameworkElement umFe && _onUnmountActions.TryGetValue(umFe, out var onUnmount))
{
_onUnmountActions.Remove(umFe);
RunUnmountAction(onUnmount, umFe);
}
if (control is FrameworkElement umFe)
RunUnmountAction(umFe);

// Issue #917 — a TitleBar going away withdraws both its
// ExtendsContentIntoTitleBar inference and its caption-height
Expand Down Expand Up @@ -4355,11 +4363,8 @@ private void UnmountAndCollect(UIElement control, List<FrameworkElement> toPool)
WithdrawAttachedValidation(control);

// OnUnmountAction (.OnUnmount) — imperative teardown half of .OnMount.
if (control is FrameworkElement umFe && _onUnmountActions.TryGetValue(umFe, out var onUnmount))
{
_onUnmountActions.Remove(umFe);
RunUnmountAction(onUnmount, umFe);
}
if (control is FrameworkElement umFe)
RunUnmountAction(umFe);

// Issue #917 — mirrors UnmountRecursive: a TitleBar reached through the
// pooling traversal (nested in a poolable container) must also withdraw
Expand Down Expand Up @@ -6255,16 +6260,27 @@ internal void ApplyModifiers(FrameworkElement fe, ElementModifiers? oldM, Elemen

// OnUnmountAction — captured here (authoritative modifier set) so it fires
// reliably at teardown regardless of the tagged element's identity. Keep the
// latest action across re-renders; clear unconditionally when absent so a
// pooled control reused for a no-OnUnmount element can't fire a stale action
// (pool reuse remounts with oldM == null, so this can't be gated on oldM).
// latest action across re-renders; don't clear an inner target's registration
// when a shared-control wrapper drops its own callback. Owner identity prevents
// a retained control from firing a disposed reconciler's callback in a new host.
// Known limitation: a shared control has one slot, so a wrapper's callback
// replaces the target's. If the wrapper later drops it while the target update is
// shallow-skipped, nothing re-registers the target's callback and it is lost.
if (m.OnUnmountAction is not null)
{
_onUnmountActions.AddOrUpdate(fe, m.OnUnmountAction);
var callbackState = GetOrCreateReactorState(fe);
callbackState.UnmountAction = m.OnUnmountAction;
callbackState.UnmountActionOwner = _unmountActionOwner;
_boundaryMountJournal?.Add(fe);
}
else
_onUnmountActions.Remove(fe);
else if (oldM?.OnUnmountAction is not null
&& TryGetReactorState(fe, out var unmountState)
&& ReferenceEquals(unmountState.UnmountActionOwner, _unmountActionOwner)
&& ReferenceEquals(unmountState.UnmountAction, oldM.OnUnmountAction))
{
unmountState.UnmountAction = null;
Comment thread
azchohfi marked this conversation as resolved.
Resolved
unmountState.UnmountActionOwner = null;
}

// Element ref — populate on mount/update so imperative APIs (FocusManager.Focus)
// can target the mounted control. Writing on every update is cheap (single field
Expand Down
4 changes: 3 additions & 1 deletion src/Reactor/Elements/ElementExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2882,7 +2882,9 @@ public static T OnMountAdd<T>(this T el, Action<FrameworkElement> action) where
/// the React <c>useEffect</c> cleanup / Compose <c>DisposableEffect { onDispose }</c>
/// shape — for controls that need an imperative stop/dispose (e.g. stopping a
/// camera preview, releasing a media session). Runs on genuine unmount, not on
/// re-render/update.
/// re-render/update. Disposing the host drops its tree without unmounting it, so
/// this callback is not guaranteed to run then. Release anything that must not
/// outlive the host from a <c>UseEffect</c> cleanup, which disposal does run.
/// Usage: CameraPreview(...).OnMount(fe =&gt; Start(fe)).OnUnmount(fe =&gt; Stop(fe))
/// </summary>
public static T OnUnmount<T>(this T el, Action<FrameworkElement> action) where T : Element =>
Expand Down
Loading
Loading