xonecas.io
6533
Yo

yoctomarkdown / commit a6aa698

fix: redraw partial streaming from saved cursor

xonecas2026-03-15 a6aa69851d15f64f69277e814bd6e30d85eade8a parent 8ad6645

2 files changed

src/index.ts+13−26
@@ -128,7 +128,14 @@ export function createHighlighter(options?: Options): Highlighter {
128128 }
129129
130130 let hasPartial = false;
131- let partialLength = 0;
131+
132+ function redrawPartialPrefix(): string {
133+ return hasPartial ? "\x1b8\x1b[J" : "";
134+ }
135+
136+ function renderPartial(line: string, isPartial: boolean): string {
137+ return `\x1b7${parseLine(line, isPartial)}`;
138+ }
132139
133140 return {
134141 write(chunk: string | Uint8Array): string {
@@ -139,30 +146,17 @@ export function createHighlighter(options?: Options): Highlighter {
139146 const lines = buffer.split("\n");
140147 buffer = lines.pop() ?? "";
141148
142- let out = "";
143- if (hasPartial) {
144- const columns =
145- typeof process !== "undefined" && process.stdout?.columns
146- ? process.stdout.columns
147- : 80;
148- const linesToClear = Math.ceil(partialLength / columns) || 1;
149- out += "\x1b[2K\r";
150- if (linesToClear > 1) {
151- out += "\x1b[1A\x1b[2K".repeat(linesToClear - 1);
152- }
153- }
149+ let out = redrawPartialPrefix();
154150
155151 if (lines.length > 0) {
156152 out += `${lines.map((line) => parseLine(line, false)).join("\n")}\n`;
157153 }
158154
159155 if (buffer.length > 0) {
160- out += parseLine(buffer, true);
156+ out += renderPartial(buffer, true);
161157 hasPartial = true;
162- partialLength = buffer.length;
163158 } else {
164159 hasPartial = false;
165- partialLength = 0;
166160 }
167161
168162 return out;
@@ -172,16 +166,9 @@ export function createHighlighter(options?: Options): Highlighter {
172166 const out = parseLine(buffer, false);
173167 buffer = "";
174168 if (hasPartial) {
175- const columns =
176- typeof process !== "undefined" && process.stdout?.columns
177- ? process.stdout.columns
178- : 80;
179- const linesToClear = Math.ceil(partialLength / columns) || 1;
180- let clearSeq = "\x1b[2K\r";
181- if (linesToClear > 1) {
182- clearSeq += "\x1b[1A\x1b[2K".repeat(linesToClear - 1);
183- }
184- return clearSeq + out;
169+ const redrawPrefix = redrawPartialPrefix();
170+ hasPartial = false;
171+ return redrawPrefix + out;
185172 }
186173 return out;
187174 }
tests/index.test.ts+110−26
@@ -32,10 +32,107 @@ describe("Programmatic Usage: highlightSync", () => {
3232 });
3333 });
3434
35+function renderTerminalOutput(
36+ output: string,
37+ columns = Number.POSITIVE_INFINITY,
38+) {
39+ const screen: string[][] = [[]];
40+ let row = 0;
41+ let column = 0;
42+ let savedCursor: { row: number; column: number } | null = null;
43+
44+ function ensureRow(targetRow: number) {
45+ while (screen.length <= targetRow) {
46+ screen.push([]);
47+ }
48+ }
49+
50+ function writeChar(char: string) {
51+ if (column >= columns) {
52+ row += 1;
53+ column = 0;
54+ }
55+
56+ ensureRow(row);
57+ if (!screen[row]) {
58+ screen[row] = [];
59+ }
60+ const currentLine = screen[row];
61+ if (!currentLine) {
62+ return;
63+ }
64+ currentLine[column] = char;
65+ column += 1;
66+ }
67+
68+ for (let i = 0; i < output.length; i += 1) {
69+ const rest = output.slice(i);
70+
71+ if (rest.startsWith("\x1b7")) {
72+ savedCursor = { row, column };
73+ i += 1;
74+ continue;
75+ }
76+
77+ if (rest.startsWith("\x1b8")) {
78+ if (savedCursor) {
79+ row = savedCursor.row;
80+ column = savedCursor.column;
81+ }
82+ i += 1;
83+ continue;
84+ }
85+
86+ if (rest.startsWith("\x1b[J")) {
87+ ensureRow(row);
88+ screen[row] = (screen[row] ?? []).slice(0, column);
89+ for (let clearRow = row + 1; clearRow < screen.length; clearRow += 1) {
90+ screen[clearRow] = [];
91+ }
92+ i += 2;
93+ continue;
94+ }
95+
96+ if (rest.startsWith("\x1b[2K")) {
97+ ensureRow(row);
98+ screen[row] = [];
99+ i += 3;
100+ continue;
101+ }
102+
103+ if (rest.startsWith("\x1b[1A")) {
104+ row = Math.max(0, row - 1);
105+ i += 3;
106+ continue;
107+ }
108+
109+ const char = output[i];
110+ if (char === "\n") {
111+ row += 1;
112+ column = 0;
113+ ensureRow(row);
114+ continue;
115+ }
116+
117+ if (char === "\r") {
118+ column = 0;
119+ continue;
120+ }
121+
122+ if (char !== undefined && char !== "\x1b") {
123+ writeChar(char);
124+ }
125+ }
126+
127+ return screen
128+ .map((line) => line.join("").replace(/\s+$/u, ""))
129+ .join("\n")
130+ .replace(/\n+$/u, "");
131+}
132+
35133 function expectStreamMatch(res: string, markdown: string) {
36134 const expected = highlightSync(markdown, { theme: "none" });
37- // biome-ignore lint/suspicious/noControlCharactersInRegex: clear line ansi escape
38- expect(res.replace(/[^\n]*\x1b\[2K\r/g, "")).toBe(expected);
135+ expect(renderTerminalOutput(res)).toBe(renderTerminalOutput(expected));
39136 }
40137
41138 describe("Programmatic Usage: createHighlighter (Streaming)", () => {
@@ -82,33 +179,20 @@ describe("Programmatic Usage: createHighlighter (Streaming)", () => {
82179 expectStreamMatch(res, markdown);
83180 });
84181
85- test("should clear multiple lines when wrapped", () => {
86- // Mock columns
87- const originalColumns = process.stdout.columns;
88- Object.defineProperty(process.stdout, "columns", {
89- value: 10,
90- configurable: true,
91- });
182+ test("should redraw wrapped partial lines after an external prefix", () => {
183+ const prefix = "◆ ";
184+ const markdown =
185+ "No `\\x1b[2K` or `\\r` sequences in the streamed text. The ANSI colour codes remain (intentional — those are static style codes from yoctocolors, not cursor-control sequences).\n";
186+ const splitAt = 134;
92187
93188 const highlighter = createHighlighter({ theme: "none" });
94- // 25 chars, columns = 10, so it takes 3 visual lines
95- const chunk1 = "1234567890123456789012345";
96- const chunk2 = "67890\n";
97-
98- let res = highlighter.write(chunk1);
99- res += highlighter.write(chunk2);
189+ let res = prefix;
190+ res += highlighter.write(markdown.slice(0, splitAt));
191+ res += highlighter.write(markdown.slice(splitAt));
100192 res += highlighter.end();
101193
102- // The first chunk is written, then cleared. Since it takes 3 lines,
103- // clear sequence should have \x1b[1A\x1b[2K repeated twice.
104- expect(res).toContain("\x1b[1A\x1b[2K\x1b[1A\x1b[2K");
105-
106- // Restore
107- if (originalColumns !== undefined) {
108- Object.defineProperty(process.stdout, "columns", {
109- value: originalColumns,
110- configurable: true,
111- });
112- }
194+ expect(renderTerminalOutput(res, 120)).toBe(
195+ renderTerminalOutput(`${prefix}${markdown}`, 120),
196+ );
113197 });
114198 });