xonecas.io
725
Ds

diff-scope / files

diff-scope / .agents / skills / cel-tui / references / composing-components.md

3.8 KB
1# Composing Components
2
3cel-tui components are plain functions that return `Node` trees. There are two patterns depending on whether the component needs internal state.
4
5## Stateless components
6
7Simple functions that take props and return a `Node`. Called every render cycle inside `cel.viewport()`. All state is external — passed in as props.
8
9```ts
10import type { ContainerNode } from "@cel-tui/types";
11import { HStack, VStack, Text } from "@cel-tui/core";
12
13function StatusBar(left: string, right: string): ContainerNode {
14  return HStack({ fgColor: "color00", bgColor: "color07" }, [
15    Text(` ${left}`),
16    VStack({ flex: 1 }, []), // spacer
17    Text(`${right} `),
18  ]);
19}
20
21// Usage — called fresh each render
22cel.viewport(() =>
23  VStack({ height: "100%" }, [
24    mainContent(),
25    StatusBar(filename, `${lines} lines`),
26  ]),
27);
28```
29
30This is the pattern used by `Button`, `Divider`, `Spacer`, `VDivider`, `Markdown`, and `SyntaxHighlight` — stateless functions that derive output from current inputs. Prefer it whenever possible — it's simple, testable, and composable.
31
32## Stateful components (factory pattern)
33
34When a component needs internal state that persists across renders (e.g., a search query, cursor position, scroll offset), use a **factory function** that returns a callable instance. State lives in the closure. The user calls the instance each render to get a fresh `Node` tree.
35
36```ts
37import type { ContainerNode, Color } from "@cel-tui/types";
38import { cel, VStack, HStack, Text } from "@cel-tui/core";
39
40interface ToggleGroupProps {
41  options: string[];
42  onSelect: (value: string) => void;
43  activeColor?: Color;
44}
45
46interface ToggleGroupInstance {
47  (): ContainerNode;
48  reset(): void;
49}
50
51function ToggleGroup(props: ToggleGroupProps): ToggleGroupInstance {
52  const { options, onSelect, activeColor = "color06" } = props;
53  let activeIndex = 0;
54
55  function handleKey(key: string): boolean | void {
56    if (key === "left" && activeIndex > 0) {
57      activeIndex--;
58      cel.render();
59    } else if (key === "right" && activeIndex < options.length - 1) {
60      activeIndex++;
61      cel.render();
62    } else if (key === "enter") {
63      onSelect(options[activeIndex]!);
64    } else {
65      return false; // unrecognized key — let it bubble to ancestors
66    }
67  }
68
69  function render(): ContainerNode {
70    return HStack(
71      { focusable: true, onKeyPress: handleKey, gap: 1 },
72      options.map((opt, i) =>
73        Text(` ${opt} `, {
74          fgColor: i === activeIndex ? "color00" : undefined,
75          bgColor: i === activeIndex ? activeColor : undefined,
76        }),
77      ),
78    );
79  }
80
81  render.reset = () => {
82    activeIndex = 0;
83  };
84  return render as ToggleGroupInstance;
85}
86
87// Usage — create once, call each render
88const formatToggle = ToggleGroup({
89  options: ["JSON", "YAML", "TOML"],
90  onSelect: (fmt) => {
91    format = fmt;
92    cel.render();
93  },
94});
95
96cel.viewport(() =>
97  VStack({ height: "100%" }, [Text("Output format:"), formatToggle()]),
98);
99```
100
101## Key points
102
103- **Create once** outside `cel.viewport()`. The closure captures mutable state.
104- **Call each render** inside `cel.viewport()` — the function builds a fresh node tree from current state.
105- **`cel.render()`** is importable from `@cel-tui/core` — stateful components call it after internal state changes to trigger re-renders.
106- **Key bubbling** — `onKeyPress` handlers bubble from innermost to root. Return `false` from a handler to signal the key was not consumed and let it continue to the next ancestor. Return `void`/`undefined` to consume (backward-compatible). Components like `Select` return `false` for unrecognized keys, so app-level shortcuts on parent containers work automatically.
107- **`.reset()`** or other methods — attach to the render function (functions are objects in JS) to expose imperative control.
108
109This is the pattern used by `Select` from `@cel-tui/components`.