xonecas.io
64875
Mc

mini-coder / files

mini-coder / src / tui / stream.ts

4.6 KB
1import { highlightCode, highlightMarkdown } from "./highlight.ts";
2import { dim } from "./styles.ts";
3
4/** One logical display line: unwrapped text plus the style its rows inherit. */
5export interface BodyLine {
6  text: string;
7  style?: (text: string) => string;
8  /** Row background, painted across the row's trailing cells by the renderer. */
9  bg?: string;
10}
11
12/**
13 * A text stream projected onto display lines. `feed` and `flush` return the
14 * lines that became final; `pending` returns what is still in flight.
15 */
16export interface StreamRenderer {
17  feed(delta: string): BodyLine[];
18  pending(): BodyLine[];
19  flush(): BodyLine[];
20  reset(): void;
21}
22
23/** A fence opening line, and the info string that names its language. */
24const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})\s*(\S*)/;
25const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})\s*$/;
26
27/**
28 * Commits each complete line, colored. A fenced code block is held until its
29 * closing marker arrives, because neither the fence's language nor its body can
30 * be known before then. A run of prose is held until its block ends, because
31 * block context is what separates a setext heading from a paragraph and spans
32 * may cross lines; a blank line, a fence or the end of the turn ends the block.
33 * The live preview shows the held lines uncolored.
34 */
35export class MarkdownStream implements StreamRenderer {
36  private rest = "";
37  private fence: { marker: string; info: string; lines: string[] } | null = null;
38  private prose: string[] = [];
39
40  feed(delta: string): BodyLine[] {
41    this.rest += delta;
42    const lines = this.rest.split("\n");
43    this.rest = lines.pop()!;
44    return lines.flatMap((line) => this.commit(line));
45  }
46
47  pending(): BodyLine[] {
48    const held = this.fence === null ? this.prose : this.fence.lines;
49    const rest = this.rest === "" ? [] : [this.rest];
50    return [...held, ...rest].map((text) => ({ text }));
51  }
52
53  flush(): BodyLine[] {
54    const fence = this.fence;
55    const lines = fence === null ? this.releaseProse(this.rest) : this.releaseFence(null);
56    if (fence !== null && this.rest !== "") lines.push({ text: highlightMarkdown(this.rest) });
57    this.reset();
58    return lines;
59  }
60
61  reset(): void {
62    this.rest = "";
63    this.fence = null;
64    this.prose = [];
65  }
66
67  private commit(line: string): BodyLine[] {
68    const fence = this.fence;
69    if (fence !== null) {
70      const close = FENCE_CLOSE.exec(line);
71      if (close === null || close[1][0] !== fence.marker[0] || close[1].length < fence.marker.length) {
72        fence.lines.push(line);
73        return [];
74      }
75      return this.releaseFence(line);
76    }
77    const open = FENCE_OPEN.exec(line);
78    if (open !== null) {
79      this.fence = { marker: open[1], info: open[2], lines: [line] };
80      return this.releaseProse("");
81    }
82    if (line.trim() === "") return [...this.releaseProse(""), { text: line }];
83    this.prose.push(line);
84    return [];
85  }
86
87  /**
88   * Emits the held prose as one text, so the grammar sees whole blocks, then
89   * hands back the lines. `tail` is the still incomplete line closing the block.
90   */
91  private releaseProse(tail: string): BodyLine[] {
92    const prose = this.prose;
93    this.prose = [];
94    if (tail !== "") prose.push(tail);
95    if (prose.length === 0) return [];
96    // A block is only a block once its last line ends, so the text needs a
97    // terminating newline. It is not a line itself: the closing reset `paint`
98    // leaves after it belongs to the last one.
99    const lines = highlightMarkdown(`${prose.join("\n")}\n`).split("\n");
100    const reset = lines.pop()!;
101    lines[lines.length - 1] += reset;
102    return lines.map((text) => ({ text }));
103  }
104
105  /** Emits a held block: the fence lines colored, the body by its language. */
106  private releaseFence(closing: string | null): BodyLine[] {
107    const fence = this.fence!;
108    this.fence = null;
109    const lines: BodyLine[] = [{ text: highlightMarkdown(fence.lines.shift()!) }];
110    if (fence.lines.length > 0) {
111      for (const line of highlightCode(fence.info, fence.lines.join("\n")).split("\n")) {
112        lines.push({ text: line });
113      }
114    }
115    if (closing !== null) lines.push({ text: highlightMarkdown(closing) });
116    return lines;
117  }
118}
119
120/** Keeps only the incomplete tail, dimmed; nothing is ever committed. */
121export class TailStream implements StreamRenderer {
122  private rest = "";
123
124  feed(delta: string): BodyLine[] {
125    const text = this.rest + delta;
126    this.rest = text.slice(text.lastIndexOf("\n") + 1);
127    return [];
128  }
129
130  pending(): BodyLine[] {
131    return this.rest === "" ? [] : [{ text: this.rest, style: dim }];
132  }
133
134  flush(): BodyLine[] {
135    this.reset();
136    return [];
137  }
138
139  reset(): void {
140    this.rest = "";
141  }
142}