App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-19] [$175] Sign-In - Shift+Tab moves focus to Select Language instead of the previous magic code slot

Open m-natarajan opened this issue 1 month ago • 33 comments

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:

  1. Open the sign-in / magic code page screen.
  2. Focus the magic code input and use the arrow keys to focus slot 3.
  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

Image

https://github.com/user-attachments/assets/c999096a-08a4-480e-b5c2-e97bdc468bff

View all open jobs on GitHub

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @mallenexpensify

m-natarajan avatar Oct 23 '26 12:10 m-natarajan

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.

  • ScreenWrapper wraps the sign-in page in FocusTrapForScreen (ScreenWrapper/index.tsx:290, FocusTrapForScreen/index.web.tsx:45-69).
  • focus-trap listens for keydown in the capture phase on document. That listener runs before React's handlers.
  • The magic code page renders one hidden TextInput behind all 6 slots. That input is the first tabbable node in the trap.
  • On Shift+Tab from the first tabbable node, focus-trap wraps to the last one: the footer LocalePicker (Licenses.tsx:27).
  • The input's onBlur then sets focusedIndex to undefined (ValidateCodeInput.tsx:492-496). When the Tab branch in onKeyPress finally runs, focusedIndex is undefined, 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):

  1. Add a keydown listener on window in the capture phase. It runs before focus-trap's document capture listener.
  2. In it, act only when document.activeElement is this component's hidden input and focusedIndex is defined.
  3. On Shift+Tab with focusedIndex > 0, or Tab with focusedIndex < maxLength - 1: call setInputAndIndex with the new index, then preventDefault() and stopImmediatePropagation().
  4. Otherwise do nothing, so Shift+Tab from slot 1 and Tab from slot 6 still leave the input normally.
  5. 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-trap registers doc.addEventListener('keydown', checkTabKey, {capture: true}). When the target is the group's first tabbable node and the key is Shift+Tab, it calls preventDefault() and focuses lastTabbableNode. It does not stop propagation.
  • React 19 attaches listeners to the root container, not document, so focus-trap always runs first. React's onKeyDownCapture would not help for the same reason.
  • react-native-web's TextInput passes the synthetic event to onKeyPress, so event.shiftKey is 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.


view run

MelvinBot avatar Oct 23 '26 12:10 MelvinBot

Triggered auto assignment to Contributor-plus team member for initial proposal review - @rojiphil (External)

melvin-bot[bot] avatar Oct 23 '26 12:10 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022113604832656559739

melvin-bot[bot] avatar Oct 23 '26 12:10 melvin-bot[bot]

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?

  1. Event Capture Phase Conflict: FocusTrapForScreen wraps the sign-in screen and relies on focus-trap, which attaches a native keydown listener to document in the capture phase ({ capture: true }).
  2. First Tabbable Node Behavior: The magic code component renders a single hidden TextInput DOM element representing the magic code input, making it the first tabbable node in the screen's focus trap.
  3. Premature Boundary Exit: When Shift+Tab is pressed, focus-trap intercepts the event on document during the capture phase—before React synthetic events fire. Because document.activeElement is the first tabbable node in the trap, focus-trap assumes the user is trying to exit the trap backwards, wraps focus around to the last tabbable node (LocalePicker), and triggers an onBlur that resets focusedIndex in ValidateCodeInput.

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.

  1. Modify src/components/ValidateCodeInput.tsx (or web-specific implementation): Add a useEffect hook that attaches a native keydown listener to window with { capture: true }:

    • Check if event.key === 'Tab'.
    • Ensure document.activeElement is the component's hidden input ref and focusedIndex is defined.
    • If event.shiftKey (Shift+Tab) AND focusedIndex > 0:
      • Call setInputAndIndex(focusedIndex - 1).
      • Call event.preventDefault() and event.stopImmediatePropagation() to prevent focus-trap on document from seeing the event.
    • If !event.shiftKey (Tab) AND focusedIndex < maxLength - 1:
      • Call setInputAndIndex(focusedIndex + 1).
      • Call event.preventDefault() and event.stopImmediatePropagation().
    • If focusedIndex === 0 on Shift+Tab or focusedIndex === maxLength - 1 on Tab, do nothing and allow the event to propagate naturally so focus-trap or default focus navigation handles boundary exits.
  2. Clean up redundant code: Remove the internal Tab handling logic in onKeyPress within ValidateCodeInput.tsx to 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)

  1. Handling in React's onKeyPress / onKeyDown: Suboptimal and non-functional because React's synthetic event handlers run after document capture listeners, meaning focus-trap changes focus before React processes the event.
  2. Modifying global FocusTrap configurations: Overriding isKeyBackward/isKeyForward in FocusTrapForScreen couples 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:

  1. Render ValidateCodeInput with maxLength={6}.
  2. Focus the input and set focusedIndex to 2.
  3. Dispatch a keydown event on window with { key: 'Tab', shiftKey: true }.
  4. Assert that setInputAndIndex was called with 1 and that defaultPrevented is true.
  5. Set focusedIndex to 0 and dispatch { key: 'Tab', shiftKey: true }.
  6. Assert that setInputAndIndex was NOT called and defaultPrevented is false (allowing exit).

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b60d704ba377be83

camesenin avatar Oct 23 '26 12:10 camesenin

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

j3ffffff avatar Oct 23 '26 12:10 j3ffffff

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?

  1. On Web, ScreenWrapper wraps the sign-in screen in FocusTrapForScreen (src/components/FocusTrap/FocusTrapForScreen/index.web.tsx), which instantiates a focus-trap instance.
  2. focus-trap attaches a native keydown listener in the capture phase on document:
    doc.addEventListener('keydown', checkTabKey, {capture: true});
    
  3. ValidateCodeInput (src/components/ValidateCodeInput.tsx) implements 6 visual digit slots backed by a single invisible TextInput. This hidden input is the first tabbable DOM node inside the screen's focus trap container.
  4. When focus is inside ValidateCodeInput (e.g. at slot 3) and the user presses Shift+Tab:
    • The native keydown capture event fires on document before React's event delegator dispatches to onKeyPress in ValidateCodeInput.tsx:416.
    • focus-trap inspects document.activeElement. Because document.activeElement is the single hidden TextInput (the first tabbable node in the trap container), focus-trap intercepts Shift+Tab as an escape/wrap-around from the top of the container and immediately focuses the last tabbable element on the screen (Select Language in Licenses.tsx).
    • Focusing the footer language selector causes the hidden TextInput to blur, which triggers blurValidateCodeInput() and resets focusedIndex to undefined (setFocusedIndex(undefined)).
    • When the React synthetic onKeyPress event finally executes, focusedIndex is already undefined, completely preventing the slot-to-slot navigation check (keyValue === 'Tab' && focusedIndex !== undefined) from running.

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, window in capture phase (addEventListener(..., true)) fires before document in capture phase.
  • When navigating between internal slots (targetIndex >= 0 && targetIndex < maxLength), calling event.preventDefault() and event.stopImmediatePropagation() stops the event on window, so focus-trap never receives the event and never blurs the input.
  • When on the first slot (slot 0) pressing Shift+Tab, or on the last slot pressing Tab, propagation is allowed to continue normally so keyboard accessibility across the rest of the page remains intact.
  • This resolves the issue universally wherever ValidateCodeInput is used (Sign-in, 2FA, Wallet verification, and RHP modals).

What alternative solutions did you explore? (Optional)

  • Configuring isKeyBackward in focusTrapOptions: Rejected because FocusTrapForScreen is 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 within ValidateCodeInput encapsulates 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 focusedIndex is 2, dispatching a keydown event for Tab with shiftKey: true updates focusedIndex to 1 and calls preventDefault().
  • Add a unit test verifying that when focusedIndex is 0, dispatching Tab with shiftKey: true does not prevent default, allowing natural exit.

bonnhatnguyen avatar Oct 23 '26 15:10 bonnhatnguyen

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 23 '26 15:10 melvin-bot[bot]

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?

  1. ScreenWrapper wraps the sign-in screen in FocusTrapForScreen (src/components/FocusTrap/FocusTrapForScreen/index.web.tsx), which activates a focus-trap instance on Web.
  2. focus-trap attaches a native keydown listener on document in the capture phase (doc.addEventListener('keydown', checkTabKey, {capture: true})), which executes before React's synthetic onKeyPress / onKeyDown handlers.
  3. ValidateCodeInput (src/components/ValidateCodeInput.tsx) renders a single backing TextInput behind all 6 visual slots. Because that TextInput is the first tabbable DOM node inside the focus trap, pressing Shift+Tab causes focus-trap to intercept the event in the capture phase and wrap focus to the last tabbable element in the trap (LocalePicker).
  4. This triggers TextInput.onBlur (src/components/ValidateCodeInput.tsx:492-496), which resets focusedIndex to undefined before onKeyPress (lines 416-425) runs.

What changes do you think we should make in order to solve the problem?

  1. Intercept Tab / Shift+Tab in the window capture phase in src/components/ValidateCodeInput.tsx: In the DOM event flow, a capture-phase listener on window (window.addEventListener('keydown', ..., true)) executes before focus-trap's capture-phase listener on document. Following the exact pattern already used by useValidateCodePaste in src/components/ValidateCodeInput.tsx (lines 32-65), check (inputRef.current as ComponentRef<typeof RNTextInput>)?.isFocused?.() (avoiding unsafe HTMLElement casts that violate @typescript-eslint/no-unsafe-type-assertion).

    When event.key === 'Tab' and the target slot index (focusedIndex - 1 for Shift+Tab, focusedIndex + 1 for Tab) is within [0, maxLength - 1], call event.preventDefault(), event.stopImmediatePropagation(), and advance the slot via setInputAndIndex(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]);
  1. Keep the keyValue === 'Tab' branch in onKeyPress (lines 416-425) for Native hardware keyboards: Unlike deleting the onKeyPress Tab branch (which would break hardware keyboard Tab / Shift+Tab navigation on iOS/Android native apps where window.addEventListener is not used), keeping onKeyPress preserves native hardware keyboard support while event.stopImmediatePropagation() in the window capture phase guarantees onKeyPress is not double-invoked on Web.

  2. Unit Tests (tests/unit/ValidateCodeInputTest.tsx):

    • Verify that pressing Shift+Tab when focusedIndex > 0 moves focus to focusedIndex - 1 and prevents focus-trap from wrapping focus outside the input.
    • Verify that pressing Shift+Tab on slot 0 or Tab on slot maxLength - 1 does not stop propagation so focus can naturally move out of the component.

What alternative solutions did you explore? (Optional)

  • Deleting the Tab branch from onKeyPress: Rejected because ValidateCodeInput supports hardware keyboards on native platforms (Android/iOS), where window.addEventListener does not run.
  • Customizing isKeyBackward / isKeyForward in FocusTrapForScreen: Rejected because coupling screen-level focus trap configuration to internal slot state of ValidateCodeInput leaks component internals into shared navigation infrastructure.

Enes2553 avatar Oct 24 '26 03:10 Enes2553

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?

  1. On Web and Desktop, the sign-in screen is wrapped in FocusTrapForScreen (src/components/FocusTrap/FocusTrapForScreen/index.web.tsx), which mounts an active focus-trap instance.
  2. focus-trap attaches a native keydown listener directly to document in the capture phase ({capture: true}).
  3. In src/components/ValidateCodeInput.tsx, all 6 visual digit slots are driven by a single hidden backing TextInput. Because that input is the very first tabbable node in the screen's focus trap, pressing Shift+Tab triggers focus-trap's capture listener on document before React's synthetic event delegator runs.
  4. focus-trap treats Shift+Tab on the first tabbable node as a backward boundary exit, immediately wrapping focus to the last tabbable element on the screen (Select Language in Licenses.tsx).
  5. Focusing the footer language selector blurs the hidden input, triggering blurValidateCodeInput(), which resets focusedIndex to undefined.
  6. When React's synthetic onKeyPress finally executes, focusedIndex is already undefined, completely preventing the slot-to-slot navigation check (keyValue === 'Tab' && focusedIndex !== undefined) from running. Additionally, top-level (event as unknown as KeyboardEvent).shiftKey in onKeyPress evaluates to undefined on React Native Web's synthetic event wrapper.

What changes do you think we should make in order to solve the problem?

  1. Capture-Phase Tab Interception on Web (src/components/ValidateCodeInput.tsx): Add a useEffect on Web that listens for keydown on window in the capture phase (window.addEventListener('keydown', handleKeyDownCapture, true)). Because window capture listeners fire before document capture listeners in the DOM dispatch hierarchy, we can intercept Shift+Tab before focus-trap detects 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]);
    
  2. Preserve Native Hardware Keyboards: Retain the existing onKeyPress Tab logic (lines 416-425) for iOS and Android platforms, ensuring hardware and Bluetooth keyboards continue to function properly on mobile devices where window is unavailable.

What specific scenarios should we cover in automated tests?

In tests/unit/ValidateCodeInputTest.tsx:

  1. Backward navigation: When focusedIndex === 2, dispatching a keydown event for Tab with shiftKey: true updates focusedIndex to 1 and asserts that defaultPrevented and immediatePropagationStopped are true.
  2. Forward navigation: When focusedIndex === 1, dispatching Tab updates focusedIndex to 2.
  3. Boundary exit backward: When focusedIndex === 0, dispatching Tab with shiftKey: true does not prevent default or stop propagation, allowing natural exit to the previous field.
  4. Boundary exit forward: When focusedIndex === maxLength - 1, dispatching Tab without Shift allows natural exit to the next field.

What alternative solutions did you explore? (Optional)

  1. Removing onKeyPress Tab logic entirely: Explored removing onKeyPress Tab handling, but rejected it because it breaks hardware keyboard navigation on native iOS and Android apps.
  2. Customizing global FocusTrapForScreen configuration: Rejected because overriding isKeyBackward or isKeyForward at the screen level tightly couples the application-wide navigation trap to the internal state of a single form input.

ADITYASINGH1206 avatar Oct 24 '26 13:10 ADITYASINGH1206

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 24 '26 13:10 melvin-bot[bot]

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?

  1. 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).
  2. FocusTrapForScreen (src/components/FocusTrap/FocusTrapForScreen/index.web.tsx) uses focus-trap, which attaches a native keydown listener on document in the capture phase (doc.addEventListener('keydown', checkTabKey, {capture: true})).
  3. When the user presses forward Tab on slots 0–4, focus-trap's checkTabKey checks 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-trap does nothing during capture, allowing the event to reach react-native-web's bubble-phase onKeyPress (onKeyDown) handler in ValidateCodeInput.tsx (lines 403–425), which calls event.preventDefault() and advances focusedIndex to focusedIndex + 1.
  4. However, when the user presses Shift+Tab (event.shiftKey === true) on slots 1–5 (focusedIndex > 0), focus-trap's checkTabKey runs in the document capture phase before ValidateCodeInput's onKeyPress handler ever runs. Because document.activeElement is the <input>—which focus-trap sees as firstTabbableNode—focus-trap's findNextNavNode returns lastTabbableNode ("Select Language" / LocalePicker), calls event.preventDefault(), and immediately calls _tryFocus(destinationNode).
  5. Focusing "Select Language" synchronously blurs the hidden <input>, triggering ValidateCodeInput's onBlur (ValidateCodeInput.tsx:492-496), which resets focusedIndex to undefined before onKeyPress is 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:

  1. Add a capture-phase window keydown listener hook (mirroring useValidateCodePaste right above it in ValidateCodeInput.tsx:32-65) that runs on web before focus-trap's document capture-phase listener:
    • Check (inputRef.current as ComponentRef<typeof RNTextInput>)?.isFocused?.() ?? false (matching useValidateCodePaste at line 44 without unsafe HTMLElement casts) and focusedIndex !== undefined.
    • Guard that event.key === CONST.KEYBOARD_SHORTCUTS.TAB.shortcutKey and 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 = newFocusedIndex and setInputAndIndex(newFocusedIndex) (note that existing Tab handling in onKeyPress forgot to update lastFocusedIndex.current, unlike tapGesture at line 313 and Backspace at line 399).
      • Call event.preventDefault() and event.stopPropagation() so focus-trap's document capture listener (checkTabKey) never runs and never wraps focus to "Select Language", and onKeyPress does not double-process the same keypress.
    • When newFocusedIndex < 0 (Shift+Tab on slot 0) or newFocusedIndex >= maxLength (Tab on slot 5):
      • Do not stop propagation or prevent default—let focus-trap / the browser move focus out of ValidateCodeInput to the previous ("Select Language") or next ("Use backup code") focusable element, while onBlur clears focusedIndex.
  2. Keep Tab handling in onKeyPress (ValidateCodeInput.tsx:403-425) for native hardware keyboards (with lastFocusedIndex.current = newFocusedIndex added):
    • On iOS/iPadOS/Android native with a hardware keyboard, typeof window.addEventListener / DOM capture does not apply, and onKeyPress handles Tab. Keeping the Tab branch in onKeyPress (while event.stopPropagation() in the web window capture listener prevents onKeyPress from firing for internal slot transitions on web) preserves native hardware keyboard behavior and existing onKeyPress tests.
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 a window capture listener without event.stopPropagation(): focus-trap's checkTabKey / checkKeyNav does not check event.defaultPrevented. Without event.stopPropagation(), the event still reaches document capture and focus-trap still focuses lastTabbableNode ("Select Language").
  • Removing Tab handling from onKeyPress entirely: That would break hardware keyboard Tab / Shift+Tab navigation on native (iPad/Android) where window/document DOM events do not exist.

xian96xx avatar Oct 25 '26 16:10 xian96xx

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

  1. Make sure you've read and understood the contributing guidelines.
  2. 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.
  3. 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.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Oct 25 '26 16:10 melvin-bot[bot]

@MelvinBot implement this

The root cause and the window capture listener are right. Implement the proposal with these adjustments.

  1. Keep the Tab branch in onKeyPress. The new listener is web only. Guard it with typeof 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 through onKeyPress. 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 outside 0 .. maxLength - 1.

  2. preventDefault() is not enough. focus-trap checkKeyNav focuses the wrapped node without reading defaultPrevented and without stopping propagation. For an in-range move, call preventDefault() and stopPropagation() on the window capture listener so the document listener never runs. Do that only when the next index is >= 0 and < maxLength. Shift+Tab on slot 1 and Tab on the last slot must still leave the field the way they do today.

  3. Ignore the event unless event.key === 'Tab' and none of altKey, ctrlKey, or metaKey is set.

  4. Handle the event only when this hidden input is focused. Use inputRef.current.isFocused(), which the paste handler already uses. When the ref is an HTMLElement, also require document.activeElement === inputRef.current, since that is the node focus-trap compares with the first tabbable node.

  5. 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. Call setInputAndIndex with the next index. Do not blur the input. An extra focus() is unnecessary, because stopping the event means the trap never moves focus.

  6. Add a short comment on the listener explaining why it exists: focus-trap listens for keydown on document in the capture phase and wraps Shift+Tab when this single input is the first tabbable node. React's onKeyPress runs only after that focus move, and onBlur has already cleared focusedIndex.

  7. Add tests/ui/ValidateCodeInputTest.tsx with Given / When / Then comments. Dispatch a native KeyboardEvent on window. fireEvent on onKeyPress does 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, defaultPrevented is true, and the input stays focused. Assert the slot with the enter digit N of 6 announcement.
    • 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.

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.

rojiphil avatar Oct 26 '26 03:10 rojiphil

🤖 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, not window. The event still passes through the window capture listener first. An event dispatched on window never reaches document, so the test's stand-in focus-trap listener would never run. Then the test could not show that stopPropagation() keeps the trap from running.
  • I added a shared isInputFocused helper (line 29). It holds the paste handler's existing isFocused() cast, and both listeners use it. A second copy of the cast would exceed the file's ESLint seatbelt limit for no-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.

MelvinBot avatar Oct 26 '26 03:10 MelvinBot

@rojiphil Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

melvin-bot[bot] avatar Oct 29 '26 21:10 melvin-bot[bot]

@rojiphil Still overdue 6 days?! Let's take care of this!

melvin-bot[bot] avatar Nov 02 '26 23:11 melvin-bot[bot]

@rojiphil Still overdue 6 days?! Let's take care of this!

melvin-bot[bot] avatar Nov 03 '26 01:11 melvin-bot[bot]

Not overdue. Evaluating Melvin's solution.

rojiphil avatar Nov 03 '26 02:11 rojiphil

@MelvinBot proposal LGTM with the mentioned adjustments at https://github.com/Expensify/App/issues/104839#issuecomment-6407378545. 🎀👀🎀 C+ reviewed

rojiphil avatar Nov 06 '26 03:11 rojiphil

Triggered auto assignment to @NikkiWines, see https://stackoverflow.com/c/expensify/questions/7972 for more details.

melvin-bot[bot] avatar Nov 06 '26 03:11 melvin-bot[bot]