@@ -0,0 +1,401 @@
1+import type {
2+ Color,
3+ ContainerNode,
4+ Node,
5+ SizeValue,
6+ StyleProps,
7+} from "@cel-tui/types";
8+import { cel, VStack, HStack, Text } from "@cel-tui/core";
9+
10+/**
11+ * An item in the select list.
12+ *
13+ * Strings are used as both label and value. Objects allow separate
14+ * display text, return value, and filter text.
15+ *
16+ * @example
17+ * // Simple string item
18+ * "apple"
19+ *
20+ * // Rich item with ANSI-colored label
21+ * { label: "claude-sonnet-4 (free)", value: "anthropic/claude-sonnet-4", filterText: "claude-sonnet-4" }
22+ */
23+export type SelectItem =
24+ | string
25+ | {
26+ /** Displayed text (can include ANSI styling). */
27+ label: string;
28+ /** Value returned on selection. */
29+ value: string;
30+ /** Text matched against the search query. Defaults to `label`. */
31+ filterText?: string;
32+ };
33+
34+/** Configuration for the {@link Select} component. */
35+export interface SelectProps {
36+ /** Items to choose from. */
37+ items: SelectItem[];
38+ /**
39+ * Called when the user selects an item (Enter or click).
40+ * @param value - The selected item's value.
41+ */
42+ onSelect: (value: string) => void;
43+ /**
44+ * Placeholder text shown when the search query is empty.
45+ * @default "type to filter..."
46+ */
47+ placeholder?: string;
48+ /**
49+ * Maximum number of items visible at once.
50+ * When the filtered list exceeds this, a "N more" indicator is shown.
51+ * @default 10
52+ */
53+ maxVisible?: number;
54+ /**
55+ * Character used for the highlight indicator.
56+ * @default "›"
57+ */
58+ indicator?: string;
59+ /**
60+ * Color of the highlighted item and its indicator.
61+ * @default "cyan"
62+ */
63+ highlightColor?: Color;
64+ /**
65+ * Called for key events not consumed by the Select
66+ * (e.g., modifier combos like `"ctrl+s"`).
67+ * Use this to handle application-level shortcuts when the Select is focused.
68+ *
69+ * @param key - The unhandled key string.
70+ */
71+ onKeyPress?: (key: string) => void;
72+ /** Fixed width in cells or percentage. */
73+ width?: SizeValue;
74+ /** Fixed height in cells or percentage. */
75+ height?: SizeValue;
76+ /** Flex grow factor. */
77+ flex?: number;
78+ /** Foreground text color. */
79+ fgColor?: Color;
80+ /** Background color (fills the container rect). */
81+ bgColor?: Color;
82+ /**
83+ * Whether the select is currently focused (controlled mode).
84+ * When omitted, focus is uncontrolled (framework-managed).
85+ */
86+ focused?: boolean;
87+ /**
88+ * Whether the select participates in focus traversal.
89+ * @default true
90+ */
91+ focusable?: boolean;
92+ /** Called when the select receives focus. */
93+ onFocus?: () => void;
94+ /** Called when the select loses focus. */
95+ onBlur?: () => void;
96+ /** Style overrides applied when focused. */
97+ focusStyle?: StyleProps;
98+}
99+
100+/**
101+ * A Select component instance returned by {@link Select}.
102+ *
103+ * Call it to get the current Node tree for rendering.
104+ * Use `.reset()` to clear the search query and highlight.
105+ */
106+export interface SelectInstance {
107+ /** Returns the current Select node tree. Call inside `cel.viewport()`. */
108+ (): ContainerNode;
109+ /** Reset the search query, highlight position, and scroll offset. */
110+ reset(): void;
111+}
112+
113+/** Normalized form of a SelectItem with all fields resolved. */
114+export interface NormalizedItem {
115+ label: string;
116+ value: string;
117+ filterText: string;
118+}
119+
120+/**
121+ * Normalize SelectItem inputs into a consistent shape.
122+ * Strings become `{ label: s, value: s, filterText: s }`.
123+ */
124+export function normalizeItems(items: SelectItem[]): NormalizedItem[] {
125+ return items.map((item) => {
126+ if (typeof item === "string") {
127+ return { label: item, value: item, filterText: item };
128+ }
129+ return {
130+ label: item.label,
131+ value: item.value,
132+ filterText: item.filterText ?? item.label,
133+ };
134+ });
135+}
136+
137+/**
138+ * Filter items by prefix match against filterText.
139+ * Matches the start of the full text or any whitespace/slash-separated word.
140+ */
141+export function prefixFilter(
142+ items: NormalizedItem[],
143+ query: string,
144+): NormalizedItem[] {
145+ if (!query) return items;
146+ const q = query.toLowerCase();
147+ return items.filter((item) => {
148+ const text = item.filterText.toLowerCase();
149+ if (text.startsWith(q)) return true;
150+ const words = text.split(/[\s/]+/);
151+ return words.some((word) => word.startsWith(q));
152+ });
153+}
154+
155+/** Move highlight up with wrapping. */
156+export function moveUp(highlight: number, total: number): number {
157+ if (total === 0) return 0;
158+ return highlight <= 0 ? total - 1 : highlight - 1;
159+}
160+
161+/** Move highlight down with wrapping. */
162+export function moveDown(highlight: number, total: number): number {
163+ if (total === 0) return 0;
164+ return highlight >= total - 1 ? 0 : highlight + 1;
165+}
166+
167+/** Adjust scroll offset to keep the highlighted item visible. */
168+export function adjustScroll(
169+ highlight: number,
170+ scrollOffset: number,
171+ maxVisible: number,
172+): number {
173+ if (highlight < scrollOffset) return highlight;
174+ if (highlight >= scrollOffset + maxVisible) return highlight - maxVisible + 1;
175+ return scrollOffset;
176+}
177+
178+/**
179+ * Creates a filterable select list component.
180+ *
181+ * Returns a {@link SelectInstance} — call it inside `cel.viewport()` to
182+ * produce the current Node tree. Internal state (search query, highlight
183+ * position, scroll offset) is managed automatically. Keyboard navigation
184+ * works when the component is focused (Tab into it or click an item).
185+ *
186+ * **Keyboard:**
187+ * | Key | Action |
188+ * |-------------|-------------------------------------|
189+ * | Type | Filter items by prefix |
190+ * | `↑` / `↓` | Move highlight (wraps around) |
191+ * | `Enter` | Select highlighted item |
192+ * | `Escape` | Unfocus (framework default) |
193+ * | `Home`/`End`| Jump to first/last |
194+ * | `Backspace` | Delete last filter character |
195+ *
196+ * @param props - Select configuration and items.
197+ * @returns A callable instance that produces the Select node tree.
198+ *
199+ * @example
200+ * ```ts
201+ * import { cel, VStack, Text, ProcessTerminal } from "@cel-tui/core";
202+ * import { Select } from "@cel-tui/components";
203+ *
204+ * let selected = "";
205+ *
206+ * const fruitSelect = Select({
207+ * items: ["apple", "banana", "cherry", "date", "elderberry"],
208+ * onSelect: (value) => {
209+ * selected = value;
210+ * cel.render();
211+ * },
212+ * });
213+ *
214+ * cel.init(new ProcessTerminal());
215+ * cel.viewport(() =>
216+ * VStack({ height: "100%" }, [
217+ * Text(`Selected: ${selected}`),
218+ * fruitSelect(),
219+ * ]),
220+ * );
221+ * ```
222+ */
223+export function Select(props: SelectProps): SelectInstance {
224+ const {
225+ items: rawItems,
226+ onSelect,
227+ placeholder = "type to filter...",
228+ maxVisible = 10,
229+ indicator = "›",
230+ highlightColor = "cyan",
231+ onKeyPress: userKeyPress,
232+ width,
233+ height,
234+ flex,
235+ fgColor,
236+ bgColor,
237+ focused,
238+ focusable,
239+ onFocus,
240+ onBlur,
241+ focusStyle,
242+ } = props;
243+
244+ let query = "";
245+ let highlightIndex = 0;
246+ let scrollOffset = 0;
247+
248+ function getFiltered(): NormalizedItem[] {
249+ return prefixFilter(normalizeItems(rawItems), query);
250+ }
251+
252+ function handleKey(key: string): void {
253+ switch (key) {
254+ case "enter": {
255+ const filtered = getFiltered();
256+ const selected = filtered[highlightIndex];
257+ if (selected) onSelect(selected.value);
258+ return;
259+ }
260+
261+ case "backspace":
262+ if (query.length > 0) {
263+ query = query.slice(0, -1);
264+ highlightIndex = 0;
265+ scrollOffset = 0;
266+ cel.render();
267+ }
268+ return;
269+
270+ case "up": {
271+ const filtered = getFiltered();
272+ highlightIndex = moveUp(highlightIndex, filtered.length);
273+ scrollOffset = adjustScroll(highlightIndex, scrollOffset, maxVisible);
274+ cel.render();
275+ return;
276+ }
277+
278+ case "down": {
279+ const filtered = getFiltered();
280+ highlightIndex = moveDown(highlightIndex, filtered.length);
281+ scrollOffset = adjustScroll(highlightIndex, scrollOffset, maxVisible);
282+ cel.render();
283+ return;
284+ }
285+
286+ case "home":
287+ highlightIndex = 0;
288+ scrollOffset = 0;
289+ cel.render();
290+ return;
291+
292+ case "end": {
293+ const filtered = getFiltered();
294+ highlightIndex = Math.max(0, filtered.length - 1);
295+ scrollOffset = adjustScroll(highlightIndex, scrollOffset, maxVisible);
296+ cel.render();
297+ return;
298+ }
299+
300+ default:
301+ // Single printable character — append to query
302+ if (key.length === 1 && key >= " ") {
303+ query += key;
304+ highlightIndex = 0;
305+ scrollOffset = 0;
306+ cel.render();
307+ } else {
308+ // Forward unrecognized keys to user callback
309+ userKeyPress?.(key);
310+ }
311+ return;
312+ }
313+ }
314+
315+ function render(): ContainerNode {
316+ const allItems = normalizeItems(rawItems);
317+ const filtered = prefixFilter(allItems, query);
318+ const visible = filtered.slice(scrollOffset, scrollOffset + maxVisible);
319+ const overflow = filtered.length - scrollOffset - visible.length;
320+
321+ const children: Node[] = [];
322+
323+ // Search line
324+ const searchContent = query
325+ ? Text(query)
326+ : Text(placeholder, { fgColor: "brightBlack" });
327+ children.push(
328+ HStack({}, [Text("search: ", { fgColor: "brightBlack" }), searchContent]),
329+ );
330+
331+ // Items
332+ if (filtered.length === 0) {
333+ children.push(
334+ HStack({}, [Text(" no matches", { fgColor: "brightBlack" })]),
335+ );
336+ } else {
337+ for (let i = 0; i < visible.length; i++) {
338+ const item = visible[i]!;
339+ const globalIndex = scrollOffset + i;
340+ const isHighlighted = globalIndex === highlightIndex;
341+
342+ if (isHighlighted) {
343+ children.push(
344+ HStack(
345+ {
346+ onClick: () => onSelect(item.value),
347+ focusable: false,
348+ },
349+ [
350+ Text(`${indicator} `, { fgColor: highlightColor }),
351+ Text(item.label, { fgColor: highlightColor }),
352+ ],
353+ ),
354+ );
355+ } else {
356+ children.push(
357+ HStack(
358+ {
359+ onClick: () => onSelect(item.value),
360+ focusable: false,
361+ },
362+ [Text(" "), Text(item.label)],
363+ ),
364+ );
365+ }
366+ }
367+ }
368+
369+ // Overflow indicator
370+ if (overflow > 0) {
371+ children.push(
372+ HStack({}, [Text(` ${overflow} more`, { fgColor: "brightBlack" })]),
373+ );
374+ }
375+
376+ return VStack(
377+ {
378+ onKeyPress: handleKey,
379+ focusable: focusable ?? true,
380+ focused,
381+ onFocus,
382+ onBlur,
383+ focusStyle,
384+ width,
385+ height,
386+ flex,
387+ fgColor,
388+ bgColor,
389+ },
390+ children,
391+ );
392+ }
393+
394+ render.reset = () => {
395+ query = "";
396+ highlightIndex = 0;
397+ scrollOffset = 0;
398+ };
399+
400+ return render as SelectInstance;
401+}