Skip to content

fix(focus): Prevent detached elements from receiving focus - #23753

Merged
morning4coffe-dev merged 3 commits into
masterfrom
dev/doti/focus-detached-elements
Jul 16, 2026
Merged

morning4coffe-dev merged 3 commits into
masterfrom
dev/doti/focus-detached-elements

Conversation

@morning4coffe-dev

@morning4coffe-dev morning4coffe-dev commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

GitHub Issue: closes #23750

PR Type:

🐞 Bugfix

What changed? 🚀

  • Prevents detached or merely logically parented elements from taking keyboard focus on cross-runtime targets.
  • Clears focus when a focused UIElement or Hyperlink leaves the live tree, including direct inline removal/replacement, and makes lifecycle cleanup non-cancellable.
  • Preserves same-tick focus for elements that are already visually attached under an active ancestor while lifecycle activation catches up.
  • Adds regression coverage for detached controls, TextBlock, Hyperlink, inline mutations, stale focus callbacks, flyout content, and focus cleanup.

PR Checklist ✅

Copilot AI review requested due to automatic review settings July 14, 2026 08:31
@github-actions

github-actions Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @morning4coffe-dev's task in 3m 51s —— View job


PR Review: fix(focus): Prevent detached elements from receiving focus

Tasks:

  • Gather context and read changed files
  • Review UIElement.FocusMixins.cs — core fix
  • Review TextBlock.cs and Hyperlink.mux.cs — consumer changes
  • Review Popup.h.mux.cs — consumer change
  • Review Given_FocusManager_DetachedElements.cs — test coverage
  • Post inline comments
  • Write summary

Summary

Verdict: fix-first — the production code is sound; three test-quality issues need attention before merge.

The core approach is correct and well-reasoned. IsActiveOrAttachedUnderActiveAncestor() properly emulates WinUI's IsActive() check while accommodating Uno's deferred lifecycle activation (where a freshly-parented child is one tick behind WinUI's synchronous tree-entry). The #if __CROSSRUNTIME__ guard is exactly the right scope, and the Popup override is explicitly documented to opt out of this check (unrooted popups are never in the live tree but still need to manage focus). The Hyperlink.mux.cs and TextBlock.cs changes consistently apply the same pattern, replacing the old /*IsActive() &&*/ //TODO placeholders with the real implementation.

Issues found (2 blocking, 1 minor):

# Severity Location Issue
1 Minor Given_FocusManager_DetachedElements.cs:16 Missing [GitHubWorkItem("https://github.com/unoplatform/uno/issues/23750")] — per runtime-tests.md convention
2 Concern Given_FocusManager_DetachedElements.cs:20 Production fix is #if __CROSSRUNTIME__ only; no [PlatformCondition] guard on the tests. If native Android/iOS can still focus detached elements (their IsFocusable doesn't get the new check), all three tests will fail on those targets. Needs confirmation or exclusion.
3 Minor Given_FocusManager_DetachedElements.cs:81 When_Stray_Focus_… re-asserts FindFirstFocusableElement nullness already covered by the previous test method; consider trimming the overlap.

Cross-cutting notes:

  • The IsActiveOrAttachedUnderActiveAncestor() ancestor walk is O(tree depth) but only called from focus operations, which are infrequent user interactions — performance impact is negligible.
  • The Hyperlink.mux.cs comment correctly notes that the Hyperlink-as-TextElement side of the IsActive check still has no Uno equivalent; the new change only covers the containing FrameworkElement side. This remaining gap is honestly documented.
  • No event Action violations, no async-void issues, no missing [Uno.NotImplemented] stubs, no edits to Generated files.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aligns Uno’s cross-runtime focusability checks with WinUI by preventing detached UIElements from being considered focusable, while still allowing same-tick focus for freshly attached elements under an active visual ancestor (to account for Uno’s delayed lifecycle activation).

Changes:

  • Gate UIElement.IsFocusable (and TextBlock / Hyperlink focusability) on a new cross-runtime “active or attached under active ancestor” predicate.
  • Add a helper (IsActiveOrAttachedUnderActiveAncestor) to detect “effectively active” elements during the activation gap.
  • Add runtime tests covering focus attempts and focus-candidate searches on detached subtrees.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/Uno.UI/UI/Xaml/UIElement.FocusMixins.cs Adds cross-runtime active/ancestor gating to IsFocusable and introduces IsActiveOrAttachedUnderActiveAncestor().
src/Uno.UI/UI/Xaml/Documents/Hyperlink.mux.cs Applies the new active/ancestor gating to hyperlink focusability (cross-runtime only).
src/Uno.UI/UI/Xaml/Controls/TextBlock/TextBlock.cs Applies the new active/ancestor gating to TextBlock.IsFocusable (cross-runtime only).
src/Uno.UI/UI/Xaml/Controls/Popup/Popup.h.mux.cs Documents why Popup.IsFocusable intentionally does not use an active-tree check.
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Input/Given_FocusManager_DetachedElements.cs Adds runtime coverage for detached focus attempts and focus-candidate search behavior on detached subtrees.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 222192 has failed on Uno.UI - CI.

Copilot AI review requested due to automatic review settings July 14, 2026 13:01
@morning4coffe-dev
morning4coffe-dev force-pushed the dev/doti/focus-detached-elements branch from b8ec37b to 901530b Compare July 14, 2026 13:01
@github-actions

github-actions Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @morning4coffe-dev's task in 9m 13s —— View job


PR Review: fix(focus): Prevent detached elements from receiving focus

Tasks:

  • Gather context and understand the request
  • Read changed production files
  • Read test file
  • Post inline review comments
  • Write summary

Summary

Verdict: fix-first — 3 blocking WASM compile errors in InlineCollection.cs; everything else is sound.

Root cause of CI failure (Uno.UI - CI build 222192):

On WASM, TextElement : UIElement (via BaseClass = UIElement), so InlineCollection._collection is a UIElementCollection whose enumerator and indexer expose UIElement — not Inline. The three new ClearFocusForRemovedInline(Inline) call sites pass UIElement without an explicit cast, giving a type-mismatch compile error on WASM:

File Location Problem
InlineCollection.cs Clear() — foreach body var inline is UIElement, passed to ClearFocusForRemovedInline(Inline)
InlineCollection.cs RemoveAt() _collection[index] is UIElement, same
InlineCollection.cs indexer setter _collection[index] is UIElement, same

The fix is #if !__WASM__ guards at all three sites. On WASM the explicit ClearFocusForRemovedInline calls are redundant anyway — UIElementCollection.RemoveAt already calls item.SetParent(null) which fires the Leave walk, and DependencyObjectStore.LeaveImpl (newly ported in this PR) now handles focus cleanup there. Inline comments with suggested fixes have been posted.

Everything else looks correct:

  • IsActiveOrAttachedUnderActiveAncestor() correctly emulates WinUI's IsActive() while bridging Uno's deferred lifecycle activation via visual-parent walk. Using GetVisualTreeParent() is right — logical parents don't imply live-tree membership.
  • DependencyObjectStore.LeaveImpl focus-cleanup block handles both direct UIElement focus and TextElement-in-FrameworkElement focus (Hyperlink inside TextBlock). The recursive Leave walk ensures the TextBlock's LeaveImpl clears focus even when the root of a removed subtree isn't the direct TextBlock.
  • FocusManager.ClearFocus(canCancel: false) — the _currentFocusOperationCancellable guard at both the finalGettingFocusElement assignment and the args.Cancel check is necessary and correctly prevents LosingFocus handlers from vetoing or redirecting a tree-removal focus clear.
  • Popup.h.mux.cs comment correctly documents the intentional IsActive() opt-out.
  • [PlatformCondition(Exclude, NativeMobile)] is the right scope — native Android/iOS don't get __CROSSRUNTIME__, and the tests on those targets would need the native platform's own focus-on-detach guarantees to hold.
  • Test coverage is thorough: detached focus, FindFirst/LastFocusableElement on detached subtrees, focused-element removal, LosingFocus cancellation resistance, Hyperlink inline removal (three mutation flavors), MenuFlyout, and closed-Flyout content. [GitHubWorkItem] is present on each method.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.

- Guard InlineCollection focus-clearing with #if !__WASM__ so the WASM
  build compiles (_collection is UIElementCollection there, not
  DependencyObjectCollection<Inline>); WASM already clears focus for a
  removed inline via the live Leave walk.
- Attach the XYFocus tree-walker and bubbling test trees to a live window
  so their elements are active and thus focusable under the new
  IsFocusable rule (detached elements are no longer focus candidates).
- Gate the Uno-specific LosingFocus mechanics assertions under HAS_UNO;
  the parity outcome (focus leaves the removed element) is kept for all
  platforms, so native WinUI mirrors the passing sibling test.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: eef860b5-08dd-4c8c-9633-9dd4bed7a23e
Copilot AI review requested due to automatic review settings July 15, 2026 07:17
@github-actions

github-actions Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @morning4coffe-dev's task in 6m 56s —— View job


PR Review: fix(focus): Prevent detached elements from receiving focus

Tasks:

  • Gather context from PR history and changed files list
  • Read InlineCollection.cs — WASM compile errors addressed ✅
  • Read UIElement.FocusMixins.cs — core fix verified
  • Read DependencyObjectStore.mux.cs — focus cleanup on Leave verified
  • Read FocusManager.mux.cs — non-cancellable ClearFocus verified
  • Read Given_FocusManager_DetachedElements.cs — test coverage verified
  • Read Given_XYFocusBubbling.cs and Given_XYFocusTreeWalker.cs — regression check
  • Post inline comments (none required — no blocking issues)
  • Write summary

Summary

Verdict: ship — all blocking issues from prior rounds are resolved; no new blocking findings.

Confirmed fixes in this round:

The three WASM compile errors in InlineCollection.cs are correctly addressed. Clear(), RemoveAt(), and the indexer setter now use #if __WASM__ / #if !__WASM__ guards: on WASM the explicit ClearFocusForRemovedInline calls are omitted, and WASM correctly relies on DependencyObjectStore.LeaveImpl via the Leave walk — which fires because both __WASM__ and __SKIA__ define UNO_HAS_ENHANCED_LIFECYCLE.

Other items are also clean:

  • IsActiveOrAttachedUnderActiveAncestor() now uses GetVisualTreeParent() (visual parents only), not logical/adjusted parents — the right boundary for live-tree membership.
  • DependencyObjectStore.LeaveImpl focus cleanup handles both the direct-UIElement case (ReferenceEquals(focusedElement, ActualInstance)) and the TextElement-in-FrameworkElement case (textElement.GetContainingFrameworkElement() == ActualInstance), covering Hyperlink-in-TextBlock.
  • ClearFocus(canCancel: false) makes tree-removal focus clears non-cancellable; LosingFocus handlers cannot veto or redirect them.
  • XYFocus tests that need live-tree membership to get a non-empty candidate list (VerifyFindElement, VerifyCorrectOverrideChosenWhen*, VerifyCorrectOverrideChosenWhenBubbling) are correctly updated to load into a real window. Tests that assert non-focusability-independent invariants (VerifyCandidateChosenWhenDescendant, VerifyOverrideAncestorOfSearchRoot, VerifyNullWhenCandidateNull, VerifyNonFocusableDirectionOverrideChosen) remain as detached unit tests and still assert the right thing — those code paths do not gate on IsFocusable.
  • [PlatformCondition(Exclude, NativeMobile)] at class level and [GitHubWorkItem] on every test method are present.

One minor pre-existing note (outside scope, no action needed):
VerifyCurrentElementNotIncludedInList in Given_XYFocusTreeWalker.cs (not changed by this PR) now passes vacuously — after the detached-focus gate, all elements in the test tree are non-focusable, so the empty result holds for a different reason than the intended "current element excluded from its own candidate list" invariant. The live-tree path is covered by VerifyFindElement. Strengthening VerifyCurrentElementNotIncludedInList to load into a real tree (with a live sibling candidate) would make the exclusion verifiable for active elements, but that's a follow-up, not a blocker for this PR.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated no new comments.

@unodevops

Copy link
Copy Markdown
Contributor

Co-authored-by: Copilot <[email protected]>
Copilot-Session: 8d4ade86-b17e-4af4-a8b2-4d6a41328960
Copilot AI review requested due to automatic review settings July 16, 2026 07:53
@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @morning4coffe-dev's task in 6m 25s —— View job


PR Review: fix(focus): Prevent detached elements from receiving focus

Tasks:

  • Load tools and initialize
  • Read current state of changed files
  • Review production code changes
  • Review test file
  • Post inline comments (none required — no new issues)
  • Write summary

Summary

Verdict: ship — no new issues found in this round; all prior blocking findings are resolved.

What was verified in this pass:

UIElement.FocusMixins.cs / IsActiveOrAttachedUnderActiveAncestor()
Correctly uses GetVisualTreeParent() (visual ancestry only — logical ownership is correctly excluded). The bridge handles Uno's deferred activation by walking up to any active visual ancestor. internal visibility is appropriate since Hyperlink.mux.cs (different namespace, same assembly) consumes it.

DependencyObjectStore.LeaveImpl focus cleanup
@params.VisualTree?.ContentRoot.FocusManager is the right access pattern (consistent with WinUI's VisualTree::GetContentRootForElement(this, LookupOptions::NoFallback)). The dual check — ReferenceEquals(focusedElement, ActualInstance) for direct UIElement focus and textElement.GetContainingFrameworkElement() == ActualInstance for TextElement-in-FrameworkElement — correctly handles both a focused Button being removed and a focused Hyperlink whose containing TextBlock is removed.

FocusManager.ClearFocus(canCancel: false)
_currentFocusOperationCancellable = _currentFocusOperationCancellable && focusChangeCancellable correctly threads through the cancellability flag. The two fixes in RaiseChangingFocusEvent (ignoring args.NewFocusedElement and ignoring args.Cancel when the operation is non-cancellable) prevent LosingFocus handlers from redirecting or vetoing a tree-removal focus clear. Cleanup() correctly resets the flag to true after every operation.

InlineCollection.cs
The #if __WASM__ / #if !__WASM__ guards are correctly scoped: on WASM, UIElementCollection.RemoveAt triggers the Leave walk which lands in LeaveImpl; on non-WASM, the explicit ClearFocusForRemovedInline call fills the gap since DependencyObjectCollection<Inline>.RemoveAt does not fire a Leave walk on removed items. All three mutation paths (Clear, RemoveAt, indexer setter) are covered. The break in Clear() is safe — there is at most one focused element, so the scan can stop on first hit. Inline.Enumerate() (defined in InlineExtensions.cs) performs a correct pre-order depth-first traversal, handling nested Span/Hyperlink hierarchies.

Test file (Given_FocusManager_DetachedElements.cs)
[GitHubWorkItem] on every method, [PlatformCondition(Exclude, NativeMobile)] at class level, all tests are async Task with [RunsOnUIThread], and cleanup is inside finally blocks. The When_Focused_Element_Is_Removed_LosingFocus_Cannot_Cancel_Or_Redirect test is correctly gated under #if HAS_UNO for the mechanics assertions while keeping the parity-relevant outcome assertion unconditional. The [DataRow] parameterisation of the three inline-mutation paths is correct.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

@unodevops

Copy link
Copy Markdown
Contributor

@morning4coffe-dev
morning4coffe-dev merged commit 9ca702c into master Jul 16, 2026
52 checks passed
@morning4coffe-dev
morning4coffe-dev deleted the dev/doti/focus-detached-elements branch July 16, 2026 13:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Detached elements can receive or retain keyboard focus

5 participants