Skip to content

[HOLD for payment 2025-11-04] [$250] Ensure the focus in the chat switcher does not change when the API results get in #71777

Closed

Description

@mountiny

Coming from here

Problem

1. CMD+K to open the chat switcher
1. Type a few letters
1. Hit arrow down to go to the 3rd result
1. Go to press enter to switch to 3rd result
1. API request completes
1. Focus jumps to 1st result, and I press enter on the 1st result by mistake

Solution

Make sure to keep the focus on the row that the user switched to, even after the API results populate. That means the content of the option row can change, but if you clicked down to third row, you will remain on third row

Upwork Automation - Do Not Edit
  • Upwork Job URL: https://www.upwork.com/jobs/~021973752690388910836
  • Upwork Job ID: 1973752690388910836
  • Last Price Increase: 2025-10-09
  • Automatic offers:
    • FitseTLT | Contributor | 109067276
Issue OwnerCurrent Issue Owner: @sonialiap

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Oct 2, 2025
  2. melvin-bot commented on Oct 2, 2025

    @melvin-bot

    Triggered auto assignment to @kadiealexander (Bug), see https://stackoverflow.com/c/expensify/questions/14418 for more details. Please add this bug to a GH project, as outlined in the SO.

  3. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Oct 2, 2025
  4. changed the title [-]Ensure the focus in the chat switcher does not change when the API results get in[/-] [+][$250] Ensure the focus in the chat switcher does not change when the API results get in[/+] on Oct 2, 2025
  5. melvin-bot commented on Oct 2, 2025

    @melvin-bot
  6. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Oct 2, 2025
  7. melvin-bot commented on Oct 2, 2025

    @melvin-bot

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

  8. ShridharGoel commented on Oct 2, 2025

    @ShridharGoel
    Contributor

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    The chat switcher (Command/Ctrl + K) moves keyboard focus back to the first search result whenever the option list refreshes after an API response. If I arrow down to the third row and the list re-renders, the highlight jumps to row one, so the next Enter opens the wrong chat.

    What is the root cause of that problem?

    BaseSelectionListWithSections unconditionally calls updateAndScrollToFocusedIndex(0) whenever the option list changes while the search input still has text. That logic lives in the focus-reset effect and ignores whatever index the user already chose, so any data refresh snaps the focus to the first item

    useEffect(() => {
    // Avoid changing focus if the textInputValue remains unchanged.
    if (
    (prevTextInputValue === textInputValue && flattenedSections.selectedOptions.length === prevSelectedOptionsLength) ||
    flattenedSections.allOptions.length === 0 ||
    (flattenedSections.selectedOptions.length !== prevSelectedOptionsLength && shouldUpdateFocusedIndex)
    ) {
    return;
    }
    // Handle clearing search
    if (prevTextInputValue !== '' && textInputValue === '') {
    const foundSelectedItemIndex = flattenedSections.allOptions.findIndex(isItemSelected);
    const singleSectionList = slicedSections.length < 2;
    if (foundSelectedItemIndex !== -1 && singleSectionList && !canSelectMultiple) {
    const requiredPage = Math.ceil((foundSelectedItemIndex + 1) / CONST.MAX_SELECTION_LIST_PAGE_LENGTH);
    setCurrentPage(requiredPage);
    updateAndScrollToFocusedIndex(foundSelectedItemIndex);
    return;
    }
    }
    // Remove the focus if the search input is empty and prev search input not empty or selected options length is changed (and allOptions length remains the same)
    // else focus on the first non disabled item
    const newSelectedIndex =
    (isEmpty(prevTextInputValue) && textInputValue === '') ||
    (flattenedSections.selectedOptions.length !== prevSelectedOptionsLength && prevAllOptionsLength === flattenedSections.allOptions.length)
    ? -1
    : 0;
    updateAndScrollToFocusedIndex(newSelectedIndex);
    }, [

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

    • Keep the current focus index when the list re-renders, only falling back to the first item if the user has never moved the highlight.
    • Clamp the preserved index when the refreshed list is shorter so we stay on the closest valid row instead of jumping to the top.
    • Allow the existing "reset to -1" path to run only when the list genuinely needs to drop focus (for example, when the filter text is cleared).
    • Add focusedIndex to the effect dependencies and skip calling updateAndScrollToFocusedIndex when the next index matches the current one to avoid redundant scrolls.
        useEffect(() => {
            if (
                (prevTextInputValue === textInputValue && flattenedSections.selectedOptions.length === prevSelectedOptionsLength) ||
                flattenedSections.allOptions.length === 0 ||
                (flattenedSections.selectedOptions.length !== prevSelectedOptionsLength && shouldUpdateFocusedIndex)
            ) {
                return;
            }
    
            if (prevTextInputValue !== '' && textInputValue === '') {
                const foundSelectedItemIndex = flattenedSections.allOptions.findIndex(isItemSelected);
                const singleSectionList = slicedSections.length < 2;
                if (foundSelectedItemIndex !== -1 && singleSectionList && !canSelectMultiple) {
                    const requiredPage = Math.ceil((foundSelectedItemIndex + 1) / CONST.MAX_SELECTION_LIST_PAGE_LENGTH);
                    setCurrentPage(requiredPage);
                    updateAndScrollToFocusedIndex(foundSelectedItemIndex);
                    return;
                }
            }
    
            const maxFocusableIndex = flattenedSections.allOptions.length - 1;
            const shouldRemoveFocus =
                (isEmpty(prevTextInputValue) && textInputValue === '') ||
                (flattenedSections.selectedOptions.length !== prevSelectedOptionsLength && prevAllOptionsLength === flattenedSections.allOptions.length);
    
            const nextIndex = focusedIndex >= 0
                ? shouldRemoveFocus
                    ? -1
                    : Math.min(focusedIndex, maxFocusableIndex)
                : shouldRemoveFocus
                ? -1
                : 0;
    
            if (nextIndex === focusedIndex || nextIndex > maxFocusableIndex) {
                return;
            }
    
            updateAndScrollToFocusedIndex(nextIndex);
        }, [
            canSelectMultiple,
            focusedIndex,
            flattenedSections.allOptions.length,
            flattenedSections.selectedOptions.length,
            prevTextInputValue,
            textInputValue,
            updateAndScrollToFocusedIndex,
            prevSelectedOptionsLength,
            prevAllOptionsLength,
            shouldUpdateFocusedIndex,
            flattenedSections.allOptions,
            isItemSelected,
            slicedSections.length,
        ]);

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    • Unit-test BaseSelectionListWithSections so that after moving focus to a non-zero index, re-rendering with the same search text keeps the highlight on that index.
    • Verify that when the refreshed list shrinks, the focus clamps to the last available row instead of resetting to the top.
    • Ensure clearing the search text (or otherwise triggering the "remove focus" branch) still drops the highlight as before.
  9. FitseTLT commented on Oct 2, 2025

    @FitseTLT
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2025-10-02 17:26:02 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    Ensure the focus in the chat switcher does not change when the API results get in

    What is the root cause of that problem?

    We have a logic to focus on the first result if its text matches the search text here

    useEffect(() => {
    const targetText = autocompleteQueryValue;
    if (shouldHighlight(normalizedReferenceText, targetText)) {
    onHighlightFirstItem?.();
    }
    }, [autocompleteQueryValue, onHighlightFirstItem, normalizedReferenceText]);

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

    This was implemented in here to highlight the first item whose text matches the search text. So here to avoid unnecessary confusion if the user has already manually focused on a non-zero index we should skip it.

    const updateAndScrollToFocusedIndex = useCallback(
    (newFocusedIndex: number) => {
    setFocusedIndex(newFocusedIndex);
    scrollToIndex(newFocusedIndex, true);
    },
    [scrollToIndex, setFocusedIndex],

    const updateAndScrollToFocusedIndex = useCallback(
            (newFocusedIndex: number, shouldSkipWhenIndexNonZero = false) => {
                if (shouldSkipWhenIndexNonZero && focusedIndex > 0) {
                    return;
                }
                setFocusedIndex(newFocusedIndex);
                scrollToIndex(newFocusedIndex, true);
            },
            [scrollToIndex, setFocusedIndex, focusedIndex],
        );
    

    onHighlightFirstItem={() => listRef.current?.updateAndScrollToFocusedIndex(1)}

                        onHighlightFirstItem={() => listRef.current?.updateAndScrollToFocusedIndex(1, true)}
    
    

    Additionally we can remove onHighlightFirstItem from dependency here

    }, [autocompleteQueryValue, onHighlightFirstItem, normalizedReferenceText]);

    or pass memoized callback here
    onHighlightFirstItem={() => listRef.current?.updateAndScrollToFocusedIndex(1)}

    because currently the effect is running even if the first result text hasn't changed (normalizedReferenceText)

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    N / A

    What alternative solutions did you explore? (Optional)

  10. M00rish commented on Oct 3, 2025

    @M00rish
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2025-10-03 02:07:47 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    Ensure the focus in the chat switcher does not change when the API results get in

    What is the root cause of that problem?

    new behavior

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

    when switching focus with arrows:

    const [focusedIndex, setFocusedIndex] = useArrowKeyFocusManager({
    initialFocusedIndex: flattenedSections.allOptions.findIndex((option) => option.keyForList === initiallyFocusedOptionKey),
    maxIndex: Math.min(flattenedSections.allOptions.length - 1, CONST.MAX_SELECTION_LIST_PAGE_LENGTH * currentPage - 1),
    disabledIndexes: disabledArrowKeyIndexes,
    isActive: shouldSubscribeToArrowKeyEvents && isFocused,
    onFocusedIndexChange: (index: number) => {
    const focusedItem = flattenedSections.allOptions.at(index);
    if (focusedItem) {
    onArrowFocus(focusedItem);
    }

    we can preserve the focused index :

        const [focusedIndex, setFocusedIndex] = useArrowKeyFocusManager({
    ...
            onFocusedIndexChange: (index: number) => {
                const focusedItem = flattenedSections.allOptions.at(index);
                if (focusedItem) {
                    focusedItemKeyRef.current = index;
                    onArrowFocus(focusedItem);
    

    and in updateAndScrollToFocusedIndex:

    const updateAndScrollToFocusedIndex = useCallback(
            (newFocusedIndex: number) => {
     
    
                    if (focusedItemKeyRef.current && focusedItemKeyRef.current !== -1) {
                        setFocusedIndex(focusedItemKeyRef.current);
                        scrollToIndex(focusedItemKeyRef.current, true);
                        return; 
                    }
    
                setFocusedIndex(newFocusedIndex);
                scrollToIndex(newFocusedIndex, true);
                }   
    

    and we could introduce a new argument for updateAndScrollToFocusedIndex when we want focusedItemKeyRef to be ignored and focus normally

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    N/A

    What alternative solutions did you explore? (Optional)

    N/A

  11. 31 remaining items

  12. added
    Awaiting PaymentAuto-added when associated PR is deployed to production
    BugSomething is broken. Auto assigns a BugZero manager.
    and removed
    ReviewingHas a PR in review
    BugSomething is broken. Auto assigns a BugZero manager.
    on Nov 4, 2025
  13. melvin-bot commented on Nov 4, 2025

    @melvin-bot

    Triggered auto assignment to @sonialiap (Bug), see https://stackoverflow.com/c/expensify/questions/14418 for more details. Please add this bug to a GH project, as outlined in the SO.

  14. changed the title [-][$250] Ensure the focus in the chat switcher does not change when the API results get in[/-] [+][HOLD for payment 2025-11-04] [$250] Ensure the focus in the chat switcher does not change when the API results get in[/+] on Nov 4, 2025
  15. mountiny commented on Nov 4, 2025

    @mountiny
    ContributorAuthor
  16. mallenexpensify commented on Nov 5, 2025

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor: @FitseTLT paid $250 via Upwork
    Contributor+: @DylanDylann due $250 via NewDot

    @DylanDylann plz complete the BZ checklist.

  17. DylanDylann commented on Nov 5, 2025

    @DylanDylann
    Contributor

    BugZero Checklist:

    • [Contributor] The offending PR has been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      Link to comment: This isn’t a bug — it looks more like an improvement we hadn’t considered before.

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      Link to discussion:

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

    • [BugZero Assignee] Create a GH issue for creating/updating the regression test once above steps have been agreed upon.

      Link to issue:https://github.com/Expensify/Expensify/issues/565231

    Regression Test Proposal

    Test:

    Note: this should be tested only on Web (mac) and Desktop platforms

    1. CMD+K to open the chat switcher
    2. Type a text that will exactly match with the text of any item (report) and at the same time will have multiple results (at least two results)
    3. While the loading indicator is still loading, hit arrow down to go to the 2nd result
    4. Verify when API request completes (loading indicator disappears) the focus still remains on the 2nd result (does not switch back to the first result).

    Do we agree 👍 or 👎

  18. sonialiap commented on Nov 5, 2025

    @sonialiap
    Contributor

    Looks like Matt made the payment in Upwork so I'm closing this out

  19. trjExpensify commented on Dec 5, 2025

    @trjExpensify
    Contributor

    approved $250 for @DylanDylann

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions