Skip to content

Commit

Permalink
fix(completion): prevent error when getting activeItem with an empt…
Browse files Browse the repository at this point in the history
…y collection (#623)
  • Loading branch information
shortcuts committed Jul 8, 2021
1 parent a58fa77 commit 0e0ce81
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 5 deletions.
2 changes: 1 addition & 1 deletion bundlesize.config.json
Expand Up @@ -2,7 +2,7 @@
"files": [
{
"path": "packages/autocomplete-core/dist/umd/index.production.js",
"maxSize": "5.25 kB"
"maxSize": "5.5 kB"
},
{
"path": "packages/autocomplete-js/dist/umd/index.production.js",
Expand Down
33 changes: 32 additions & 1 deletion packages/autocomplete-core/src/__tests__/completion.test.ts
@@ -1,6 +1,10 @@
import userEvent from '@testing-library/user-event';

import { createCollection, createPlayground } from '../../../../test/utils';
import {
createCollection,
createPlayground,
runAllMicroTasks,
} from '../../../../test/utils';
import { createAutocomplete } from '../createAutocomplete';

describe('completion', () => {
Expand Down Expand Up @@ -55,6 +59,33 @@ describe('completion', () => {
);
});

test('does not throw without collections with panel open', async () => {
const onStateChange = jest.fn();
const { inputElement } = createPlayground(createAutocomplete, {
onStateChange,
openOnFocus: true,
initialState: {
collections: [],
},
shouldPanelOpen() {
return true;
},
});

inputElement.focus();
await runAllMicroTasks();

userEvent.type(inputElement, '{arrowup}');
await runAllMicroTasks();
expect(onStateChange).toHaveBeenLastCalledWith(
expect.objectContaining({
state: expect.objectContaining({
completion: null,
}),
})
);
});

test('does not set completion when panel is closed', () => {
const onStateChange = jest.fn();
const { inputElement } = createPlayground(createAutocomplete, {
Expand Down
4 changes: 1 addition & 3 deletions packages/autocomplete-core/src/getCompletion.ts
Expand Up @@ -12,7 +12,5 @@ export function getCompletion<TItem extends BaseItem>({
return null;
}

const { itemInputValue } = getActiveItem(state)!;

return itemInputValue || null;
return getActiveItem(state)?.itemInputValue || null;
}
4 changes: 4 additions & 0 deletions packages/autocomplete-core/src/utils/getNextActiveItemId.ts
Expand Up @@ -20,6 +20,10 @@ export function getNextActiveItemId(
itemCount: number,
defaultActiveItemId: number | null
): number | null {
if (!itemCount) {
return null;
}

if (
moveAmount < 0 &&
(baseIndex === null || (defaultActiveItemId !== null && baseIndex === 0))
Expand Down

0 comments on commit 0e0ce81

Please sign in to comment.