File size: 7,978 Bytes
f500658 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | import {
type Component,
Container,
fuzzyFilter,
getKeybindings,
Input,
type SelectItem,
SelectList,
type SelectListLayoutOptions,
Spacer,
Text,
} from "@earendil-works/pi-tui";
import { getSelectListTheme, theme } from "../theme/theme.ts";
const SUBMENU_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
minPrimaryColumnWidth: 12,
maxPrimaryColumnWidth: 32,
};
export interface SelectSubmenuOptions {
/** Enable type-to-search fuzzy filtering. */
searchable?: boolean;
/** Override the select list layout (column widths). */
layout?: SelectListLayoutOptions;
}
/**
* Single-step submenu that shows a titled select list.
* With `searchable: true`, typing filters the list using fuzzy matching.
*/
export class SelectSubmenu extends Container {
private selectList: SelectList;
private listChildIndex: number;
private allOptions: SelectItem[];
private listLayout: SelectListLayoutOptions;
private searchInput: Input | undefined;
private onSelectCb: (value: string) => void;
private onCancelCb: () => void;
private onSelectionChangeCb?: (value: string) => void;
constructor(
title: string,
description: string,
options: SelectItem[],
currentValue: string,
onSelect: (value: string) => void,
onCancel: () => void,
onSelectionChange?: (value: string) => void,
submenuOptions?: SelectSubmenuOptions,
) {
super();
this.allOptions = options;
this.listLayout = submenuOptions?.layout ?? SUBMENU_SELECT_LIST_LAYOUT;
this.onSelectCb = onSelect;
this.onCancelCb = onCancel;
this.onSelectionChangeCb = onSelectionChange;
// Title
this.addChild(new Text(theme.bold(theme.fg("accent", title)), 0, 0));
// Description
if (description) {
this.addChild(new Spacer(1));
this.addChild(new Text(theme.fg("muted", description), 0, 0));
}
// Search input
if (submenuOptions?.searchable) {
this.addChild(new Spacer(1));
this.searchInput = new Input();
this.searchInput.onSubmit = () => {
this.selectList.handleInput("\r");
};
this.addChild(this.searchInput);
}
// Spacer
this.addChild(new Spacer(1));
// Select list
this.selectList = this.buildSelectList(options, currentValue);
this.listChildIndex = this.children.length;
this.addChild(this.selectList);
// Hint
this.addChild(new Spacer(1));
const hint = submenuOptions?.searchable
? " Type to filter \u00b7 Enter to select \u00b7 Esc to go back"
: " Enter to select \u00b7 Esc to go back";
this.addChild(new Text(theme.fg("dim", hint), 0, 0));
}
private buildSelectList(options: SelectItem[], preselect: string): SelectList {
const list = new SelectList(options, Math.min(options.length, 10), getSelectListTheme(), this.listLayout);
const idx = options.findIndex((o) => o.value === preselect);
if (idx !== -1) list.setSelectedIndex(idx);
list.onSelect = (item) => this.onSelectCb(item.value);
list.onCancel = this.onCancelCb;
if (this.onSelectionChangeCb) {
const cb = this.onSelectionChangeCb;
list.onSelectionChange = (item) => cb(item.value);
}
return list;
}
private applyFilter(query: string): void {
const filtered = query
? fuzzyFilter(this.allOptions, query, (item) => `${item.label} ${item.description ?? ""}`)
: this.allOptions;
const newList = this.buildSelectList(filtered, "");
this.children[this.listChildIndex] = newList;
this.selectList = newList;
}
handleInput(data: string): void {
if (this.searchInput) {
const kb = getKeybindings();
const isNav =
kb.matches(data, "tui.select.up") ||
kb.matches(data, "tui.select.down") ||
kb.matches(data, "tui.select.confirm") ||
kb.matches(data, "tui.select.cancel");
if (isNav) {
this.selectList.handleInput(data);
} else {
this.searchInput.handleInput(data);
this.applyFilter(this.searchInput.getValue());
}
} else {
this.selectList.handleInput(data);
}
}
}
// ============================================================================
// SteppedSubmenu — reusable multi-step selector
// ============================================================================
/** One step in a {@link SteppedSubmenu}. */
export interface SteppedSubmenuStep {
/** Unique key \u2014 the selected value is stored in the result context under this key. */
key: string;
/** Title shown at the top of the step. Receives prior selections. */
title: string | ((context: Record<string, string>) => string);
/** Description shown below the title. Receives prior selections. */
description: string | ((context: Record<string, string>) => string);
/** Build the option list for this step. Called fresh each time the step is shown. */
options: (context: Record<string, string>) => SelectItem[];
/** Optionally pre-select a value when entering this step. */
preselect?: (context: Record<string, string>) => string | undefined;
/** Enable type-to-search fuzzy filtering for this step. */
searchable?: boolean;
/** Override the select list layout (column widths) for this step. */
layout?: SelectListLayoutOptions;
}
interface SteppedSubmenuOptions {
/** Start at this step index (0-based), skipping earlier steps. Requires initialContext for skipped keys. */
startAtStep?: number;
/** Pre-fill selections for skipped steps. */
initialContext?: Record<string, string>;
/** After completing the last step, loop back to step 0 instead of closing. */
loop?: boolean;
}
/**
* Generic N-step submenu built on top of {@link SelectSubmenu}.
*
* Each step's options can depend on prior selections via the shared context.
* Esc goes back one step; Esc at step 0 cancels.
* With `loop: true`, completing the final step invokes `onComplete` then returns to step 0.
*/
export class SteppedSubmenu extends Container {
private readonly steps: SteppedSubmenuStep[];
private readonly onComplete: (context: Record<string, string>) => void;
private readonly onCancel: () => void;
private readonly opts: SteppedSubmenuOptions;
private activeComponent: Component;
private context: Record<string, string>;
constructor(
steps: SteppedSubmenuStep[],
onComplete: (context: Record<string, string>) => void,
onCancel: () => void,
opts: SteppedSubmenuOptions = {},
) {
super();
this.steps = steps;
this.onComplete = onComplete;
this.onCancel = onCancel;
this.opts = opts;
this.context = { ...(opts.initialContext ?? {}) };
this.activeComponent = this.buildStep(opts.startAtStep ?? 0);
}
private buildStep(stepIndex: number): Component {
const step = this.steps[stepIndex];
const total = this.steps.length;
const stepLabel = total > 1 ? `Step ${stepIndex + 1}/${total} \u00b7 ` : "";
const title = typeof step.title === "function" ? step.title(this.context) : step.title;
const desc = typeof step.description === "function" ? step.description(this.context) : step.description;
const items = step.options(this.context);
const preselect = step.preselect?.(this.context) ?? "";
return new SelectSubmenu(
title,
`${stepLabel}${desc}`,
items,
preselect,
(value) => {
this.context[step.key] = value;
if (stepIndex < total - 1) {
// Advance to next step
this.activeComponent = this.buildStep(stepIndex + 1);
} else {
// Final step \u2014 deliver result
this.onComplete({ ...this.context });
if (this.opts.loop) {
this.context = {};
this.activeComponent = this.buildStep(0);
} else {
this.onCancel();
}
}
},
() => {
if (stepIndex > 0) {
delete this.context[step.key];
this.activeComponent = this.buildStep(stepIndex - 1);
} else {
this.onCancel();
}
},
undefined,
step.searchable || step.layout ? { searchable: step.searchable, layout: step.layout } : undefined,
);
}
render(width: number): string[] {
return this.activeComponent.render(width);
}
handleInput(data: string): void {
this.activeComponent.handleInput?.(data);
}
invalidate(): void {
this.activeComponent.invalidate?.();
}
}
|