xonecas.io
70160
Ce

cel-tui / files

cel-tui / examples / chat.ts

11.4 KB
1/**
2 * cel-tui: Agentic Chat UI
3 *
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
10 *
11 * Run: bun run examples/chat.ts
12 */
13
14import {
15  Button,
16  Divider,
17  Markdown,
18  Spacer,
19  Spinner,
20} from "@cel-tui/components";
21import {
22  cel,
23  HStack,
24  ProcessTerminal,
25  Text,
26  TextInput,
27  VStack,
28} from "@cel-tui/core";
29import { warningBox } from "./warning-box";
30
31const MIN_COLS = 56;
32const MIN_ROWS = 18;
33
34const RESPONSES = [
35  `Here’s the high-level layout model.
36
37## cel-tui in one screen
38
39- **VStack** lays children out top-to-bottom
40- **HStack** lays children out left-to-right
41- **Text** is a pure leaf node
42- **TextInput** is an editable container
43
44\`flex\`, fixed sizes, padding, and gap work together to make terminal layout feel predictable.`,
45
46  `A good focus + scroll pattern usually looks like this:
47
481. Let the framework manage focus by default
492. Only control focus when app logic genuinely needs it
503. Use \`scrollOffset: Infinity\` for sticky-bottom UIs
514. Keep state outside the framework, then call \`cel.render()\`
52
53> The framework owns rendering. Your app owns state.`,
54
55  `Markdown is a fun fit for chat UIs because it makes streamed responses feel richer.
56
57\`\`\`ts
58const history = VStack(
59  { flex: 1, overflow: "scroll", scrollbar: true },
60  messages.flatMap(renderMessage)
61);
62\`\`\`
63
64That lets you mix **lists**, *emphasis*, code fences, and quotes without building a separate renderer.`,
65
66  `If you want the app to feel polished, focus on a few small UX details:
67
68- starter actions when the screen is empty
69- clear keyboard hints
70- sticky scroll when new content arrives
71- buttons that still work well with Tab + Enter
72
73---
74
75That’s the kind of “boring but good” structure cel-tui is great at.`,
76];
77
78const STARTER_PROMPTS = [
79  {
80    label: "layout",
81    prompt: "Explain cel-tui's layout model in one screen.",
82  },
83  {
84    label: "focus + scroll",
85    prompt: "What focus and scroll patterns work well in cel-tui?",
86  },
87  {
88    label: "markdown",
89    prompt: "Why does markdown work nicely for terminal chat demos?",
90  },
91  {
92    label: "ux tips",
93    prompt: "Give me a few concrete UX tips for a cel-tui app.",
94  },
95] as const;
96
97interface Message {
98  role: "user" | "agent";
99  content: string;
100  streaming?: boolean;
101}
102
103let messages: Message[] = [];
104let input = "";
105let inputFocused = true;
106let responseIndex = 0;
107let streamTimer: ReturnType<typeof setTimeout> | null = null;
108let streamSource = "";
109let streamPos = 0;
110let scrollOffset = 0;
111let stickToBottom = true;
112
113const spinner = Spinner({ maxFps: 12.5 });
114
115function startSpinner() {
116  spinner.reset();
117  spinner.start();
118}
119
120function stopSpinner() {
121  spinner.stop();
122}
123
124function stopStreaming() {
125  if (streamTimer) {
126    clearTimeout(streamTimer);
127    streamTimer = null;
128  }
129  stopSpinner();
130}
131
132function isStreaming(): boolean {
133  return streamTimer !== null;
134}
135
136function canSend(text = input): boolean {
137  return text.trim().length > 0 && !isStreaming();
138}
139
140function streamNextChar() {
141  const agentMessage = messages[messages.length - 1];
142  if (agentMessage?.role !== "agent") {
143    stopStreaming();
144    return;
145  }
146
147  if (streamPos < streamSource.length) {
148    const chunk = streamSource.slice(streamPos, streamPos + 4);
149    streamPos += chunk.length;
150    agentMessage.content = streamSource.slice(0, streamPos);
151    cel.render();
152    streamTimer = setTimeout(streamNextChar, 14);
153    return;
154  }
155
156  agentMessage.streaming = false;
157  streamTimer = null;
158  stopSpinner();
159  cel.render();
160}
161
162function queueResponse(response: string) {
163  streamSource = response;
164  streamPos = 0;
165  messages.push({ role: "agent", content: "", streaming: true });
166  startSpinner();
167  streamTimer = setTimeout(streamNextChar, 240);
168}
169
170function handleSend(nextText = input) {
171  const text = nextText.trim();
172  if (!canSend(nextText)) return;
173
174  messages.push({ role: "user", content: text });
175  input = "";
176  stickToBottom = true;
177
178  const response = RESPONSES[responseIndex % RESPONSES.length]!;
179  responseIndex++;
180  queueResponse(response);
181  cel.render();
182}
183
184function handleChange(value: string) {
185  input = value;
186  cel.render();
187}
188
189function resetChat() {
190  stopStreaming();
191  messages = [];
192  input = "";
193  responseIndex = 0;
194  streamSource = "";
195  streamPos = 0;
196  scrollOffset = 0;
197  stickToBottom = true;
198  inputFocused = true;
199  cel.render();
200}
201
202function quit() {
203  stopStreaming();
204  spinner.dispose();
205  cel.stop();
206  process.exit(0);
207}
208
209function currentSpinner(): string {
210  return spinner.current;
211}
212
213function renderMarkdownNode(node: ReturnType<typeof Markdown>[number]) {
214  if (node.type === "text" && node.content === "") return node;
215  return HStack({}, [Text("  "), VStack({ flex: 1 }, [node])]);
216}
217
218function renderMessage(message: Message) {
219  const isUser = message.role === "user";
220  const accent = isUser ? "color04" : "color02";
221  const label = isUser ? "You" : "Demo Agent";
222  const icon = isUser ? "▶" : "✦";
223  const spinner = message.streaming ? ` ${currentSpinner()}` : "";
224
225  return VStack(
226    {
227      gap: 0,
228      padding: { x: 1 },
229      bgColor: isUser ? "color08" : undefined,
230    },
231    [
232      Text(`${icon} ${label}${spinner}`, {
233        bold: true,
234        fgColor: accent,
235      }),
236      ...(isUser
237        ? [Text(message.content, { wrap: "word" })]
238        : message.content.length > 0
239          ? Markdown(message.content).map(renderMarkdownNode)
240          : [
241              Text(`  ${currentSpinner()} thinking...`, {
242                fgColor: "color08",
243                italic: true,
244              }),
245            ]),
246    ],
247  );
248}
249
250function renderStarterPrompts() {
251  return HStack(
252    { flexWrap: "wrap", gap: 1, justifyContent: "center" },
253    STARTER_PROMPTS.map((starter) =>
254      Button(` ${starter.label} `, {
255        onClick: () => handleSend(starter.prompt),
256        fgColor: "color06",
257        bold: true,
258        focusStyle: { bgColor: "color06", fgColor: "color00" },
259      }),
260    ),
261  );
262}
263
264function emptyState(compact = false) {
265  const intro = VStack({ alignItems: "center", gap: 1, padding: { x: 2 } }, [
266    Text("Ask the demo agent about cel-tui", {
267      bold: true,
268      fgColor: "color06",
269    }),
270    Text("Starter prompts stream markdown replies.", {
271      fgColor: "color08",
272    }),
273    ...(compact
274      ? []
275      : [
276          Text("They also keep the first screen from feeling empty.", {
277            fgColor: "color08",
278          }),
279          Text("Try one of these:", { fgColor: "color08", italic: true }),
280        ]),
281    renderStarterPrompts(),
282  ]);
283
284  return compact ? [intro] : [Spacer(), intro, Spacer()];
285}
286
287cel.init(new ProcessTerminal());
288cel.viewport(() => {
289  const cols = process.stdout.columns || 80;
290  const rows = process.stdout.rows || 24;
291  const compact = cols < 70;
292  const sendLabel = isStreaming() ? " Wait " : " Send ";
293  const sendColor = canSend() ? "color06" : "color08";
294  const placeholderText = compact
295    ? "ask about layout or ux..."
296    : "ask about layout, focus, markdown, or UX...";
297
298  const composerInput = TextInput({
299    flex: 1,
300    maxHeight: 5,
301    value: input,
302    onChange: handleChange,
303    placeholder: Text(placeholderText, {
304      fgColor: "color08",
305    }),
306    onKeyPress: (key) => {
307      if (key === "enter") {
308        handleSend();
309        return false;
310      }
311    },
312    focused: inputFocused,
313    onFocus: () => {
314      inputFocused = true;
315      cel.render();
316    },
317    onBlur: () => {
318      inputFocused = false;
319      cel.render();
320    },
321  });
322
323  const clearButton = Button(" Clear ", {
324    onClick: resetChat,
325    fgColor: "color08",
326    focusStyle: { bgColor: "color08", fgColor: "color00" },
327  });
328
329  const sendButton = Button(sendLabel, {
330    onClick: () => handleSend(),
331    bgColor: sendColor,
332    fgColor: "color00",
333    bold: true,
334    focusStyle: { bgColor: "color06", fgColor: "color00" },
335  });
336
337  if (cols < MIN_COLS || rows < MIN_ROWS) {
338    return VStack(
339      {
340        height: "100%",
341        justifyContent: "center",
342        alignItems: "center",
343        onKeyPress: (key) => {
344          if (key === "ctrl+q" || key === "ctrl+c") quit();
345        },
346      },
347      [
348        ...warningBox([
349          "  Terminal too small :(",
350          "",
351          "  Please resize to at",
352          `  least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars.`,
353          "",
354          "  Ctrl+Q to quit",
355        ]),
356      ],
357    );
358  }
359
360  return VStack(
361    {
362      height: "100%",
363      onKeyPress: (key) => {
364        if (key === "ctrl+q" || key === "ctrl+c") quit();
365        if (key === "ctrl+l") resetChat();
366      },
367    },
368    [
369      HStack(
370        {
371          height: 1,
372          padding: { x: 1 },
373          bgColor: "color04",
374          fgColor: "color07",
375        },
376        [
377          Text(" Demo Agent ", { bold: true }),
378          Spacer(),
379          Text(isStreaming() ? `${currentSpinner()} streaming` : "ready"),
380          Text("  "),
381          Text(`${messages.length} msgs`, { fgColor: "color15" }),
382        ],
383      ),
384      compact
385        ? HStack({ padding: { x: 1 } }, [
386            Text("Starter prompts, markdown streaming, sticky scroll.", {
387              fgColor: "color08",
388            }),
389          ])
390        : HStack({ padding: { x: 1 }, gap: 2 }, [
391            Text("Simulated replies with markdown streaming.", {
392              fgColor: "color08",
393            }),
394            Spacer(),
395            Text("Ctrl+L clear", { fgColor: "color08" }),
396          ]),
397      Divider({ fgColor: "color08" }),
398      VStack(
399        {
400          flex: 1,
401          overflow: "scroll",
402          scrollbar: true,
403          padding: { x: 1, y: 1 },
404          gap: 1,
405          scrollOffset: stickToBottom ? Infinity : scrollOffset,
406          onScroll: (offset, maxOffset) => {
407            scrollOffset = offset;
408            stickToBottom = offset >= maxOffset;
409            cel.render();
410          },
411        },
412        messages.length > 0 ? messages.map(renderMessage) : emptyState(compact),
413      ),
414      Divider({ fgColor: "color08" }),
415      ...(compact
416        ? [
417            VStack({ padding: { x: 1 }, gap: 1 }, [
418              HStack({ gap: 1 }, [
419                Text(">", {
420                  fgColor: canSend() ? "color06" : "color08",
421                  bold: true,
422                }),
423                composerInput,
424              ]),
425              HStack({ justifyContent: "end", gap: 1 }, [
426                clearButton,
427                sendButton,
428              ]),
429            ]),
430          ]
431        : [
432            HStack({ padding: { x: 1 }, gap: 1 }, [
433              Text(">", {
434                fgColor: canSend() ? "color06" : "color08",
435                bold: true,
436              }),
437              composerInput,
438              clearButton,
439              sendButton,
440            ]),
441          ]),
442      HStack({ padding: { x: 1 }, gap: 1, flexWrap: "wrap" }, [
443        Text("Enter", { fgColor: "color08", bold: true }),
444        Text("send", { fgColor: "color08" }),
445        Text("·", { fgColor: "color08" }),
446        Text("Tab", { fgColor: "color08", bold: true }),
447        Text("move focus", { fgColor: "color08" }),
448        Text("·", { fgColor: "color08" }),
449        Text("Esc", { fgColor: "color08", bold: true }),
450        Text("blur", { fgColor: "color08" }),
451        Text("·", { fgColor: "color08" }),
452        Text("Ctrl+Q", { fgColor: "color08", bold: true }),
453        Text("quit", { fgColor: "color08" }),
454      ]),
455    ],
456  );
457});