xonecas.io
70160
Ce

cel-tui / commit 8d66159

wip(components): Markdown component with local tokenizer

Placeholder implementation — the local tokenizer (tokenize/parseInline)
duplicates yoctomarkdown's parsing logic and will be replaced by
yoctomarkdown's token API once its ANSI-free refactor lands.

- Tokenizer: line-by-line parser producing BlockToken/InlineSpan
- Theme: configurable styles per block type with defaults
- Component: Markdown(content, props?) → Node[]
- 45 tests covering tokenizer, component, streaming edge cases
- Known limitation: inline styling not rendered (stripped to plain text)

Depends on: yoctomarkdown token API refactor

xonecas2026-04-04 8d6615917b331be6e179fa517983d1f06ed05288 parent 7d5bdfa

4 files changed

TODO.md+2−0
@@ -24,6 +24,8 @@ Remaining work, known bugs, and planned improvements.
2424
2525 ## Not Yet Implemented
2626
27+- ❌ **`Markdown` component** — Depends on yoctomarkdown exposing an ANSI-free token API (`BlockToken`/`InlineSpan` types). Once available, the `Markdown(content, props?)` component in `@cel-tui/components` maps tokens to cel-tui Nodes. See `packages/components/src/markdown.ts`. Tracked upstream in yoctomarkdown.
28+
2729 - ❌ Bracketed paste mode support
2830
2931 ## Future Enhancements
packages/components/src/index.ts+9−0
@@ -26,3 +26,12 @@ export {
2626 type SelectItem,
2727 type SelectInstance,
2828 } from "./select.js";
29+export {
30+ Markdown,
31+ tokenize,
32+ parseInline,
33+ type MarkdownProps,
34+ type MarkdownTheme,
35+ type BlockToken,
36+ type InlineSpan,
37+} from "./markdown.js";
packages/components/src/markdown.test.ts+522−0
@@ -0,0 +1,522 @@
1+import { describe, test, expect } from "bun:test";
2+import type { ContainerNode, Node, TextNode } from "@cel-tui/types";
3+import {
4+ parseInline,
5+ tokenize,
6+ Markdown,
7+ type BlockToken,
8+ type InlineSpan,
9+} from "./markdown";
10+
11+// ─── Helpers ────────────────────────────────────────────────────
12+
13+/** Extract the text content of a Text node. */
14+function textContent(node: Node): string {
15+ if (node.type === "text") return node.content;
16+ throw new Error(`Expected text node, got ${node.type}`);
17+}
18+
19+/** Assert a node is a Text node and return it. */
20+function asText(node: Node): TextNode {
21+ expect(node.type).toBe("text");
22+ return node as TextNode;
23+}
24+
25+/** Assert a node is a container (vstack/hstack) and return it. */
26+function asContainer(node: Node): ContainerNode {
27+ expect(["vstack", "hstack"]).toContain(node.type);
28+ return node as ContainerNode;
29+}
30+
31+// ─── parseInline ────────────────────────────────────────────────
32+
33+describe("parseInline", () => {
34+ test("plain text", () => {
35+ expect(parseInline("hello world")).toEqual([
36+ { type: "text", content: "hello world" },
37+ ]);
38+ });
39+
40+ test("bold", () => {
41+ expect(parseInline("some **bold** text")).toEqual([
42+ { type: "text", content: "some " },
43+ { type: "bold", content: "bold" },
44+ { type: "text", content: " text" },
45+ ]);
46+ });
47+
48+ test("italic", () => {
49+ expect(parseInline("some *italic* text")).toEqual([
50+ { type: "text", content: "some " },
51+ { type: "italic", content: "italic" },
52+ { type: "text", content: " text" },
53+ ]);
54+ });
55+
56+ test("inline code", () => {
57+ expect(parseInline("use `foo()` here")).toEqual([
58+ { type: "text", content: "use " },
59+ { type: "code", content: "foo()" },
60+ { type: "text", content: " here" },
61+ ]);
62+ });
63+
64+ test("link", () => {
65+ expect(parseInline("see [docs](https://example.com) now")).toEqual([
66+ { type: "text", content: "see " },
67+ { type: "link", text: "docs", url: "https://example.com" },
68+ { type: "text", content: " now" },
69+ ]);
70+ });
71+
72+ test("mixed inline", () => {
73+ const spans = parseInline("**bold** and *italic* and `code`");
74+ expect(spans).toEqual([
75+ { type: "bold", content: "bold" },
76+ { type: "text", content: " and " },
77+ { type: "italic", content: "italic" },
78+ { type: "text", content: " and " },
79+ { type: "code", content: "code" },
80+ ]);
81+ });
82+
83+ test("unclosed bold is plain text", () => {
84+ expect(parseInline("some **unclosed")).toEqual([
85+ { type: "text", content: "some **unclosed" },
86+ ]);
87+ });
88+
89+ test("unclosed italic is plain text", () => {
90+ expect(parseInline("some *unclosed")).toEqual([
91+ { type: "text", content: "some *unclosed" },
92+ ]);
93+ });
94+
95+ test("unclosed code is plain text", () => {
96+ expect(parseInline("some `unclosed")).toEqual([
97+ { type: "text", content: "some `unclosed" },
98+ ]);
99+ });
100+
101+ test("unclosed link is plain text", () => {
102+ expect(parseInline("see [docs](no-close")).toEqual([
103+ { type: "text", content: "see [docs](no-close" },
104+ ]);
105+ });
106+
107+ test("empty string", () => {
108+ expect(parseInline("")).toEqual([]);
109+ });
110+
111+ test("code has priority over bold", () => {
112+ // The ` opens before ** can match
113+ expect(parseInline("`**not bold**`")).toEqual([
114+ { type: "code", content: "**not bold**" },
115+ ]);
116+ });
117+});
118+
119+// ─── tokenize ───────────────────────────────────────────────────
120+
121+describe("tokenize", () => {
122+ test("heading levels", () => {
123+ const tokens = tokenize("# H1\n## H2\n### H3");
124+ expect(tokens).toEqual([
125+ { type: "heading", depth: 1, spans: [{ type: "text", content: "H1" }] },
126+ { type: "heading", depth: 2, spans: [{ type: "text", content: "H2" }] },
127+ { type: "heading", depth: 3, spans: [{ type: "text", content: "H3" }] },
128+ ]);
129+ });
130+
131+ test("heading with inline formatting", () => {
132+ const tokens = tokenize("# Hello **world**");
133+ expect(tokens[0]).toEqual({
134+ type: "heading",
135+ depth: 1,
136+ spans: [
137+ { type: "text", content: "Hello " },
138+ { type: "bold", content: "world" },
139+ ],
140+ });
141+ });
142+
143+ test("paragraph", () => {
144+ const tokens = tokenize("Hello world");
145+ expect(tokens).toEqual([
146+ { type: "paragraph", spans: [{ type: "text", content: "Hello world" }] },
147+ ]);
148+ });
149+
150+ test("code block with lang", () => {
151+ const tokens = tokenize("```js\nconst x = 1;\nconst y = 2;\n```");
152+ expect(tokens).toEqual([
153+ {
154+ type: "code_block",
155+ lang: "js",
156+ content: "const x = 1;\nconst y = 2;",
157+ },
158+ ]);
159+ });
160+
161+ test("code block without lang", () => {
162+ const tokens = tokenize("```\nsome code\n```");
163+ expect(tokens).toEqual([
164+ { type: "code_block", lang: "", content: "some code" },
165+ ]);
166+ });
167+
168+ test("unclosed code block (streaming)", () => {
169+ const tokens = tokenize("```js\nconst x = 1;");
170+ expect(tokens).toEqual([
171+ { type: "code_block", lang: "js", content: "const x = 1;" },
172+ ]);
173+ });
174+
175+ test("unordered list", () => {
176+ const tokens = tokenize("- first\n- second\n* third");
177+ expect(tokens).toEqual([
178+ {
179+ type: "list_item",
180+ ordered: false,
181+ index: 0,
182+ spans: [{ type: "text", content: "first" }],
183+ },
184+ {
185+ type: "list_item",
186+ ordered: false,
187+ index: 0,
188+ spans: [{ type: "text", content: "second" }],
189+ },
190+ {
191+ type: "list_item",
192+ ordered: false,
193+ index: 0,
194+ spans: [{ type: "text", content: "third" }],
195+ },
196+ ]);
197+ });
198+
199+ test("ordered list", () => {
200+ const tokens = tokenize("1. first\n2. second");
201+ expect(tokens).toEqual([
202+ {
203+ type: "list_item",
204+ ordered: true,
205+ index: 1,
206+ spans: [{ type: "text", content: "first" }],
207+ },
208+ {
209+ type: "list_item",
210+ ordered: true,
211+ index: 2,
212+ spans: [{ type: "text", content: "second" }],
213+ },
214+ ]);
215+ });
216+
217+ test("blockquote", () => {
218+ const tokens = tokenize("> some quote");
219+ expect(tokens).toEqual([
220+ {
221+ type: "blockquote",
222+ spans: [{ type: "text", content: "some quote" }],
223+ },
224+ ]);
225+ });
226+
227+ test("blockquote with inline formatting", () => {
228+ const tokens = tokenize("> a **bold** quote");
229+ expect(tokens[0]).toEqual({
230+ type: "blockquote",
231+ spans: [
232+ { type: "text", content: "a " },
233+ { type: "bold", content: "bold" },
234+ { type: "text", content: " quote" },
235+ ],
236+ });
237+ });
238+
239+ test("horizontal rules", () => {
240+ expect(tokenize("---")).toEqual([{ type: "hr" }]);
241+ expect(tokenize("***")).toEqual([{ type: "hr" }]);
242+ expect(tokenize("___")).toEqual([{ type: "hr" }]);
243+ expect(tokenize("----")).toEqual([{ type: "hr" }]);
244+ });
245+
246+ test("blank lines", () => {
247+ const tokens = tokenize("hello\n\nworld");
248+ expect(tokens).toEqual([
249+ { type: "paragraph", spans: [{ type: "text", content: "hello" }] },
250+ { type: "blank" },
251+ { type: "paragraph", spans: [{ type: "text", content: "world" }] },
252+ ]);
253+ });
254+
255+ test("full document", () => {
256+ const md = [
257+ "# Title",
258+ "",
259+ "A paragraph with **bold**.",
260+ "",
261+ "```ts",
262+ "const x = 1;",
263+ "```",
264+ "",
265+ "- item one",
266+ "- item two",
267+ "",
268+ "> a quote",
269+ "",
270+ "---",
271+ ].join("\n");
272+
273+ const tokens = tokenize(md);
274+ const types = tokens.map((t) => t.type);
275+ expect(types).toEqual([
276+ "heading",
277+ "blank",
278+ "paragraph",
279+ "blank",
280+ "code_block",
281+ "blank",
282+ "list_item",
283+ "list_item",
284+ "blank",
285+ "blockquote",
286+ "blank",
287+ "hr",
288+ ]);
289+ });
290+
291+ test("empty content", () => {
292+ expect(tokenize("")).toEqual([{ type: "blank" }]);
293+ });
294+
295+ test("code block preserves content verbatim", () => {
296+ const tokens = tokenize("```\n indented\n**not bold**\n```");
297+ const cb = tokens[0] as { type: "code_block"; content: string };
298+ expect(cb.content).toBe(" indented\n**not bold**");
299+ });
300+
301+ test("list item with inline formatting", () => {
302+ const tokens = tokenize("- some **bold** item");
303+ expect(tokens[0]).toEqual({
304+ type: "list_item",
305+ ordered: false,
306+ index: 0,
307+ spans: [
308+ { type: "text", content: "some " },
309+ { type: "bold", content: "bold" },
310+ { type: "text", content: " item" },
311+ ],
312+ });
313+ });
314+});
315+
316+// ─── Markdown component ─────────────────────────────────────────
317+
318+describe("Markdown", () => {
319+ test("returns empty array for empty string", () => {
320+ // Empty string tokenizes to one blank → one Text("")
321+ const nodes = Markdown("");
322+ expect(nodes).toHaveLength(1);
323+ expect(textContent(nodes[0]!)).toBe("");
324+ });
325+
326+ test("heading renders as styled Text", () => {
327+ const nodes = Markdown("# Hello");
328+ expect(nodes).toHaveLength(1);
329+ const t = asText(nodes[0]!);
330+ expect(t.content).toBe("Hello");
331+ expect(t.props.bold).toBe(true);
332+ expect(t.props.fgColor).toBe("cyan");
333+ });
334+
335+ test("heading levels have different styles", () => {
336+ const nodes = Markdown("# H1\n## H2\n### H3");
337+ const h1 = asText(nodes[0]!);
338+ const h2 = asText(nodes[1]!);
339+ const h3 = asText(nodes[2]!);
340+ expect(h1.props.fgColor).toBe("cyan");
341+ expect(h2.props.fgColor).toBe("yellow");
342+ expect(h3.props.fgColor).toBe("green");
343+ });
344+
345+ test("paragraph renders as wrapping Text", () => {
346+ const nodes = Markdown("Hello **bold** world");
347+ expect(nodes).toHaveLength(1);
348+ const t = asText(nodes[0]!);
349+ // Inline markers stripped, plain text content
350+ expect(t.content).toBe("Hello bold world");
351+ expect(t.props.wrap).toBe("word");
352+ });
353+
354+ test("code block renders as VStack with Text", () => {
355+ const nodes = Markdown("```js\nconst x = 1;\n```");
356+ expect(nodes).toHaveLength(1);
357+ const container = asContainer(nodes[0]!);
358+ expect(container.type).toBe("vstack");
359+ expect(container.props.padding).toEqual({ x: 1 });
360+ expect(container.props.bgColor).toBe("brightBlack");
361+ expect(container.children).toHaveLength(1);
362+ expect(textContent(container.children[0]!)).toBe("const x = 1;");
363+ });
364+
365+ test("unordered list item renders as HStack with marker", () => {
366+ const nodes = Markdown("- hello world");
367+ expect(nodes).toHaveLength(1);
368+ const row = asContainer(nodes[0]!);
369+ expect(row.type).toBe("hstack");
370+ expect(row.children).toHaveLength(2);
371+
372+ // Marker
373+ const marker = asText(row.children[0]!);
374+ expect(marker.content).toBe("• ");
375+ expect(marker.props.fgColor).toBe("yellow");
376+
377+ // Content in flex VStack
378+ const wrapper = asContainer(row.children[1]!);
379+ expect(wrapper.type).toBe("vstack");
380+ expect(wrapper.props.flex).toBe(1);
381+ const content = asText(wrapper.children[0]!);
382+ expect(content.content).toBe("hello world");
383+ expect(content.props.wrap).toBe("word");
384+ });
385+
386+ test("ordered list item uses index as marker", () => {
387+ const nodes = Markdown("3. third item");
388+ const row = asContainer(nodes[0]!);
389+ const marker = asText(row.children[0]!);
390+ expect(marker.content).toBe("3. ");
391+ });
392+
393+ test("blockquote renders with bar and italic content", () => {
394+ const nodes = Markdown("> quoted text");
395+ expect(nodes).toHaveLength(1);
396+ const row = asContainer(nodes[0]!);
397+ expect(row.type).toBe("hstack");
398+
399+ // Bar
400+ const bar = asText(row.children[0]!);
401+ expect(bar.content).toBe("│ ");
402+ expect(bar.props.fgColor).toBe("green");
403+
404+ // Content
405+ const wrapper = asContainer(row.children[1]!);
406+ const content = asText(wrapper.children[0]!);
407+ expect(content.content).toBe("quoted text");
408+ expect(content.props.italic).toBe(true);
409+ expect(content.props.wrap).toBe("word");
410+ });
411+
412+ test("horizontal rule renders as Divider", () => {
413+ const nodes = Markdown("---");
414+ expect(nodes).toHaveLength(1);
415+ const t = asText(nodes[0]!);
416+ // Divider is a Text with repeat: "fill"
417+ expect(t.content).toBe("─");
418+ expect(t.props.repeat).toBe("fill");
419+ expect(t.props.fgColor).toBe("brightBlack");
420+ });
421+
422+ test("blank line renders as empty Text", () => {
423+ const nodes = Markdown("hello\n\nworld");
424+ expect(nodes).toHaveLength(3);
425+ expect(textContent(nodes[1]!)).toBe("");
426+ });
427+
428+ test("custom theme overrides defaults", () => {
429+ const nodes = Markdown("# Hello", {
430+ theme: { heading1: { bold: true, fgColor: "magenta" } },
431+ });
432+ const t = asText(nodes[0]!);
433+ expect(t.props.fgColor).toBe("magenta");
434+ });
435+
436+ test("custom theme partial — unset properties use defaults", () => {
437+ const nodes = Markdown("# H1\n> quote", {
438+ theme: { heading1: { fgColor: "red" } },
439+ });
440+ // Heading uses custom
441+ expect(asText(nodes[0]!).props.fgColor).toBe("red");
442+ // Blockquote bar uses default
443+ const row = asContainer(nodes[1]!);
444+ expect(asText(row.children[0]!).props.fgColor).toBe("green");
445+ });
446+
447+ test("inline formatting in headings is stripped to plain text", () => {
448+ const nodes = Markdown("# Hello **world** and `code`");
449+ const t = asText(nodes[0]!);
450+ expect(t.content).toBe("Hello world and code");
451+ });
452+
453+ test("link text is used, url is stripped", () => {
454+ const nodes = Markdown("See [the docs](https://example.com) here.");
455+ const t = asText(nodes[0]!);
456+ expect(t.content).toBe("See the docs here.");
457+ });
458+
459+ test("streaming: unclosed code block renders as code", () => {
460+ const nodes = Markdown("```js\nconst x = 1;");
461+ expect(nodes).toHaveLength(1);
462+ const container = asContainer(nodes[0]!);
463+ expect(container.props.bgColor).toBe("brightBlack");
464+ expect(textContent(container.children[0]!)).toBe("const x = 1;");
465+ });
466+
467+ test("streaming: unclosed bold appears as plain text", () => {
468+ const nodes = Markdown("hello **world");
469+ const t = asText(nodes[0]!);
470+ expect(t.content).toBe("hello **world");
471+ });
472+
473+ test("full document produces correct node sequence", () => {
474+ const md = [
475+ "# Title",
476+ "",
477+ "Some text here.",
478+ "",
479+ "```",
480+ "code",
481+ "```",
482+ "",
483+ "- item",
484+ "",
485+ "> quote",
486+ "",
487+ "---",
488+ ].join("\n");
489+
490+ const nodes = Markdown(md);
491+ const types = nodes.map((n) => {
492+ if (n.type === "text") {
493+ if (n.content === "") return "blank";
494+ if (n.props.repeat === "fill") return "hr";
495+ if (n.props.bold && n.props.fgColor) return "heading";
496+ return "paragraph";
497+ }
498+ if (n.type === "vstack") return "code_block";
499+ if (n.type === "hstack") {
500+ const first = (n as ContainerNode).children[0];
501+ if (first?.type === "text" && (first as TextNode).content === "│ ")
502+ return "blockquote";
503+ return "list_item";
504+ }
505+ return n.type;
506+ });
507+
508+ expect(types).toEqual([
509+ "heading",
510+ "blank",
511+ "paragraph",
512+ "blank",
513+ "code_block",
514+ "blank",
515+ "list_item",
516+ "blank",
517+ "blockquote",
518+ "blank",
519+ "hr",
520+ ]);
521+ });
522+});
packages/components/src/markdown.ts+442−0
@@ -0,0 +1,442 @@
1+import type { Color, Node, StyleProps } from "@cel-tui/types";
2+import { VStack, HStack, Text } from "@cel-tui/core";
3+import { Divider } from "./divider.js";
4+
5+// ─── Token Types ────────────────────────────────────────────────
6+// These mirror the token API that yoctomarkdown will expose after
7+// its ANSI-free refactor. Until then, we use a local tokenizer.
8+
9+/**
10+ * An inline span within a block of markdown text.
11+ *
12+ * Represents a segment of text with a specific formatting type.
13+ * A paragraph like `"Some **bold** and *italic* text"` is parsed
14+ * into an array of spans:
15+ * ```
16+ * [
17+ * { type: "text", content: "Some " },
18+ * { type: "bold", content: "bold" },
19+ * { type: "text", content: " and " },
20+ * { type: "italic", content: "italic" },
21+ * { type: "text", content: " text" },
22+ * ]
23+ * ```
24+ */
25+export type InlineSpan =
26+ | { type: "text"; content: string }
27+ | { type: "bold"; content: string }
28+ | { type: "italic"; content: string }
29+ | { type: "code"; content: string }
30+ | { type: "link"; text: string; url: string };
31+
32+/**
33+ * A block-level markdown token.
34+ *
35+ * Each token represents one logical block in the document:
36+ * a heading, paragraph, code block, list item, blockquote,
37+ * horizontal rule, or blank line.
38+ */
39+export type BlockToken =
40+ | { type: "heading"; depth: 1 | 2 | 3; spans: InlineSpan[] }
41+ | { type: "paragraph"; spans: InlineSpan[] }
42+ | { type: "code_block"; lang: string; content: string }
43+ | {
44+ type: "list_item";
45+ ordered: boolean;
46+ index: number;
47+ spans: InlineSpan[];
48+ }
49+ | { type: "blockquote"; spans: InlineSpan[] }
50+ | { type: "hr" }
51+ | { type: "blank" };
52+
53+// ─── Tokenizer ──────────────────────────────────────────────────
54+// Line-by-line parser matching yoctomarkdown's supported subset.
55+// Will be replaced by yoctomarkdown's token API once available.
56+
57+/**
58+ * Parse inline formatting within a line of text.
59+ *
60+ * Recognizes: `` `code` ``, `**bold**`, `*italic*`, `[text](url)`.
61+ * Unclosed constructs are emitted as plain text (safe for streaming).
62+ *
63+ * @param text - A single line of text (no newlines).
64+ * @returns Array of inline spans.
65+ */
66+export function parseInline(text: string): InlineSpan[] {
67+ const spans: InlineSpan[] = [];
68+ let i = 0;
69+ let current = "";
70+
71+ function flush(): void {
72+ if (current.length > 0) {
73+ spans.push({ type: "text", content: current });
74+ current = "";
75+ }
76+ }
77+
78+ while (i < text.length) {
79+ // Inline code: `code`
80+ if (text[i] === "`" && text[i + 1] !== "`") {
81+ const end = text.indexOf("`", i + 1);
82+ if (end !== -1) {
83+ flush();
84+ spans.push({ type: "code", content: text.slice(i + 1, end) });
85+ i = end + 1;
86+ continue;
87+ }
88+ }
89+
90+ // Bold: **text**
91+ if (text[i] === "*" && text[i + 1] === "*") {
92+ const end = text.indexOf("**", i + 2);
93+ if (end !== -1) {
94+ flush();
95+ spans.push({ type: "bold", content: text.slice(i + 2, end) });
96+ i = end + 2;
97+ continue;
98+ }
99+ }
100+
101+ // Italic: *text* (not **)
102+ if (text[i] === "*" && text[i + 1] !== "*") {
103+ const end = text.indexOf("*", i + 1);
104+ if (end !== -1 && text[end + 1] !== "*") {
105+ flush();
106+ spans.push({ type: "italic", content: text.slice(i + 1, end) });
107+ i = end + 1;
108+ continue;
109+ }
110+ }
111+
112+ // Link: [text](url)
113+ if (text[i] === "[") {
114+ const bracketEnd = text.indexOf("]", i + 1);
115+ if (bracketEnd !== -1 && text[bracketEnd + 1] === "(") {
116+ const parenEnd = text.indexOf(")", bracketEnd + 2);
117+ if (parenEnd !== -1) {
118+ flush();
119+ spans.push({
120+ type: "link",
121+ text: text.slice(i + 1, bracketEnd),
122+ url: text.slice(bracketEnd + 2, parenEnd),
123+ });
124+ i = parenEnd + 1;
125+ continue;
126+ }
127+ }
128+ }
129+
130+ current += text[i];
131+ i++;
132+ }
133+
134+ flush();
135+ return spans;
136+}
137+
138+/**
139+ * Tokenize a markdown string into block-level tokens.
140+ *
141+ * Parses line-by-line, recognizing headings, code blocks, lists,
142+ * blockquotes, horizontal rules, and paragraphs. Inline formatting
143+ * within text blocks is parsed into {@link InlineSpan} arrays.
144+ *
145+ * Handles streaming gracefully: unclosed code blocks are emitted
146+ * as `code_block` tokens, and unclosed inline formatting appears
147+ * as plain text.
148+ *
149+ * @param content - Markdown string (may be partial during streaming).
150+ * @returns Array of block tokens.
151+ */
152+export function tokenize(content: string): BlockToken[] {
153+ const tokens: BlockToken[] = [];
154+ const lines = content.split("\n");
155+ let inCodeBlock = false;
156+ let codeBlockLang = "";
157+ let codeBlockLines: string[] = [];
158+
159+ for (const line of lines) {
160+ if (inCodeBlock) {
161+ if (line.trim().startsWith("```")) {
162+ tokens.push({
163+ type: "code_block",
164+ lang: codeBlockLang,
165+ content: codeBlockLines.join("\n"),
166+ });
167+ inCodeBlock = false;
168+ codeBlockLang = "";
169+ codeBlockLines = [];
170+ continue;
171+ }
172+ codeBlockLines.push(line);
173+ continue;
174+ }
175+
176+ const trimmed = line.trim();
177+
178+ // Code block opening
179+ if (trimmed.startsWith("```")) {
180+ inCodeBlock = true;
181+ codeBlockLang = trimmed.slice(3).trim();
182+ continue;
183+ }
184+
185+ // Horizontal rule
186+ if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) {
187+ tokens.push({ type: "hr" });
188+ continue;
189+ }
190+
191+ // Heading
192+ const headingMatch = line.match(/^(#{1,3})\s+(.*)$/);
193+ if (headingMatch) {
194+ const depth = headingMatch[1]!.length as 1 | 2 | 3;
195+ tokens.push({
196+ type: "heading",
197+ depth,
198+ spans: parseInline(headingMatch[2]!),
199+ });
200+ continue;
201+ }
202+
203+ // Blockquote
204+ const bqMatch = line.match(/^>\s?(.*)$/);
205+ if (bqMatch) {
206+ tokens.push({ type: "blockquote", spans: parseInline(bqMatch[1]!) });
207+ continue;
208+ }
209+
210+ // Unordered list
211+ const ulMatch = line.match(/^[-*]\s+(.*)$/);
212+ if (ulMatch) {
213+ tokens.push({
214+ type: "list_item",
215+ ordered: false,
216+ index: 0,
217+ spans: parseInline(ulMatch[1]!),
218+ });
219+ continue;
220+ }
221+
222+ // Ordered list
223+ const olMatch = line.match(/^(\d+)\.\s+(.*)$/);
224+ if (olMatch) {
225+ tokens.push({
226+ type: "list_item",
227+ ordered: true,
228+ index: parseInt(olMatch[1]!, 10),
229+ spans: parseInline(olMatch[2]!),
230+ });
231+ continue;
232+ }
233+
234+ // Blank line
235+ if (trimmed === "") {
236+ tokens.push({ type: "blank" });
237+ continue;
238+ }
239+
240+ // Plain paragraph
241+ tokens.push({ type: "paragraph", spans: parseInline(line) });
242+ }
243+
244+ // Unclosed code block — emit what we have (streaming case)
245+ if (inCodeBlock) {
246+ tokens.push({
247+ type: "code_block",
248+ lang: codeBlockLang,
249+ content: codeBlockLines.join("\n"),
250+ });
251+ }
252+
253+ return tokens;
254+}
255+
256+// ─── Theme ──────────────────────────────────────────────────────
257+
258+/**
259+ * Style configuration for the {@link Markdown} component.
260+ *
261+ * Each property controls the styling of a specific markdown element.
262+ * All properties are optional — unset values fall back to the
263+ * built-in default theme.
264+ */
265+export interface MarkdownTheme {
266+ /** Style for `# heading` (level 1). */
267+ heading1?: StyleProps;
268+ /** Style for `## heading` (level 2). */
269+ heading2?: StyleProps;
270+ /** Style for `### heading` (level 3). */
271+ heading3?: StyleProps;
272+ /** Container style for fenced code blocks (applied to the wrapping VStack). */
273+ codeBlock?: StyleProps;
274+ /** Text style inside fenced code blocks. */
275+ codeContent?: StyleProps;
276+ /** Style for list markers (`•`, `1.`). */
277+ listMarker?: StyleProps;
278+ /** Style for the blockquote bar character (`│`). */
279+ blockquoteBar?: StyleProps;
280+ /** Text style for blockquote content. */
281+ blockquoteText?: StyleProps;
282+ /** Divider color and character for horizontal rules. */
283+ hr?: { fgColor?: Color; char?: string };
284+}
285+
286+const defaults: Required<MarkdownTheme> = {
287+ heading1: { bold: true, fgColor: "cyan" },
288+ heading2: { bold: true, fgColor: "yellow" },
289+ heading3: { bold: true, fgColor: "green" },
290+ codeBlock: { bgColor: "brightBlack" },
291+ codeContent: {},
292+ listMarker: { fgColor: "yellow", bold: true },
293+ blockquoteBar: { fgColor: "green" },
294+ blockquoteText: { italic: true },
295+ hr: { fgColor: "brightBlack", char: "─" },
296+};
297+
298+function resolveTheme(theme?: MarkdownTheme): Required<MarkdownTheme> {
299+ if (!theme) return defaults;
300+ return {
301+ heading1: theme.heading1 ?? defaults.heading1,
302+ heading2: theme.heading2 ?? defaults.heading2,
303+ heading3: theme.heading3 ?? defaults.heading3,
304+ codeBlock: theme.codeBlock ?? defaults.codeBlock,
305+ codeContent: theme.codeContent ?? defaults.codeContent,
306+ listMarker: theme.listMarker ?? defaults.listMarker,
307+ blockquoteBar: theme.blockquoteBar ?? defaults.blockquoteBar,
308+ blockquoteText: theme.blockquoteText ?? defaults.blockquoteText,
309+ hr: theme.hr ?? defaults.hr,
310+ };
311+}
312+
313+// ─── Helpers ────────────────────────────────────────────────────
314+
315+/** Concatenate inline spans into plain text (markdown markers stripped). */
316+function spansToText(spans: InlineSpan[]): string {
317+ return spans.map((s) => (s.type === "link" ? s.text : s.content)).join("");
318+}
319+
320+// ─── Component ──────────────────────────────────────────────────
321+
322+/** Props for the {@link Markdown} component. */
323+export interface MarkdownProps {
324+ /**
325+ * Theme overrides. Unset properties fall back to the built-in
326+ * default theme (cyan headings, yellow code blocks, etc.).
327+ */
328+ theme?: MarkdownTheme;
329+}
330+
331+/**
332+ * Render a markdown string as an array of cel-tui nodes.
333+ *
334+ * Parses the content into block-level tokens and maps each to
335+ * styled primitives. The returned array is meant to be used as
336+ * children of a container (typically a scrollable VStack).
337+ *
338+ * **Block-level styling** is fully supported: headings, code blocks,
339+ * lists, blockquotes, and horizontal rules are rendered with distinct
340+ * styles. **Inline styling** (bold, italic, code, links within
341+ * paragraphs) is not yet rendered — inline-formatted text appears
342+ * as clean plain text with markdown markers stripped.
343+ *
344+ * **Streaming** works naturally: append chunks to the content string
345+ * and call `cel.render()`. The component re-tokenizes the full string
346+ * each render. Unclosed code blocks and inline formatting are handled
347+ * gracefully.
348+ *
349+ * @param content - Markdown string (may be partial during streaming).
350+ * @param props - Optional theme overrides.
351+ * @returns Array of nodes to spread into a container's children.
352+ *
353+ * @example
354+ * // Static content
355+ * VStack({ flex: 1, overflow: "scroll", padding: { x: 1 } },
356+ * Markdown("# Hello\n\nSome **bold** text.\n\n```js\nconst x = 1;\n```")
357+ * )
358+ *
359+ * @example
360+ * // Streaming from an LLM
361+ * let content = "";
362+ * onChunk((chunk) => { content += chunk; cel.render(); });
363+ *
364+ * VStack({ flex: 1, overflow: "scroll" },
365+ * Markdown(content)
366+ * )
367+ *
368+ * @example
369+ * // Custom theme
370+ * Markdown(content, {
371+ * theme: { heading1: { bold: true, fgColor: "magenta" } }
372+ * })
373+ */
374+export function Markdown(content: string, props?: MarkdownProps): Node[] {
375+ const theme = resolveTheme(props?.theme);
376+ const tokens = tokenize(content);
377+ const nodes: Node[] = [];
378+
379+ for (const token of tokens) {
380+ switch (token.type) {
381+ case "heading": {
382+ const style =
383+ token.depth === 1
384+ ? theme.heading1
385+ : token.depth === 2
386+ ? theme.heading2
387+ : theme.heading3;
388+ nodes.push(Text(spansToText(token.spans), style));
389+ break;
390+ }
391+
392+ case "paragraph":
393+ nodes.push(Text(spansToText(token.spans), { wrap: "word" }));
394+ break;
395+
396+ case "code_block":
397+ nodes.push(
398+ VStack({ padding: { x: 1 }, ...theme.codeBlock }, [
399+ Text(token.content, theme.codeContent),
400+ ]),
401+ );
402+ break;
403+
404+ case "list_item": {
405+ const marker = token.ordered ? `${token.index}.` : "•";
406+ nodes.push(
407+ HStack({}, [
408+ Text(`${marker} `, theme.listMarker),
409+ VStack({ flex: 1 }, [
410+ Text(spansToText(token.spans), { wrap: "word" }),
411+ ]),
412+ ]),
413+ );
414+ break;
415+ }
416+
417+ case "blockquote":
418+ nodes.push(
419+ HStack({}, [
420+ Text("│ ", theme.blockquoteBar),
421+ VStack({ flex: 1 }, [
422+ Text(spansToText(token.spans), {
423+ wrap: "word",
424+ ...theme.blockquoteText,
425+ }),
426+ ]),
427+ ]),
428+ );
429+ break;
430+
431+ case "hr":
432+ nodes.push(Divider({ fgColor: theme.hr.fgColor, char: theme.hr.char }));
433+ break;
434+
435+ case "blank":
436+ nodes.push(Text(""));
437+ break;
438+ }
439+ }
440+
441+ return nodes;
442+}