xonecas.io
70160
Ce

cel-tui / files

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

16.4 KB
1import { afterEach, describe, expect, it } from "bun:test";
2import {
3  MockTerminal,
4  type Node,
5  Text,
6  type TextInputNode,
7  VStack,
8} from "@cel-tui/core";
9import { testCel as cel } from "../../core/src/test-helpers.js";
10import type { NormalizedItem } from "./select.js";
11import {
12  adjustScroll,
13  moveDown,
14  moveUp,
15  normalizeItems,
16  prefixFilter,
17  Select,
18} from "./select.js";
19
20const LEFT = "\x1b[D";
21const DOWN = "\x1b[B";
22const ENTER = "\x1b[13u";
23const ESCAPE = "\x1b[27u";
24const BACKSPACE = "\x1b[127u";
25const TAB = "\x1b[9u";
26const CTRL_Q = "\x1b[113;5u";
27const BRACKETED_PASTE_START = "\x1b[200~";
28const BRACKETED_PASTE_END = "\x1b[201~";
29
30function bracketedPaste(text: string): string {
31  return `${BRACKETED_PASTE_START}${text}${BRACKETED_PASTE_END}`;
32}
33
34function item<T>(items: readonly T[], index: number): T {
35  const value = items[index];
36  expect(value).toBeDefined();
37  if (value === undefined) {
38    throw new Error(`Missing item at index ${index}`);
39  }
40  return value;
41}
42
43function findTextInput(node: Node): TextInputNode {
44  if (node.type === "textinput") return node;
45  if (node.type !== "text") {
46    for (const child of node.children) {
47      try {
48        return findTextInput(child);
49      } catch {
50        // Search the next branch.
51      }
52    }
53  }
54  throw new Error("Expected Select to contain a TextInput");
55}
56
57function collectText(node: Node): string {
58  if (node.type === "text") return node.content;
59  if (node.type === "textinput") return node.props.value;
60  return node.children.map(collectText).join("");
61}
62
63describe("normalizeItems", () => {
64  it("normalizes string items", () => {
65    const result = normalizeItems(["apple", "banana"]);
66    expect(result).toEqual([
67      { label: "apple", value: "apple", filterText: "apple" },
68      { label: "banana", value: "banana", filterText: "banana" },
69    ]);
70  });
71
72  it("normalizes object items with filterText", () => {
73    const result = normalizeItems([
74      { label: "Apple (red)", value: "apple", filterText: "apple" },
75    ]);
76    expect(result).toEqual([
77      { label: "Apple (red)", value: "apple", filterText: "apple" },
78    ]);
79  });
80
81  it("defaults filterText to label", () => {
82    const result = normalizeItems([{ label: "Apple", value: "apple" }]);
83    expect(result).toEqual([
84      { label: "Apple", value: "apple", filterText: "Apple" },
85    ]);
86  });
87});
88
89describe("prefixFilter", () => {
90  const items: NormalizedItem[] = [
91    { label: "apple", value: "apple", filterText: "apple" },
92    { label: "banana", value: "banana", filterText: "banana" },
93    { label: "cherry", value: "cherry", filterText: "cherry" },
94    { label: "avocado", value: "avocado", filterText: "avocado" },
95  ];
96
97  it("returns all items for empty query", () => {
98    expect(prefixFilter(items, "")).toEqual(items);
99  });
100
101  it("filters by prefix", () => {
102    const result = prefixFilter(items, "a");
103    expect(result).toEqual([
104      { label: "apple", value: "apple", filterText: "apple" },
105      { label: "avocado", value: "avocado", filterText: "avocado" },
106    ]);
107  });
108
109  it("is case-insensitive", () => {
110    const result = prefixFilter(items, "A");
111    expect(result.length).toBe(2);
112  });
113
114  it("matches word boundaries", () => {
115    const paths: NormalizedItem[] = [
116      {
117        label: "src/components/button.ts",
118        value: "button",
119        filterText: "src/components/button.ts",
120      },
121    ];
122    const result = prefixFilter(paths, "button");
123    expect(result.length).toBe(1);
124  });
125
126  it("returns empty for no matches", () => {
127    const result = prefixFilter(items, "xyz");
128    expect(result).toEqual([]);
129  });
130});
131
132describe("moveUp", () => {
133  it("moves up by one", () => {
134    expect(moveUp(2, 5)).toBe(1);
135  });
136
137  it("wraps from first to last", () => {
138    expect(moveUp(0, 5)).toBe(4);
139  });
140
141  it("returns 0 for empty list", () => {
142    expect(moveUp(0, 0)).toBe(0);
143  });
144});
145
146describe("moveDown", () => {
147  it("moves down by one", () => {
148    expect(moveDown(2, 5)).toBe(3);
149  });
150
151  it("wraps from last to first", () => {
152    expect(moveDown(4, 5)).toBe(0);
153  });
154
155  it("returns 0 for empty list", () => {
156    expect(moveDown(0, 0)).toBe(0);
157  });
158});
159
160describe("adjustScroll", () => {
161  it("keeps scroll when highlight is visible", () => {
162    expect(adjustScroll(3, 0, 5)).toBe(0);
163  });
164
165  it("scrolls up when highlight is above viewport", () => {
166    expect(adjustScroll(1, 3, 5)).toBe(1);
167  });
168
169  it("scrolls down when highlight is below viewport", () => {
170    expect(adjustScroll(7, 0, 5)).toBe(3);
171  });
172});
173
174describe("Select", () => {
175  it("returns a callable render function", () => {
176    const select = Select({
177      items: ["apple", "banana"],
178      onSelect: () => {},
179    });
180    const node = select();
181    expect(node.type).toBe("vstack");
182    expect(node.children.length).toBeGreaterThan(0);
183  });
184
185  it("renders search line and items", () => {
186    const select = Select({
187      items: ["apple", "banana", "cherry"],
188      onSelect: () => {},
189    });
190    const node = select();
191    // Search line + 3 items = 4 children
192    expect(node.children.length).toBe(4);
193  });
194
195  it("shows overflow indicator when items exceed maxVisible", () => {
196    const items = Array.from({ length: 15 }, (_, i) => `item-${i}`);
197    const select = Select({
198      items,
199      onSelect: () => {},
200      maxVisible: 5,
201    });
202    const node = select();
203    // Search line + 5 visible items + overflow indicator = 7
204    expect(node.children.length).toBe(7);
205    // Last child should contain overflow text
206    const lastChild = item(node.children, 6);
207    expect(lastChild.type).toBe("hstack");
208    if (lastChild.type === "hstack") {
209      const text = lastChild.children[0];
210      expect(text).toBeDefined();
211      if (text?.type === "text") {
212        expect(text.content).toContain("10 more");
213      }
214    }
215  });
216
217  it("has reset method that clears state", () => {
218    const select = Select({
219      items: ["apple", "banana"],
220      onSelect: () => {},
221    });
222    // reset exists and is callable
223    expect(typeof select.reset).toBe("function");
224    select.reset(); // should not throw
225  });
226
227  it("uses a TextInput as its sole focus target", () => {
228    const select = Select({
229      items: ["apple"],
230      onSelect: () => {},
231    });
232    const node = select();
233    expect(node.props.focusable).toBe(false);
234    expect(findTextInput(node).props.focusable).toBe(true);
235  });
236
237  it("forwards container props", () => {
238    const select = Select({
239      items: ["apple"],
240      onSelect: () => {},
241      width: 30,
242      fgColor: "color02",
243      bgColor: "color00",
244      flex: 1,
245    });
246    const node = select();
247    expect(node.props.width).toBe(30);
248    expect(node.props.fgColor).toBe("color02");
249    expect(node.props.bgColor).toBe("color00");
250    expect(node.props.flex).toBe(1);
251  });
252
253  it("applies focusStyle to the whole Select while its input is focused", () => {
254    const select = Select({
255      items: ["apple"],
256      focused: true,
257      fgColor: "color07",
258      focusStyle: {
259        fgColor: "color00",
260        bgColor: "color06",
261        bold: true,
262      },
263      onSelect: () => {},
264    });
265
266    const node = select();
267    expect(node.props.fgColor).toBe("color00");
268    expect(node.props.bgColor).toBe("color06");
269    expect(node.props.bold).toBe(true);
270  });
271
272  it("supports initial query and highlight state", () => {
273    const select = Select({
274      items: ["banana", "bandana", "apple"],
275      initialQuery: "ban",
276      initialHighlightIndex: 1,
277      onSelect: () => {},
278    });
279
280    const node = select();
281    expect(findTextInput(node).props.value).toBe("ban");
282    expect(select.getState()).toMatchObject({
283      query: "ban",
284      cursor: 3,
285      highlightIndex: 1,
286    });
287  });
288
289  it("clamps a controlled cursor backward to a query grapheme boundary", () => {
290    const family = "👨‍👩‍👧‍👦";
291    const select = Select({
292      items: ["anything"],
293      query: `A${family}B`,
294      cursor: 2,
295      onSelect: () => {},
296    });
297
298    const node = select();
299    expect(findTextInput(node).props.cursor).toBe(1);
300    expect(select.getState().cursor).toBe(1);
301  });
302
303  it("updates items and uncontrolled state without recreating the instance", () => {
304    const select = Select({ items: ["old"], onSelect: () => {} });
305
306    select.update({
307      items: ["new one", "new two"],
308      query: "two",
309      cursor: 1,
310      highlightIndex: 0,
311    });
312
313    const node = select();
314    expect(collectText(node)).toContain("new two");
315    expect(collectText(node)).not.toContain("old");
316    expect(select.getState()).toMatchObject({ query: "two", cursor: 1 });
317
318    const overridden = select({ items: ["render model"], query: "" });
319    expect(collectText(overridden)).toContain("render model");
320  });
321
322  it("accepts custom list filtering and row rendering", () => {
323    const calls: string[] = [];
324    const select = Select({
325      items: ["apple", "cherry"],
326      initialQuery: "err",
327      onSelect: () => {},
328      filter: (items, query) => {
329        calls.push(query);
330        return items.filter((candidate) => candidate.label.includes(query));
331      },
332      renderRow: (candidate, context) =>
333        Text(
334          `${context.highlighted ? "*" : "-"}${candidate.label}:${context.query}`,
335        ),
336    });
337
338    const node = select();
339    expect(calls).toEqual(["err"]);
340    expect(collectText(node)).toContain("*cherry:err");
341    expect(collectText(node)).not.toContain("apple");
342  });
343});
344
345describe("Select TextInput integration", () => {
346  let terminal: MockTerminal | undefined;
347
348  afterEach(() => {
349    cel.stop();
350    terminal = undefined;
351  });
352
353  function setup(select: ReturnType<typeof Select>): MockTerminal {
354    terminal = new MockTerminal(60, 12);
355    cel.init(terminal);
356    cel.viewport(() => VStack({ width: 60, height: 12 }, [select()]));
357    return terminal;
358  }
359
360  it("preserves exact text and uses cursor-aware grapheme editing and paste", async () => {
361    const family = "👨‍👩‍👧‍👦";
362    const pasted = "É 🧑🏽‍💻";
363    const changes: string[] = [];
364    const select = Select({
365      items: ["anything"],
366      initialQuery: `A${family}B`,
367      focused: true,
368      onQueryChange: (query) => changes.push(query),
369      onSelect: () => {},
370    });
371    const term = setup(select);
372    await cel._flush();
373
374    // One input chunk exercises TextInput's batched edit accumulator: the
375    // Backspace must observe the cursor move that precedes it.
376    term.sendInput(`${LEFT}${BACKSPACE}`);
377    await cel._flush();
378    expect(select.getState().query).toBe("AB");
379
380    term.sendInput(" z");
381    await cel._flush();
382    expect(select.getState().query).toBe("A zB");
383
384    const changesBeforePaste = changes.length;
385    term.sendInput(bracketedPaste(pasted));
386    await cel._flush();
387
388    expect(select.getState()).toMatchObject({
389      query: `A z${pasted}B`,
390      cursor: `A z${pasted}`.length,
391    });
392    expect(changes).toHaveLength(changesBeforePaste + 1);
393  });
394
395  it("keeps controlled query, cursor, and highlight authoritative", async () => {
396    let query = "ac";
397    let cursor = 1;
398    let highlightIndex = 0;
399    const queryRequests: string[] = [];
400    const cursorRequests: number[] = [];
401    const highlightRequests: number[] = [];
402    const select = Select({
403      items: ["acorn", "active", "actor"],
404      query,
405      cursor,
406      highlightIndex,
407      focused: true,
408      onQueryChange: (next) => queryRequests.push(next),
409      onCursorChange: (next) => cursorRequests.push(next),
410      onHighlightChange: (next) => highlightRequests.push(next),
411      onSelect: () => {},
412    });
413
414    terminal = new MockTerminal(60, 12);
415    cel.init(terminal);
416    cel.viewport(() =>
417      VStack({ width: 60, height: 12 }, [
418        select({ query, cursor, highlightIndex }),
419      ]),
420    );
421    await cel._flush();
422
423    terminal.sendInput("Z");
424    await cel._flush();
425    expect(queryRequests).toEqual(["aZc"]);
426    expect(cursorRequests).toEqual([2]);
427    expect(select.getState()).toMatchObject({ query: "ac", cursor: 1 });
428
429    query = "";
430    cursor = 0;
431    cel.render();
432    await cel._flush();
433    terminal.sendInput(DOWN);
434    await cel._flush();
435    expect(highlightRequests.at(-1)).toBe(1);
436    expect(select.getState().highlightIndex).toBe(0);
437
438    highlightIndex = 1;
439    cel.render();
440    await cel._flush();
441    expect(select.getState().highlightIndex).toBe(1);
442  });
443
444  it("selects with Enter without inserting a newline", async () => {
445    const selected: string[] = [];
446    const select = Select({
447      items: ["apple", "banana"],
448      initialQuery: "ban",
449      focused: true,
450      onSelect: (value) => selected.push(value),
451    });
452    const term = setup(select);
453    await cel._flush();
454
455    term.sendInput(ENTER);
456    await cel._flush();
457
458    expect(selected).toEqual(["banana"]);
459    expect(select.getState().query).toBe("ban");
460  });
461
462  it("uses the latest query and highlight throughout one mixed input chunk", async () => {
463    const selected: string[] = [];
464    const highlightRequests: number[] = [];
465    const select = Select({
466      items: ["banana", "apple", "apricot"],
467      focused: true,
468      onHighlightChange: (index) => highlightRequests.push(index),
469      onSelect: (value) => selected.push(value),
470    });
471    const term = setup(select);
472    await cel._flush();
473
474    // Filter, move within the newly filtered list, and select before any
475    // render can rebuild the handler closures.
476    term.sendInput(`a${DOWN}${ENTER}`);
477    await cel._flush();
478
479    expect(highlightRequests).toEqual([1]);
480    expect(selected).toEqual(["apricot"]);
481    expect(select.getState()).toMatchObject({
482      query: "a",
483      highlightIndex: 1,
484    });
485  });
486
487  it("routes Escape to onCancel and keeps the input mounted and focused", async () => {
488    const cancellations: string[] = [];
489    const blurReasons: string[] = [];
490    const select = Select({
491      items: ["apple"],
492      initialQuery: "app",
493      autoFocus: true,
494      onCancel: (state) => cancellations.push(state.query),
495      onBlur: ({ reason }) => blurReasons.push(reason),
496      onSelect: () => {},
497    });
498    const term = setup(select);
499    await cel._flush();
500
501    term.sendInput(ESCAPE);
502    await cel._flush();
503
504    expect(cancellations).toEqual(["app"]);
505    expect(blurReasons).toEqual([]);
506  });
507
508  it("retains the framework Escape blur fallback without onCancel", async () => {
509    const blurReasons: string[] = [];
510    const select = Select({
511      items: ["apple"],
512      autoFocus: true,
513      onBlur: ({ reason }) => blurReasons.push(reason),
514      onSelect: () => {},
515    });
516    const term = setup(select);
517    await cel._flush();
518
519    term.sendInput(ESCAPE);
520    await cel._flush();
521
522    expect(blurReasons).toEqual(["escape"]);
523  });
524
525  it("lets non-editing shortcuts bubble through the Select", async () => {
526    const keys: string[] = [];
527    const select = Select({
528      items: ["apple"],
529      focused: true,
530      onKeyPress: (key) => {
531        keys.push(key);
532      },
533      onSelect: () => {},
534    });
535    const term = setup(select);
536    await cel._flush();
537
538    term.sendInput(CTRL_Q);
539    await cel._flush();
540
541    expect(keys).toEqual(["ctrl+q"]);
542  });
543
544  it("continues bubbling when its onKeyPress returns false", async () => {
545    const keys: string[] = [];
546    const select = Select({
547      items: ["apple"],
548      focused: true,
549      onKeyPress: (key) => {
550        keys.push(`select:${key}`);
551        return false;
552      },
553      onSelect: () => {},
554    });
555
556    terminal = new MockTerminal(60, 12);
557    cel.init(terminal);
558    cel.viewport(() =>
559      VStack(
560        {
561          width: 60,
562          height: 12,
563          onKeyPress: (key) => {
564            keys.push(`root:${key}`);
565          },
566        },
567        [select()],
568      ),
569    );
570    await cel._flush();
571
572    terminal.sendInput(CTRL_Q);
573    await cel._flush();
574
575    expect(keys).toEqual(["select:ctrl+q", "root:ctrl+q"]);
576  });
577
578  it("honors focusable: false for keyboard traversal and clicks", async () => {
579    const focusReasons: string[] = [];
580    const select = Select({
581      items: ["apple"],
582      focusable: false,
583      onFocus: ({ reason }) => focusReasons.push(reason),
584      onSelect: () => {},
585    });
586    const term = setup(select);
587    await cel._flush();
588
589    term.sendInput(TAB);
590    await cel._flush();
591    term.sendInput("x");
592    await cel._flush();
593
594    // Search input begins after "search: "; this is a mouse-button release
595    // inside it. A non-focusable TextInput must not become focused by click.
596    term.sendInput("\x1b[<0;10;1m");
597    await cel._flush();
598    term.sendInput("y");
599    await cel._flush();
600
601    expect(focusReasons).toEqual([]);
602    expect(select.getState().query).toBe("");
603  });
604});