The best way to control Claude Code, Codex and more from any computer or phone

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