Skip to content

Commit

Permalink
fix(@react-aria/selection): don't mutate non-empty selection upon focus
Browse files Browse the repository at this point in the history
closes adobe#7512
  • Loading branch information
alirezamirian committed Dec 13, 2024
1 parent 326f481 commit 1e591a5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
9 changes: 4 additions & 5 deletions packages/@react-aria/selection/src/useSelectableCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,12 +342,11 @@ export function useSelectableCollection(options: AriaSelectableCollectionOptions
}

manager.setFocused(true);

if (manager.focusedKey == null) {
let navigateToFirstKey = (key: Key | undefined | null) => {
let navigateToKey = (key: Key | undefined | null) => {
if (key != null) {
manager.setFocusedKey(key);
if (selectOnFocus) {
if (selectOnFocus && !manager.isSelected(key)) {
manager.replaceSelection(key);
}
}
Expand All @@ -357,9 +356,9 @@ export function useSelectableCollection(options: AriaSelectableCollectionOptions
// and either focus the first or last item accordingly.
let relatedTarget = e.relatedTarget as Element;
if (relatedTarget && (e.currentTarget.compareDocumentPosition(relatedTarget) & Node.DOCUMENT_POSITION_FOLLOWING)) {
navigateToFirstKey(manager.lastSelectedKey ?? delegate.getLastKey?.());
navigateToKey(manager.lastSelectedKey ?? delegate.getLastKey?.());
} else {
navigateToFirstKey(manager.firstSelectedKey ?? delegate.getFirstKey?.());
navigateToKey(manager.firstSelectedKey ?? delegate.getFirstKey?.());
}
} else if (!isVirtualized && scrollRef.current) {
// Restore the scroll position to what it was before.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,5 +107,27 @@ describe('useSelectableCollection', () => {
expect(options[1]).not.toHaveAttribute('aria-selected');
expect(options[2]).toHaveAttribute('aria-selected', 'true');
});

it("doesn't change the selection on focus in multiple selection selectOnFocus", async () => {
let onSelectionChange = jest.fn();
let {getByText} = render(
<>
<button>before</button>
<List
selectionMode="multiple"
selectionBehavior="replace"
defaultSelectedKeys={['i2', 'i3']}
onSelectionChange={onSelectionChange}>
<Item key="i1">Paco de Lucia</Item>
<Item key="i2">Vicente Amigo</Item>
<Item key="i3">Gerardo Nunez</Item>
</List>
</>
);
await user.click(getByText('before'));
await user.tab();

expect(onSelectionChange).not.toHaveBeenCalled();
});
});
});

0 comments on commit 1e591a5

Please sign in to comment.