Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[C+ Checklist Needs Completion] [$250] The focused background isn't updated when the selected option is updated from BE side #54089

Closed
1 of 8 tasks
m-natarajan opened this issue Dec 13, 2024 · 33 comments
Assignees
Labels
Awaiting Payment Auto-added when associated PR is deployed to production Bug Something is broken. Auto assigns a BugZero manager. Daily KSv2 External Added to denote the issue can be worked on by a contributor

Comments

@m-natarajan
Copy link

m-natarajan commented Dec 13, 2024

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: 9.0.75-6
Reproducible in staging?: Y
Reproducible in production?: Y
If this was caught on HybridApp, is this reproducible on New Expensify Standalone?:
If this was caught during regression testing, add the test name, ID and link from TestRail:
Email or phone of affected tester (no customers):
Logs: https://stackoverflow.com/c/expensify/questions/4856
Expensify/Expensify Issue URL:
Issue reported by: @DylanDylann
Slack conversation (hyperlinked to channel name): expensify_bugs

Action Performed:

  1. In the device 1, go to Settings> Preferences > Priority mode
  2. In the device 2, go to Settings> Preferences > Priority mode
  3. In the device 2, click on another option

Expected Result:

The selected option is updated in the device 1 but the focus background isn't updated

Actual Result:

The focused background isn't updated in the device 1

Workaround:

Unknown

Platforms:

Which of our officially supported platforms is this issue occurring on?

  • Android: Standalone
  • Android: HybridApp
  • Android: mWeb Chrome
  • iOS: Standalone
  • iOS: HybridApp
  • iOS: mWeb Safari
  • MacOS: Chrome / Safari
  • MacOS: Desktop

Screenshots/Videos

Add any screenshot/video evidence
Screen.Recording.2024-12-12.at.11.29.54.mov
Recording.844.mp4

View all open jobs on GitHub

Upwork Automation - Do Not Edit
  • Upwork Job URL: https://www.upwork.com/jobs/~021867633562881780913
  • Upwork Job ID: 1867633562881780913
  • Last Price Increase: 2024-12-13
  • Automatic offers:
    • DylanDylann | Reviewer | 105417829
    • daledah | Contributor | 105417830
Issue OwnerCurrent Issue Owner: @michaelkwardrop
@m-natarajan m-natarajan added Daily KSv2 Bug Something is broken. Auto assigns a BugZero manager. labels Dec 13, 2024
Copy link

melvin-bot bot commented Dec 13, 2024

Triggered auto assignment to @michaelkwardrop (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.

@nyomanjyotisa
Copy link
Contributor

Proposal

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

The focused background isn't updated when the selected option is updated from BE side

What is the root cause of that problem?

The focus is not updated when the selected priority mode changes, causing the UI to stay focused on the old selection.

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

We should manage the focus using a state variable (focusedKey) that gets updated when the priorityMode changes. This ensures the UI focus stays in sync with the selected priority mode.

    const [focusedKey, setFocusedKey] = useState(priorityMode);

    useEffect(() => {
        setFocusedKey(priorityMode);
    }, [priorityMode]);

And change the SelectionList to this

            <SelectionList
                sections={[{data: priorityModes}]}
                ListItem={RadioListItem}
                onSelectRow={(mode) => {
                    updateMode(mode);
                    setFocusedKey(mode.keyForList);
                }}
                shouldSingleExecuteRowSelect
                initiallyFocusedOptionKey={focusedKey}
                key={focusedKey}
            />

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

What alternative solutions did you explore? (Optional)

POC

New-Expensify.mp4

@linhvovan29546
Copy link
Contributor

linhvovan29546 commented Dec 13, 2024

Edited by proposal-police: This proposal was edited at 2024-12-13 02:47:13 UTC.

Proposal

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

The focused background isn't updated when the selected option is updated from BE side

What is the root cause of that problem?

In BaseSelectionList, the getItemBackgroundColorStyle function is used to get the background color for an item. This function only applies a background color if isFocused is true. When updates are received from the backend, only the isSelected state of priorityModes is updated, but isFocused is not. As a result, the focused background does not change.

isFocused && StyleUtils.getItemBackgroundColorStyle(!!item.isSelected, !!isFocused, !!item.isDisabled, theme.activeComponentBG, theme.hoverComponentBG),

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

Out dated

In PreferencesPage, we should use a useEffect with priorityModes as a dependency to determine the focusedIndex and then call ref.current.setFocusedIndex(focusedIndex).

useEffect(() => {
        const handleFocus = () => {
            const focusedIndex = priorityModes.findIndex((mode) => mode.isSelected)
            refSelectionList.current?.setFocusedIndex(focusedIndex)
        }
        handleFocus()
    }, [priorityModes])
.....
            <SelectionList
                ref={refSectionList}
                //    other props
             />

We also need to export the setFocusedIndex method from BaseSelectionList using useImperativeHandle to enable this functionality.

useImperativeHandle(ref, () => ({scrollAndHighlightItem, clearInputAfterSelect, updateAndScrollToFocusedIndex, updateExternalTextInputFocus, scrollToIndex}), [
scrollAndHighlightItem,
clearInputAfterSelect,
updateAndScrollToFocusedIndex,
updateExternalTextInputFocus,
scrollToIndex,
]);

New proposal:

In the BaseSelectionList add a new prop shouldAutoUpdateFocusedIndex, with a default value of false. This prop will be set to true only in the specific places where the focused index needs to be updated automatically, in order to avoid regression.
Use useEffect with flattenedSections as a dependency to update focusedIndex

    const isRenderRef = useRef(false)

    useEffect(() => {
        if (!shouldAutoUpdateFocusedIndex) return
        if (!isRenderRef.current) {
            isRenderRef.true
            return
        }
        const handleUpdateFocusedIndex = () => {
            const focusedIndex = flattenedSections.allOptions.findIndex((section) => section.isSelected)
            setFocusedIndex(focusedIndex)
        }
        handleUpdateFocusedIndex()
    }, [shouldAutoUpdateFocusedIndex, flattenedSections.allOptions])

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

Edited at 2024-12-14 04:46:13 UTC.
I don't see any test files for this, so I think we need to implement UI tests for the BaseSelectionList component, including the following actions: render the BaseSelectionList with the correct selected status, handling item press, and rerender the BaseSelectionList with the updated selected status.

N/A

What alternative solutions did you explore? (Optional)

N/A

@daledah
Copy link
Contributor

daledah commented Dec 13, 2024

Edited by proposal-police: This proposal was edited at 2024-12-19 16:20:50 UTC.

Proposal

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

The focused background isn't updated in the device 1

What is the root cause of that problem?

In BaseSelectionList, we don't have logics to change focusedIndex when there's update from BE.

This Bug also appears on similar pages: Language and Theme settings.

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

Add an useEffect to change focusedIndex when list data is updated to after here:

    useEffect(() => {
        const selectedItemIndex = flattenedSections.allOptions.findIndex((option) => option.isSelected);
        if (selectedItemIndex === -1 || selectedItemIndex === focusedIndex) {
            return;
        }
        setFocusedIndex(selectedItemIndex);
    }, [flattenedSections]);

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

For this specific issue, we can introduce these test cases for BaseSelectionList:

  1. Item press
    it('should handle item press correctly', () => {
        render(<RenderBaseSelectionList sections={[{data: SECTIONS}]} />);
        fireEvent.press(screen.getByTestId('base-list-item-2'));
        expect(mockOnSelectRow).toHaveBeenCalledWith({
            ...SECTIONS.at(1),
            shouldAnimateInHighlight: false,
        });
    });
  1. Changes to data from BE
    it('should update focused item when sections are updated from BE', () => {
        const updatedSections = SECTIONS.map((section) => ({
            ...section,
            isSelected: section.keyForList === '2',
        }));
        const {rerender} = render(<RenderBaseSelectionList sections={[{data: SECTIONS}]} />);
        fireEvent.press(screen.getByTestId('base-list-item-1'));
        rerender(<RenderBaseSelectionList sections={[{data: updatedSections}]} />);
        expect(screen.getByTestId('base-list-item-2')).toHaveAccessibilityValue({
            selected: true,
        });
    });
  1. Optionally, we can test for keyboard control as well, but this test will require to install an additional package @testing-library/user-event:
    it('should handle keyboard navigation correctly', async () => {
        render(<RenderBaseSelectionList sections={[{data: SECTIONS}]} />);
        await userEvent.keyboard('{arrowdown}');
        expect(screen.getByTestId('base-list-item-2', {})).toHaveAccessibilityValue({
            selected: true,
        });
    });

What alternative solutions did you explore? (Optional)

We can pass key to SelectionList in PriorityModePage to force re-render when priority mode is changed, however this can cause unwanted extra render count and make the UI briefly flashes but still noticeable.

@DylanDylann
Copy link
Contributor

hey contributors, please make sure that your proposal also fix this problem

@DylanDylann
Copy link
Contributor

DylanDylann commented Dec 13, 2024

@linhvovan29546
Copy link
Contributor

Updated proposal to fix this problem

#54089 (comment)

@mountiny mountiny added the External Added to denote the issue can be worked on by a contributor label Dec 13, 2024
Copy link

melvin-bot bot commented Dec 13, 2024

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

@melvin-bot melvin-bot bot changed the title The focused background isn't updated when the selected option is updated from BE side [$250] The focused background isn't updated when the selected option is updated from BE side Dec 13, 2024
@melvin-bot melvin-bot bot added the Help Wanted Apply this label when an issue is open to proposals by contributors label Dec 13, 2024
Copy link

melvin-bot bot commented Dec 13, 2024

Current assignee @DylanDylann is eligible for the External assigner, not assigning anyone new.

@mountiny
Copy link
Contributor

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

Make sure to add tests too

@linhvovan29546
Copy link
Contributor

Updated proposal to add automated tests

#54089 (comment)

@DylanDylann
Copy link
Contributor

@daledah Could you suggest an automated test for this one?

@linhvovan29546 It seems your test doesn't match this issue

@linhvovan29546
Copy link
Contributor

@DylanDylann The root issue lies in the BaseSelectionList component. In the PriorityModePage (and several other places), the SelectionList component is used, which is a wrapper around BaseSelectionList. Therefore, I write automated tests for the BaseSelectionList component covering three basic scenarios: rendering initial sections, handling item selection via press, and updating sections outside the component (simulating updates from the backend)

@DylanDylann
Copy link
Contributor

@linhvovan29546 Could you please detail your point maybe with some pseudo code?

@linhvovan29546
Copy link
Contributor

linhvovan29546 commented Dec 16, 2024

@DylanDylann Here are some details:

  • Mock Setup:
    • Mock the useIsFocused and useFocusEffect hooks from @react-navigation/native to simulate navigation-related behaviors during testing and .
    • Mocked data sections base on PriorityModePage, named MOCK_SECTIONS
    • Add testID and accessibilityState properties to the BaseListItem component
    • <View
      style={[
      wrapperStyle,
      isFocused && StyleUtils.getItemBackgroundColorStyle(!!item.isSelected, !!isFocused, !!item.isDisabled, theme.activeComponentBG, theme.hoverComponentBG),
      ]}
  • Implement test
    • Test Case: Render BaseSelectionList Correctly
      • Render BaseSelectionList with MOCK_SECTIONS
      • Verify that the component is rendered as expected.
        • EXPECTATION: The accessibilityState of the selected item should be true.
    • Test Case: Handle Item Press Correctly
      • Render BaseSelectionList with MOCK_SECTIONS
      • Simulate a press event on the item with test ID
      • Verify that the onSelectRow handler is called with the correct data.
        • EXPECTATION: The function is called using toHaveBeenCalledWith and contains the selected item data.
    • Test Case: Update Focused Item When Sections Change
      • Render the component with MOCK_SECTIONS.
      • Rerender the component with MOCK_UPDATED_SECTION
      • Verify that the accessibilityState updates correctly to reflect the changes.
        • EXPECTATION: The accessibilityState of the newly selected item should be true
Demo code
const ALTERNATE_TEXT = "Only show unread sorted alphabetically"
const MOCK_SECTIONS = [
  {
    "value": "gsd",
    "text": "#focus",
    "alternateText": ALTERNATE_TEXT,
    "keyForList": "gsd",
    "isSelected": true
  },
  {
    "value": "default",
    "text": "Most recent",
    "alternateText": "Show all chats sorted by most recent",
    "keyForList": "default",
    "isSelected": false
  }
]

jest.mock('@react-navigation/native', () => {
  const actualNav = jest.requireActual<typeof Navigation>('@react-navigation/native');
  return {
    ...actualNav,
    useIsFocused: jest.fn(),
    useFocusEffect: jest.fn()
  };
});

describe('BaseSelectionList Component', () => {
  const mockOnSelectRow = jest.fn();

  const RenderBaseSelectionList = (props: BaseSelectionListProps = {}) => (
    <BaseSelectionList
      sections={[{ data: props.sections }]}
      ListItem={RadioListItem}
      onSelectRow={mockOnSelectRow}
      shouldSingleExecuteRowSelect
      initiallyFocusedOptionKey={props.sections.find((mode) => mode.isSelected)?.keyForList}
    />
  )

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('renders BaseSelectionList correctly', () => {
    render(<RenderBaseSelectionList sections={MOCK_SECTIONS} />);
    expect(screen.getByTestId('base-list-item-gsd')).toHaveAccessibilityState({
      selected: true
    })
  });

  it('handles item press correctly', async () => {
    render(<RenderBaseSelectionList sections={MOCK_SECTIONS} />);
    fireEvent.press(screen.getByTestId('base-list-item-default'));
    expect(mockOnSelectRow).toHaveBeenCalledWith({
      ...MOCK_SECTIONS[1],
      shouldAnimateInHighlight: false
    })
  });

  it('updates focused Item when sections are updated from the background', async () => {
    const updatedSections = MOCK_SECTIONS.map((section) => ({
      ...section,
      isSelected: section.keyForList === 'default' ? true : false
    }))
    const { rerender, getByTestId } = render(<RenderBaseSelectionList sections={MOCK_SECTIONS} />);
    expect(screen.getByTestId('base-list-item-gsd')).toHaveAccessibilityState({
      selected: true
    })

    fireEvent.press(getByTestId('BaseListItem-gsd'));
    rerender(<RenderBaseSelectionList sections={updatedSections} />)
    await waitFor(() => expect(screen.getByTestId('base-list-item-default')).toHaveAccessibilityState({
      selected: true,
    }));

  });
});

@DylanDylann
Copy link
Contributor

@daledah Any update from you?

@melvin-bot melvin-bot bot added the Overdue label Dec 19, 2024
@daledah
Copy link
Contributor

daledah commented Dec 19, 2024

@DylanDylann i updated proposal

@DylanDylann
Copy link
Contributor

Let's go with @daledah's proposal because they come first with the correct RCA and solution. For the test section, I will review it thoroughly with the code change in the PR phase

🎀 👀 🎀 C+ Reviewed

@melvin-bot melvin-bot bot removed the Overdue label Dec 20, 2024
Copy link

melvin-bot bot commented Dec 20, 2024

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

@melvin-bot melvin-bot bot added Reviewing Has a PR in review Weekly KSv2 and removed Daily KSv2 labels Dec 24, 2024
Copy link

melvin-bot bot commented Jan 8, 2025

⚠️ Looks like this issue was linked to a Deploy Blocker here

If you are the assigned CME please investigate whether the linked PR caused a regression and leave a comment with the results.

If a regression has occurred and you are the assigned CM follow the instructions here.

If this regression could have been avoided please consider also proposing a recommendation to the PR checklist so that we can avoid it in the future.

Copy link

melvin-bot bot commented Jan 8, 2025

⚠️ Looks like this issue was linked to a Deploy Blocker here

If you are the assigned CME please investigate whether the linked PR caused a regression and leave a comment with the results.

If a regression has occurred and you are the assigned CM follow the instructions here.

If this regression could have been avoided please consider also proposing a recommendation to the PR checklist so that we can avoid it in the future.

@melvin-bot melvin-bot bot added Weekly KSv2 Awaiting Payment Auto-added when associated PR is deployed to production and removed Weekly KSv2 labels Jan 10, 2025
@melvin-bot melvin-bot bot changed the title [$250] The focused background isn't updated when the selected option is updated from BE side [HOLD for payment 2025-01-17] [$250] The focused background isn't updated when the selected option is updated from BE side Jan 10, 2025
@melvin-bot melvin-bot bot removed the Reviewing Has a PR in review label Jan 10, 2025
Copy link

melvin-bot bot commented Jan 10, 2025

Reviewing label has been removed, please complete the "BugZero Checklist".

Copy link

melvin-bot bot commented Jan 10, 2025

The solution for this issue has been 🚀 deployed to production 🚀 in version 9.0.82-12 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:

If no regressions arise, payment will be issued on 2025-01-17. 🎊

For reference, here are some details about the assignees on this issue:

Copy link

melvin-bot bot commented Jan 10, 2025

@DylanDylann @michaelkwardrop @DylanDylann The PR fixing this issue has been merged! The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the BugZero Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]

@srikarparsi
Copy link
Contributor

Hi @daledah and @DylanDylann, do you think you could take a look at this regression please which seems to come from this PR?

@DylanDylann
Copy link
Contributor

@srikarparsi Yes it is a regression from our prev PR. @daledah Let's create a PR to fix it, I believe that the fix is small

@michaelkwardrop
Copy link
Contributor

michaelkwardrop commented Jan 17, 2025

Payment summary:

Contributor: @daledah $125 - paid via UpWork ✅
C+: @DylanDylann $125 - paying via UpWork (once checklist is completed)

50% regression penalty #54931

@michaelkwardrop michaelkwardrop changed the title [HOLD for payment 2025-01-17] [$250] The focused background isn't updated when the selected option is updated from BE side [C+ Checklist Needs Completion] [$250] The focused background isn't updated when the selected option is updated from BE side Jan 17, 2025
@DylanDylann
Copy link
Contributor

DylanDylann commented Jan 20, 2025

BugZero Checklist:

  • [Contributor] Classify the bug:
Bug classification

Source of bug:

  • 1a. Result of the original design (eg. a case wasn't considered)
  • 1b. Mistake during implementation
  • 1c. Backend bug
  • 1z. Other:

Where bug was reported:

  • 2a. Reported on production (eg. bug slipped through the normal regression and PR testing process on staging)
  • 2b. Reported on staging (eg. found during regression or PR testing)
  • 2d. Reported on a PR
  • 2z. Other:

Who reported the bug:

  • 3a. Expensify user
  • 3b. Expensify employee
  • 3c. Contributor
  • 3d. QA
  • 3z. Other:
  • [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: No. This is a new improvement, not a bug

  • [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:

Regression Test Proposal

Test:

  1. In the device 1, go to Settings > Preferences > Priority mode
  2. In the device 2, go to Settings > Preferences > Priority mode
  3. In the device 2, click on another option
  4. Verify that: In device 1, selected option is updated and focused background is displayed correctly.

Do we agree 👍 or 👎

Sorry, something went wrong.

@michaelkwardrop
Copy link
Contributor

@melvin-bot melvin-bot bot added the Overdue label Jan 23, 2025
@michaelkwardrop
Copy link
Contributor

UPDATE

Payment summary:

Contributor: @daledah $125 - paid via UpWork ✅
C+: @DylanDylann $125 - paid via UpWork ✅

50% regression penalty #54931

@melvin-bot melvin-bot bot removed the Overdue label Jan 23, 2025
@michaelkwardrop
Copy link
Contributor

michaelkwardrop commented Jan 23, 2025

Job has been closed in Upwork, closing this out. Great work.

Image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting Payment Auto-added when associated PR is deployed to production Bug Something is broken. Auto assigns a BugZero manager. Daily KSv2 External Added to denote the issue can be worked on by a contributor
Projects
Status: Done
Development

No branches or pull requests

9 participants