Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

notebookOutput.ts

61 lines2.0 KB

1import {
2 terminalOutputCollapseRedraws,
3 terminalOutputPlainText,
4 terminalOutputReplayLineEdits,
5} from "./terminalOutput.ts";
6​
7const ERASE_IN_LINE = /(?:\u001b\[|\u009b)[\d;]*K/u;
8​
9export function notebookStreamText(
10 text: string,
11 stripControls: (text: string) => string = terminalOutputPlainText,
12): string {
13 if (!ERASE_IN_LINE.test(text)) return terminalOutputCollapseRedraws(stripControls(text));
14​
15 // Replay horizontal commands on lines with erases. Other cursor commands stay
16 // out of the replay so a saved stream cannot overwrite previous rows.
17 const lines = text.split(/(\r?\n)/u);
18 for (let index = 0; index < lines.length; index += 2) {
19 const line = lines[index]!;
20 lines[index] = ERASE_IN_LINE.test(line)
21 ? (terminalOutputReplayLineEdits(line) ?? stripControls(line))
22 : stripControls(line);
23 }
24 return terminalOutputCollapseRedraws(lines.join(""));
26​
27function notebookStream(output: unknown) {
28 if (
29 !output ||
30 typeof output !== "object" ||
31 !("output_type" in output) ||
32 output.output_type !== "stream" ||
33 !("name" in output) ||
34 (output.name !== "stdout" && output.name !== "stderr") ||
35 !("text" in output) ||
36 (typeof output.text !== "string" && !Array.isArray(output.text)) ||
37 "data" in output
38 ) {
39 return undefined;
40 }
41 return { name: output.name, text: output.text };
43​
44export function* notebookOutputGroups(
45 outputs: readonly unknown[],
46 readText: (value: unknown) => string,
47) {
48 let streamName: string | undefined;
49 let chunks: string[] = [];
50 for (const output of outputs) {
51 const stream = notebookStream(output);
52 if (streamName !== undefined && streamName !== stream?.name) {
53 yield { kind: "stream" as const, text: chunks.join("") };
54 chunks = [];
55 }
56 streamName = stream?.name;
57 if (stream) chunks.push(readText(stream.text));
58 else yield { kind: "output" as const, output };
59 }
60 if (streamName !== undefined) yield { kind: "stream" as const, text: chunks.join("") };