|
| 1 | +import Prompt, { PromptOptions } from './prompt'; |
| 2 | + |
| 3 | +interface GroupMultiSelectOptions<T extends { value: any }> extends PromptOptions<GroupMultiSelectPrompt<T>> { |
| 4 | + options: Record<string, T[]>; |
| 5 | + initialValues?: T['value'][]; |
| 6 | + required?: boolean; |
| 7 | + cursorAt?: T['value']; |
| 8 | +} |
| 9 | +export default class GroupMultiSelectPrompt<T extends { value: any }> extends Prompt { |
| 10 | + options: (T & { group: string | boolean })[]; |
| 11 | + cursor: number = 0; |
| 12 | + |
| 13 | + getGroupItems(group: string): T[] { |
| 14 | + return this.options.filter(o => o.group === group); |
| 15 | + } |
| 16 | + |
| 17 | + isGroupSelected(group: string) { |
| 18 | + const items = this.getGroupItems(group); |
| 19 | + return items.every(i => this.value.includes(i.value)); |
| 20 | + } |
| 21 | + |
| 22 | + private toggleValue() { |
| 23 | + const item = this.options[this.cursor]; |
| 24 | + if (item.group === true) { |
| 25 | + const group = item.value; |
| 26 | + const groupedItems = this.getGroupItems(group); |
| 27 | + if (this.isGroupSelected(group)) { |
| 28 | + this.value = this.value.filter((v: string) => groupedItems.findIndex(i => i.value === v) === -1); |
| 29 | + } else { |
| 30 | + this.value = [...this.value, ...groupedItems.map(i => i.value)]; |
| 31 | + } |
| 32 | + this.value = Array.from(new Set(this.value)); |
| 33 | + } else { |
| 34 | + const selected = this.value.includes(item.value); |
| 35 | + this.value = selected |
| 36 | + ? this.value.filter((v: T['value']) => v !== item.value) |
| 37 | + : [...this.value, item.value]; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + constructor(opts: GroupMultiSelectOptions<T>) { |
| 42 | + super(opts, false); |
| 43 | + const { options } = opts; |
| 44 | + this.options = Object.entries(options).flatMap(([key, option]) => [ |
| 45 | + { value: key, group: true, label: key }, |
| 46 | + ...option.map((opt) => ({ ...opt, group: key })), |
| 47 | +]) |
| 48 | + this.value = [...(opts.initialValues ?? [])]; |
| 49 | + this.cursor = Math.max( |
| 50 | + this.options.findIndex(({ value }) => value === opts.cursorAt), |
| 51 | + 0 |
| 52 | + ); |
| 53 | + |
| 54 | + this.on('cursor', (key) => { |
| 55 | + switch (key) { |
| 56 | + case 'left': |
| 57 | + case 'up': |
| 58 | + this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1; |
| 59 | + break; |
| 60 | + case 'down': |
| 61 | + case 'right': |
| 62 | + this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1; |
| 63 | + break; |
| 64 | + case 'space': |
| 65 | + this.toggleValue(); |
| 66 | + break; |
| 67 | + } |
| 68 | + }); |
| 69 | + } |
| 70 | +} |
0 commit comments