Skip to content

Commit

Permalink
fix: defaultValue broken when setting mutiple to false
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffwcx committed Oct 29, 2024
1 parent 302c5c2 commit b8ed1ea
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 13 deletions.
35 changes: 26 additions & 9 deletions src/useSelect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,20 @@ export function useSelect<Value, Multiple extends boolean>(
}
const targetOption = displayItems[cursor];
if (isSelectable(targetOption)) {
if (targetOption.checked) {
const currentSelection = selections.current.filter(
(op) => !equals(targetOption.value, op.value),
);
setBehavior('deselect', true);
selections.current = currentSelection;
if (multiple) {
if (targetOption.checked) {
const currentSelection = selections.current.filter(
(op) => !equals(targetOption.value, op.value),
);
setBehavior('deselect', true);
selections.current = currentSelection;
} else {
setBehavior('select', true);
selections.current = [...selections.current, { ...targetOption }];
}
} else {
setBehavior('select', true);
selections.current = [...selections.current, { ...targetOption }];
selections.current = [{ ...targetOption }];
}
if (enableFilter && !targetOption.checked && clearInput) {
clearFilterInput(rl);
Expand Down Expand Up @@ -297,21 +302,33 @@ export function useSelect<Value, Multiple extends boolean>(
return;
}
const ss = [...selections.current];
const finalItems = items.map((item) => {
let firstChecked = -1;
let firstSelectable = -1;
const finalItems = items.map((item, index) => {
const finalItem = { ...item };
if (isSelectable(finalItem)) {
if (firstSelectable < 0) {
firstSelectable = index;
}
ss.forEach((op) => {
if (equals(op.value, finalItem.value)) {
finalItem.checked = true;
op.name = finalItem.name;
if (firstChecked < 0) {
firstChecked = index;
}
}
});
}
return finalItem;
});
setDisplayItems(finalItems);
selections.current = ss;
setCursor(finalItems.findIndex(isSelectable));
if (multiple) {
setCursor(firstSelectable);
} else {
setCursor(firstChecked < 0 ? firstSelectable : firstChecked);
}
}

async function loadData() {
Expand Down
10 changes: 6 additions & 4 deletions tests/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -494,17 +494,19 @@ describe('inquirer-select-pro', () => {
// @ts-ignore
await renderPrompt({
...optionsForDisplayValue,
defaultValue: 'a',
defaultValue: 1,
multiple: false,
});
await waitForInteraction();
expect(getScreen()).toMatchInlineSnapshot(`
"? Choose movie:
>> a
> a
One
>> One
a
> One
[object Object]"
`);
events.keypress('enter');
expect(await answer).toMatchInlineSnapshot(`1`);
});

it('should throw error when `defaultValue` is non-array in multiple selection mode', async () => {
Expand Down

0 comments on commit b8ed1ea

Please sign in to comment.