@@ -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+});