xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / components / src / markdown.ts

9.5 KB
1import { HStack, Text, VStack } from "@cel-tui/core";
2import type { Color, Node, StyleProps } from "@cel-tui/types";
3import { type InlineSpan, tokenize } from "yoctomarkdown";
4import { Divider } from "./divider.js";
5
6// Re-export token types so consumers don't need a direct yoctomarkdown dep
7export type { BlockToken, InlineSpan } from "yoctomarkdown";
8export { tokenize } from "yoctomarkdown";
9
10// ─── Theme ──────────────────────────────────────────────────────
11
12/**
13 * Style configuration for the {@link Markdown} component.
14 *
15 * Each property controls the styling of a specific markdown element.
16 * All properties are optional — unset values fall back to the
17 * built-in default theme.
18 */
19export interface MarkdownTheme {
20  /** Style for `# heading` (level 1). */
21  heading1?: StyleProps;
22  /** Style for `## heading` (level 2). */
23  heading2?: StyleProps;
24  /** Style for `### heading` (level 3). */
25  heading3?: StyleProps;
26  /** Container style for fenced code blocks (applied to the wrapping VStack). */
27  codeBlock?: StyleProps;
28  /** Text style inside fenced code blocks. */
29  codeContent?: StyleProps;
30  /** Style for list markers (`•`, `1.`). */
31  listMarker?: StyleProps;
32  /** Style for the blockquote bar character (`│`). */
33  blockquoteBar?: StyleProps;
34  /** Text style for blockquote content. */
35  blockquoteText?: StyleProps;
36  /** Divider color and character for horizontal rules. */
37  hr?: { fgColor?: Color; char?: string };
38  /** Style for **bold** inline text. */
39  bold?: StyleProps;
40  /** Style for *italic* inline text. */
41  italic?: StyleProps;
42  /** Style for `inline code` text. */
43  inlineCode?: StyleProps;
44  /** Style for `[link](url)` inline text. */
45  link?: StyleProps;
46}
47
48const defaults: Required<MarkdownTheme> = {
49  heading1: { bold: true, fgColor: "color06" },
50  heading2: { bold: true, fgColor: "color03" },
51  heading3: { bold: true, fgColor: "color02" },
52  codeBlock: { bgColor: "color08" },
53  codeContent: {},
54  listMarker: { fgColor: "color03", bold: true },
55  blockquoteBar: { fgColor: "color02" },
56  blockquoteText: { italic: true },
57  hr: { fgColor: "color08", char: "─" },
58  bold: { bold: true },
59  italic: { italic: true },
60  inlineCode: { fgColor: "color03" },
61  link: { fgColor: "color06", underline: true },
62};
63
64function resolveTheme(theme?: MarkdownTheme): Required<MarkdownTheme> {
65  if (!theme) return defaults;
66  return {
67    heading1: theme.heading1 ?? defaults.heading1,
68    heading2: theme.heading2 ?? defaults.heading2,
69    heading3: theme.heading3 ?? defaults.heading3,
70    codeBlock: theme.codeBlock ?? defaults.codeBlock,
71    codeContent: theme.codeContent ?? defaults.codeContent,
72    listMarker: theme.listMarker ?? defaults.listMarker,
73    blockquoteBar: theme.blockquoteBar ?? defaults.blockquoteBar,
74    blockquoteText: theme.blockquoteText ?? defaults.blockquoteText,
75    hr: theme.hr ?? defaults.hr,
76    bold: theme.bold ?? defaults.bold,
77    italic: theme.italic ?? defaults.italic,
78    inlineCode: theme.inlineCode ?? defaults.inlineCode,
79    link: theme.link ?? defaults.link,
80  };
81}
82
83// ─── Helpers ────────────────────────────────────────────────────
84
85/** Concatenate inline spans into plain text (markdown markers stripped). */
86function spansToText(spans: InlineSpan[]): string {
87  return spans.map((s) => (s.type === "link" ? s.text : s.content)).join("");
88}
89
90/** Check whether spans contain any inline formatting. */
91function hasFormatting(spans: InlineSpan[]): boolean {
92  return spans.some((s) => s.type !== "text");
93}
94
95/**
96 * Convert inline spans into individual Text nodes for use inside a
97 * wrapping HStack. Text/bold/italic spans are split at word/whitespace
98 * boundaries (`/\S+|\s+/g`) so flexWrap can break between words.
99 * Code and link spans are kept atomic (single node, no split).
100 */
101function spansToNodes(
102  spans: InlineSpan[],
103  theme: Required<MarkdownTheme>,
104): Node[] {
105  const nodes: Node[] = [];
106
107  for (const span of spans) {
108    let style: StyleProps;
109    let text: string;
110
111    switch (span.type) {
112      case "text":
113        style = {};
114        text = span.content;
115        break;
116      case "bold":
117        style = theme.bold;
118        text = span.content;
119        break;
120      case "italic":
121        style = theme.italic;
122        text = span.content;
123        break;
124      case "code":
125        // Code spans are atomic — don't split at word boundaries
126        nodes.push(Text(span.content, theme.inlineCode));
127        continue;
128      case "link":
129        // Links are atomic — keep link text as one unit
130        nodes.push(Text(span.text, theme.link));
131        continue;
132    }
133
134    // Split at word/whitespace boundaries so flexWrap can break between words
135    const pieces = text.match(/\S+|\s+/g);
136    if (pieces) {
137      for (const piece of pieces) {
138        nodes.push(Text(piece, style));
139      }
140    }
141  }
142
143  return nodes;
144}
145
146/** Render formatted spans in a wrapping row with an optional inherited style. */
147function formattedSpans(
148  spans: InlineSpan[],
149  theme: Required<MarkdownTheme>,
150  style: StyleProps = {},
151): Node {
152  return HStack({ flexWrap: "wrap", ...style }, spansToNodes(spans, theme));
153}
154
155// ─── Component ──────────────────────────────────────────────────
156
157/** Props for the {@link Markdown} component. */
158export interface MarkdownProps {
159  /**
160   * Theme overrides. Unset properties fall back to the built-in
161   * default theme (cyan headings, yellow code blocks, etc.).
162   */
163  theme?: MarkdownTheme;
164}
165
166/**
167 * Render a markdown string as an array of cel-tui nodes.
168 *
169 * Parses the content into block-level tokens (via
170 * [yoctomarkdown](https://www.npmjs.com/package/yoctomarkdown))
171 * and maps each to styled primitives. The returned array is meant
172 * to be used as children of a container (typically a scrollable VStack).
173 *
174 * **Block-level styling** is fully supported: headings, code blocks,
175 * lists, blockquotes, and horizontal rules are rendered with distinct
176 * styles. **Inline styling** (bold, italic, code, links) is rendered
177 * in headings, paragraphs, list items, and blockquotes by splitting spans at
178 * word boundaries into individual `Text` nodes inside a wrapping
179 * `HStack({ flexWrap: "wrap" })`. Block styles are applied to that
180 * container and inherited by every inline span.
181 *
182 * **Streaming** works naturally: append chunks to the content string
183 * and call `cel.render()`. The component re-tokenizes the full string
184 * each render. Unclosed code blocks and inline formatting are handled
185 * gracefully.
186 *
187 * @param content - Markdown string (may be partial during streaming).
188 * @param props - Optional theme overrides.
189 * @returns Array of nodes to spread into a container's children.
190 *
191 * @example
192 * // Static content
193 * VStack({ flex: 1, overflow: "scroll", padding: { x: 1 } },
194 *   Markdown("# Hello\n\nSome **bold** text.\n\n```js\nconst x = 1;\n```")
195 * )
196 *
197 * @example
198 * // Streaming from an LLM
199 * let content = "";
200 * onChunk((chunk) => { content += chunk; cel.render(); });
201 *
202 * VStack({ flex: 1, overflow: "scroll" },
203 *   Markdown(content)
204 * )
205 *
206 * @example
207 * // Custom theme
208 * Markdown(content, {
209 *   theme: { heading1: { bold: true, fgColor: "color05" } }
210 * })
211 */
212export function Markdown(content: string, props?: MarkdownProps): Node[] {
213  const theme = resolveTheme(props?.theme);
214  const tokens = tokenize(content);
215  const nodes: Node[] = [];
216
217  for (const token of tokens) {
218    switch (token.type) {
219      case "heading": {
220        const style =
221          token.depth === 1
222            ? theme.heading1
223            : token.depth === 2
224              ? theme.heading2
225              : theme.heading3;
226        nodes.push(
227          hasFormatting(token.spans)
228            ? formattedSpans(token.spans, theme, style)
229            : Text(spansToText(token.spans), style),
230        );
231        break;
232      }
233
234      case "paragraph":
235        if (hasFormatting(token.spans)) {
236          nodes.push(formattedSpans(token.spans, theme));
237        } else {
238          nodes.push(Text(spansToText(token.spans), { wrap: "word" }));
239        }
240        break;
241
242      case "code_block":
243        nodes.push(
244          VStack({ padding: { x: 1 }, ...theme.codeBlock }, [
245            Text(token.content, theme.codeContent),
246          ]),
247        );
248        break;
249
250      case "list_item": {
251        const marker = token.ordered ? `${token.index}.` : "•";
252        const liContent = hasFormatting(token.spans)
253          ? formattedSpans(token.spans, theme)
254          : Text(spansToText(token.spans), { wrap: "word" });
255        nodes.push(
256          HStack({}, [
257            Text(`${marker} `, theme.listMarker),
258            VStack({ flex: 1 }, [liContent]),
259          ]),
260        );
261        break;
262      }
263
264      case "blockquote": {
265        const bqContent = hasFormatting(token.spans)
266          ? formattedSpans(token.spans, theme, theme.blockquoteText)
267          : Text(spansToText(token.spans), {
268              wrap: "word",
269              ...theme.blockquoteText,
270            });
271        nodes.push(
272          HStack({}, [
273            Text("│ ", theme.blockquoteBar),
274            VStack({ flex: 1 }, [bqContent]),
275          ]),
276        );
277        break;
278      }
279
280      case "hr":
281        nodes.push(Divider({ fgColor: theme.hr.fgColor, char: theme.hr.char }));
282        break;
283
284      case "blank":
285        nodes.push(Text(""));
286        break;
287    }
288  }
289
290  return nodes;
291}