| 9 | selectableGroups?: boolean; |
| 10 | } |
| 11 | export default class GroupMultiSelectPrompt<T extends { value: any }> extends Prompt<T['value'][]> { |
| 12 | options: (T & { group: string | boolean })[]; |
| 13 | cursor = 0; |
| 14 | #selectableGroups: boolean; |
| 15 | |
| 16 | getGroupItems(group: string): T[] { |
| 17 | return this.options.filter((o) => o.group === group); |
| 18 | } |
| 19 | |
| 20 | isGroupSelected(group: string) { |
| 21 | const items = this.getGroupItems(group); |
| 22 | const value = this.value; |
| 23 | if (value === undefined) { |
| 24 | return false; |
| 25 | } |
| 26 | return items.every((i) => value.includes(i.value)); |
| 27 | } |
| 28 | |
| 29 | private toggleValue() { |
| 30 | const item = this.options[this.cursor]; |
| 31 | if (this.value === undefined) { |
| 32 | this.value = []; |
| 33 | } |
| 34 | if (item.group === true) { |
| 35 | const group = item.value; |
| 36 | const groupedItems = this.getGroupItems(group); |
| 37 | if (this.isGroupSelected(group)) { |
| 38 | this.value = this.value.filter( |
| 39 | (v: string) => groupedItems.findIndex((i) => i.value === v) === -1 |
| 40 | ); |
| 41 | } else { |
| 42 | this.value = [...this.value, ...groupedItems.map((i) => i.value)]; |
| 43 | } |
| 44 | this.value = Array.from(new Set(this.value)); |
| 45 | } else { |
| 46 | const selected = this.value.includes(item.value); |
| 47 | this.value = selected |
| 48 | ? this.value.filter((v: T['value']) => v !== item.value) |
| 49 | : [...this.value, item.value]; |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | constructor(opts: GroupMultiSelectOptions<T>) { |
| 54 | super(opts, false); |
| 55 | const { options } = opts; |
| 56 | this.#selectableGroups = opts.selectableGroups !== false; |
| 57 | this.options = Object.entries(options).flatMap(([key, option]) => [ |
| 58 | { value: key, group: true, label: key }, |
| 59 | ...option.map((opt) => ({ ...opt, group: key })), |
| 60 | ]) as any; |
| 61 | this.value = [...(opts.initialValues ?? [])]; |
| 62 | this.cursor = Math.max( |
| 63 | this.options.findIndex(({ value }) => value === opts.cursorAt), |
| 64 | this.#selectableGroups ? 0 : 1 |
| 65 | ); |
| 66 | |
| 67 | this.on('cursor', (key) => { |
| 68 | switch (key) { |
nothing calls this directly
no outgoing calls
no test coverage detected