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