@@ -0,0 +1,300 @@
1+/**
2+ * cel-tui: Agentic Chat UI
3+ *
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.
15+ *
16+ * Run: bun run examples/chat.ts
17+ */
18+
19+import {
20+ cel,
21+ VStack,
22+ HStack,
23+ Text,
24+ TextInput,
25+ ProcessTerminal,
26+} from "@cel-tui/core";
27+import { Button, Divider, Markdown, Spacer } from "@cel-tui/components";
28+
29+// ─── Simulated Agent Responses ──────────────────────────────────
30+
31+const RESPONSES = [
32+ `I'll check that for you.
33+
34+\`\`\`
35+$ ls -la
36+file1.ts
37+file2.ts
38+README.md
39+\`\`\`
40+
41+Found **3 files** in the current directory.`,
42+
43+ `Here's a quick overview:
44+
45+## Project Structure
46+
47+- **file1.ts** — Main entry point
48+- **file2.ts** — Utility functions
49+- **README.md** — Project documentation
50+
51+> All files were last modified today.`,
52+
53+ `Sure, I can help with that. Here's a code snippet:
54+
55+\`\`\`ts
56+function greet(name: string): string {
57+ return \`Hello, \${name}!\`;
58+}
59+
60+console.log(greet("world"));
61+\`\`\`
62+
63+This defines a simple \`greet\` function that returns a formatted string.
64+
65+---
66+
67+Let me know if you need anything else!`,
68+
69+ `Here's what I found:
70+
71+### Summary
72+
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.
78+
79+Everything looks good!`,
80+];
81+
82+// ─── State ──────────────────────────────────────────────────────
83+
84+interface Message {
85+ role: "user" | "agent";
86+ content: string;
87+ streaming?: boolean;
88+}
89+
90+let messages: Message[] = [];
91+let input = "";
92+let inputFocused = true;
93+let responseIndex = 0;
94+let streamTimer: ReturnType<typeof setTimeout> | null = null;
95+let streamSource = "";
96+let streamPos = 0;
97+let scrollOffset = 0;
98+let stickToBottom = true;
99+
100+// ─── Helpers ────────────────────────────────────────────────────
101+
102+const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
103+let spinnerTick = 0;
104+let spinnerTimer: ReturnType<typeof setInterval> | null = null;
105+
106+function startSpinner() {
107+ stopSpinner();
108+ spinnerTimer = setInterval(() => {
109+ spinnerTick++;
110+ cel.render();
111+ }, 80);
112+}
113+
114+function stopSpinner() {
115+ if (spinnerTimer) {
116+ clearInterval(spinnerTimer);
117+ spinnerTimer = null;
118+ }
119+}
120+
121+function isStreaming(): boolean {
122+ return streamTimer !== null;
123+}
124+
125+function streamNextChar() {
126+ const agentMsg = messages[messages.length - 1];
127+ if (!agentMsg || agentMsg.role !== "agent") return;
128+
129+ if (streamPos < streamSource.length) {
130+ // Stream a few characters at a time for speed
131+ const chunk = streamSource.slice(streamPos, streamPos + 3);
132+ 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();
141+ cel.render();
142+ }
143+}
144+
145+function handleSend() {
146+ const text = input.trim();
147+ if (text.length === 0 || isStreaming()) return;
148+
149+ // Add user message
150+ messages.push({ role: "user", content: text });
151+ input = "";
152+ stickToBottom = true;
153+
154+ // Pick a response and start streaming
155+ streamSource = RESPONSES[responseIndex % RESPONSES.length]!;
156+ responseIndex++;
157+ streamPos = 0;
158+ messages.push({ role: "agent", content: "", streaming: true });
159+
160+ startSpinner();
161+ streamTimer = setTimeout(streamNextChar, 300);
162+ cel.render();
163+}
164+
165+function handleChange(value: string) {
166+ input = value;
167+ cel.render();
168+}
169+
170+function quit() {
171+ stopSpinner();
172+ if (streamTimer) clearTimeout(streamTimer);
173+ cel.stop();
174+ process.exit(0);
175+}
176+
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 ? "blue" : "green";
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: "brightBlack", italic: true },
209+ ),
210+ ]),
211+ ]);
212+}
213+
214+// ─── UI ─────────────────────────────────────────────────────────
215+
216+cel.init(new ProcessTerminal());
217+
218+cel.viewport(() =>
219+ VStack(
220+ {
221+ height: "100%",
222+ fgColor: "white",
223+ onKeyPress: (key) => {
224+ if (key === "ctrl+q" || key === "ctrl+c") quit();
225+ },
226+ },
227+ [
228+ // ── Header ──
229+ HStack({ height: 1, padding: { x: 1 }, bgColor: "blue" }, [
230+ Text(" Agent ", { bold: true, fgColor: "white", bgColor: "blue" }),
231+ Spacer(),
232+ Text("model: gpt-4", { fgColor: "brightBlack" }),
233+ ]),
234+ Divider({ fgColor: "brightBlack" }),
235+
236+ // ── Message History ──
237+ VStack(
238+ {
239+ flex: 1,
240+ overflow: "scroll",
241+ scrollbar: true,
242+ padding: { x: 1 },
243+ scrollOffset: stickToBottom ? Infinity : scrollOffset,
244+ onScroll: (offset, maxOffset) => {
245+ scrollOffset = offset;
246+ stickToBottom = offset >= maxOffset;
247+ cel.render();
248+ },
249+ },
250+ messages.length > 0
251+ ? messages.flatMap((msg, i) => [
252+ ...(i > 0 ? [Text("")] : []),
253+ renderMessage(msg, i),
254+ ])
255+ : [
256+ Spacer(),
257+ VStack({ alignItems: "center" }, [
258+ Text("No messages yet.", {
259+ fgColor: "brightBlack",
260+ italic: true,
261+ }),
262+ Text("Type a message below to start.", {
263+ fgColor: "brightBlack",
264+ }),
265+ ]),
266+ Spacer(),
267+ ],
268+ ),
269+
270+ // ── Input Area ──
271+ Divider({ fgColor: "brightBlack" }),
272+ HStack({ padding: { x: 1 }, gap: 1 }, [
273+ Text(">", { fgColor: "cyan", bold: true }),
274+ TextInput({
275+ flex: 1,
276+ maxHeight: 5,
277+ value: input,
278+ onChange: handleChange,
279+ placeholder: Text("type a message...", { fgColor: "brightBlack" }),
280+ onSubmit: handleSend,
281+ focused: inputFocused,
282+ onFocus: () => {
283+ inputFocused = true;
284+ cel.render();
285+ },
286+ onBlur: () => {
287+ inputFocused = false;
288+ cel.render();
289+ },
290+ }),
291+ Button(" Send ", {
292+ onClick: handleSend,
293+ bgColor: "brightBlack",
294+ bold: true,
295+ focusStyle: { bgColor: "cyan", fgColor: "black" },
296+ }),
297+ ]),
298+ ],
299+ ),
300+);