xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / components / src / select.ts

19.4 KB
1import { cel, HStack, Text, TextInput, VStack } from "@cel-tui/core";
2import type {
3  Color,
4  ContainerNode,
5  ContainerProps,
6  Node,
7  SizeValue,
8  StateKey,
9  StyleProps,
10} from "@cel-tui/types";
11
12/**
13 * An item in a Select list.
14 *
15 * Strings use the same text for their label, value, and filtering. Object
16 * items can separate the value returned to the app from visible/filter text.
17 */
18export type SelectItem =
19  | string
20  | {
21      /** Displayed text. */
22      label: string;
23      /** Value returned on selection. */
24      value: string;
25      /** Text matched against the search query. Defaults to `label`. */
26      filterText?: string;
27    };
28
29/** Normalized form of a {@link SelectItem}. */
30export interface NormalizedItem {
31  label: string;
32  value: string;
33  filterText: string;
34}
35
36/** Filter and optionally rank normalized items for a query. */
37export type SelectFilter = (
38  items: readonly NormalizedItem[],
39  query: string,
40) => readonly NormalizedItem[];
41
42/** Context passed to {@link SelectProps.renderRow}. */
43export interface SelectRowContext {
44  /** Zero-based index in the filtered list. */
45  index: number;
46  /** Current exact query text. */
47  query: string;
48  /** Whether this row is the keyboard highlight. */
49  highlighted: boolean;
50  /** Configured indicator string. */
51  indicator: string;
52  /** Configured highlight color. */
53  highlightColor: Color;
54  /** Select this row programmatically. */
55  select: () => void;
56}
57
58/** Render one filtered Select row. Click handling is supplied by Select. */
59export type SelectRowRenderer = (
60  item: NormalizedItem,
61  context: SelectRowContext,
62) => Node;
63
64/**
65 * Dynamic values accepted by a Select instance at render time or through
66 * {@link SelectInstance.update}. Render-time values are controlled for that
67 * render; `update()` changes the instance's uncontrolled fallback state.
68 */
69export interface SelectModel {
70  items?: readonly SelectItem[];
71  query?: string;
72  cursor?: number;
73  highlightIndex?: number;
74}
75
76/** Snapshot of the model used by the most recent Select render. */
77export interface SelectState {
78  readonly query: string;
79  /** UTF-16 query cursor offset, matching TextInput. */
80  readonly cursor: number;
81  readonly highlightIndex: number;
82  readonly items: readonly NormalizedItem[];
83  readonly filteredItems: readonly NormalizedItem[];
84  readonly highlightedItem: NormalizedItem | undefined;
85}
86
87type SelectKeyPressHandler = NonNullable<ContainerProps["onKeyPress"]>;
88
89/** Configuration for the {@link Select} component. */
90export interface SelectProps {
91  /** Items to choose from. May be replaced with `select.update()` or `select({ items })`. */
92  items: readonly SelectItem[];
93  /** Called when the user selects an item with Enter or a click. */
94  onSelect: (value: string, item: NormalizedItem) => void;
95
96  /** Initial query for uncontrolled use. Ignored while `query` is provided. */
97  initialQuery?: string;
98  /** Controlled exact query text. */
99  query?: string;
100  /** Called with the exact TextInput value after an edit or paste. */
101  onQueryChange?: (query: string) => void;
102
103  /** Initial filtered-list highlight for uncontrolled use. @default 0 */
104  initialHighlightIndex?: number;
105  /** Controlled index in the filtered item list. */
106  highlightIndex?: number;
107  /** Called when keyboard navigation requests a highlight change. */
108  onHighlightChange?: (
109    highlightIndex: number,
110    item: NormalizedItem | undefined,
111  ) => void;
112
113  /** Controlled UTF-16 query cursor offset. */
114  cursor?: number;
115  /** Called when TextInput editing/navigation requests a cursor change. */
116  onCursorChange?: (cursor: number) => void;
117
118  /** Called when Escape cancels the Select. Supplying it consumes Escape. */
119  onCancel?: (state: SelectState) => void;
120  /** Custom filtering/ranking function. Defaults to {@link prefixFilter}. */
121  filter?: SelectFilter;
122  /** Custom row content. Select still supplies click handling and highlight style. */
123  renderRow?: SelectRowRenderer;
124
125  /** Placeholder shown in the query TextInput. @default "type to filter..." */
126  placeholder?: string;
127  /** Label before the query TextInput. @default "search: " */
128  searchLabel?: string;
129  /** Text shown when no items match. @default "no matches" */
130  emptyLabel?: string;
131  /** Maximum number of visible rows. Values below one are clamped to one. @default 10 */
132  maxVisible?: number;
133  /** Character used for the highlight indicator. @default "›" */
134  indicator?: string;
135  /** Color inherited by the highlighted row. @default "color06" */
136  highlightColor?: Color;
137
138  /** Non-editing keys bubble from the query TextInput to this handler. */
139  onKeyPress?: SelectKeyPressHandler;
140  /** Stable identity used by the query TextInput's cursor/focus state. */
141  stateKey?: StateKey;
142  /** Fixed width in cells or percentage. */
143  width?: SizeValue;
144  /** Fixed height in cells or percentage. */
145  height?: SizeValue;
146  /** Flex grow factor. */
147  flex?: number;
148  /** Foreground text color. */
149  fgColor?: Color;
150  /** Background color (fills the component rect). */
151  bgColor?: Color;
152  /** Controlled focus for the query TextInput. */
153  focused?: boolean;
154  /** Whether the query TextInput participates in focus traversal. @default true */
155  focusable?: boolean;
156  /** Seed uncontrolled focus when this Select first mounts. */
157  autoFocus?: boolean;
158  /** Called when the query TextInput receives focus. */
159  onFocus?: ContainerProps["onFocus"];
160  /** Called when the query TextInput loses focus. */
161  onBlur?: ContainerProps["onBlur"];
162  /** Query TextInput style overrides while focused. */
163  focusStyle?: StyleProps;
164}
165
166/** A callable Select component instance returned by {@link Select}. */
167export interface SelectInstance {
168  /**
169   * Produce the current node tree. Optional values override the instance for
170   * this render, which supports ordinary external/controlled app state.
171   */
172  (model?: SelectModel): ContainerNode;
173  /** Clear the query, cursor, highlight, and list scroll. */
174  reset(): void;
175  /** Imperatively update the uncontrolled fallback model and schedule a render. */
176  update(model: SelectModel): void;
177  /** Read the model snapshot used by the latest render. */
178  getState(): SelectState;
179}
180
181/** Normalize Select inputs into a consistent shape. */
182export function normalizeItems(items: readonly SelectItem[]): NormalizedItem[] {
183  return items.map((item) => {
184    if (typeof item === "string") {
185      return { label: item, value: item, filterText: item };
186    }
187    return {
188      label: item.label,
189      value: item.value,
190      filterText: item.filterText ?? item.label,
191    };
192  });
193}
194
195/**
196 * Case-insensitive prefix matching against the full filter text or any
197 * whitespace/slash-separated word.
198 */
199export function prefixFilter(
200  items: readonly NormalizedItem[],
201  query: string,
202): NormalizedItem[] {
203  if (!query) return [...items];
204  const normalizedQuery = query.toLowerCase();
205  return items.filter((item) => {
206    const text = item.filterText.toLowerCase();
207    if (text.startsWith(normalizedQuery)) return true;
208    return text
209      .split(/[\s/]+/)
210      .some((word) => word.startsWith(normalizedQuery));
211  });
212}
213
214/** Move a highlight up one row, wrapping at the beginning. */
215export function moveUp(highlight: number, total: number): number {
216  if (total === 0) return 0;
217  return highlight <= 0 ? total - 1 : highlight - 1;
218}
219
220/** Move a highlight down one row, wrapping at the end. */
221export function moveDown(highlight: number, total: number): number {
222  if (total === 0) return 0;
223  return highlight >= total - 1 ? 0 : highlight + 1;
224}
225
226/** Adjust list scroll so the highlighted row remains visible. */
227export function adjustScroll(
228  highlight: number,
229  scrollOffset: number,
230  maxVisible: number,
231): number {
232  if (highlight < scrollOffset) return highlight;
233  if (highlight >= scrollOffset + maxVisible) {
234    return highlight - maxVisible + 1;
235  }
236  return scrollOffset;
237}
238
239let nextGeneratedStateKey = 1;
240const querySegmenter = new Intl.Segmenter(undefined, {
241  granularity: "grapheme",
242});
243
244function generatedStateKey(): StateKey {
245  const key = `@cel-tui/select/${nextGeneratedStateKey}`;
246  nextGeneratedStateKey += 1;
247  return key;
248}
249
250function clampInteger(value: number, minimum: number, maximum: number): number {
251  if (!Number.isFinite(value)) {
252    return value === Number.POSITIVE_INFINITY ? maximum : minimum;
253  }
254  return Math.max(minimum, Math.min(maximum, Math.trunc(value)));
255}
256
257function clampQueryCursor(query: string, cursor: number): number {
258  const target = Number.isFinite(cursor) ? Math.trunc(cursor) : 0;
259  if (target <= 0) return 0;
260  if (target >= query.length) return query.length;
261
262  for (const { index, segment } of querySegmenter.segment(query)) {
263    const end = index + segment.length;
264    if (target <= index) return index;
265    if (target < end) return index;
266    if (target === end) return end;
267  }
268  return query.length;
269}
270
271function clampHighlight(index: number, total: number): number {
272  return total === 0 ? 0 : clampInteger(index, 0, total - 1);
273}
274
275function copyState(state: SelectState): SelectState {
276  return {
277    query: state.query,
278    cursor: state.cursor,
279    highlightIndex: state.highlightIndex,
280    items: state.items,
281    filteredItems: state.filteredItems,
282    highlightedItem: state.highlightedItem,
283  };
284}
285
286/**
287 * Create a filterable Select/Combobox backed by a real TextInput.
288 *
289 * The returned function preserves the original small static-list API:
290 * create it once and call `select()` inside `cel.viewport()`. For async or
291 * controlled callers, pass current values to `select(model)` each render or
292 * update its uncontrolled fallback with `select.update(model)`.
293 *
294 * Text editing is delegated to TextInput, so exact case, spaces, grapheme
295 * deletion, cursor movement, readline shortcuts, and bracketed paste all use
296 * the same behavior as a standalone input. Up/Down navigate results, Enter
297 * selects, and Escape invokes `onCancel` when supplied. Home/End and
298 * Left/Right remain query-cursor editing keys.
299 */
300export function Select(props: SelectProps): SelectInstance {
301  const requestedMaxVisible = props.maxVisible ?? 10;
302  const maxVisible = Number.isFinite(requestedMaxVisible)
303    ? Math.max(1, Math.trunc(requestedMaxVisible))
304    : 10;
305  const indicator = props.indicator ?? "›";
306  const highlightColor = props.highlightColor ?? "color06";
307  const filter = props.filter ?? prefixFilter;
308  const inputStateKey = props.stateKey ?? generatedStateKey();
309
310  let updatedItems: readonly SelectItem[] | undefined;
311  let internalQuery = props.initialQuery ?? props.query ?? "";
312  let internalCursor = props.cursor ?? internalQuery.length;
313  let internalHighlightIndex =
314    props.initialHighlightIndex ?? props.highlightIndex ?? 0;
315  let internalFocused = false;
316  let scrollOffset = 0;
317  let latestState: SelectState | undefined;
318
319  function resolveState(model?: SelectModel): SelectState {
320    const items = normalizeItems(model?.items ?? updatedItems ?? props.items);
321    const query = model?.query ?? props.query ?? internalQuery;
322    const filteredItems = [...filter(items, query)];
323    const highlightIndex = clampHighlight(
324      model?.highlightIndex ?? props.highlightIndex ?? internalHighlightIndex,
325      filteredItems.length,
326    );
327    const cursor = clampQueryCursor(
328      query,
329      model?.cursor ?? props.cursor ?? internalCursor,
330    );
331
332    if (
333      model?.highlightIndex === undefined &&
334      props.highlightIndex === undefined
335    ) {
336      internalHighlightIndex = highlightIndex;
337    }
338    if (model?.cursor === undefined && props.cursor === undefined) {
339      internalCursor = cursor;
340    }
341
342    const maximumScroll = Math.max(0, filteredItems.length - maxVisible);
343    scrollOffset = clampInteger(scrollOffset, 0, maximumScroll);
344    scrollOffset = adjustScroll(highlightIndex, scrollOffset, maxVisible);
345
346    return {
347      query,
348      cursor,
349      highlightIndex,
350      items,
351      filteredItems,
352      highlightedItem: filteredItems[highlightIndex],
353    };
354  }
355
356  function filteredFor(items: readonly NormalizedItem[], query: string) {
357    return [...filter(items, query)];
358  }
359
360  function render(model?: SelectModel): ContainerNode {
361    const state = resolveState(model);
362    latestState = state;
363    // Core can decode several edits/navigation keys from one stdin chunk
364    // before the scheduled render runs. Keep the event model current so each
365    // handler observes all preceding events in that same batch.
366    let eventState = state;
367
368    const queryControlled =
369      model?.query !== undefined || props.query !== undefined;
370    const cursorControlled =
371      model?.cursor !== undefined || props.cursor !== undefined;
372    const highlightControlled =
373      model?.highlightIndex !== undefined || props.highlightIndex !== undefined;
374    const inputFocused = props.focused ?? internalFocused;
375    const inheritedFocusStyle = inputFocused ? props.focusStyle : undefined;
376
377    function requestHighlight(
378      nextIndex: number,
379      filteredItems = eventState.filteredItems,
380    ): void {
381      const next = clampHighlight(nextIndex, filteredItems.length);
382      if (!highlightControlled) internalHighlightIndex = next;
383      scrollOffset = adjustScroll(next, scrollOffset, maxVisible);
384      if (next !== eventState.highlightIndex) {
385        props.onHighlightChange?.(next, filteredItems[next]);
386      }
387      eventState = {
388        ...eventState,
389        highlightIndex: next,
390        filteredItems,
391        highlightedItem: filteredItems[next],
392      };
393      cel.render();
394    }
395
396    function handleQueryChange(nextQuery: string): void {
397      if (!queryControlled) internalQuery = nextQuery;
398      scrollOffset = 0;
399      props.onQueryChange?.(nextQuery);
400
401      const nextFiltered = filteredFor(eventState.items, nextQuery);
402      eventState = {
403        ...eventState,
404        query: nextQuery,
405        cursor: clampQueryCursor(nextQuery, eventState.cursor),
406        filteredItems: nextFiltered,
407        highlightedItem: nextFiltered[eventState.highlightIndex],
408      };
409      requestHighlight(0, nextFiltered);
410    }
411
412    function handleCursorChange(nextCursor: number): void {
413      const clamped = clampQueryCursor(eventState.query, nextCursor);
414      if (!cursorControlled) internalCursor = clamped;
415      eventState = { ...eventState, cursor: clamped };
416      props.onCursorChange?.(clamped);
417    }
418
419    function selectItem(selected: NormalizedItem): void {
420      props.onSelect(selected.value, selected);
421    }
422
423    function handleInputKey(key: string): ReturnType<SelectKeyPressHandler> {
424      switch (key) {
425        case "up":
426          requestHighlight(
427            moveUp(eventState.highlightIndex, eventState.filteredItems.length),
428          );
429          return false;
430        case "down":
431          requestHighlight(
432            moveDown(
433              eventState.highlightIndex,
434              eventState.filteredItems.length,
435            ),
436          );
437          return false;
438        case "pageup":
439          requestHighlight(eventState.highlightIndex - maxVisible);
440          return false;
441        case "pagedown":
442          requestHighlight(eventState.highlightIndex + maxVisible);
443          return false;
444        case "enter":
445        case "shift+enter":
446          if (eventState.highlightedItem)
447            selectItem(eventState.highlightedItem);
448          return false;
449        case "escape":
450          if (props.onCancel) {
451            props.onCancel(copyState(eventState));
452            return false;
453          }
454          return;
455        default:
456          // Let TextInput edit printable text/navigation keys. Non-editing
457          // keys then bubble to the Select root and its ancestors.
458          return;
459      }
460    }
461
462    const visible = state.filteredItems.slice(
463      scrollOffset,
464      scrollOffset + maxVisible,
465    );
466    const overflow = state.filteredItems.length - scrollOffset - visible.length;
467    const children: Node[] = [
468      HStack({}, [
469        Text(props.searchLabel ?? "search: ", { fgColor: "color08" }),
470        TextInput({
471          stateKey: inputStateKey,
472          flex: 1,
473          height: 1,
474          value: state.query,
475          cursor: state.cursor,
476          onChange: handleQueryChange,
477          onCursorChange: handleCursorChange,
478          onKeyPress: handleInputKey,
479          placeholder: Text(props.placeholder ?? "type to filter...", {
480            fgColor: "color08",
481          }),
482          focused: props.focused,
483          focusable: props.focusable ?? true,
484          autoFocus: props.autoFocus,
485          onFocus: (event) => {
486            internalFocused = true;
487            props.onFocus?.(event);
488          },
489          onBlur: (event) => {
490            internalFocused = false;
491            props.onBlur?.(event);
492          },
493          focusStyle: props.focusStyle,
494        }),
495      ]),
496    ];
497
498    if (state.filteredItems.length === 0) {
499      children.push(
500        HStack({}, [
501          Text(`  ${props.emptyLabel ?? "no matches"}`, {
502            fgColor: "color08",
503          }),
504        ]),
505      );
506    } else {
507      for (
508        let visibleIndex = 0;
509        visibleIndex < visible.length;
510        visibleIndex++
511      ) {
512        const candidate = visible[visibleIndex];
513        if (!candidate) continue;
514        const index = scrollOffset + visibleIndex;
515        const highlighted = index === state.highlightIndex;
516        const select = () => selectItem(candidate);
517        const row = props.renderRow?.(candidate, {
518          index,
519          query: state.query,
520          highlighted,
521          indicator,
522          highlightColor,
523          select,
524        });
525
526        children.push(
527          HStack(
528            {
529              onClick: select,
530              focusable: false,
531              fgColor: highlighted ? highlightColor : undefined,
532            },
533            row
534              ? [row]
535              : [
536                  Text(highlighted ? `${indicator} ` : "  "),
537                  Text(candidate.label),
538                ],
539          ),
540        );
541      }
542    }
543
544    if (overflow > 0) {
545      children.push(
546        HStack({}, [Text(`  ${overflow} more`, { fgColor: "color08" })]),
547      );
548    }
549
550    return VStack(
551      {
552        // The actual TextInput is the only focus target. Keeping the wrapper
553        // non-focusable avoids a dead intermediate Tab stop.
554        focusable: false,
555        onKeyPress: props.onKeyPress,
556        width: props.width,
557        height: props.height,
558        flex: props.flex,
559        bold: inheritedFocusStyle?.bold,
560        italic: inheritedFocusStyle?.italic,
561        underline: inheritedFocusStyle?.underline,
562        fgColor: inheritedFocusStyle?.fgColor ?? props.fgColor,
563        bgColor: inheritedFocusStyle?.bgColor ?? props.bgColor,
564      },
565      children,
566    );
567  }
568
569  render.reset = () => {
570    const state = latestState ?? resolveState();
571    internalQuery = "";
572    internalCursor = 0;
573    internalHighlightIndex = 0;
574    scrollOffset = 0;
575
576    if (state.query !== "") props.onQueryChange?.("");
577    if (state.cursor !== 0) props.onCursorChange?.(0);
578    if (state.highlightIndex !== 0) {
579      const unfiltered = filteredFor(state.items, "");
580      props.onHighlightChange?.(0, unfiltered[0]);
581    }
582    latestState = undefined;
583    cel.render();
584  };
585
586  render.update = (model: SelectModel) => {
587    if (model.items !== undefined) updatedItems = model.items;
588    if (model.query !== undefined) {
589      internalQuery = model.query;
590      if (model.cursor === undefined) internalCursor = model.query.length;
591      scrollOffset = 0;
592    }
593    if (model.cursor !== undefined) internalCursor = model.cursor;
594    if (model.highlightIndex !== undefined) {
595      internalHighlightIndex = model.highlightIndex;
596    }
597    latestState = undefined;
598    cel.render();
599  };
600
601  render.getState = () => copyState(latestState ?? resolveState());
602
603  return render as SelectInstance;
604}