[Due for payment 2026-11-19] [$175] Sign-In - Shift+Tab moves focus to Select Language instead of the previous magic code slot
If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.
Version Number: 9.5.18-1 Reproducible in staging?: Y Reproducible in production?: Y If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @ikevin127 Slack conversation (hyperlinked to channel name): #Expensify Bugs
Action Performed:
- Open the sign-in / magic code page screen.
- Focus the magic code input and use the arrow keys to focus slot 3.
- Press Shift+Tab.
Expected Result:
Focus moves back to slot 2.
Actual Result:
Focus leaves the magic code input and moves to the footer language selector input.
Workaround:
Can the user still use Expensify without this being fixed? Have you informed them of the workaround?
Platforms:
Select the officially supported platforms where the issue was reproduced:
- [ ] Android: App
- [ ] Android: mWeb Chrome
- [ ] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [x] Windows: Chrome
- [x] MacOS: Chrome / Safari
Screenshots/Videos
https://github.com/user-attachments/assets/c999096a-08a4-480e-b5c2-e97bdc468bff
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022113604832656559739
- Upwork Job ID: 2113604832656559739
- Last Price Increase: 2026-10-23
Issue Owner
Current Issue Owner: @mallenexpensify
Proposal
What is the root cause of that problem?
The screen-level focus trap handles Shift+Tab before the magic code input gets the key press.
ScreenWrapperwraps the sign-in page inFocusTrapForScreen(ScreenWrapper/index.tsx:290, FocusTrapForScreen/index.web.tsx:45-69).focus-traplistens forkeydownin the capture phase ondocument. That listener runs before React's handlers.- The magic code page renders one hidden
TextInputbehind all 6 slots. That input is the first tabbable node in the trap. - On Shift+Tab from the first tabbable node,
focus-trapwraps to the last one: the footerLocalePicker(Licenses.tsx:27). - The input's
onBlurthen setsfocusedIndextoundefined(ValidateCodeInput.tsx:492-496). When the Tab branch inonKeyPressfinally runs,focusedIndexisundefined, so it does nothing (ValidateCodeInput.tsx:416-425).
Forward Tab works because the input is not the last tabbable node, so focus-trap ignores it. The Tab handling came from fix: press Tab to move around magic code input, which only tested forward Tab.
What changes do you think we should make in order to solve the problem?
Handle slot-to-slot Tab navigation in ValidateCodeInput before focus-trap sees the key (web only):
- Add a
keydownlistener onwindowin the capture phase. It runs beforefocus-trap'sdocumentcapture listener. - In it, act only when
document.activeElementis this component's hidden input andfocusedIndexis defined. - On Shift+Tab with
focusedIndex > 0, or Tab withfocusedIndex < maxLength - 1: callsetInputAndIndexwith the new index, thenpreventDefault()andstopImmediatePropagation(). - Otherwise do nothing, so Shift+Tab from slot 1 and Tab from slot 6 still leave the input normally.
- Remove the now-redundant Tab branch in
onKeyPress.
This also fixes the same bug anywhere else ValidateCodeInput is the first tabbable node in a trap, such as 2FA or magic code pages in the RHP.
What alternative solutions did you explore? (Optional)
Override isKeyBackward and isKeyForward in FocusTrapForScreen and FocusTrapForModal. They would skip the trap when the target input reports, through a data attribute, that it has a previous or next slot. This works but changes the shared focus trap config for one component.
Investigation details
focus-trapregistersdoc.addEventListener('keydown', checkTabKey, {capture: true}). When the target is the group's first tabbable node and the key is Shift+Tab, it callspreventDefault()and focuseslastTabbableNode. It does not stop propagation.- React 19 attaches listeners to the root container, not
document, sofocus-trapalways runs first. React'sonKeyDownCapturewould not help for the same reason. react-native-web'sTextInputpasses the synthetic event toonKeyPress, soevent.shiftKeyis read correctly. The handler logic itself is fine.- The hidden login form stays mounted with
visibility: hidden, so it has no tabbable nodes. Nothing focusable comes before the magic code input on this page. - I couldn't reproduce this in a browser because the test session can't sign out to reach the magic code screen. The root cause comes from code tracing.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/104839) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Triggered auto assignment to Contributor-plus team member for initial proposal review - @rojiphil (External)
Job added to Upwork: https://www.upwork.com/jobs/~022113604832656559739
Proposal
Please re-state the problem that we are trying to solve in this issue.
When navigating backwards using Shift+Tab from any slot other than the first one in the magic code input (ValidateCodeInput), focus leaves the input entirely and jumps to the language selector (LocalePicker) in the footer instead of moving to the previous magic code slot.
What is the root cause of that problem?
- Event Capture Phase Conflict:
FocusTrapForScreenwraps the sign-in screen and relies onfocus-trap, which attaches a nativekeydownlistener todocumentin the capture phase ({ capture: true }). - First Tabbable Node Behavior: The magic code component renders a single hidden
TextInputDOM element representing the magic code input, making it the first tabbable node in the screen's focus trap. - Premature Boundary Exit: When
Shift+Tabis pressed,focus-trapintercepts the event ondocumentduring the capture phase—before React synthetic events fire. Becausedocument.activeElementis the first tabbable node in the trap,focus-trapassumes the user is trying to exit the trap backwards, wraps focus around to the last tabbable node (LocalePicker), and triggers anonBlurthat resetsfocusedIndexinValidateCodeInput.
What changes do you think we should make in order to solve the problem?
We will intercept the keydown event at the window level in the capture phase before focus-trap's document capture listener can execute.
-
Modify
src/components/ValidateCodeInput.tsx(or web-specific implementation): Add auseEffecthook that attaches a nativekeydownlistener towindowwith{ capture: true }:- Check if
event.key === 'Tab'. - Ensure
document.activeElementis the component's hidden input ref andfocusedIndexis defined. - If
event.shiftKey(Shift+Tab) ANDfocusedIndex > 0:- Call
setInputAndIndex(focusedIndex - 1). - Call
event.preventDefault()andevent.stopImmediatePropagation()to preventfocus-trapondocumentfrom seeing the event.
- Call
- If
!event.shiftKey(Tab) ANDfocusedIndex < maxLength - 1:- Call
setInputAndIndex(focusedIndex + 1). - Call
event.preventDefault()andevent.stopImmediatePropagation().
- Call
- If
focusedIndex === 0onShift+TaborfocusedIndex === maxLength - 1onTab, do nothing and allow the event to propagate naturally sofocus-trapor default focus navigation handles boundary exits.
- Check if
-
Clean up redundant code: Remove the internal Tab handling logic in
onKeyPresswithinValidateCodeInput.tsxto prevent duplicate state updates.
useEffect(() => {
// Only apply on Web platform
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') return;
if (document.activeElement !== inputRef.current) return;
if (focusedIndex === undefined) return;
const isShiftTab = event.shiftKey;
const isTab = !event.shiftKey;
if (isShiftTab && focusedIndex > 0) {
event.preventDefault();
event.stopImmediatePropagation();
setInputAndIndex(focusedIndex - 1);
return;
}
if (isTab && focusedIndex < maxLength - 1) {
event.preventDefault();
event.stopImmediatePropagation();
setInputAndIndex(focusedIndex + 1);
return;
}
};
window.addEventListener('keydown', handleKeyDown, { capture: true });
return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });
}, [focusedIndex, maxLength, setInputAndIndex]);
What alternative solutions did you explore? (Optional)
- Handling in React's
onKeyPress/onKeyDown: Suboptimal and non-functional because React's synthetic event handlers run afterdocumentcapture listeners, meaningfocus-trapchanges focus before React processes the event. - Modifying global
FocusTrapconfigurations: OverridingisKeyBackward/isKeyForwardinFocusTrapForScreencouples global accessibility wrappers to a specific child component's internal logic, violating component encapsulation.
What automated tests can you add to prevent this from re-occurring?
Add a unit test in tests/unit/ValidateCodeInputTest.tsx:
- Render
ValidateCodeInputwithmaxLength={6}. - Focus the input and set
focusedIndexto2. - Dispatch a
keydownevent onwindowwith{ key: 'Tab', shiftKey: true }. - Assert that
setInputAndIndexwas called with1and thatdefaultPreventedistrue. - Set
focusedIndexto0and dispatch{ key: 'Tab', shiftKey: true }. - Assert that
setInputAndIndexwas NOT called anddefaultPreventedisfalse(allowing exit).
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b60d704ba377be83
VERDICT: POST
ROOT_CAUSE_ONELINER: In ValidateCodeInput.tsx, the Tab/Shift+Tab handler in onKeyPress never calls event.preventDefault() because it guards the call with if (event?.preventDefault) — but React Native Web's TextInputKeyPressEvent wrapper object does NOT expose preventDefault directly (it's a plain {nativeEvent: {...}} wrapper), so the guard is always falsy, the browser's native Shift+Tab focus move is never prevented, and focus escapes to the language selector.
PROPOSAL_TYPE: FIRST
AUTOPOST_SAFE: YES
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0139ed4098bdc50182
Proposal
Please re-state the problem that we are trying to solve in this issue.
On the sign-in / magic code screen on Web / Desktop, when focus is on an intermediate digit slot (e.g. slot 3) in the magic code input, pressing Shift+Tab moves focus outside the magic code input to the footer language selector (Select Language) instead of moving back to the previous slot (slot 2).
What is the root cause of that problem?
- On Web,
ScreenWrapperwraps the sign-in screen inFocusTrapForScreen(src/components/FocusTrap/FocusTrapForScreen/index.web.tsx), which instantiates afocus-trapinstance. focus-trapattaches a nativekeydownlistener in the capture phase ondocument:doc.addEventListener('keydown', checkTabKey, {capture: true});ValidateCodeInput(src/components/ValidateCodeInput.tsx) implements 6 visual digit slots backed by a single invisibleTextInput. This hidden input is the first tabbable DOM node inside the screen's focus trap container.- When focus is inside
ValidateCodeInput(e.g. at slot 3) and the user pressesShift+Tab:- The native
keydowncapture event fires ondocumentbefore React's event delegator dispatches toonKeyPressinValidateCodeInput.tsx:416. focus-trapinspectsdocument.activeElement. Becausedocument.activeElementis the single hiddenTextInput(the first tabbable node in the trap container),focus-trapinterceptsShift+Tabas an escape/wrap-around from the top of the container and immediately focuses the last tabbable element on the screen (Select LanguageinLicenses.tsx).- Focusing the footer language selector causes the hidden
TextInputto blur, which triggersblurValidateCodeInput()and resetsfocusedIndextoundefined(setFocusedIndex(undefined)). - When the React synthetic
onKeyPressevent finally executes,focusedIndexis alreadyundefined, completely preventing the slot-to-slot navigation check (keyValue === 'Tab' && focusedIndex !== undefined) from running.
- The native
What changes do you think we should make in order to solve the problem?
In src/components/ValidateCodeInput.tsx:
Intercept Tab and Shift+Tab on window in the capture phase on Web before the document-level focus-trap capture listener executes.
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
const handleKeyDownCapture = (event: KeyboardEvent) => {
if (event.key !== 'Tab' || focusedIndex === undefined) {
return;
}
const isInputFocused = document.activeElement === (inputRef.current as unknown as HTMLElement);
if (!isInputFocused) {
return;
}
const isShift = event.shiftKey;
const targetIndex = isShift ? focusedIndex - 1 : focusedIndex + 1;
// If target slot is within the input bounds (0 to maxLength - 1), navigate internally
if (targetIndex >= 0 && targetIndex < maxLength) {
event.preventDefault();
event.stopImmediatePropagation();
setInputAndIndex(targetIndex);
inputRef.current?.focus();
}
// If targetIndex < 0 (Shift+Tab on slot 0) or targetIndex >= maxLength (Tab on slot 5),
// do not stop propagation, allowing natural tabbing in/out of the component.
};
window.addEventListener('keydown', handleKeyDownCapture, true);
return () => {
window.removeEventListener('keydown', handleKeyDownCapture, true);
};
}, [focusedIndex, maxLength]);
Why this is clean, robust, and safe:
- In the DOM event dispatch pipeline,
windowin capture phase (addEventListener(..., true)) fires beforedocumentin capture phase. - When navigating between internal slots (
targetIndex >= 0 && targetIndex < maxLength), callingevent.preventDefault()andevent.stopImmediatePropagation()stops the event onwindow, sofocus-trapnever receives the event and never blurs the input. - When on the first slot (slot 0) pressing
Shift+Tab, or on the last slot pressingTab, propagation is allowed to continue normally so keyboard accessibility across the rest of the page remains intact. - This resolves the issue universally wherever
ValidateCodeInputis used (Sign-in, 2FA, Wallet verification, and RHP modals).
What alternative solutions did you explore? (Optional)
- Configuring
isKeyBackwardinfocusTrapOptions: Rejected becauseFocusTrapForScreenis a shared component used across dozens of screens; adding component-specific heuristics to the screen-level focus trap creates tight coupling. Intercepting the event cleanly withinValidateCodeInputencapsulates the slot-navigation logic within the component that owns the slots.
What automated tests can you add to prevent this from re-occurring?
In tests/unit/ValidateCodeInputTest.tsx:
- Add a unit test verifying that when
focusedIndexis 2, dispatching akeydownevent forTabwithshiftKey: trueupdatesfocusedIndexto 1 and callspreventDefault(). - Add a unit test verifying that when
focusedIndexis 0, dispatchingTabwithshiftKey: truedoes not prevent default, allowing natural exit.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
On the sign-in / magic code screen on Web and Desktop, when focus is on any magic code digit slot after the first one (e.g., slot 3) and the user presses Shift+Tab, focus jumps out of the magic code input to the footer language selector (LocalePicker) instead of moving backward to the previous digit slot (slot 2).
What is the root cause of that problem?
ScreenWrapperwraps the sign-in screen inFocusTrapForScreen(src/components/FocusTrap/FocusTrapForScreen/index.web.tsx), which activates afocus-trapinstance on Web.focus-trapattaches a nativekeydownlistener ondocumentin the capture phase (doc.addEventListener('keydown', checkTabKey, {capture: true})), which executes before React's syntheticonKeyPress/onKeyDownhandlers.ValidateCodeInput(src/components/ValidateCodeInput.tsx) renders a single backingTextInputbehind all 6 visual slots. Because thatTextInputis the first tabbable DOM node inside the focus trap, pressingShift+Tabcausesfocus-trapto intercept the event in the capture phase and wrap focus to the last tabbable element in the trap (LocalePicker).- This triggers
TextInput.onBlur(src/components/ValidateCodeInput.tsx:492-496), which resetsfocusedIndextoundefinedbeforeonKeyPress(lines 416-425) runs.
What changes do you think we should make in order to solve the problem?
-
Intercept
Tab/Shift+Tabin thewindowcapture phase insrc/components/ValidateCodeInput.tsx: In the DOM event flow, a capture-phase listener onwindow(window.addEventListener('keydown', ..., true)) executes beforefocus-trap's capture-phase listener ondocument. Following the exact pattern already used byuseValidateCodePasteinsrc/components/ValidateCodeInput.tsx(lines 32-65), check(inputRef.current as ComponentRef<typeof RNTextInput>)?.isFocused?.()(avoiding unsafeHTMLElementcasts that violate@typescript-eslint/no-unsafe-type-assertion).When
event.key === 'Tab'and the target slot index (focusedIndex - 1forShift+Tab,focusedIndex + 1forTab) is within[0, maxLength - 1], callevent.preventDefault(),event.stopImmediatePropagation(), and advance the slot viasetInputAndIndex(newFocusedIndex):
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key !== 'Tab' || focusedIndex === undefined || !inputRef.current) {
return;
}
const isFocused = (inputRef.current as ComponentRef<typeof RNTextInput>)?.isFocused?.() ?? false;
if (!isFocused) {
return;
}
const newFocusedIndex = event.shiftKey ? focusedIndex - 1 : focusedIndex + 1;
if (newFocusedIndex >= 0 && newFocusedIndex < maxLength) {
event.preventDefault();
event.stopImmediatePropagation();
setInputAndIndex(newFocusedIndex);
inputRef.current?.focus();
}
};
window.addEventListener('keydown', handleKeyDown, true);
return () => {
window.removeEventListener('keydown', handleKeyDown, true);
};
}, [focusedIndex, maxLength]);
-
Keep the
keyValue === 'Tab'branch inonKeyPress(lines 416-425) for Native hardware keyboards: Unlike deleting theonKeyPressTabbranch (which would break hardware keyboardTab/Shift+Tabnavigation on iOS/Android native apps wherewindow.addEventListeneris not used), keepingonKeyPresspreserves native hardware keyboard support whileevent.stopImmediatePropagation()in thewindowcapture phase guaranteesonKeyPressis not double-invoked on Web. -
Unit Tests (
tests/unit/ValidateCodeInputTest.tsx):- Verify that pressing
Shift+TabwhenfocusedIndex > 0moves focus tofocusedIndex - 1and preventsfocus-trapfrom wrapping focus outside the input. - Verify that pressing
Shift+Tabon slot0orTabon slotmaxLength - 1does not stop propagation so focus can naturally move out of the component.
- Verify that pressing
What alternative solutions did you explore? (Optional)
- Deleting the
Tabbranch fromonKeyPress: Rejected becauseValidateCodeInputsupports hardware keyboards on native platforms (Android/iOS), wherewindow.addEventListenerdoes not run. - Customizing
isKeyBackward/isKeyForwardinFocusTrapForScreen: Rejected because coupling screen-level focus trap configuration to internal slot state ofValidateCodeInputleaks component internals into shared navigation infrastructure.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b6be874e7d6b47d1
Proposal
Please re-state the problem that we are trying to solve in this issue.
On the sign-in / magic code screen on Web and Desktop, when focus is on any digit slot after the first one (e.g. slot 3) and the user presses Shift+Tab, focus escapes the magic code input completely and jumps to the bottom language selector (Select Language / LocalePicker) in the footer instead of moving back to the previous digit slot (slot 2).
What is the root cause of that problem?
- On Web and Desktop, the sign-in screen is wrapped in
FocusTrapForScreen(src/components/FocusTrap/FocusTrapForScreen/index.web.tsx), which mounts an activefocus-trapinstance. focus-trapattaches a nativekeydownlistener directly todocumentin the capture phase ({capture: true}).- In
src/components/ValidateCodeInput.tsx, all 6 visual digit slots are driven by a single hidden backingTextInput. Because that input is the very first tabbable node in the screen's focus trap, pressingShift+Tabtriggersfocus-trap's capture listener ondocumentbefore React's synthetic event delegator runs. focus-traptreatsShift+Tabon the first tabbable node as a backward boundary exit, immediately wrapping focus to the last tabbable element on the screen (Select LanguageinLicenses.tsx).- Focusing the footer language selector blurs the hidden input, triggering
blurValidateCodeInput(), which resetsfocusedIndextoundefined. - When React's synthetic
onKeyPressfinally executes,focusedIndexis alreadyundefined, completely preventing the slot-to-slot navigation check (keyValue === 'Tab' && focusedIndex !== undefined) from running. Additionally, top-level(event as unknown as KeyboardEvent).shiftKeyinonKeyPressevaluates toundefinedon React Native Web's synthetic event wrapper.
What changes do you think we should make in order to solve the problem?
-
Capture-Phase Tab Interception on Web (
src/components/ValidateCodeInput.tsx): Add auseEffecton Web that listens forkeydownonwindowin the capture phase (window.addEventListener('keydown', handleKeyDownCapture, true)). Becausewindowcapture listeners fire beforedocumentcapture listeners in the DOM dispatch hierarchy, we can interceptShift+Tabbeforefocus-trapdetects it:useEffect(() => { if (typeof window === 'undefined') { return; } const handleKeyDownCapture = (event: KeyboardEvent) => { if (event.key !== 'Tab' || focusedIndex === undefined) { return; } const isInputFocused = document.activeElement === (inputRef.current as unknown as HTMLElement) || (inputRef.current as ComponentRef<typeof RNTextInput>)?.isFocused?.(); if (!isInputFocused) { return; } const isShift = event.shiftKey; const targetIndex = isShift ? focusedIndex - 1 : focusedIndex + 1; // Navigate internally between slots if (targetIndex >= 0 && targetIndex < maxLength) { event.preventDefault(); event.stopImmediatePropagation(); setInputAndIndex(targetIndex); inputRef.current?.focus(); } // At boundaries (Shift+Tab on index 0 or Tab on index maxLength - 1), do not prevent default // or stop propagation, allowing natural tabbing in/out of the component. }; window.addEventListener('keydown', handleKeyDownCapture, true); return () => { window.removeEventListener('keydown', handleKeyDownCapture, true); }; }, [focusedIndex, maxLength]); -
Preserve Native Hardware Keyboards: Retain the existing
onKeyPressTab logic (lines 416-425) for iOS and Android platforms, ensuring hardware and Bluetooth keyboards continue to function properly on mobile devices wherewindowis unavailable.
What specific scenarios should we cover in automated tests?
In tests/unit/ValidateCodeInputTest.tsx:
- Backward navigation: When
focusedIndex === 2, dispatching akeydownevent forTabwithshiftKey: trueupdatesfocusedIndexto1and asserts thatdefaultPreventedandimmediatePropagationStoppedaretrue. - Forward navigation: When
focusedIndex === 1, dispatchingTabupdatesfocusedIndexto2. - Boundary exit backward: When
focusedIndex === 0, dispatchingTabwithshiftKey: truedoes not prevent default or stop propagation, allowing natural exit to the previous field. - Boundary exit forward: When
focusedIndex === maxLength - 1, dispatchingTabwithout Shift allows natural exit to the next field.
What alternative solutions did you explore? (Optional)
- Removing
onKeyPressTab logic entirely: Explored removingonKeyPressTab handling, but rejected it because it breaks hardware keyboard navigation on native iOS and Android apps. - Customizing global
FocusTrapForScreenconfiguration: Rejected because overridingisKeyBackwardorisKeyForwardat the screen level tightly couples the application-wide navigation trap to the internal state of a single form input.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
On the Sign-In magic code screen on Web, pressing Tab moves focus forward from one magic code digit slot to the next, and pressing Shift+Tab on the first slot moves focus out of the magic code input to "Select Language". However, when focused on any slot after the first (slots 2–6, i.e. focusedIndex > 0), pressing Shift+Tab jumps straight to "Select Language" instead of moving focus back to the previous magic code slot (focusedIndex - 1).
What is the root cause of that problem?
ValidateCodeInput(src/components/ValidateCodeInput.tsx) renders 6 visual digit slots backed by a single underlying<TextInput>DOM<input>, tracking the active slot in React state (focusedIndex). That single<input>is the first tabbable DOM node inside the screen's focus trap (FocusTrapForScreen).FocusTrapForScreen(src/components/FocusTrap/FocusTrapForScreen/index.web.tsx) usesfocus-trap, which attaches a nativekeydownlistener ondocumentin the capture phase (doc.addEventListener('keydown', checkTabKey, {capture: true})).- When the user presses forward
Tabon slots 0–4,focus-trap'scheckTabKeychecks whether the active element is the last tabbable node in the trap. Since the<input>is the first tabbable node (followed by "Use backup code", "Select Language", etc.),focus-trapdoes nothing during capture, allowing the event to reachreact-native-web's bubble-phaseonKeyPress(onKeyDown) handler inValidateCodeInput.tsx(lines 403–425), which callsevent.preventDefault()and advancesfocusedIndextofocusedIndex + 1. - However, when the user presses
Shift+Tab(event.shiftKey === true) on slots 1–5 (focusedIndex > 0),focus-trap'scheckTabKeyruns in thedocumentcapture phase beforeValidateCodeInput'sonKeyPresshandler ever runs. Becausedocument.activeElementis the<input>—whichfocus-trapsees asfirstTabbableNode—focus-trap'sfindNextNavNodereturnslastTabbableNode("Select Language" /LocalePicker), callsevent.preventDefault(), and immediately calls_tryFocus(destinationNode). - Focusing "Select Language" synchronously blurs the hidden
<input>, triggeringValidateCodeInput'sonBlur(ValidateCodeInput.tsx:492-496), which resetsfocusedIndextoundefinedbeforeonKeyPressis ever reached.
(Note: In [email protected], checkTabKey / checkKeyNav does not check event.defaultPrevented, so a capture listener on window that only calls event.preventDefault() without event.stopPropagation() will still allow focus-trap on document to steal focus to "Select Language".)
What changes do you think we should make in order to solve the problem?
In src/components/ValidateCodeInput.tsx:
- Add a capture-phase
windowkeydownlistener hook (mirroringuseValidateCodePasteright above it inValidateCodeInput.tsx:32-65) that runs on web beforefocus-trap'sdocumentcapture-phase listener:- Check
(inputRef.current as ComponentRef<typeof RNTextInput>)?.isFocused?.() ?? false(matchinguseValidateCodePasteat line 44 without unsafe HTMLElement casts) andfocusedIndex !== undefined. - Guard that
event.key === CONST.KEYBOARD_SHORTCUTS.TAB.shortcutKeyand no non-Shift modifier is held (!event.altKey && !event.ctrlKey && !event.metaKey). - Compute
newFocusedIndex = event.shiftKey ? focusedIndex - 1 : focusedIndex + 1. - When
newFocusedIndex >= 0 && newFocusedIndex < maxLength(an internal slot-to-slot transition):- Update both
lastFocusedIndex.current = newFocusedIndexandsetInputAndIndex(newFocusedIndex)(note that existingTabhandling inonKeyPressforgot to updatelastFocusedIndex.current, unliketapGestureat line 313 andBackspaceat line 399). - Call
event.preventDefault()andevent.stopPropagation()sofocus-trap'sdocumentcapture listener (checkTabKey) never runs and never wraps focus to "Select Language", andonKeyPressdoes not double-process the same keypress.
- Update both
- When
newFocusedIndex < 0(Shift+Tabon slot 0) ornewFocusedIndex >= maxLength(Tabon slot 5):- Do not stop propagation or prevent default—let
focus-trap/ the browser move focus out ofValidateCodeInputto the previous ("Select Language") or next ("Use backup code") focusable element, whileonBlurclearsfocusedIndex.
- Do not stop propagation or prevent default—let
- Check
- Keep
Tabhandling inonKeyPress(ValidateCodeInput.tsx:403-425) for native hardware keyboards (withlastFocusedIndex.current = newFocusedIndexadded):- On iOS/iPadOS/Android native with a hardware keyboard,
typeof window.addEventListener/ DOM capture does not apply, andonKeyPresshandlesTab. Keeping theTabbranch inonKeyPress(whileevent.stopPropagation()in the webwindowcapture listener preventsonKeyPressfrom firing for internal slot transitions on web) preserves native hardware keyboard behavior and existingonKeyPresstests.
- On iOS/iPadOS/Android native with a hardware keyboard,
type UseValidateCodeTabNavigationParams = {
inputRef: React.MutableRefObject<InputType | null>;
focusedIndex: number | undefined;
maxLength: number;
lastFocusedIndex: React.MutableRefObject<number>;
setInputAndIndex: (index: number) => void;
};
function useValidateCodeTabNavigation({
inputRef,
focusedIndex,
maxLength,
lastFocusedIndex,
setInputAndIndex,
}: UseValidateCodeTabNavigationParams) {
useEffect(() => {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return;
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== CONST.KEYBOARD_SHORTCUTS.TAB.shortcutKey || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
const isFocused = (inputRef.current as ComponentRef<typeof RNTextInput>)?.isFocused?.() ?? false;
if (!isFocused || focusedIndex === undefined) {
return;
}
const newFocusedIndex = event.shiftKey ? focusedIndex - 1 : focusedIndex + 1;
if (newFocusedIndex >= 0 && newFocusedIndex < maxLength) {
lastFocusedIndex.current = newFocusedIndex;
setInputAndIndex(newFocusedIndex);
event.preventDefault();
event.stopPropagation();
}
};
window.addEventListener('keydown', handleKeyDown, true);
return () => window.removeEventListener('keydown', handleKeyDown, true);
}, [focusedIndex, inputRef, lastFocusedIndex, maxLength, setInputAndIndex]);
}
What alternative solutions did you explore? (Optional)
- Calling only
event.preventDefault()in awindowcapture listener withoutevent.stopPropagation():focus-trap'scheckTabKey/checkKeyNavdoes not checkevent.defaultPrevented. Withoutevent.stopPropagation(), the event still reachesdocumentcapture andfocus-trapstill focuseslastTabbableNode("Select Language"). - Removing
Tabhandling fromonKeyPressentirely: That would break hardware keyboardTab/Shift+Tabnavigation on native (iPad/Android) wherewindow/documentDOM events do not exist.
📣 @xian96xx! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
@MelvinBot implement this
The root cause and the window capture listener are right. Implement the proposal with these adjustments.
-
Keep the Tab branch in
onKeyPress. The new listener is web only. Guard it withtypeof document === 'undefined', same as the paste listener in this file, and return early there. On iOS and Android, hardware-keyboard Tab still has to move between slots throughonKeyPress. On web, an in-range Tab never reaches that branch because propagation is stopped. Shift+Tab from slot 1 and Tab from the last slot stay unstopped, and the existing branch already ignores an index outside0 .. maxLength - 1. -
preventDefault()is not enough.focus-trapcheckKeyNavfocuses the wrapped node without readingdefaultPreventedand without stopping propagation. For an in-range move, callpreventDefault()andstopPropagation()on the window capture listener so thedocumentlistener never runs. Do that only when the next index is>= 0and< maxLength. Shift+Tab on slot 1 and Tab on the last slot must still leave the field the way they do today. -
Ignore the event unless
event.key === 'Tab'and none ofaltKey,ctrlKey, ormetaKeyis set. -
Handle the event only when this hidden input is focused. Use
inputRef.current.isFocused(), which the paste handler already uses. When the ref is anHTMLElement, also requiredocument.activeElement === inputRef.current, since that is the nodefocus-trapcompares with the first tabbable node. -
Keep the current index in a ref and update that ref inside the handler before
setInputAndIndex. The effect closure is stale if another Tab is delivered before React re-renders, so key repeat would apply the same slot twice. CallsetInputAndIndexwith the next index. Do not blur the input. An extrafocus()is unnecessary, because stopping the event means the trap never moves focus. -
Add a short comment on the listener explaining why it exists:
focus-traplistens forkeydownondocumentin the capture phase and wraps Shift+Tab when this single input is the first tabbable node. React'sonKeyPressruns only after that focus move, andonBlurhas already clearedfocusedIndex. -
Add
tests/ui/ValidateCodeInputTest.tsxwith Given / When / Then comments. Dispatch a nativeKeyboardEventonwindow.fireEventononKeyPressdoes not reach this listener. Move to a middle slot with ArrowRight first. Then assert:- Shift+Tab from a middle slot moves to the previous slot,
defaultPreventedis true, and the input stays focused. Assert the slot with theenter digit N of 6announcement. - Tab from a middle slot moves to the next slot and prevents default.
- Shift+Tab from slot 1 does not prevent default.
- Tab from the last slot does not prevent default.
- ArrowLeft, ArrowRight, Backspace, and a digit still behave as they do now.
- Shift+Tab from a middle slot moves to the previous slot,
Please verify on web: sign-in magic code, 2FA, and one RHP magic-code screen. Shift+Tab from slot 3 lands on slot 2. Shift+Tab from slot 1 and Tab from the last slot still leave the field. Forward Tab between slots still works.
🤖 Draft PR created: Move Shift+Tab to the previous magic code slot instead of leaving the input Please mark it as "Ready for review" or ask me to do that for you when it is ready for review.
I applied all 7 adjustments in ValidateCodeInput.tsx:346-385. I also added tests/ui/ValidateCodeInputTest.tsx, which passes 7 of 7. The in-range Tab and key-repeat tests fail on main.
Two deviations to review:
- The test dispatches on
document.body, notwindow. The event still passes through thewindowcapture listener first. An event dispatched onwindownever reachesdocument, so the test's stand-infocus-traplistener would never run. Then the test could not show thatstopPropagation()keeps the trap from running. - I added a shared
isInputFocusedhelper (line 29). It holds the paste handler's existingisFocused()cast, and both listeners use it. A second copy of the cast would exceed the file's ESLint seatbelt limit forno-unsafe-type-assertion.
Not verified on a device. This run was limited to the Android tester, so I couldn't run the web checks you asked for. The Android emulator was also unreachable for the whole run (adb: device 'emulator-5554' not found). The web checks are still open: sign-in, 2FA, and an RHP magic-code screen.
Local checks
npm test -- tests/ui/ValidateCodeInputTest.tsx: 7 passed.npm run typecheck: passed.npm run lint-changed: no errors in the changed files.npm run spell-changed: 0 issues.- React Compiler compliance check on
ValidateCodeInput.tsx: passed. oxfmt: no changes.
@rojiphil Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!
@rojiphil Still overdue 6 days?! Let's take care of this!
@rojiphil Still overdue 6 days?! Let's take care of this!
Not overdue. Evaluating Melvin's solution.
@MelvinBot proposal LGTM with the mentioned adjustments at https://github.com/Expensify/App/issues/104839#issuecomment-6407378545. 🎀👀🎀 C+ reviewed
Triggered auto assignment to @NikkiWines, see https://stackoverflow.com/c/expensify/questions/7972 for more details.