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

NotebookPreview.tsx

254 lines10.8 KB

1/* oxlint-disable react/no-array-index-key -- Notebook cells and outputs retain their saved source order. */
2import { EXTENSION_TO_FILE_FORMAT } from "@pierre/diffs";
3import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
4import { T, useGT, useMessages, plural, part } from "gt-react";
5import { useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
6import ChatMarkdown from "~/components/ChatMarkdown";
7import type { MarkdownExtensions } from "~/markdown/wordsHast";
8import { Button } from "~/components/ui/button";
9import ReadOnlySourcePreview from "./ReadOnlySourcePreview";
10import DocumentPages from "./DocumentPages";
11import { FileSurfaceNotice, selectRenderedContentOnSelectAll } from "./fileSurfaceChrome";
12import type { OfficeWorkerResult } from "./officePreviewProtocol";
13import { createPositionMemory, PreviewPositionKey } from "./previewPosition";
14​
15const savedPositions = createPositionMemory<{
16 readonly visible: number;
17 readonly cell: number;
18 readonly offset: number;
19}>();
20const cellsOf = (root: HTMLElement) => root.querySelectorAll(":scope > div > div > section");
21​
22// Saved notebooks must not load URLs or turn authored links into app actions.
23const NOTEBOOK_MARKDOWN: MarkdownExtensions = { inert: true };
24​
25const FORMAT_TO_EXTENSION = new Map<string, string>();
26for (const [extension, format] of Object.entries(EXTENSION_TO_FILE_FORMAT)) {
27 if (format && !FORMAT_TO_EXTENSION.has(format)) FORMAT_TO_EXTENSION.set(format, extension);
29​
30function notebookCellFileName(kind: "code" | "raw", language: string) {
31 if (kind !== "code") return "cell.txt";
32 const normalized = language.toLowerCase();
33 if (/^c\+\+\d*$/.test(normalized)) return "cell.cpp";
34 if (normalized === "c#") return "cell.cs";
35 if (normalized === "f#") return "cell.fs";
36 return `cell.${FORMAT_TO_EXTENSION.get(normalized) ?? normalized}`;
38​
39function NotebookSource(props: { readonly name: string; readonly text: string }) {
40 const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16));
41 const measure = (node: HTMLElement) => {
42 setHeight(Math.min(360, Math.ceil(node.getBoundingClientRect().height)));
43 };
44 return (
45 <div className="flex min-h-0 flex-col" style={{ height }}>
46 <ReadOnlySourcePreview {...props} onPostRender={measure} />
47 </div>
48 );
50​
51export default function NotebookPreview(props: {
52 readonly notebook: Extract<OfficeWorkerResult, { type: "notebook" }>;
53 readonly sizeBytes?: number | undefined;
54}) {
55 const gt = useGT();
56 const messages = useMessages();
57 const positionKey = useContext(PreviewPositionKey);
58 const [saved] = useState(() => savedPositions.get(positionKey));
59 const [visible, setVisible] = useState(saved?.visible ?? 20);
60 const scroll = useRef<HTMLDivElement>(null);
61 const savePosition = (root: HTMLElement, expanded: number) => {
62 const top = root.getBoundingClientRect().top;
63 const cells = Array.from(cellsOf(root));
64 const cell = Math.max(
65 0,
66 cells.findIndex((node) => node.getBoundingClientRect().bottom > top),
67 );
68 savedPositions.set(positionKey, {
69 visible: expanded,
70 cell,
71 offset: top - (cells[cell]?.getBoundingClientRect().top ?? top),
72 });
73 };
74 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Return a reopened notebook to its saved cell once the cells have laid out.
75 useLayoutEffect(() => {
76 const root = scroll.current;
77 const cell = saved && root ? cellsOf(root)[saved.cell] : undefined;
78 if (!root || !saved || !cell) return;
79 root.scrollTop +=
80 cell.getBoundingClientRect().top - root.getBoundingClientRect().top + saved.offset;
81 }, [saved]);
82 const [outputView, setOutputView] = useState(() => ({
83 mounted: new Set<string>(),
84 heights: new Map<string, number>(),
85 }));
86 const outputCount = props.notebook.cells
87 .slice(0, visible)
88 .reduce(
89 (count, cell) => count + cell.outputs.filter((output) => output.kind === "html").length,
90 0,
91 );
92 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Observe output visibility and measure departing outputs to bound iframe lifetimes while preserving scroll height.
93 useEffect(() => {
94 const root = scroll.current;
95 if (!root || !outputCount) return;
96 const inView = new Set<Element>();
97 const nearby = new Set<Element>();
98 let active = new Set<Element>();
99 const outputKey = (node: Element) => node.getAttribute("data-notebook-output")!;
100 const track = (candidates: Set<Element>) => (entries: IntersectionObserverEntry[]) => {
101 for (const entry of entries) {
102 if (entry.isIntersecting) candidates.add(entry.target);
103 else candidates.delete(entry.target);
104 }
105 // Mount every visible output. Only preload while the total is below 16.
106 const next = new Set(inView);
107 for (const node of nearby) {
108 if (next.size >= 16) break;
109 next.add(node);
110 }
111 const departing = [...active].filter((node) => !next.has(node));
112 if (active.size === next.size && departing.length === 0) return;
113 const measured = departing
114 .map((node) => [outputKey(node), node.clientHeight] as const)
115 .filter(([, height]) => height > 0);
116 active = next;
117 setOutputView((old) => ({
118 mounted: new Set(Array.from(next, outputKey)),
119 heights: new Map([...old.heights, ...measured]),
120 }));
121 };
122 const viewportObserver = new IntersectionObserver(track(inView), { root });
123 const preloadObserver = new IntersectionObserver(track(nearby), { root, rootMargin: "160px" });
124 for (const node of root.querySelectorAll("[data-notebook-output]")) {
125 viewportObserver.observe(node);
126 preloadObserver.observe(node);
127 }
128 return () => {
129 viewportObserver.disconnect();
130 preloadObserver.disconnect();
131 };
132 }, [outputCount]);
133 return (
134 <>
135 <div
136 className="border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"
137 role="status"
138 >
139 {gt`${plural(
140 { count: props.notebook.cells.length },
141 {
142 one: part`${{ formatted: props.notebook.cells.length.toLocaleString() }} cell`,
143 other: part`${{ formatted: props.notebook.cells.length.toLocaleString() }} cells`,
144 },
145 )}`}{" "}
146 · {props.notebook.language}
147 {props.sizeBytes !== undefined
148 ? ` · ${props.sizeBytes === 0 ? gt`0 bytes` : formatAttachmentSize(props.sizeBytes, messages)}`
149 : ""}
150 </div>
151 <FileSurfaceNotice>
152 <T>Saved outputs only. Code is never executed.</T>
153 </FileSurfaceNotice>
154 <div
155 ref={scroll}
156 className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto"
157 onKeyDown={selectRenderedContentOnSelectAll}
158 onScroll={(event) => savePosition(event.currentTarget, visible)}
159 >
160 <div tabIndex={-1} className="min-h-full outline-none">
161 <div className="mx-auto max-w-4xl space-y-5 px-5 py-6">
162 {props.notebook.cells.slice(0, visible).map((cell, index) => (
163 <section
164 key={index}
165 aria-label={gt`Cell ${{ number: String(index + 1) }}`}
166 className="min-w-0 overflow-hidden rounded-md border border-border/60"
167 >
168 <div className="border-b border-border/60 bg-muted/30 px-3 py-1.5 text-xs text-muted-foreground">
169 {cell.kind === "code" ? props.notebook.language : cell.kind} · {index + 1}
170 </div>
171 {cell.kind === "markdown" ? (
172 <ChatMarkdown
173 text={cell.source}
174 cwd={undefined}
175 parseRawHtml={false}
176 extensions={NOTEBOOK_MARKDOWN}
177 className="px-4 py-3"
178 />
179 ) : cell.source.trim() ? (
180 <NotebookSource
181 name={notebookCellFileName(cell.kind, props.notebook.language)}
182 text={cell.source}
183 />
184 ) : null}
185 {cell.outputs.map((output, outputIndex) => {
186 const key = `${index}-${outputIndex}`;
187 const mounted = outputView.mounted.has(key);
188 const estimatedHeight = outputView.heights.get(key) ?? 80;
189 return (
190 <div
191 key={outputIndex}
192 data-notebook-output={output.kind === "html" ? key : undefined}
193 className="box-content border-t border-border/60"
194 style={{
195 minHeight: output.kind === "html" && !mounted ? estimatedHeight : undefined,
196 }}
197 >
198 {output.kind === "html" ? (
199 mounted ? (
200 <DocumentPages
201 html={output.text}
202 name={gt`Cell ${{ number: String(index + 1) }} HTML output`}
203 output
204 estimatedOutputHeight={estimatedHeight}
205 />
206 ) : null
207 ) : output.kind === "image" ? (
208 <img
209 src={output.text}
210 alt={gt`Cell ${{ number: String(index + 1) }} output`}
211 loading="lazy"
212 className="max-h-96 max-w-full p-4 object-contain"
213 />
214 ) : (
215 <pre className="overflow-x-auto p-4 text-xs whitespace-pre-wrap break-words">
216 {output.text}
217 </pre>
218 )}
219 </div>
220 );
221 })}
222 </section>
223 ))}
224 {props.notebook.cells.length === 0 ? (
225 <p className="text-sm text-muted-foreground">
226 <T>This notebook is empty.</T>
227 </p>
228 ) : null}
229 {visible < props.notebook.cells.length ? (
230 <div className="select-none">
231 <Button
232 variant="outline"
233 size="sm"
234 onClick={() => {
235 if (scroll.current) savePosition(scroll.current, visible + 20);
236 setVisible(visible + 20);
237 }}
238 >
239 {gt`${plural(
240 { count: props.notebook.cells.length - visible },
241 {
242 one: part`Show more cells (${{ count: props.notebook.cells.length - visible }} remaining)`,
243 other: part`Show more cells (${{ count: props.notebook.cells.length - visible }} remaining)`,
244 },
245 )}`}
246 </Button>
247 </div>
248 ) : null}
249 </div>
250 </div>
251 </div>
252 </>
253 );