import {
createPrompt,
isDownKey,
isEnterKey,
isNumberKey,
isSpaceKey,
isUpKey,
makeTheme,
Separator,
useKeypress,
useMemo,
usePagination,
usePrefix,
useRef,
useState,
ValidationError,
} from "@inquirer/core";
import figures from "@inquirer/figures";
import ansiEscapes from "ansi-escapes";
import colors from "picocolors";
const checkboxTheme = {
icon: {
checked: colors.green(figures.circleFilled),
unchecked: figures.circle,
cursor: figures.pointer,
},
style: {
disabledChoice: (text) => colors.dim(`- ${text}`),
renderSelectedChoices: (selectedChoices) =>
selectedChoices.map((choice) => choice.short).join(", "),
description: (text) => colors.cyan(text),
},
helpMode: "auto",
};
function isSelectable(item) {
return !Separator.isSeparator(item) && !item.disabled;
}
function isChecked(item) {
return isSelectable(item) && Boolean(item.checked);
}
function toggle(item) {
return isSelectable(item) ? { ...item, checked: !item.checked } : item;
}
function check(checked) {
return function (item) {
return isSelectable(item) ? { ...item, checked } : item;
};
}
function normalizeChoices(choices) {
return choices.map((choice) => {
if (Separator.isSeparator(choice)) return choice;
if (typeof choice === "string") {
return {
value: choice,
name: choice,
short: choice,
disabled: false,
checked: false,
};
}
const name = choice.name ?? String(choice.value);
return {
value: choice.value,
name,
short: choice.short ?? name,
description: choice.description,
disabled: choice.disabled ?? false,
checked: choice.checked ?? false,
};
});
}
export default createPrompt((config, done) => {
const {
instructions,
pageSize = 7,
loop = true,
required,
validate = () => true,
} = config;
const theme = makeTheme(checkboxTheme, config.theme);
const firstRender = useRef(true);
const [status, setStatus] = useState("idle");
const prefix = usePrefix({ status, theme });
const [items, setItems] = useState(
normalizeChoices(
typeof config.choices === "function" ? config.choices([]) : config.choices
)
);
const bounds = useMemo(() => {
const first = items.findIndex(isSelectable);
const last = items.findLastIndex(isSelectable);
if (first === -1) {
throw new ValidationError(
"[checkbox prompt] No selectable choices. All choices are disabled."
);
}
return { first, last };
}, [items]);
const [active, setActive] = useState(bounds.first);
const [showHelpTip, setShowHelpTip] = useState(true);
const [errorMsg, setError] = useState();
useKeypress(async (key) => {
if (isEnterKey(key)) {
const selection = items.filter(isChecked);
const isValid = await validate([...selection]);
if (required && !items.some(isChecked)) {
setError("At least one choice must be selected");
} else if (isValid === true) {
setStatus("done");
done(selection.map((choice) => choice.value));
} else {
setError(isValid || "You must select a valid value");
}
} else if (isUpKey(key) || isDownKey(key)) {
if (
loop ||
(isUpKey(key) && active !== bounds.first) ||
(isDownKey(key) && active !== bounds.last)
) {
const offset = isUpKey(key) ? -1 : 1;
let next = active;
do {
next = (next + offset + items.length) % items.length;
} while (!isSelectable(items[next]));
setActive(next);
}
} else if (isSpaceKey(key)) {
setError(undefined);
setShowHelpTip(false);
let newItems = items.map((choice, i) =>
i === active ? toggle(choice) : choice
);
if (typeof config.choices === "function") {
const selected = newItems
.filter(isChecked)
.map((choice) => choice.value);
const choices = config.choices(selected);
newItems = newItems.map((choice) => {
const updated = choices.find((c) => c.value === choice.value);
return { ...choice, ...updated };
});
}
setItems(newItems);
} else if (key.name === "a") {
const selectAll = items.some(
(choice) => isSelectable(choice) && !choice.checked
);
setItems(items.map(check(selectAll)));
} else if (key.name === "i") {
setItems(items.map(toggle));
} else if (isNumberKey(key)) {
// Adjust index to start at 1
const position = Number(key.name) - 1;
const item = items[position];
if (item != null && isSelectable(item)) {
setActive(position);
setItems(
items.map((choice, i) => (i === position ? toggle(choice) : choice))
);
}
}
});
const message = theme.style.message(config.message, status);
let description;
const page = usePagination({
items,
active,
renderItem({ item, isActive }) {
if (Separator.isSeparator(item)) {
return ` ${item.separator}`;
}
if (item.disabled) {
const disabledLabel =
typeof item.disabled === "string" ? item.disabled : "(disabled)";
return theme.style.disabledChoice(`${item.name} ${disabledLabel}`);
}
if (isActive) {
description = item.description;
}
const checkbox = item.checked ? theme.icon.checked : theme.icon.unchecked;
const color = isActive ? theme.style.highlight : (x) => x;