Skip to content

Commit 0e0ce81

Browse files
authored
fix(completion): prevent error when getting activeItem with an empty collection (#623)
1 parent a58fa77 commit 0e0ce81

4 files changed

Lines changed: 38 additions & 5 deletions

File tree

bundlesize.config.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"files": [
33
{
44
"path": "packages/autocomplete-core/dist/umd/index.production.js",
5-
"maxSize": "5.25 kB"
5+
"maxSize": "5.5 kB"
66
},
77
{
88
"path": "packages/autocomplete-js/dist/umd/index.production.js",

packages/autocomplete-core/src/__tests__/completion.test.ts

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import userEvent from '@testing-library/user-event';
22

3-
import { createCollection, createPlayground } from '../../../../test/utils';
3+
import {
4+
createCollection,
5+
createPlayground,
6+
runAllMicroTasks,
7+
} from '../../../../test/utils';
48
import { createAutocomplete } from '../createAutocomplete';
59

610
describe('completion', () => {
@@ -55,6 +59,33 @@ describe('completion', () => {
5559
);
5660
});
5761

62+
test('does not throw without collections with panel open', async () => {
63+
const onStateChange = jest.fn();
64+
const { inputElement } = createPlayground(createAutocomplete, {
65+
onStateChange,
66+
openOnFocus: true,
67+
initialState: {
68+
collections: [],
69+
},
70+
shouldPanelOpen() {
71+
return true;
72+
},
73+
});
74+
75+
inputElement.focus();
76+
await runAllMicroTasks();
77+
78+
userEvent.type(inputElement, '{arrowup}');
79+
await runAllMicroTasks();
80+
expect(onStateChange).toHaveBeenLastCalledWith(
81+
expect.objectContaining({
82+
state: expect.objectContaining({
83+
completion: null,
84+
}),
85+
})
86+
);
87+
});
88+
5889
test('does not set completion when panel is closed', () => {
5990
const onStateChange = jest.fn();
6091
const { inputElement } = createPlayground(createAutocomplete, {

packages/autocomplete-core/src/getCompletion.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,5 @@ export function getCompletion<TItem extends BaseItem>({
1212
return null;
1313
}
1414

15-
const { itemInputValue } = getActiveItem(state)!;
16-
17-
return itemInputValue || null;
15+
return getActiveItem(state)?.itemInputValue || null;
1816
}

packages/autocomplete-core/src/utils/getNextActiveItemId.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ export function getNextActiveItemId(
2020
itemCount: number,
2121
defaultActiveItemId: number | null
2222
): number | null {
23+
if (!itemCount) {
24+
return null;
25+
}
26+
2327
if (
2428
moveAmount < 0 &&
2529
(baseIndex === null || (defaultActiveItemId !== null && baseIndex === 0))

0 commit comments

Comments
 (0)