xonecas.io
70160
Ce

cel-tui / commit c7eeb07

feat(core): expose maxOffset in onScroll, clamp scrollOffset in paint

onScroll callback now receives (offset, maxOffset) — apps can
implement complex scroll behaviors like sticky-bottom without
hacks. scrollOffset values exceeding the max are clamped during
rendering, so passing Infinity means 'scroll to end'.

- types: update onScroll signature to (offset, maxOffset)
- cel.ts: pass maxOffset to onScroll callback
- paint.ts: add computeMaxScrollOffset, clamp scrollOffset before use
- paint.test.ts: update/add scroll clamping tests
- cel.test.ts: add test for maxOffset in onScroll
- spec.md: document maxOffset parameter and sticky-bottom pattern
- examples/chat.ts: agentic chat UI using Markdown component,
  streamed responses, sticky-bottom scroll, TextInput, Button

xonecas2026-04-04 c7eeb07401e20b8df07922e6a9fd212be5c85d45 parent 037080c

7 files changed

examples/chat.ts+300−0
@@ -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+);
packages/core/src/cel.test.ts+29−0
@@ -277,6 +277,35 @@ describe("cel end-to-end", () => {
277277 expect(scrollOffset).toBe(3);
278278 });
279279
280+ test("onScroll receives maxOffset", async () => {
281+ const term = setup(20, 5);
282+ let scrollOffset = 0;
283+ let receivedMax = -1;
284+ cel.viewport(() =>
285+ VStack(
286+ {
287+ width: 20,
288+ height: 5,
289+ overflow: "scroll",
290+ scrollOffset: scrollOffset,
291+ onScroll: (offset, maxOffset) => {
292+ scrollOffset = offset;
293+ receivedMax = maxOffset;
294+ },
295+ },
296+ // 8 items in 5-row viewport → max offset = 3
297+ Array.from({ length: 8 }, (_, i) => Text(`item ${i + 1}`)),
298+ ),
299+ );
300+ await waitForRender();
301+
302+ term.sendInput("\x1b[<65;4;3M");
303+ await waitForRender();
304+
305+ expect(scrollOffset).toBe(1);
306+ expect(receivedMax).toBe(3);
307+ });
308+
280309 test("uncontrolled scroll works without onScroll", async () => {
281310 const term = setup(20, 5);
282311 cel.viewport(() =>
packages/core/src/cel.ts+1−1
@@ -500,7 +500,7 @@ function handleMouseEvent(event: MouseEvent): void {
500500 Math.min(maxOffset, baseOffset + delta),
501501 );
502502 batchScrollOffsets?.set(props, newOffset);
503- props.onScroll(newOffset);
503+ props.onScroll(newOffset, maxOffset);
504504 } else {
505505 // Uncontrolled scroll: framework manages state via path key
506506 const pathKey = getScrollPathKey(target);
packages/core/src/paint.test.ts+21−6
@@ -370,18 +370,33 @@ describe("paint", () => {
370370 expect(lastCol.some((c) => c !== " ")).toBe(true);
371371 });
372372
373- test("scroll clamps content — no painting above container", () => {
373+ test("scroll clamps to max offset", () => {
374374 const node = VStack(
375- { width: 10, height: 3, overflow: "scroll", scrollOffset: 2 },
375+ { width: 10, height: 3, overflow: "scroll", scrollOffset: 99 },
376376 [Text("line0"), Text("line1"), Text("line2"), Text("line3")],
377377 );
378378 const ln = layout(node, 10, 5);
379379 const buf = new CellBuffer(10, 5);
380380 paint(ln, buf);
381- // With scrollOffset=2, line2 and line3 visible
382- expect(readRow(buf, 0)).toBe("line2");
383- expect(readRow(buf, 1)).toBe("line3");
384- expect(readRow(buf, 2)).toBe("");
381+ // 4 items in 3-row viewport → max offset = 1
382+ // scrollOffset=99 is clamped to 1, so line1–line3 visible
383+ expect(readRow(buf, 0)).toBe("line1");
384+ expect(readRow(buf, 1)).toBe("line2");
385+ expect(readRow(buf, 2)).toBe("line3");
386+ });
387+
388+ test("scroll clamps to 0 when content fits", () => {
389+ const node = VStack(
390+ { width: 10, height: 5, overflow: "scroll", scrollOffset: 10 },
391+ [Text("line0"), Text("line1")],
392+ );
393+ const ln = layout(node, 10, 5);
394+ const buf = new CellBuffer(10, 5);
395+ paint(ln, buf);
396+ // 2 items in 5-row viewport → max offset = 0
397+ // scrollOffset=10 clamped to 0
398+ expect(readRow(buf, 0)).toBe("line0");
399+ expect(readRow(buf, 1)).toBe("line1");
385400 });
386401 });
387402
packages/core/src/paint.ts+34−3
@@ -104,6 +104,32 @@ function fillBackground(
104104 }
105105 }
106106
107+/**
108+ * Compute the maximum scroll offset for a scrollable container.
109+ * This is the content size minus the viewport size along the main axis.
110+ */
111+function computeMaxScrollOffset(ln: LayoutNode, isVertical: boolean): number {
112+ const { rect, children } = ln;
113+ const props = ln.node.type !== "text" ? ln.node.props : null;
114+ const padX = (props as any)?.padding?.x ?? 0;
115+ const padY = (props as any)?.padding?.y ?? 0;
116+
117+ if (isVertical) {
118+ let contentHeight = 0;
119+ for (const child of children) {
120+ const childBottom = child.rect.y + child.rect.height - rect.y;
121+ if (childBottom > contentHeight) contentHeight = childBottom;
122+ }
123+ return Math.max(0, contentHeight + padY - rect.height);
124+ }
125+ let contentWidth = 0;
126+ for (const child of children) {
127+ const childRight = child.rect.x + child.rect.width - rect.x;
128+ if (childRight > contentWidth) contentWidth = childRight;
129+ }
130+ return Math.max(0, contentWidth + padX - rect.width);
131+}
132+
107133 function paintLayoutNode(
108134 ln: LayoutNode,
109135 buf: CellBuffer,
@@ -172,10 +198,15 @@ function paintLayoutNode(
172198 const isContainer = node.type === "vstack" || node.type === "hstack";
173199 const containerProps = isContainer ? node.props : null;
174200 const isScrollable = containerProps?.overflow === "scroll";
175- const scrollOffset = isScrollable
176- ? (containerProps.scrollOffset ?? getContainerScroll(containerProps))
177- : 0;
178201 const isVertical = node.type === "vstack";
202+ let scrollOffset = 0;
203+ if (isScrollable) {
204+ const raw =
205+ containerProps.scrollOffset ?? getContainerScroll(containerProps);
206+ // Clamp to valid range so apps can pass large values to mean "scroll to end"
207+ const maxOffset = computeMaxScrollOffset(ln, isVertical);
208+ scrollOffset = Math.max(0, Math.min(raw, maxOffset));
209+ }
179210
180211 // Recurse into children, using this node's clipped rect as the clip for children
181212 for (const child of ln.children) {
packages/types/src/index.ts+2−1
@@ -140,8 +140,9 @@ export interface ContainerProps extends StyleProps {
140140 * to move the scroll position.
141141 *
142142 * @param offset - The new scroll offset in cells.
143+ * @param maxOffset - The maximum scroll offset (content size minus viewport size).
143144 */
144- onScroll?: (offset: number) => void;
145+ onScroll?: (offset: number, maxOffset: number) => void;
145146
146147 /**
147148 * Called on mouse click or Enter key when this container is focused.
spec.md+44−26
@@ -65,30 +65,30 @@ HStack(props, children);
6565
6666 Shared by both VStack and HStack. Containers also accept styling props (see [Styling](#styling)).
6767
68-| Prop | Type | Description |
69-| ---------------- | ---------------------------------- | --------------------------------------------------- |
70-| `width` | `number \| string` | Fixed cells or percentage (`"50%"`) |
71-| `height` | `number \| string` | Fixed cells or percentage (`"100%"`) |
72-| `flex` | `number` | Flex grow factor, proportional to siblings |
73-| `minWidth` | `number` | Minimum width constraint |
74-| `maxWidth` | `number` | Maximum width constraint |
75-| `minHeight` | `number` | Minimum height constraint |
76-| `maxHeight` | `number` | Maximum height constraint |
77-| `padding` | `{ x?: number, y?: number }` | Internal padding (cells) |
78-| `gap` | `number` | Spacing between children (cells) |
79-| `justifyContent` | `string` | Distribute children along the main axis |
80-| `alignItems` | `string` | Align children along the cross axis |
81-| `overflow` | `"hidden" \| "scroll"` | Content overflow behavior (default: `"hidden"`) |
82-| `scrollbar` | `boolean` | Show scrollbar indicator |
83-| `scrollOffset` | `number` | Scroll position in cells (controlled) |
84-| `onScroll` | `(offset: number) => void` | Called on scroll input |
85-| `onClick` | `() => void` | Called on mouse click or Enter when focused |
86-| `focusable` | `boolean` | Opt out of focus (default: `true` if `onClick`) |
87-| `focused` | `boolean` | Whether this element is focused (controlled) |
88-| `onFocus` | `() => void` | Called when element receives focus |
89-| `onBlur` | `() => void` | Called when element loses focus |
90-| `focusStyle` | `StyleProps` | Style overrides applied when focused |
91-| `onKeyPress` | `(key: string) => boolean \| void` | Key event handler. Return `false` to keep bubbling. |
68+| Prop | Type | Description |
69+| ---------------- | --------------------------------------------- | --------------------------------------------------- |
70+| `width` | `number \| string` | Fixed cells or percentage (`"50%"`) |
71+| `height` | `number \| string` | Fixed cells or percentage (`"100%"`) |
72+| `flex` | `number` | Flex grow factor, proportional to siblings |
73+| `minWidth` | `number` | Minimum width constraint |
74+| `maxWidth` | `number` | Maximum width constraint |
75+| `minHeight` | `number` | Minimum height constraint |
76+| `maxHeight` | `number` | Maximum height constraint |
77+| `padding` | `{ x?: number, y?: number }` | Internal padding (cells) |
78+| `gap` | `number` | Spacing between children (cells) |
79+| `justifyContent` | `string` | Distribute children along the main axis |
80+| `alignItems` | `string` | Align children along the cross axis |
81+| `overflow` | `"hidden" \| "scroll"` | Content overflow behavior (default: `"hidden"`) |
82+| `scrollbar` | `boolean` | Show scrollbar indicator |
83+| `scrollOffset` | `number` | Scroll position in cells (controlled) |
84+| `onScroll` | `(offset: number, maxOffset: number) => void` | Called on scroll input |
85+| `onClick` | `() => void` | Called on mouse click or Enter when focused |
86+| `focusable` | `boolean` | Opt out of focus (default: `true` if `onClick`) |
87+| `focused` | `boolean` | Whether this element is focused (controlled) |
88+| `onFocus` | `() => void` | Called when element receives focus |
89+| `onBlur` | `() => void` | Called when element loses focus |
90+| `focusStyle` | `StyleProps` | Style overrides applied when focused |
91+| `onKeyPress` | `(key: string) => boolean \| void` | Key event handler. Return `false` to keep bubbling. |
9292
9393 ### Sizing
9494
@@ -183,13 +183,31 @@ VStack({ overflow: "scroll" }, [...])
183183 VStack({
184184 overflow: "scroll",
185185 scrollOffset: offset,
186- onScroll: (newOffset) => {
186+ onScroll: (newOffset, maxOffset) => {
187187 offset = newOffset;
188188 },
189189 }, [...])
190190 ```
191191
192-In controlled mode, mouse wheel events fire `onScroll` with the new offset; the UI only moves when the app passes the updated `scrollOffset` back.
192+In controlled mode, mouse wheel events fire `onScroll` with the new offset and maximum offset (total content size minus viewport size); the UI only moves when the app passes the updated `scrollOffset` back.
193+
194+Values exceeding the maximum scroll offset are clamped during rendering — passing `Infinity` means "scroll to the end". This enables patterns like sticky-bottom scroll:
195+
196+```ts
197+let offset = 0;
198+let stickToBottom = true;
199+
200+VStack({
201+ overflow: "scroll",
202+ scrollOffset: stickToBottom ? Infinity : offset,
203+ onScroll: (newOffset, maxOffset) => {
204+ offset = newOffset;
205+ stickToBottom = newOffset >= maxOffset;
206+ },
207+}, [...])
208+```
209+
210+While `stickToBottom` is true, `Infinity` is clamped to the current maximum on each render — new content automatically scrolls into view. When the user scrolls up, `stickToBottom` becomes false and the explicit offset takes over. Scrolling back to the bottom re-enables sticky mode.
193211
194212 ---