Skip to content

Fix workspace keyboard focus not returning to 3-dot trigger after Back - #97171

Open
Krishna2323 wants to merge 11 commits into
Expensify:mainfrom
Krishna2323:krishna2323/issue/96971
Open

Fix workspace keyboard focus not returning to 3-dot trigger after Back#97171
Krishna2323 wants to merge 11 commits into
Expensify:mainfrom
Krishna2323:krishna2323/issue/96971

Conversation

@Krishna2323

@Krishna2323 Krishna2323 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Fixed Issues

$ #96971 (comment)
PROPOSAL:

Tests

  1. Using Windows + Chrome, open a workspace under https://new.expensify.com/workspaces
  2. Navigate using TAB and press enter to open one of the flows below:
  3. Workspace 3-dot menu → Duplicate workspace
  4. Workspace 3-dot menu → Delete workspace
  5. Workspace → Overview → Workspace Name
  6. Workspace → Categories → Settings
  7. Navigate to the 'Back' button (or close/cancel) using TAB, press enter to activate
  8. Verify focus returns to the element that triggered the navigation.
  • Verify that no errors appear in the JS console

Offline tests

  • Same as tests

QA Steps

  • Same as tests

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
web_chrome_mac.mp4
web_chrome_windows.mp4

Signed-off-by: krishna2323 <belivethatkg@gmail.com>
@codecov

codecov Bot commented Jul 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/components/ButtonWithDropdownMenu/index.tsx 92.46% <100.00%> (+0.79%) ⬆️
...mponents/FocusTrap/FocusTrapForModal/index.web.tsx 100.00% <100.00%> (ø)
...s/WorkspaceListTable/WorkspaceRowThreeDotsMenu.tsx 68.83% <ø> (ø)
src/components/ThreeDotsMenu/index.tsx 94.87% <100.00%> (+0.66%) ⬆️
src/libs/resolveFocusTrapLauncher.ts 100.00% <100.00%> (ø)
src/pages/workspace/WorkspaceOverviewPage.tsx 0.00% <ø> (ø)
src/pages/workspace/WorkspaceNamePage.tsx 0.00% <0.00%> (ø)
src/libs/LauncherStack.ts 85.50% <81.25%> (+0.05%) ⬆️
...ges/workspace/WorkspaceOverviewDescriptionPage.tsx 0.00% <0.00%> (ø)
... and 11 files with indirect coverage changes

Signed-off-by: krishna2323 <belivethatkg@gmail.com>
@Krishna2323

Copy link
Copy Markdown
Contributor Author

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

Review

Overall this is a solid, well-reasoned change — the LauncherStack registration + shouldCallAfterModalHide handshake is a clean way to bridge the "anchor blurred before the trap activates" gap, and the tests and inline comments are genuinely good. A few things worth a second look before this ships:

1. Blast radius on shared components (main concern). ThreeDotsMenu/index.tsx and FocusTrapForModal/index.web.tsx are used app-wide (~19 ThreeDotsMenu call sites, plus every PopoverMenu/modal goes through FocusTrapForModal). Two behaviors now change globally, not just for workspaces:

  • onThreeDotsPress always registers the anchor into LauncherStack before blur.
  • onActivate now falls back to pickLauncher() whenever document.activeElement is body, for every trap.

The registration looks self-cleaning (PopoverMenu renders FocusTrapForModal, whose onPostDeactivate marks the entry deactivated, and setActivePopoverLauncher dedupes by element), so I don't see a leak. But the Tests/QA steps only cover the 4 workspace flows. Please spot-check a couple of unrelated high-traffic ThreeDotsMenu + modal flows (e.g. report-header 3-dot menu, money-request, search) to confirm focus still returns where expected and nothing jumps to a stale anchor — that's where a regression would hide.

2. onActivate pickLauncher fallback in trigger-less modals. With the new fallback, a modal opened while nothing is focused (activeElement === body) will now capture a recently-used launcher from the stack and return focus to it on close, where previously it captured nothing. This is usually the desired behavior, but it's a new focus-return path for modals that never had one — worth confirming it doesn't surprise anywhere (part of the spot-check above).

3. Coverage on the new onModalHide restore branch. Codecov flags ThreeDotsMenu down ~4.6%; the uncovered lines are the new onModalHide anchor-restore path and the shouldCallAfterModalHide branch in onItemSelected. Since that handshake is the core of the fix, a small unit test asserting the anchor regains focus on hide (and that restoreFocusType stays PRESERVE in the non-deferred branch) would lock it in.

Minor / nits

  • The delete item's shouldCallAfterModalHide: !shouldCalculateBillNewDot || wouldBlockDeletion and the Leave/Transfer items already use this flag, so the confirm-modal flows look covered — good.
  • FocusTrapForModal swapping launcher !== document.body for document.contains(launcher) is a safe, strictly-better guard (both fromActive and pickLauncher() already exclude body).
  • The useAutoFocusInput swap in the Name/Description pages is a nice cleanup and should improve native too, not just web.

Nothing here is a blocker on the approach — the design is sound. The asks are really about confirming the shared-component changes don't ripple into other flows, plus a test on the new hide-restore branch.

Signed-off-by: krishna2323 <belivethatkg@gmail.com>
@Krishna2323
Krishna2323 marked this pull request as ready for review July 28, 2026 14:11
@Krishna2323
Krishna2323 requested review from a team as code owners July 28, 2026 14:11
@melvin-bot
melvin-bot Bot requested review from heyjennahay and mkhutornyi and removed request for a team and heyjennahay July 28, 2026 14:11
@melvin-bot

melvin-bot Bot commented Jul 28, 2026

Copy link
Copy Markdown

@mkhutornyi Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot removed the request for review from a team July 28, 2026 14:11
Signed-off-by: krishna2323 <belivethatkg@gmail.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b25fd3c0a2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/components/FocusTrap/FocusTrapForModal/index.web.tsx Outdated
Signed-off-by: krishna2323 <belivethatkg@gmail.com>
Signed-off-by: krishna2323 <belivethatkg@gmail.com>
Signed-off-by: krishna2323 <belivethatkg@gmail.com>
@Krishna2323

Copy link
Copy Markdown
Contributor Author

@codex review

@Krishna2323

Copy link
Copy Markdown
Contributor Author

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

Review

Solid, well-scoped accessibility fix with strong test coverage (4 test files, pure resolveFocusTrapLauncher is nicely unit-testable). The launcher-registration approach is the right, higher-leverage fix. Code reads clearly and the "why" comments are genuinely helpful. I found no blocking bugs, but two behavior changes are global (they affect every modal, not just the workspace flows in scope), and one platform gap is worth confirming before merge.

1. pickLauncher() fallback now applies to every FocusTrapForModal, not just ThreeDots

In FocusTrapForModal/index.web.tsx:31, when document.activeElement is body (nothing focused) and no focus is inside the trap, onActivate now falls back to pickLauncher() — the most-recent stacked launcher, active or deactivated within LAUNCHER_CLEAR_DELAY_MS. Previously this case captured nothing.

That's exactly what fixes the ThreeDots pre-blur case, but it changes capture behavior for all modals built on FocusTrapForModal. A modal opened programmatically while focus is on body, shortly after an unrelated popover closed, could now adopt that popover's still-in-DOM launcher and restore focus there on close. It's bounded by the document.contains checks and the clear-delay window, so the blast radius is small — but it's the main thing to regression-test beyond the 4 workspace flows (e.g. confirm a plain modal opened with no prior focus doesn't inherit a stale launcher). Worth a sanity pass.

2. Safari path for shouldCallAfterModalHide

The handshake relies on PopoverMenu deferring onSelected until after onModalHide re-focuses the anchor. But PopoverMenu/index.tsx:421 disables that deferral on Safari (!isSafari() || shouldAvoidSafariException), and ThreeDotsMenu does not pass shouldAvoidSafariException. On Safari, onSelected (navigate) fires immediately, while onItemSelected set shouldRestoreAnchorOnHideRef = true but deliberately did not set PRESERVE — so the anchor re-focus lands in onModalHide after navigation already happened. The linked issue is scoped to Windows + Chrome, so this may be acceptable, but the PR checklist claims all-platform testing — please confirm Duplicate/Categories→Settings Back-focus still returns correctly (and without a focus flash) on iOS/macOS Safari.

3. Global <View style={dContents}> wrapper

Every FocusTrapForModal child is now wrapped in a display: contents View. dContents is an existing utility and display:contents is layout-neutral, so this is low-risk — just flagging that it's a global structural change to all modals, not just these flows. If anything downstream assumed the trap child was a direct DOM child it could be affected; a quick scan of other modal consumers would put it to bed.

Things I checked that look correct
  • resolveFocusTrapLauncher logic (resolveFocusTrapLauncher.ts:13) — nested-trap case (focus already inside container → keep activeStacked) and new-nested-modal case (opener outside container → use fromActive) both resolve correctly. This also correctly addresses the Codex bot's earlier concern about overwriting the pre-registered trigger with the transient menu item.
  • LauncherStack splitpickActiveLauncher (active-only) vs pickLauncher (active-first, then recently-deactivated) is clean; the DOM-contains pruning still runs.
  • WorkspaceOverviewDescriptionPage ref callback — the !inputRef.current guard runs before inputCallbackRef sets the ref, preserving the once-only updateMultilineInputRange init. Equivalent to (or better than) the old isInputInitializedRef.
  • onActivate still captures the launcher regardless of shouldReturnFocus (only onPostDeactivate gates restore on it) — matches the prior intent even though the explanatory comment was dropped.

Next Steps: Reply with @MelvinBot <feedback> to refine this review. I wasn't able to run the unit suite in this environment, so I confirmed the logic by reading rather than by executing the tests — worth a local npx jest on the four touched test files before merge.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cff41306b1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/components/ThreeDotsMenu/index.tsx Outdated
Comment thread src/components/FocusTrap/FocusTrapForModal/index.web.tsx
Signed-off-by: krishna2323 <belivethatkg@gmail.com>
Signed-off-by: krishna2323 <belivethatkg@gmail.com>
@Krishna2323

Copy link
Copy Markdown
Contributor Author

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

Review

Re-reviewed at e89efd9. The design holds up — registering the anchor in LauncherStack at open time and using the shouldCallAfterModalHide handshake to re-focus it before the deferred onSelected is the right, higher-leverage fix, and it's now applied consistently to both ThreeDotsMenu and ButtonWithDropdownMenu. I verified the referenced symbols resolve (dContents, isSafari, BaseModalProps.restoreFocusType, restoreFocusWithModality) and re-checked the resolveFocusTrapLauncher branch logic — internally consistent. No blocking bugs found. Two items remain before merge:

1. One load-bearing assumption is not covered by the unit tests. The whole fix depends on the Modal firing onModalHide (which re-focuses the anchor) before it runs the deferred shouldCallAfterModalHide onSelected (the navigate). But the new ThreeDotsMenuFocusRestoreTest / ButtonWithDropdownMenuFocusRestoreTest both mock PopoverMenu and drive onItemSelectedonModalHide by hand. So they prove the components arm the ref correctly, but not that Modal/PopoverMenu actually orders those two callbacks the way the comments claim. That ordering is exactly what breaks the Back-focus return if it ever regresses, and it's only covered by manual QA — worth calling out so a future refactor of the modal-hide sequence doesn't silently break this.

2. Shared-component blast radius still needs a manual sanity pass (carried over from the earlier reviews, still the main gate). Two behaviors now change for every consumer, not just the 4 workspace flows in the Tests section:

  • onThreeDotsPress always registers the anchor into LauncherStack before blur.
  • FocusTrapForModal.onActivate now falls back to pickLauncher() whenever document.activeElement === body, for every trap (index.web.tsx:31).

The registration looks self-cleaning (onPostDeactivatemarkActivePopoverLauncherDeactivated, and setActivePopoverLauncher dedupes by element) and the fallback is bounded by document.contains + LAUNCHER_CLEAR_DELAY_MS, so I don't see a leak or a stale-anchor hazard on paper. But please spot-check a couple of unrelated high-traffic surfaces — a report-header 3-dot menu and any plain modal opened while nothing is focused — to confirm Back/close focus still lands where expected and no modal inherits a stale launcher.

Things I checked that look correct
  • All open paths register the launcher in ButtonWithDropdownMenuhandlePress, onPressChevron, and the split-button cart-icon onPress all route through toggleMenuVisiblesetMenuVisible(true)registerDropdownLauncher, and the imperative setIsMenuVisible handle is now setMenuVisible too.
  • shouldRestoreAnchorOnHideRef lifecycle — armed only on the deferred branch, consumed-and-reset in onModalHide; the outside-click/escape close path leaves it false, so no spurious re-focus.
  • Safari path — non-deferred branch sets PRESERVE; the anchor is still recoverable for Back via LauncherStack (covered by the new NavigationFocusReturnTest case), so this shouldn't regress even though onSelected fires immediately.
  • resolveFocusTrapLauncher — nested-trap (focus already inside container → keep activeStacked) vs new-nested-modal (opener outside container → fromActive) both resolve correctly; unit-tested in resolveFocusTrapLauncherTest.
  • useAutoFocusInput swap in the Name/Description pages — the !inputRef.current guard runs before inputCallbackRef sets the ref, preserving the once-only updateMultilineInputRange init.
  • document.contains(launcher) guard replacing launcher !== document.body is strictly safer.

Note: I could not execute the Jest suite in this environment, so the above is from reading the code, not from a green test run. Please confirm a local npx jest on the five touched test files passes before merge.


Next Steps: Reply with @MelvinBot <feedback> to refine this review.

Signed-off-by: krishna2323 <belivethatkg@gmail.com>
defaultValue={policy?.name}
spellCheck={false}
autoFocus
ref={inputCallbackRef}

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.

This doesn't fix the root cause.
I think we should hold this PR for #97306 as immediate auto focused pages like this will be fixed there.

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.

3 participants