xonecas.io
70160
Ce

cel-tui / commit 40f4117

feat: polish examples

xonecas2026-04-18 40f4117c2d73bcb3bd2f9433d8f144f427042c89 parent b74f539

4 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

examples/chat.ts+318−169
@@ -1,17 +1,12 @@
11 /**
22 * cel-tui: Agentic Chat UI
33 *
4- * A simulated agentic chat interface showcasing the full API:
5- * - Markdown rendering in streamed agent responses
6- * - TextInput with controlled focus
7- * - Scrollable message history
8- * - Button with focusStyle
9- * - Divider, Spacer components
10- * - Key bindings (Ctrl+Q quit, Escape/Tab focus traversal)
11- *
12- * The agent responses are simulated — characters stream in one by
13- * one with a small delay, exercising the Markdown component's
14- * streaming behavior.
4+ * A polished chat demo showing:
5+ * - Scrollable message history with sticky-bottom behavior
6+ * - Streaming markdown responses
7+ * - Controlled TextInput focus
8+ * - Buttons, starter prompts, and keyboard shortcuts
9+ * - Explicit external state with a small render tree
1510 *
1611 * Run: bun run examples/chat.ts
1712 */
@@ -25,61 +20,73 @@ import {
2520 ProcessTerminal,
2621 } from "@cel-tui/core";
2722 import { Button, Divider, Markdown, Spacer } from "@cel-tui/components";
23+import { warningBox } from "./warning-box";
2824
29-// ─── Simulated Agent Responses ──────────────────────────────────
25+const MIN_COLS = 56;
26+const MIN_ROWS = 18;
3027
3128 const RESPONSES = [
32- `I'll check that for you.
29+ `Here’s the high-level layout model.
3330
34-\`\`\`
35-$ ls -la
36-file1.ts
37-file2.ts
38-README.md
39-\`\`\`
31+## cel-tui in one screen
4032
41-Found **3 files** in the current directory.`,
33+- **VStack** lays children out top-to-bottom
34+- **HStack** lays children out left-to-right
35+- **Text** is a pure leaf node
36+- **TextInput** is an editable container
4237
43- `Here's a quick overview:
38+\`flex\`, fixed sizes, padding, and gap work together to make terminal layout feel predictable.`,
4439
45-## Project Structure
40+ `A good focus + scroll pattern usually looks like this:
4641
47-- **file1.ts** — Main entry point
48-- **file2.ts** — Utility functions
49-- **README.md** — Project documentation
42+1. Let the framework manage focus by default
43+2. Only control focus when app logic genuinely needs it
44+3. Use \`scrollOffset: Infinity\` for sticky-bottom UIs
45+4. Keep state outside the framework, then call \`cel.render()\`
5046
51-> All files were last modified today.`,
47+> The framework owns rendering. Your app owns state.`,
5248
53- `Sure, I can help with that. Here's a code snippet:
49+ `Markdown is a fun fit for chat UIs because it makes streamed responses feel richer.
5450
5551 \`\`\`ts
56-function greet(name: string): string {
57- return \`Hello, \${name}!\`;
58-}
59-
60-console.log(greet("world"));
52+const history = VStack(
53+ { flex: 1, overflow: "scroll", scrollbar: true },
54+ messages.flatMap(renderMessage)
55+);
6156 \`\`\`
6257
63-This defines a simple \`greet\` function that returns a formatted string.
58+That lets you mix **lists**, *emphasis*, code fences, and quotes without building a separate renderer.`,
6459
65----
66-
67-Let me know if you need anything else!`,
68-
69- `Here's what I found:
60+ `If you want the app to feel polished, focus on a few small UX details:
7061
71-### Summary
62+- starter actions when the screen is empty
63+- clear keyboard hints
64+- sticky scroll when new content arrives
65+- buttons that still work well with Tab + Enter
7266
73-1. The project uses **TypeScript** with strict mode
74-2. Dependencies are managed via \`bun\`
75-3. Tests use the built-in \`bun test\` runner
76-
77-> The codebase follows conventional commits and has pre-commit hooks.
67+---
7868
79-Everything looks good!`,
69+That’s the kind of “boring but good” structure cel-tui is great at.`,
8070 ];
8171
82-// ─── State ──────────────────────────────────────────────────────
72+const STARTER_PROMPTS = [
73+ {
74+ label: "layout",
75+ prompt: "Explain cel-tui's layout model in one screen.",
76+ },
77+ {
78+ label: "focus + scroll",
79+ prompt: "What focus and scroll patterns work well in cel-tui?",
80+ },
81+ {
82+ label: "markdown",
83+ prompt: "Why does markdown work nicely for terminal chat demos?",
84+ },
85+ {
86+ label: "ux tips",
87+ prompt: "Give me a few concrete UX tips for a cel-tui app.",
88+ },
89+] as const;
8390
8491 interface Message {
8592 role: "user" | "agent";
@@ -97,8 +104,6 @@ let streamPos = 0;
97104 let scrollOffset = 0;
98105 let stickToBottom = true;
99106
100-// ─── Helpers ────────────────────────────────────────────────────
101-
102107 const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
103108 let spinnerTick = 0;
104109 let spinnerTimer: ReturnType<typeof setInterval> | null = null;
@@ -118,47 +123,63 @@ function stopSpinner() {
118123 }
119124 }
120125
126+function stopStreaming() {
127+ if (streamTimer) {
128+ clearTimeout(streamTimer);
129+ streamTimer = null;
130+ }
131+ stopSpinner();
132+}
133+
121134 function isStreaming(): boolean {
122135 return streamTimer !== null;
123136 }
124137
138+function canSend(text = input): boolean {
139+ return text.trim().length > 0 && !isStreaming();
140+}
141+
125142 function streamNextChar() {
126- const agentMsg = messages[messages.length - 1];
127- if (!agentMsg || agentMsg.role !== "agent") return;
143+ const agentMessage = messages[messages.length - 1];
144+ if (!agentMessage || agentMessage.role !== "agent") {
145+ stopStreaming();
146+ return;
147+ }
128148
129149 if (streamPos < streamSource.length) {
130- // Stream a few characters at a time for speed
131- const chunk = streamSource.slice(streamPos, streamPos + 3);
150+ const chunk = streamSource.slice(streamPos, streamPos + 4);
132151 streamPos += chunk.length;
133- agentMsg.content = streamSource.slice(0, streamPos);
134- cel.render();
135- streamTimer = setTimeout(streamNextChar, 15);
136- } else {
137- // Done streaming
138- agentMsg.streaming = false;
139- streamTimer = null;
140- stopSpinner();
152+ agentMessage.content = streamSource.slice(0, streamPos);
141153 cel.render();
154+ streamTimer = setTimeout(streamNextChar, 14);
155+ return;
142156 }
157+
158+ agentMessage.streaming = false;
159+ streamTimer = null;
160+ stopSpinner();
161+ cel.render();
143162 }
144163
145-function handleSend() {
146- const text = input.trim();
147- if (text.length === 0 || isStreaming()) return;
164+function queueResponse(response: string) {
165+ streamSource = response;
166+ streamPos = 0;
167+ messages.push({ role: "agent", content: "", streaming: true });
168+ startSpinner();
169+ streamTimer = setTimeout(streamNextChar, 240);
170+}
171+
172+function handleSend(nextText = input) {
173+ const text = nextText.trim();
174+ if (!canSend(nextText)) return;
148175
149- // Add user message
150176 messages.push({ role: "user", content: text });
151177 input = "";
152178 stickToBottom = true;
153179
154- // Pick a response and start streaming
155- streamSource = RESPONSES[responseIndex % RESPONSES.length]!;
180+ const response = RESPONSES[responseIndex % RESPONSES.length]!;
156181 responseIndex++;
157- streamPos = 0;
158- messages.push({ role: "agent", content: "", streaming: true });
159-
160- startSpinner();
161- streamTimer = setTimeout(streamNextChar, 300);
182+ queueResponse(response);
162183 cel.render();
163184 }
164185
@@ -167,64 +188,185 @@ function handleChange(value: string) {
167188 cel.render();
168189 }
169190
191+function resetChat() {
192+ stopStreaming();
193+ messages = [];
194+ input = "";
195+ responseIndex = 0;
196+ streamSource = "";
197+ streamPos = 0;
198+ scrollOffset = 0;
199+ stickToBottom = true;
200+ inputFocused = true;
201+ cel.render();
202+}
203+
170204 function quit() {
171- stopSpinner();
172- if (streamTimer) clearTimeout(streamTimer);
205+ stopStreaming();
173206 cel.stop();
174207 process.exit(0);
175208 }
176209
177-// ─── Message Rendering ──────────────────────────────────────────
178-
179-function renderMessage(msg: Message, idx: number) {
180- const isUser = msg.role === "user";
181- const icon = isUser ? "▶" : "▷";
182- const label = isUser ? "You" : "Agent";
183- const color = isUser ? "color04" : "color02";
184-
185- const spinner =
186- msg.streaming && msg.content.length > 0
187- ? ` ${spinnerFrames[spinnerTick % spinnerFrames.length]}`
188- : "";
189-
190- return VStack({ gap: 0 }, [
191- // Role header
192- HStack({ gap: 1 }, [
193- Text(`${icon} ${label}${spinner}`, { bold: true, fgColor: color }),
194- ]),
195-
196- // Content
197- ...(isUser
198- ? [Text(` ${msg.content}`, { wrap: "word" })]
199- : msg.content.length > 0
200- ? Markdown(msg.content).map((node) => {
201- // Indent agent content by wrapping in a padded container
202- if (node.type === "text" && node.content === "") return node;
203- return HStack({}, [Text(" "), VStack({ flex: 1 }, [node])]);
204- })
205- : [
206- Text(
207- ` ${spinnerFrames[spinnerTick % spinnerFrames.length]} thinking...`,
208- { fgColor: "color08", italic: true },
209- ),
210- ]),
211- ]);
210+function currentSpinner(): string {
211+ return spinnerFrames[spinnerTick % spinnerFrames.length]!;
212+}
213+
214+function renderMarkdownNode(node: ReturnType<typeof Markdown>[number]) {
215+ if (node.type === "text" && node.content === "") return node;
216+ return HStack({}, [Text(" "), VStack({ flex: 1 }, [node])]);
212217 }
213218
214-// ─── UI ─────────────────────────────────────────────────────────
219+function renderMessage(message: Message) {
220+ const isUser = message.role === "user";
221+ const accent = isUser ? "color04" : "color02";
222+ const label = isUser ? "You" : "Demo Agent";
223+ const icon = isUser ? "▶" : "✦";
224+ const spinner = message.streaming ? ` ${currentSpinner()}` : "";
225+
226+ return VStack(
227+ {
228+ gap: 0,
229+ padding: { x: 1 },
230+ bgColor: isUser ? "color08" : undefined,
231+ },
232+ [
233+ Text(`${icon} ${label}${spinner}`, {
234+ bold: true,
235+ fgColor: accent,
236+ }),
237+ ...(isUser
238+ ? [Text(message.content, { wrap: "word" })]
239+ : message.content.length > 0
240+ ? Markdown(message.content).map(renderMarkdownNode)
241+ : [
242+ Text(` ${currentSpinner()} thinking...`, {
243+ fgColor: "color08",
244+ italic: true,
245+ }),
246+ ]),
247+ ],
248+ );
249+}
250+
251+function renderStarterPrompts() {
252+ return HStack(
253+ { flexWrap: "wrap", gap: 1, justifyContent: "center" },
254+ STARTER_PROMPTS.map((starter) =>
255+ Button(` ${starter.label} `, {
256+ onClick: () => handleSend(starter.prompt),
257+ fgColor: "color06",
258+ bold: true,
259+ focusStyle: { bgColor: "color06", fgColor: "color00" },
260+ }),
261+ ),
262+ );
263+}
264+
265+function emptyState(compact = false) {
266+ const intro = VStack({ alignItems: "center", gap: 1, padding: { x: 2 } }, [
267+ Text("Ask the demo agent about cel-tui", {
268+ bold: true,
269+ fgColor: "color06",
270+ }),
271+ Text("Starter prompts stream markdown replies.", {
272+ fgColor: "color08",
273+ }),
274+ ...(compact
275+ ? []
276+ : [
277+ Text("They also keep the first screen from feeling empty.", {
278+ fgColor: "color08",
279+ }),
280+ Text("Try one of these:", { fgColor: "color08", italic: true }),
281+ ]),
282+ renderStarterPrompts(),
283+ ]);
284+
285+ return compact ? [intro] : [Spacer(), intro, Spacer()];
286+}
215287
216288 cel.init(new ProcessTerminal());
289+cel.viewport(() => {
290+ const cols = process.stdout.columns || 80;
291+ const rows = process.stdout.rows || 24;
292+ const compact = cols < 70;
293+ const sendLabel = isStreaming() ? " Wait " : " Send ";
294+ const sendColor = canSend() ? "color06" : "color08";
295+ const placeholderText = compact
296+ ? "ask about layout or ux..."
297+ : "ask about layout, focus, markdown, or UX...";
298+
299+ const composerInput = TextInput({
300+ flex: 1,
301+ maxHeight: 5,
302+ value: input,
303+ onChange: handleChange,
304+ placeholder: Text(placeholderText, {
305+ fgColor: "color08",
306+ }),
307+ onKeyPress: (key) => {
308+ if (key === "enter") {
309+ handleSend();
310+ return false;
311+ }
312+ },
313+ focused: inputFocused,
314+ onFocus: () => {
315+ inputFocused = true;
316+ cel.render();
317+ },
318+ onBlur: () => {
319+ inputFocused = false;
320+ cel.render();
321+ },
322+ });
323+
324+ const clearButton = Button(" Clear ", {
325+ onClick: resetChat,
326+ fgColor: "color08",
327+ focusStyle: { bgColor: "color08", fgColor: "color00" },
328+ });
329+
330+ const sendButton = Button(sendLabel, {
331+ onClick: () => handleSend(),
332+ bgColor: sendColor,
333+ fgColor: "color00",
334+ bold: true,
335+ focusStyle: { bgColor: "color06", fgColor: "color00" },
336+ });
337+
338+ if (cols < MIN_COLS || rows < MIN_ROWS) {
339+ return VStack(
340+ {
341+ height: "100%",
342+ justifyContent: "center",
343+ alignItems: "center",
344+ onKeyPress: (key) => {
345+ if (key === "ctrl+q" || key === "ctrl+c") quit();
346+ },
347+ },
348+ [
349+ ...warningBox([
350+ " Terminal too small :(",
351+ "",
352+ " Please resize to at",
353+ ` least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars.`,
354+ "",
355+ " Ctrl+Q to quit",
356+ ]),
357+ ],
358+ );
359+ }
217360
218-cel.viewport(() =>
219- VStack(
361+ return VStack(
220362 {
221363 height: "100%",
222364 onKeyPress: (key) => {
223365 if (key === "ctrl+q" || key === "ctrl+c") quit();
366+ if (key === "ctrl+l") resetChat();
224367 },
225368 },
226369 [
227- // ── Header ──
228370 HStack(
229371 {
230372 height: 1,
@@ -232,17 +374,35 @@ cel.viewport(() =>
232374 bgColor: "color04",
233375 fgColor: "color07",
234376 },
235- [Text(" Agent ", { bold: true }), Spacer(), Text("model: gpt-4")],
377+ [
378+ Text(" Demo Agent ", { bold: true }),
379+ Spacer(),
380+ Text(isStreaming() ? `${currentSpinner()} streaming` : "ready"),
381+ Text(" "),
382+ Text(`${messages.length} msgs`, { fgColor: "color15" }),
383+ ],
236384 ),
385+ compact
386+ ? HStack({ padding: { x: 1 } }, [
387+ Text("Starter prompts, markdown streaming, sticky scroll.", {
388+ fgColor: "color08",
389+ }),
390+ ])
391+ : HStack({ padding: { x: 1 }, gap: 2 }, [
392+ Text("Simulated replies with markdown streaming.", {
393+ fgColor: "color08",
394+ }),
395+ Spacer(),
396+ Text("Ctrl+L clear", { fgColor: "color08" }),
397+ ]),
237398 Divider({ fgColor: "color08" }),
238-
239- // ── Message History ──
240399 VStack(
241400 {
242401 flex: 1,
243402 overflow: "scroll",
244403 scrollbar: true,
245- padding: { x: 1 },
404+ padding: { x: 1, y: 1 },
405+ gap: 1,
246406 scrollOffset: stickToBottom ? Infinity : scrollOffset,
247407 onScroll: (offset, maxOffset) => {
248408 scrollOffset = offset;
@@ -250,60 +410,49 @@ cel.viewport(() =>
250410 cel.render();
251411 },
252412 },
253- messages.length > 0
254- ? messages.flatMap((msg, i) => [
255- ...(i > 0 ? [Text("")] : []),
256- renderMessage(msg, i),
257- ])
258- : [
259- Spacer(),
260- VStack({ alignItems: "center" }, [
261- Text("No messages yet.", {
262- fgColor: "color08",
263- italic: true,
264- }),
265- Text("Type a message below to start.", {
266- fgColor: "color08",
267- }),
268- ]),
269- Spacer(),
270- ],
413+ messages.length > 0 ? messages.map(renderMessage) : emptyState(compact),
271414 ),
272-
273- // ── Input Area ──
274415 Divider({ fgColor: "color08" }),
275- HStack({ padding: { x: 1 }, gap: 1 }, [
276- Text(">", { fgColor: "color06", bold: true }),
277- TextInput({
278- flex: 1,
279- maxHeight: 5,
280- value: input,
281- onChange: handleChange,
282- placeholder: Text("type a message...", { fgColor: "color08" }),
283- onKeyPress: (key) => {
284- if (key === "enter") {
285- handleSend();
286- return false;
287- }
288- },
289- focused: inputFocused,
290- onFocus: () => {
291- inputFocused = true;
292- cel.render();
293- },
294- onBlur: () => {
295- inputFocused = false;
296- cel.render();
297- },
298- }),
299- Button(" Send ", {
300- onClick: handleSend,
301- bgColor: "color08",
302- fgColor: "color00",
303- bold: true,
304- focusStyle: { bgColor: "color06", fgColor: "color00" },
305- }),
416+ ...(compact
417+ ? [
418+ VStack({ padding: { x: 1 }, gap: 1 }, [
419+ HStack({ gap: 1 }, [
420+ Text(">", {
421+ fgColor: canSend() ? "color06" : "color08",
422+ bold: true,
423+ }),
424+ composerInput,
425+ ]),
426+ HStack({ justifyContent: "end", gap: 1 }, [
427+ clearButton,
428+ sendButton,
429+ ]),
430+ ]),
431+ ]
432+ : [
433+ HStack({ padding: { x: 1 }, gap: 1 }, [
434+ Text(">", {
435+ fgColor: canSend() ? "color06" : "color08",
436+ bold: true,
437+ }),
438+ composerInput,
439+ clearButton,
440+ sendButton,
441+ ]),
442+ ]),
443+ HStack({ padding: { x: 1 }, gap: 1, flexWrap: "wrap" }, [
444+ Text("Enter", { fgColor: "color08", bold: true }),
445+ Text("send", { fgColor: "color08" }),
446+ Text("·", { fgColor: "color08" }),
447+ Text("Tab", { fgColor: "color08", bold: true }),
448+ Text("move focus", { fgColor: "color08" }),
449+ Text("·", { fgColor: "color08" }),
450+ Text("Esc", { fgColor: "color08", bold: true }),
451+ Text("blur", { fgColor: "color08" }),
452+ Text("·", { fgColor: "color08" }),
453+ Text("Ctrl+Q", { fgColor: "color08", bold: true }),
454+ Text("quit", { fgColor: "color08" }),
306455 ]),
307456 ],
308- ),
309-);
457+ );
458+});
examples/pet.ts+11−4
@@ -197,7 +197,7 @@ let screen: Screen = "create";
197197 // -- Creation state --
198198 let petName = "";
199199 let selectedKind = 0;
200-let nameInputFocused = false; // only TextInput needs controlled focus (arrow key routing)
200+let nameInputFocused = true; // only TextInput needs controlled focus (arrow key routing)
201201
202202 // -- Pet state --
203203 let pet: PetDef | null = null;
@@ -232,13 +232,15 @@ function addLog(msg: string) {
232232
233233 function startGame() {
234234 pet = PETS[selectedKind]!;
235- if (!petName.trim()) petName = pet.kind;
235+ petName = petName.trim() || pet.kind;
236236 health = 100;
237237 hunger = 0;
238238 happiness = 100;
239239 anim = "idle";
240240 frame = 0;
241241 log = [];
242+ showLog = false;
243+ nameInputFocused = false;
242244 screen = "main";
243245
244246 addLog(`${petName} the ${pet.kind} was born!`);
@@ -313,8 +315,10 @@ function restart() {
313315 pet = null;
314316 petName = "";
315317 selectedKind = 0;
318+ nameInputFocused = true;
316319 screen = "create";
317320 log = [];
321+ logScroll = 0;
318322 showLog = false;
319323 cel.render();
320324 }
@@ -484,8 +488,7 @@ function createView() {
484488 },
485489 onKeyPress: (key) => {
486490 if (key === "enter") {
487- nameInputFocused = false;
488- cel.render();
491+ startGame();
489492 return false;
490493 }
491494 },
@@ -546,6 +549,10 @@ function createView() {
546549
547550 // Hints — wrapping for narrow terminals
548551 HStack({ justifyContent: "center", flexWrap: "wrap", gap: 1 }, [
552+ HStack({}, [
553+ Text("Enter", { fgColor: "color08", bold: true }),
554+ Text(" create", { fgColor: "color08" }),
555+ ]),
549556 HStack({}, [
550557 Text("Tab", { fgColor: "color08", bold: true }),
551558 Text(" navigate", { fgColor: "color08" }),
examples/select.ts+229−62
@@ -1,88 +1,255 @@
11 import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
2-import { Select, Divider, Spacer } from "@cel-tui/components";
2+import { Select, Divider, Spacer, VDivider } from "@cel-tui/components";
33
4-let selected = "";
4+interface ThemePreset {
5+ id: string;
6+ name: string;
7+ vibe: string;
8+ summary: string;
9+ accent: AccentColor;
10+ keywords: string[];
11+ palette: readonly string[];
12+}
513
6-const fruits = [
7- "apple",
8- "apricot",
9- "avocado",
10- "banana",
11- "blackberry",
12- "blueberry",
13- "cherry",
14- "coconut",
15- "cranberry",
16- "date",
17- "dragonfruit",
18- "elderberry",
19- "fig",
20- "grape",
21- "guava",
22- "kiwi",
23- "lemon",
24- "lime",
25- "lychee",
26- "mango",
27- "nectarine",
28- "orange",
29- "papaya",
30- "peach",
31- "pear",
32- "pineapple",
33- "plum",
34- "pomegranate",
35- "raspberry",
36- "strawberry",
37- "watermelon",
14+type AccentColor =
15+ | "color06"
16+ | "color05"
17+ | "color03"
18+ | "color02"
19+ | "color04"
20+ | "color01";
21+
22+const THEMES: ThemePreset[] = [
23+ {
24+ id: "catppuccin/mocha",
25+ name: "Catppuccin Mocha",
26+ vibe: "cozy purple dusk",
27+ summary:
28+ "A warm, low-contrast palette for long terminal sessions, writing, and dashboards that should feel calm instead of clinical.",
29+ accent: "color05",
30+ keywords: ["cozy", "purple", "soft", "night", "editorial"],
31+ palette: ["mauve", "rosewater", "teal"],
32+ },
33+ {
34+ id: "nord/frost",
35+ name: "Nord Frost",
36+ vibe: "icy blue minimalism",
37+ summary:
38+ "Cool blues, crisp contrast, and a restrained look that works well for logs, monitoring, and data-heavy layouts.",
39+ accent: "color06",
40+ keywords: ["cool", "blue", "minimal", "ops", "monitoring"],
41+ palette: ["frost", "snow", "storm"],
42+ },
43+ {
44+ id: "tokyo-night/storm",
45+ name: "Tokyo Night Storm",
46+ vibe: "electric city glow",
47+ summary:
48+ "A sharper dark theme with vibrant accents that helps demos feel energetic without getting noisy.",
49+ accent: "color04",
50+ keywords: ["neon", "city", "energetic", "sharp", "modern"],
51+ palette: ["indigo", "cyan", "amber"],
52+ },
53+ {
54+ id: "gruvbox/material",
55+ name: "Gruvbox Material",
56+ vibe: "earthy amber studio",
57+ summary:
58+ "Muted warmth and clear hierarchy. Great when you want a dense interface to stay readable and grounded.",
59+ accent: "color03",
60+ keywords: ["warm", "amber", "retro", "earthy", "dense"],
61+ palette: ["sand", "olive", "rust"],
62+ },
63+ {
64+ id: "forest/mint",
65+ name: "Forest Mint",
66+ vibe: "fresh green utility",
67+ summary:
68+ "High-signal greens for positive actions, health checks, and clean success-heavy dashboards.",
69+ accent: "color02",
70+ keywords: ["green", "fresh", "success", "health", "utility"],
71+ palette: ["mint", "sage", "pine"],
72+ },
73+ {
74+ id: "ember/redline",
75+ name: "Ember Redline",
76+ vibe: "alert-focused crimson",
77+ summary:
78+ "Built for warnings, incident tooling, and views where urgency should be visible immediately.",
79+ accent: "color01",
80+ keywords: ["red", "alert", "incident", "urgent", "ops"],
81+ palette: ["ember", "flame", "ash"],
82+ },
3883 ];
3984
40-const fruitSelect = Select({
41- items: fruits,
42- maxVisible: 8,
43- placeholder: "search fruits...",
85+const themeById = new Map(THEMES.map((theme) => [theme.id, theme]));
86+let selectedThemeId = THEMES[0]!.id;
87+
88+const themeSelect = Select({
89+ items: THEMES.map((theme) => ({
90+ label: theme.name,
91+ value: theme.id,
92+ filterText: `${theme.name} ${theme.vibe} ${theme.keywords.join(" ")}`,
93+ })),
94+ maxVisible: 7,
95+ placeholder: "search themes or keywords...",
96+ highlightColor: "color06",
4497 onSelect: (value) => {
45- selected = value;
98+ selectedThemeId = value;
4699 cel.render();
47100 },
48101 });
49102
103+function activeTheme(): ThemePreset {
104+ return themeById.get(selectedThemeId) ?? THEMES[0]!;
105+}
106+
107+function resetDemo() {
108+ selectedThemeId = THEMES[0]!.id;
109+ themeSelect.reset();
110+ cel.render();
111+}
112+
113+function quit() {
114+ cel.stop();
115+ process.exit(0);
116+}
117+
118+function sampleFilters() {
119+ return HStack(
120+ { flexWrap: "wrap", gap: 1 },
121+ ["cozy", "blue", "alert", "modern", "success"].map((sample) =>
122+ Text(` ${sample} `, {
123+ fgColor: "color15",
124+ bgColor: "color08",
125+ }),
126+ ),
127+ );
128+}
129+
130+function paletteRow(theme: ThemePreset) {
131+ return HStack(
132+ { flexWrap: "wrap", gap: 1 },
133+ theme.palette.map((label) =>
134+ Text(` ${label} `, {
135+ fgColor: "color00",
136+ bgColor: theme.accent,
137+ bold: true,
138+ }),
139+ ),
140+ );
141+}
142+
143+function previewPane(theme: ThemePreset) {
144+ return VStack({ flex: 1, gap: 1 }, [
145+ HStack({ gap: 1 }, [
146+ Text(" Theme Preview ", {
147+ fgColor: "color00",
148+ bgColor: theme.accent,
149+ bold: true,
150+ }),
151+ Text(theme.id, { fgColor: "color08" }),
152+ ]),
153+ Text(theme.name, { bold: true, fgColor: theme.accent }),
154+ Text(theme.vibe, { fgColor: theme.accent, italic: true }),
155+ Text(theme.summary, { wrap: "word" }),
156+ Divider({ fgColor: "color08" }),
157+ Text("Palette vibe", { bold: true, fgColor: "color08" }),
158+ paletteRow(theme),
159+ Text("Keywords", { bold: true, fgColor: "color08" }),
160+ HStack(
161+ { flexWrap: "wrap", gap: 1 },
162+ theme.keywords.map((keyword) =>
163+ Text(` ${keyword} `, {
164+ fgColor: theme.accent,
165+ bgColor: "color08",
166+ bold: true,
167+ }),
168+ ),
169+ ),
170+ Divider({ fgColor: "color08" }),
171+ Text("Why this is a good Select demo", { bold: true, fgColor: "color08" }),
172+ Text(
173+ "• Uses rich items with display text separate from the selected value.",
174+ ),
175+ Text("• Filter text includes mood words, so prefix search feels useful."),
176+ Text(
177+ "• External app state stays tiny: the Select manages its own query and highlight.",
178+ ),
179+ Spacer(),
180+ Text("Try typing one of the sample filters above, then press Enter.", {
181+ fgColor: "color08",
182+ italic: true,
183+ wrap: "word",
184+ }),
185+ ]);
186+}
187+
188+function pickerPane(theme: ThemePreset) {
189+ return VStack({ gap: 1 }, [
190+ Text("Select component demo", { bold: true, fgColor: theme.accent }),
191+ Text("A palette picker for theme presets.", {
192+ fgColor: "color08",
193+ italic: true,
194+ }),
195+ Divider({ fgColor: "color08" }),
196+ Text("Sample filters", { bold: true, fgColor: "color08" }),
197+ sampleFilters(),
198+ Text("Picker", { bold: true, fgColor: "color08" }),
199+ themeSelect(),
200+ ]);
201+}
202+
50203 cel.init(new ProcessTerminal());
51-cel.viewport(() =>
52- VStack(
204+cel.viewport(() => {
205+ const cols = process.stdout.columns || 80;
206+ const theme = activeTheme();
207+ const wide = cols >= 80;
208+ const paneWidth = cols >= 100 ? 42 : 36;
209+
210+ return VStack(
53211 {
54212 height: "100%",
55213 padding: { x: 2, y: 1 },
56214 onKeyPress: (key) => {
57- if (key === "ctrl+q") {
58- cel.stop();
59- process.exit();
215+ if (key === "ctrl+q" || key === "ctrl+c") {
216+ quit();
60217 }
61218 if (key === "ctrl+r") {
62- selected = "";
63- fruitSelect.reset();
64- cel.render();
219+ resetDemo();
65220 }
66221 },
67222 },
68223 [
69- Text("Select Component Demo", { bold: true, fgColor: "color06" }),
70- Text("Tab to focus · type to filter · ↑↓ to navigate · Enter to select", {
224+ HStack({ gap: 1 }, [
225+ Text("◈", { fgColor: theme.accent, bold: true }),
226+ Text("Theme Preset Picker", { bold: true }),
227+ Spacer(),
228+ Text(theme.vibe, { fgColor: "color08", italic: true }),
229+ ]),
230+ Text("Search by vibe, inspect the value, and compare the preview pane.", {
71231 fgColor: "color08",
72232 }),
73233 Divider({ fgColor: "color08" }),
74- Text(""),
75- fruitSelect(),
76- Text(""),
234+ ...(wide
235+ ? [
236+ HStack({ flex: 1 }, [
237+ VStack({ width: paneWidth, padding: { x: 1 } }, [
238+ pickerPane(theme),
239+ ]),
240+ VDivider({ fgColor: "color08" }),
241+ VStack({ flex: 1, padding: { x: 1 } }, [previewPane(theme)]),
242+ ]),
243+ ]
244+ : [
245+ pickerPane(theme),
246+ Divider({ fgColor: "color08" }),
247+ previewPane(theme),
248+ ]),
77249 Divider({ fgColor: "color08" }),
78- selected
79- ? HStack({}, [
80- Text("Selected: ", { fgColor: "color08" }),
81- Text(selected, { bold: true, fgColor: "color02" }),
82- ])
83- : Text("No selection yet", { fgColor: "color08" }),
84- Spacer(),
85- Text("Ctrl+R reset · Ctrl+Q quit", { fgColor: "color08" }),
250+ Text("Tab/filter/enter · Ctrl+R reset · Ctrl+Q quit", {
251+ fgColor: "color08",
252+ }),
86253 ],
87- ),
88-);
254+ );
255+});
examples/simple-scroll.ts+204−53
@@ -1,52 +1,177 @@
11 /**
2- * Scroll test — a large list inside a scrollable VStack.
3- * Mouse wheel should scroll the list up/down.
2+ * cel-tui: Activity Feed
43 *
5- * Uses uncontrolled scroll — the framework manages scroll position
6- * internally. No scrollOffset/onScroll state needed.
4+ * A polished uncontrolled-scroll example: a live-looking feed of
5+ * deploys, alerts, and background jobs. The framework owns scroll
6+ * position; the app just renders a long list.
77 *
88 * Run: bun run examples/simple-scroll.ts
99 */
10+
1011 import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
1112 import { Divider, Spacer } from "@cel-tui/components";
1213 import { warningBox } from "./warning-box";
1314
14-const MIN_COLS = 30;
15-const MIN_ROWS = 8;
16-
17-const items = Array.from({ length: 50 }, (_, i) => `Item ${i + 1} — ${fake()}`);
18-
19-function fake(): string {
Cut short: this commit's diff is over 1000 lines.