Skip to content

fix: Screen Reader: Global: Focus is lost when returning to the previous screen#91752

Open
TaduJR wants to merge 4 commits into
Expensify:mainfrom
TaduJR:fix-Screen-Reader-Global-Focus-is-lost-when-returning-to-the-previous-screen
Open

fix: Screen Reader: Global: Focus is lost when returning to the previous screen#91752
TaduJR wants to merge 4 commits into
Expensify:mainfrom
TaduJR:fix-Screen-Reader-Global-Focus-is-lost-when-returning-to-the-previous-screen

Conversation

@TaduJR

@TaduJR TaduJR commented May 26, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

When a screen-reader user navigates back, focus now returns to the row they tapped to go forward (WCAG 2.4.3). Also fixes WCAG 2.4.7 (Focus Visible) on touch initial-focus and modal close.

Approach. On press, we record the element + its identifier against the screen the user is leaving. On back navigation, after the transition settles, we re-fire accessibility focus on that element. If react-native-screens detached the original view, a per-screen registry resolves the live re-mounted one by identifier. Bounded retry budget covers slow re-attach. Sighted users pay nothing the pipeline short-circuits when the screen reader is known-off.

  • Native rescue (new) capture on press, restore after transition, registry fallback for detached views, retry budget for slow re-attach.
  • Web rescue (refactor) migrated off the deprecated InteractionManager onto TransitionTracker. Also fixes a latent ~1s back-nav stall.
  • Focus priority all focus claimers go through one arbiter so the next screen's autofocus can't trample the restore.
  • Stable row identity 6 pages re-keyed off value-derived React keys so the captured row doesn't remount on every edit.
  • Save-and-close submit-driven goBack skips restore so a re-focused row can't hijack the destination form's Save button.

Fixed Issues

$ #77411
PROPOSAL:

Tests

1. Going back returns focus to the item you opened

  1. Turn the screen reader ON.
  2. Go to Account (Settings) → Profile → Display name.
  3. On the Display name screen, activate the Back button.
  4. Expected: focus goes back to the Display name row and the screen reader reads it out. Focus is not lost or silent.
  5. Repeat from a few other screens (e.g. Profile → Contact methods, then back) and confirm focus always returns to the row or button you opened.

2. Same behavior inside Workspace settings

  1. Screen reader ON.
  2. Go to Settings → Workspaces → [a workspace] and open any settings sub-page (e.g. More features, Members, Categories).
  3. Open a row from there, then activate Back.
  4. Expected: focus returns to the exact row you opened — not the Back button and not the top of the screen.

3. Opening a screen announces it

  1. On Android Chrome or iOS Safari, screen reader ON.
  2. Navigate into a settings screen (e.g. Account → Profile → Display name).
  3. Expected: once the screen finishes opening, the screen reader automatically announces the screen (focus lands on the Back button). Before, nothing was announced on open.
  4. Confirm the page does not jump or scroll when the screen opens.
  • Verify that no errors appear in the JS console

Offline tests

Same as tests

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."
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-Native-1.mp4
Android: mWeb Chrome
Android-mWeb-2.mp4
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
Mac-Chrome.mp4

@TaduJR
TaduJR requested review from a team as code owners May 26, 2026 19:12
@melvin-bot
melvin-bot Bot requested review from JmillsExpensify and marufsharifi and removed request for a team and marufsharifi May 26, 2026 19:12
@melvin-bot

melvin-bot Bot commented May 26, 2026

Copy link
Copy Markdown

@marufsharifi 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]

@TaduJR

TaduJR commented May 26, 2026

Copy link
Copy Markdown
Contributor Author

cc @mkhutornyi

@TaduJR
TaduJR marked this pull request as draft May 26, 2026 19:13
Comment thread src/libs/Accessibility/index.ts Outdated
Comment thread src/libs/NavigationFocusReturn/index.native.ts
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@codecov

codecov Bot commented May 26, 2026

Copy link
Copy Markdown

@TaduJR

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@TaduJR

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@TaduJR

This comment was marked as resolved.

@chatgpt-codex-connector

This comment was marked as outdated.

@mkhutornyi

Copy link
Copy Markdown
Contributor

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

Code Review

Summary: This PR implements native screen reader focus-return — when a user navigates back, TalkBack/VoiceOver refocuses the element that triggered the forward navigation. The architecture mirrors the existing web implementation in NavigationFocusReturn.ts, sharing the new navigationStateDiff.ts module and reusing TransitionTracker.runAfterTransitions for timing. The approach is sound and well-tested.

Issues to address

1. New findNodeHandle usage despite deprecation

findNodeHandle has an explicit comment: "Don't add new findNodeHandle usages, this is only a temporary solution." This PR adds two new call sites:

The view-attachment check is genuinely needed to avoid sending focus events to detached views. However, is there an alternative approach that doesn't deepen the dependency on this deprecated API? If not, a code comment explaining why this usage is justified (and what would replace it when findNodeHandle is removed) would help future maintainers.

2. composedRef missing exhaustive deps

In BaseGenericPressable.tsx:55:

const composedRef = useMemo(() => mergeRefs(ref, internalRef), [ref]);

internalRef is omitted from the dependency array. While useRef returns a stable object so this is functionally correct, ESLint's react-hooks/exhaustive-deps rule will flag it. Either add internalRef to the array or add an eslint-disable comment explaining why it's safe to omit.

3. prev cast removed in diffNavigationState changes semantics

In the original web code (line 535 of the old NavigationFocusReturn.ts), the findFocusedRoute call used prev as NavigationState. In the extracted navigationStateDiff.ts:25, it's now findFocusedRoute(prev) without the cast. The AnyState type includes PartialState | undefined. Confirm that findFocusedRoute accepts PartialState in the version of @react-navigation/core used here — if it only accepts NavigationState, this could cause a type error or runtime difference.

Suggestions (non-blocking)

4. Android scheduleRefocus timing

scheduleRefocus/index.android.ts uses requestIdleCallback with a 300ms timeout to work around TalkBack's TYPE_WINDOW_STATE_CHANGED auto-focus clobbering. This is a reasonable workaround, but the 300ms value may need tuning on slower devices. Consider whether this should be a constant in CONST.ts for visibility, or at minimum document how the value was determined.

5. warmCache error swallowing

In Accessibility/index.ts, the top-level warmCache call uses Log.warn on failure, which is good. But the module-level call (line 23) fires on import — if isScreenReaderEnabled throws synchronously during module init (e.g., native module not ready), the .catch handles it, but worth verifying this doesn't delay app startup on slow cold boots.


Next Steps: Reply with @MelvinBot <your feedback> to discuss any of these points.

@TaduJR

This comment was marked as resolved.

@chatgpt-codex-connector

This comment was marked as outdated.

@TaduJR

TaduJR commented May 27, 2026

Copy link
Copy Markdown
Contributor Author

#91752 (comment)

Most are Invalid.

But was initially working on findNodeHandle migration.

@TaduJR

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@TaduJR

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@TaduJR

TaduJR commented Jul 4, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@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: 1a2a3e8120

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/hooks/useInitialFocusRef.ts Outdated
Comment thread src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx Outdated
@TaduJR

TaduJR commented Jul 4, 2026

Copy link
Copy Markdown
Contributor Author

Please pull main, fix conflict

Done.

@mkhutornyi

mkhutornyi commented Jul 5, 2026

Copy link
Copy Markdown
Contributor
-- Added Deleted Files
Non-test +1,401 −434 52
Test +3,312 −52 36
Total +4,713 −486 88

There are sooooo many tests but are they really useful and able to catch regressions in the future?

@TaduJR

TaduJR commented Jul 5, 2026

Copy link
Copy Markdown
Contributor Author

Yes

There are most that I have added during testing to prevent future regressions. Also since we are orchestrating lib workarounds I am trying to simulate different cases and race conditions for future conditions.

Hopefully react-native-screens and react-navigations would fix some of the bugs and states so we can remove unneeded diffs. I am planning to try to handle these on upstream in the future.

Comment thread src/components/SpendRules/configuration/SpendRuleMerchantEditBase.tsx Outdated
@TaduJR

TaduJR commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@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: f1ec067f9c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/NavigationFocusReturn/index.native.ts Outdated
Comment thread src/hooks/useInitialFocusRef.ts Outdated
@TaduJR

TaduJR commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@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: e6c37412e6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/hooks/useScreenInitialFocus/index.ts Outdated
@TaduJR
TaduJR requested review from a team and stephanieelliott as code owners July 10, 2026 12:26
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ This PR is possibly changing native code and/or updating libraries, it may cause problems with HybridApp. Please check if any patch updates are required in the HybridApp repo and run an AdHoc build to verify that HybridApp will not break. Ask Contributor Plus for help if you are not sure how to handle this. ⚠️

@TaduJR
TaduJR force-pushed the fix-Screen-Reader-Global-Focus-is-lost-when-returning-to-the-previous-screen branch from 3859725 to a654a36 Compare July 10, 2026 12:27
@TaduJR

TaduJR commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

⚠️ This PR is possibly changing native code and/or updating libraries, it may cause problems with HybridApp. Please check if any patch updates are required in the HybridApp repo and run an AdHoc build to verify that HybridApp will not break. Ask Contributor Plus for help if you are not sure how to handle this. ⚠️

Ugghh, Sorry everyone. Please ignore this. I made a mistake during conflict resolution. Lost a all the commits.

@TaduJR

TaduJR commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 14cdfe2ccb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@TaduJR
TaduJR requested a review from mkhutornyi July 10, 2026 15:25
@stephanieelliott
stephanieelliott removed their request for review July 10, 2026 20:20

@mkhutornyi mkhutornyi 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.

No blocker from my side
@roryabraham need your 👁️ on this big boy. 5k lines of code

@roryabraham roryabraham 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.

Let's split this PR up a bit into smaller, easier-to-review chunks that each provide some incremental value.

PR 1 — Stable row identity

Replace title-derived and array-index React keys with stable, value-derived keys across a handful of pages and components. Pure React hygiene (prevents remount-on-edit bugs) with no accessibility dependency — can ship anytime.

Example: ProfilePage.tsx keys menu items by detail.testID instead of ${detail.title}_${index}, and SpendRuleMerchantsBase.tsx keys rows by rowId instead of a merchant-name-derived string.

PR 2 — Accessibility warm-cache

Rewrite the screen-reader/reduce-motion state cache to warm eagerly on load and refresh when the app resumes from background, fixing a boot-race and a stale-cache bug that affects every existing caller today. Purely additive — no new call sites required.

Example: the new makeWarmCache helper backs the rewritten subscribeScreenReader, replacing the old fire-and-forget AccessibilityInfo.addEventListener/isScreenReaderEnabled() pair.

PR 3 — Save-and-close skip-restore

Add an explicit "skip focus restore" option to back navigation, plus a reusable hook, so a submit-driven save-and-close doesn't re-focus the row that opened the form and hijack the next Enter press. This generalizes a pattern already live on one screen and rolls it out more broadly. No native dependency.

Example: the new shouldSkipFocusRestore option on GoBackOptions, consumed via the new useNavigateBackOnSave hook, which replaces an ad-hoc ref+effect pattern already in production in IOURequestStepMerchant.tsx.

PR 4 — Extract shared focus utilities

Pure refactor of the already-shipped web focus-return module: pull the navigation-state diffing, a small FIFO map, timing constants, and a visibility check out into standalone files, and reorganize the module into a directory so a native counterpart can be added later. Zero behavior change.

Example: navigationStateDiff.ts's diffNavigationState is lifted verbatim out of the old NavigationFocusReturn.ts, which now imports it back in at its new path.

PR 5 — TransitionTracker nav-kind fix

Teach the transition tracker to tell screen-navigation transitions apart from unrelated modal/keyboard ones, fixing a real ~1s stall that happens on back navigation today. Builds directly on PR 4's refactor.

Example: the new TransitionKind distinction, fed by ScreenLayout.tsx marking screen transitions as 'navigation'.

PR 6 — WCAG 2.4.7 initial focus + dialog labeling

Add proper focus-visible handling for initial focus when a screen opens (so screen readers announce it) and when a modal closes, sharing one "claim focus" helper between both. Web-only. Needs PR 2's screen-reader state and PR 4's timing constants.

Example: the new claimInitialFocus helper is shared by the new useScreenInitialFocus hook (screen open) and the modal-close path in FocusTrapForModal.

PR 7 — Native focus-return rescue (this PR)

The core new feature: the actual native (iOS/Android) mechanism that restores accessibility focus to the row a user pressed, once they navigate back to that screen. This is the biggest, riskiest chunk, and where the reviewer concerns about findNodeHandle, retry budgets, and race conditions apply. Needs PR 2, 4, and 5; works more reliably with PR 1's stable row identifiers but doesn't strictly require them.

Example: the new restoreTriggerForRoute/registerPressable registry in the new native module, fed by BaseGenericPressable.tsx registering every press.

Rollout / dependency graph

Critical path is only 3 PRs deep: PR4 → PR5 → PR7. Everything else is parallel.

flowchart TD
    subgraph wave1 ["Wave 1 - parallel, no deps"]
        PR1["PR 1: Stable row identity"]
        PR2["PR 2: Accessibility warm-cache"]
        PR3["PR 3: Save-and-close"]
        PR4["PR 4: Extract shared utilities"]
    end
    subgraph wave2 ["Wave 2 - parallel to each other"]
        PR5["PR 5: TransitionTracker fix"]
        PR6["PR 6: WCAG 2.4.7 initial focus"]
    end
    subgraph wave3 ["Wave 3"]
        PR7["PR 7: Native focus-return rescue"]
    end
    PR4 --> PR5
    PR2 --> PR6
    PR4 --> PR6
    PR2 --> PR7
    PR4 --> PR7
    PR5 --> PR7
    PR1 -.->|soft dep| PR7
Loading

Merge PR1-4 first, any order. Then PR5+PR6 in parallel. PR7 last.

@TaduJR

TaduJR commented Jul 19, 2026

Copy link
Copy Markdown
Contributor Author

Hi @roryabraham @rushatgabhane

Is the splitting idea still around or are we going to continue on the PR due to the urgency of this issue?

@mkhutornyi

Copy link
Copy Markdown
Contributor

Hi @roryabraham @rushatgabhane

Is the splitting idea still around or are we going to continue on the PR due to the urgency of this issue?

splitting idea is still around. Please work on all PRs as priority.

@TaduJR

TaduJR commented Jul 19, 2026

Copy link
Copy Markdown
Contributor Author

splitting idea is still around. Please work on all PRs as priority.

Screenshot 2026-07-19 at 1 29 19 PM

…Reader-Global-Focus-is-lost-when-returning-to-the-previous-screen

# Conflicts:
#	src/libs/Navigation/TransitionTracker.ts
#	src/pages/iou/request/step/IOURequestStepMerchant.tsx
#	src/pages/workspace/rules/SpendRules/SpendRuleCardPage.tsx
@TaduJR

TaduJR commented Jul 21, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 07994e077a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

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.

6 participants