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

NotebookPreview.tsx

186 lines8.0 KB

1/* oxlint-disable react/no-array-index-key -- Notebook cells and outputs retain their saved source order. */
2import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
3import { T, useGT, useMessages } from "gt-react";
4import { useEffect, useRef, useState } from "react";
5import ChatMarkdown from "~/components/ChatMarkdown";
6import type { MarkdownExtensions } from "~/markdown/wordsHast";
7import { Button } from "~/components/ui/button";
8import ReadOnlySourcePreview from "./ReadOnlySourcePreview";
9import DocumentPages from "./DocumentPages";
10import { FileSurfaceNotice } from "./fileSurfaceChrome";
11import type { OfficeWorkerResult } from "./officePreviewProtocol";
12​
13// Saved notebooks must not load URLs or turn authored links into app actions.
14const NOTEBOOK_MARKDOWN: MarkdownExtensions = { inert: true };
15​
16function NotebookSource(props: { readonly name: string; readonly text: string }) {
17 const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16));
18 const measure = (node: HTMLElement) => {
19 setHeight(Math.min(360, Math.ceil(node.getBoundingClientRect().height)));
20 };
21 return (
22 <div className="flex min-h-0 flex-col" style={{ height }}>
23 <ReadOnlySourcePreview {...props} onPostRender={measure} />
24 </div>
25 );
27​
28export default function NotebookPreview(props: {
29 readonly notebook: Extract<OfficeWorkerResult, { type: "notebook" }>;
30 readonly sizeBytes?: number | undefined;
31}) {
32 const gt = useGT();
33 const messages = useMessages();
34 const [visible, setVisible] = useState(20);
35 const scroll = useRef<HTMLDivElement>(null);
36 const [outputView, setOutputView] = useState(() => ({
37 mounted: new Set<string>(),
38 heights: new Map<string, number>(),
39 }));
40 const outputCount = props.notebook.cells
41 .slice(0, visible)
42 .reduce(
43 (count, cell) => count + cell.outputs.filter((output) => output.kind === "html").length,
44 0,
45 );
46 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Observe output visibility and measure departing outputs to bound iframe lifetimes while preserving scroll height.
47 useEffect(() => {
48 const root = scroll.current;
49 if (!root || !outputCount) return;
50 const inView = new Set<Element>();
51 const nearby = new Set<Element>();
52 let active = new Set<Element>();
53 const outputKey = (node: Element) => node.getAttribute("data-notebook-output")!;
54 const track = (candidates: Set<Element>) => (entries: IntersectionObserverEntry[]) => {
55 for (const entry of entries) {
56 if (entry.isIntersecting) candidates.add(entry.target);
57 else candidates.delete(entry.target);
58 }
59 // Mount every visible output. Only preload while the total is below 16.
60 const next = new Set(inView);
61 for (const node of nearby) {
62 if (next.size >= 16) break;
63 next.add(node);
64 }
65 const departing = [...active].filter((node) => !next.has(node));
66 if (active.size === next.size && departing.length === 0) return;
67 const measured = departing
68 .map((node) => [outputKey(node), node.clientHeight] as const)
69 .filter(([, height]) => height > 0);
70 active = next;
71 setOutputView((old) => ({
72 mounted: new Set(Array.from(next, outputKey)),
73 heights: new Map([...old.heights, ...measured]),
74 }));
75 };
76 const viewportObserver = new IntersectionObserver(track(inView), { root });
77 const preloadObserver = new IntersectionObserver(track(nearby), { root, rootMargin: "160px" });
78 for (const node of root.querySelectorAll("[data-notebook-output]")) {
79 viewportObserver.observe(node);
80 preloadObserver.observe(node);
81 }
82 return () => {
83 viewportObserver.disconnect();
84 preloadObserver.disconnect();
85 };
86 }, [outputCount]);
87 return (
88 <>
89 <div
90 className="border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"
91 role="status"
92 >
93 {gt("{count, plural, one {{formatted} cell} other {{formatted} cells}}", {
94 count: props.notebook.cells.length,
95 formatted: props.notebook.cells.length.toLocaleString(),
96 })}{" "}
97 · {props.notebook.language}
98 {props.sizeBytes !== undefined
99 ? ` · ${props.sizeBytes === 0 ? gt("0 bytes") : formatAttachmentSize(props.sizeBytes, messages)}`
100 : ""}
101 </div>
102 <FileSurfaceNotice>
103 <T>Saved outputs only. Code is never executed.</T>
104 </FileSurfaceNotice>
105 <div ref={scroll} className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto">
106 <div className="mx-auto max-w-4xl space-y-5 px-5 py-6">
107 {props.notebook.cells.slice(0, visible).map((cell, index) => (
108 <section
109 key={index}
110 aria-label={gt("Cell {number}", { number: String(index + 1) })}
111 className="min-w-0 overflow-hidden rounded-md border border-border/60"
112 >
113 <div className="border-b border-border/60 bg-muted/30 px-3 py-1.5 text-xs text-muted-foreground">
114 {cell.kind === "code" ? props.notebook.language : cell.kind} · {index + 1}
115 </div>
116 {cell.kind === "markdown" ? (
117 <ChatMarkdown
118 text={cell.source}
119 cwd={undefined}
120 parseRawHtml={false}
121 extensions={NOTEBOOK_MARKDOWN}
122 className="px-4 py-3"
123 />
124 ) : cell.source.trim() ? (
125 <NotebookSource
126 name={`cell.${cell.kind === "code" ? (({ python: "py", javascript: "js", typescript: "ts", julia: "jl" } as Record<string, string>)[props.notebook.language] ?? props.notebook.language) : "txt"}`}
127 text={cell.source}
128 />
129 ) : null}
130 {cell.outputs.map((output, outputIndex) => {
131 const key = `${index}-${outputIndex}`;
132 const mounted = outputView.mounted.has(key);
133 const estimatedHeight = outputView.heights.get(key) ?? 80;
134 return (
135 <div
136 key={outputIndex}
137 data-notebook-output={output.kind === "html" ? key : undefined}
138 className="box-content border-t border-border/60"
139 style={{
140 minHeight: output.kind === "html" && !mounted ? estimatedHeight : undefined,
141 }}
142 >
143 {output.kind === "html" ? (
144 mounted ? (
145 <DocumentPages
146 html={output.text}
147 name={gt("Cell {number} HTML output", { number: String(index + 1) })}
148 output
149 estimatedOutputHeight={estimatedHeight}
150 />
151 ) : null
152 ) : output.kind === "image" ? (
153 <img
154 src={output.text}
155 alt={gt("Cell {number} output", { number: String(index + 1) })}
156 loading="lazy"
157 className="max-h-96 max-w-full p-4 object-contain"
158 />
159 ) : (
160 <pre className="overflow-x-auto p-4 text-xs whitespace-pre-wrap break-words">
161 {output.text}
162 </pre>
163 )}
164 </div>
165 );
166 })}
167 </section>
168 ))}
169 {props.notebook.cells.length === 0 ? (
170 <p className="text-sm text-muted-foreground">
171 <T>This notebook is empty.</T>
172 </p>
173 ) : null}
174 {visible < props.notebook.cells.length ? (
175 <Button variant="outline" size="sm" onClick={() => setVisible((count) => count + 20)}>
176 {gt(
177 "{count, plural, one {Show more cells ({count} remaining)} other {Show more cells ({count} remaining)}}",
178 { count: props.notebook.cells.length - visible },
179 )}
180 </Button>
181 ) : null}
182 </div>
183 </div>
184 </>
185 );