Open History to see the last commit
1import type { ScopedThreadRef } from "@t3tools/contracts";
2import { LegendList, type LegendListRef } from "@legendapp/list/react";
3import { useRef, type MouseEvent as ReactMouseEvent } from "react";
4
5import { normalizeMarkdownFragmentId } from "~/components/chat/markdownFragments";
6import { Spinner } from "~/components/ui/spinner";
7import type { MarkdownExtensions } from "~/markdown/wordsHast";
8import { FileMarkdownPreview } from "./FileMarkdownPreview";
9import { selectRenderedContentOnSelectAll } from "./fileSurfaceChrome";
10import { createPositionMemory, previewPositionKey } from "./previewPosition";
11import {
12 buildMarkdownFootnotesSection,
13 findFootnoteRefChunkIndex,
14 joinMarkdownChunks,
15 LARGE_MARKDOWN_CHUNK_MAX_CHARS,
16 type MarkdownChunk,
17 type MarkdownFootnotes,
18 type MarkdownFootnotesSection,
19 prepareMarkdownChunk,
20} from "@t3tools/shared/markdownChunks";
21
22const ESTIMATED_LINE_PX = 24;
23const FOOTNOTE_TARGET_ID = /^fn-\d+$/;
24const FOOTNOTE_REF_ID = /^fnref-(\d+)(?:-(\d+))?$/;
25
26const CHUNK_FOOTNOTES_OMIT: MarkdownExtensions = { footnotes: "omit" };
27const CHUNK_FOOTNOTES_OMIT_SEEDED: MarkdownExtensions = { footnotes: "omit-seeded" };
28const CHUNK_FOOTNOTES_ONLY: MarkdownExtensions = { footnotes: "only" };
29
30const savedPositions = createPositionMemory<{
31 readonly index: number;
32 readonly viewOffset: number;
33}>();
34
35type ChunkItem =
36 | {
37 readonly kind: "chunk";
38 readonly index: number;
39 readonly start: number;
40 readonly chunk: MarkdownChunk;
41 }
42 | {
43 readonly kind: "footnotes";
44 readonly index: number;
45 readonly section: MarkdownFootnotesSection;
46 };
47
48function findScopedFragmentTarget(
49 container: HTMLElement,
50 normalizedId: string,
51): HTMLElement | null {
52 for (const element of container.querySelectorAll<HTMLElement>("[id]")) {
53 if (normalizeMarkdownFragmentId(element.id) === normalizedId) return element;
54 }
55 return null;
56}
57
58/** Renders Markdown pieces in a virtualized list; task offsets are file offsets. */
59export function ChunkedMarkdown(props: {
60 readonly chunks: readonly MarkdownChunk[];
61 /** Link definitions from the whole file, so references resolve across pieces. */
62 readonly definitions: string;
63 /** Document-wide footnote metadata so references and definitions resolve across pieces. */
64 readonly footnotes?: MarkdownFootnotes | undefined;
65 /** Shows a spinner after the last chunk while more of the file streams in. */
66 readonly loading?: boolean;
67 readonly cwd: string;
68 readonly relativePath: string;
69 readonly threadRef: ScopedThreadRef;
70 readonly workspaceMutationId: string | null;
71 readonly onTaskListChange?:
72 | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void)
73 | undefined;
74}) {
75 const { chunks, onTaskListChange } = props;
76 const items: ChunkItem[] = [];
77 let start = 0;
78 let lines = 0;
79 for (const [index, chunk] of chunks.entries()) {
80 items.push({ kind: "chunk", index, start, chunk });
81 lines += chunk.lines;
82 start += chunk.text.length + 1;
83 }
84 const footnotesSection = buildMarkdownFootnotesSection(props.definitions, props.footnotes);
85 const footnotesItemIndex = footnotesSection !== null ? items.length : null;
86 if (footnotesSection !== null) {
87 items.push({ kind: "footnotes", index: items.length, section: footnotesSection });
88 }
89 const containerRef = useRef<HTMLDivElement | null>(null);
90 const listRef = useRef<LegendListRef | null>(null);
91 const positionKey = previewPositionKey(
92 props.threadRef.environmentId,
93 props.threadRef.threadId,
94 props.cwd,
95 props.relativePath,
96 );
97 const saved = savedPositions.get(positionKey);
98 // The list applies its initial index once, so wait for the saved chunk to stream in.
99 const awaitingSaved = props.loading && saved !== undefined && saved.index >= items.length;
100 const spinner = (
101 <div className="flex justify-center py-4">
102 <Spinner size="md" tone="muted" />
103 </div>
104 );
105 if (awaitingSaved) return spinner;
106
107 const handleFragmentClickCapture = (event: ReactMouseEvent<HTMLDivElement>) => {
108 // Without shared footnotes each piece keeps its own section, which ChatMarkdown resolves.
109 if (
110 !props.footnotes ||
111 event.defaultPrevented ||
112 event.button !== 0 ||
113 event.metaKey ||
114 event.ctrlKey ||
115 event.shiftKey ||
116 event.altKey
117 ) {
118 return;
119 }
120 const target = event.target;
121 if (!(target instanceof Element)) return;
122 const anchor = target.closest<HTMLAnchorElement>('a[href^="#"]');
123 if (!anchor) return;
124 const href = anchor.getAttribute("href");
125 if (!href) return;
126 const container = containerRef.current;
127 if (!container) return;
128
129 const normalizedId = normalizeMarkdownFragmentId(href);
130 const isFootnoteTarget = FOOTNOTE_TARGET_ID.test(normalizedId);
131 const refMatch = isFootnoteTarget ? null : FOOTNOTE_REF_ID.exec(normalizedId);
132 if (!isFootnoteTarget && !refMatch) return;
133
134 const local = findScopedFragmentTarget(container, normalizedId);
135 if (local) {
136 event.preventDefault();
137 event.stopPropagation();
138 local.scrollIntoView({ block: "start" });
139 return;
140 }
141
142 let targetIndex: number | null = null;
143 if (isFootnoteTarget) {
144 targetIndex = footnotesItemIndex;
145 } else if (refMatch) {
146 const fnNumber = Number(refMatch[1]);
147 const occurrence = refMatch[2] ? Number(refMatch[2]) : 1;
148 targetIndex = findFootnoteRefChunkIndex(props.footnotes, fnNumber, occurrence);
149 }
150 if (targetIndex === null || !listRef.current) return;
151
152 event.preventDefault();
153 event.stopPropagation();
154 void listRef.current
155 .scrollToIndex({ index: targetIndex, viewPosition: 0, animated: false })
156 .then(() => {
157 const mounted = containerRef.current
158 ? findScopedFragmentTarget(containerRef.current, normalizedId)
159 : null;
160 mounted?.scrollIntoView({ block: "start" });
161 });
162 };
163
164 // Rows re-render only when this changes; a new workspace revision re-mints their images.
165 const extraData = `${props.workspaceMutationId ?? ""}\0${
166 props.footnotes
167 ? `${props.definitions}\0${props.footnotes.stubs}\0${props.footnotes.definitions}\0${props.footnotes.chunkRefs.map((refs) => refs.join(",")).join("|")}`
168 : props.definitions
169 }`;
170
171 return (
172 <div
173 ref={containerRef}
174 // Clicking the text focuses the preview, so Select All stays inside it.
175 tabIndex={-1}
176 className="flex min-h-0 flex-1 flex-col outline-none"
177 onClickCapture={handleFragmentClickCapture}
178 onKeyDown={selectRenderedContentOnSelectAll}
179 onCopy={(event) => {
180 // Select All only reaches rendered pieces; copying all of it copies the whole file.
181 const list = event.currentTarget.firstElementChild;
182 const selection = window.getSelection();
183 if (!list || !selection?.rangeCount) return;
184 // Chromium's containsNode says false for a list selected through its parent's children.
185 const range = selection.getRangeAt(0);
186 const listRange = document.createRange();
187 listRange.selectNode(list);
188 if (
189 range.compareBoundaryPoints(Range.START_TO_START, listRange) > 0 ||
190 range.compareBoundaryPoints(Range.END_TO_END, listRange) < 0
191 ) {
192 return;
193 }
194 event.preventDefault();
195 // A rendered piece's own handler already wrote just its part.
196 event.clipboardData.clearData();
197 event.clipboardData.setData("text/plain", joinMarkdownChunks(chunks));
198 }}
199 >
200 <LegendList<ChunkItem>
201 // The panel keeps this mounted across threads; the initial index only applies on mount.
202 key={positionKey}
203 ref={listRef}
204 data={items}
205 {...(saved && {
206 initialScrollIndex: {
207 index: Math.min(saved.index, Math.max(items.length - 1, 0)),
208 viewOffset: saved.viewOffset,
209 },
210 })}
211 onScroll={() => {
212 const list = listRef.current?.getState();
213 if (!list) return;
214 savedPositions.set(positionKey, {
215 index: list.start,
216 viewOffset: list.positionAtIndex(list.start) - list.scroll,
217 });
218 }}
219 extraData={extraData}
220 keyExtractor={(item) => (item.kind === "footnotes" ? "footnotes" : String(item.index))}
221 estimatedItemSize={(lines / Math.max(items.length, 1)) * ESTIMATED_LINE_PX}
222 drawDistance={800}
223 recycleItems={false}
224 className="h-full scrollbar-gutter-both"
225 contentContainerClassName="py-5"
226 ListFooterComponent={props.loading ? spinner : null}
227 renderItem={({ item }) => {
228 if (item.kind === "footnotes") {
229 return (
230 <div className="pb-5">
231 <FileMarkdownPreview
232 text={item.section.text}
233 cwd={props.cwd}
234 relativePath={props.relativePath}
235 threadRef={props.threadRef}
236 workspaceMutationId={props.workspaceMutationId}
237 className="mx-auto max-w-4xl px-6"
238 extensions={CHUNK_FOOTNOTES_ONLY}
239 onTaskListChange={
240 onTaskListChange &&
241 ((input) => {
242 const markerOffset = item.section.fileOffset(input.markerOffset);
243 if (markerOffset !== null) {
244 onTaskListChange({ markerOffset, checked: input.checked });
245 }
246 })
247 }
248 />
249 </div>
250 );
251 }
252 if (item.chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS) {
253 return (
254 <div className="pb-5">
255 {/* One block this long (a huge fence or HTML block) is too slow to parse. */}
256 <pre className="mx-auto max-w-4xl overflow-x-auto px-6 font-mono text-xs whitespace-pre">
257 {item.chunk.text}
258 </pre>
259 </div>
260 );
261 }
262 const prepared = prepareMarkdownChunk(
263 item.chunk.text,
264 item.index,
265 props.definitions,
266 props.footnotes,
267 );
268 const extensions =
269 prepared.footnotesMode === "omit-seeded"
270 ? CHUNK_FOOTNOTES_OMIT_SEEDED
271 : prepared.footnotesMode === "omit"
272 ? CHUNK_FOOTNOTES_OMIT
273 : undefined;
274 return (
275 <div className="pb-5">
276 <FileMarkdownPreview
277 text={prepared.text}
278 cwd={props.cwd}
279 relativePath={props.relativePath}
280 threadRef={props.threadRef}
281 workspaceMutationId={props.workspaceMutationId}
282 className="mx-auto max-w-4xl px-6"
283 extensions={extensions}
284 onTaskListChange={
285 onTaskListChange &&
286 ((input) =>
287 onTaskListChange({
288 markerOffset: item.start + input.markerOffset - prepared.offsetShift,
289 checked: input.checked,
290 }))
291 }
292 />
293 </div>
294 );
295 }}
296 />
297 </div>
298 );
299}