Lines wider than the terminal (wide markdown tables, long code lines) were soft-wrapped by the terminal but counted as one row by Ink's <Static> redraw, desyncing its cursor math and stranding duplicate copies of the status bar and input box in scrollback on every re-render. renderMarkdown now wraps its output to the caller's width via wrap-ansi, and every <Static> item (plus the live streaming line) is held within a width-bounded Box so nothing the terminal would soft-wrap reaches Ink. Also sets cli-table3 header color to yellow (red-on-blue themes made table headers unreadable). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
39 lines
2.4 KiB
TypeScript
39 lines
2.4 KiB
TypeScript
import { marked } from "marked";
|
|
import { markedTerminal } from "marked-terminal";
|
|
import wrapAnsi from "wrap-ansi";
|
|
|
|
// @types/marked-terminal's MarkedExtension shape doesn't line up with the installed marked version;
|
|
// the two packages are functionally compatible at runtime per marked-terminal's own peer range.
|
|
//
|
|
// tableOptions overrides cli-table3's own default header color (style.head: ['red']) — red-on-blue
|
|
// terminal themes make table headers hard to read. "yellow" is the closest this color scheme
|
|
// actually supports: it only recognizes standard ANSI 16-color names, and terminals have no true
|
|
// "orange" in that palette — literal "orange"/hex values are silently accepted but render with no
|
|
// color at all (verified empirically), so this is the practical substitute, not a compromise pick.
|
|
marked.use(markedTerminal({ tableOptions: { style: { head: ["yellow"] } } }) as Parameters<typeof marked.use>[0]);
|
|
|
|
// marked.parse() + marked-terminal's ANSI formatting is real CPU work (word-wrap, table layout,
|
|
// syntax highlighting). Historical assistant messages are immutable once committed, so re-parsing
|
|
// the same text on every re-render (every spinner tick, every streamed-token frame) is pure waste
|
|
// that scales with total conversation length — cache by input text so each message is parsed once.
|
|
const renderCache = new Map<string, string>();
|
|
|
|
// marked-terminal (and cli-table3, for tables) emit lines that can be far wider than the terminal —
|
|
// a wide table, a long code line, a URL. The terminal soft-wraps those, but Ink's <Static> redraw
|
|
// math counts one physical row per logical line, so anything that soft-wrapped throws off its
|
|
// accounting: the live region below (status bar + input box) gets stranded copies of itself in
|
|
// scrollback on every subsequent re-render. Hard-wrapping the finished output to the caller's width
|
|
// keeps every physical line within bounds so Ink's line count stays exact.
|
|
export function renderMarkdown(text: string, width?: number): string {
|
|
const key = width && width > 0 ? `${width} |