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 { 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 );
26}
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 candidates = new Map<Element, string>();
51 let active: Element[] = [];
52 const observer = new IntersectionObserver(
53 (entries) => {
54 for (const entry of entries) {
55 if (entry.isIntersecting)
56 candidates.set(entry.target, (entry.target as HTMLElement).dataset.notebookOutput!);
57 else candidates.delete(entry.target);
58 }
59 // Bound browsing contexts even when a cell contains hundreds of tiny HTML outputs.
60 const next = [...candidates.keys()].slice(0, 16);
61 const measured = active
62 .filter((node) => !next.includes(node))
63 .map(
64 (node) =>
65 [
66 (node as HTMLElement).dataset.notebookOutput!,
67 node.getBoundingClientRect().height,
68 ] as const,
69 );
70 active = next;
71 setOutputView((old) => ({
72 mounted: new Set(next.map((node) => candidates.get(node)!)),
73 heights: new Map([...old.heights, ...measured]),
74 }));
75 },
76 { root, rootMargin: "160px" },
77 );
78 for (const node of root.querySelectorAll("[data-notebook-output]")) observer.observe(node);
79 return () => observer.disconnect();
80 }, [outputCount]);
81 return (
82 <>
83 <div
84 className="border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"
85 role="status"
86 >
87 {gt("{count, plural, one {{formatted} cell} other {{formatted} cells}}", {
88 count: props.notebook.cells.length,
89 formatted: props.notebook.cells.length.toLocaleString(),
90 })}{" "}
91 · {props.notebook.language}
92 {props.sizeBytes !== undefined
93 ? ` · ${props.sizeBytes === 0 ? gt("0 bytes") : formatAttachmentSize(props.sizeBytes, messages)}`
94 : ""}
95 </div>
96 <FileSurfaceNotice>
97 <T>Saved outputs only. Code is never executed.</T>
98 </FileSurfaceNotice>
99 <div ref={scroll} className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto">
100 <div className="mx-auto max-w-4xl space-y-5 px-5 py-6">
101 {props.notebook.cells.slice(0, visible).map((cell, index) => (
102 <section
103 key={index}
104 aria-label={gt("Cell {number}", { number: String(index + 1) })}
105 className="min-w-0 overflow-hidden rounded-md border border-border/60"
106 >
107 <div className="border-b border-border/60 bg-muted/30 px-3 py-1.5 text-xs text-muted-foreground">
108 {cell.kind === "code" ? props.notebook.language : cell.kind} · {index + 1}
109 </div>
110 {cell.kind === "markdown" ? (
111 <ChatMarkdown
112 text={cell.source}
113 cwd={undefined}
114 parseRawHtml={false}
115 extensions={NOTEBOOK_MARKDOWN}
116 className="px-4 py-3"
117 />
118 ) : cell.source.trim() ? (
119 <NotebookSource
120 name={`cell.${cell.kind === "code" ? (({ python: "py", javascript: "js", typescript: "ts", julia: "jl" } as Record<string, string>)[props.notebook.language] ?? props.notebook.language) : "txt"}`}
121 text={cell.source}
122 />
123 ) : null}
124 {cell.outputs.map((output, outputIndex) => (
125 <div
126 key={outputIndex}
127 data-notebook-output={
128 output.kind === "html" ? `${index}-${outputIndex}` : undefined
129 }
130 className="border-t border-border/60"
131 style={{
132 minHeight:
133 output.kind !== "html" || outputView.mounted.has(`${index}-${outputIndex}`)
134 ? undefined
135 : (outputView.heights.get(`${index}-${outputIndex}`) ?? 80),
136 }}
137 >
138 {output.kind === "html" ? (
139 !outputView.mounted.has(`${index}-${outputIndex}`) ? null : (
140 <DocumentPages
141 html={output.text}
142 name={gt("Cell {number} HTML output", { number: String(index + 1) })}
143 output
144 />
145 )
146 ) : output.kind === "image" ? (
147 <img
148 src={output.text}
149 alt={gt("Cell {number} output", { number: String(index + 1) })}
150 loading="lazy"
151 className="max-h-96 max-w-full p-4 object-contain"
152 />
153 ) : (
154 <pre className="overflow-x-auto p-4 text-xs whitespace-pre-wrap break-words">
155 {output.text}
156 </pre>
157 )}
158 </div>
159 ))}
160 </section>
161 ))}
162 {props.notebook.cells.length === 0 ? (
163 <p className="text-sm text-muted-foreground">
164 <T>This notebook is empty.</T>
165 </p>
166 ) : null}
167 {visible < props.notebook.cells.length ? (
168 <Button variant="outline" size="sm" onClick={() => setVisible((count) => count + 20)}>
169 {gt(
170 "{count, plural, one {Show more cells ({count} remaining)} other {Show more cells ({count} remaining)}}",
171 { count: props.notebook.cells.length - visible },
172 )}
173 </Button>
174 ) : null}
175 </div>
176 </div>
177 </>
178 );
179}