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

VirtualTablePreview.tsx

507 lines20.5 KB

1/* oxlint-disable react/no-array-index-key -- Positions identify source rows and columns. */
2import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
3import { observeResize } from "~/lib/observeResize";
4import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
5import { PREVIEW_PAGE_ROWS } from "./largeTextProtocol";
6​
7export default function VirtualTablePreview(props: {
8 readonly name: string;
9 readonly count: number;
10 readonly columns: number;
11 readonly getRows: (page: number) => readonly (readonly string[])[] | undefined;
12 readonly loadPage?: (page: number) => void;
13 readonly header?: readonly string[] | undefined;
14 readonly source?: boolean;
15 readonly wrap?: boolean;
16 readonly revealLine?: number | null;
17 readonly revealRequestId?: number;
18}) {
19 const ref = useRef<HTMLDivElement>(null);
20 const [left, setLeft] = useState(0);
21 const [size, setSize] = useState({ width: 0, height: 600 });
22 const { width } = size;
23 const widthRef = useRef(0);
24 const measureRef = useRef<HTMLTableElement>(null);
25 const [measured, setMeasured] = useState<number[] | null>(null);
26 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure the viewport before paint and observe container resizes to invalidate column measurements.
27 useLayoutEffect(() => {
28 const node = ref.current;
29 if (!node) return;
30 const update = () => {
31 const width = node.clientWidth;
32 const height = node.clientHeight;
33 setSize((old) => (old.width === width && old.height === height ? old : { width, height }));
34 if (widthRef.current !== width) {
35 widthRef.current = width;
36 setMeasured(null);
37 }
38 };
39 update();
40 return observeResize(node, update);
41 }, []);
42 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Read the browser's laid-out table column widths before displaying the virtual table.
43 useLayoutEffect(() => {
44 if (!width || !props.header || !measureRef.current || measured) return;
45 const widths = [...measureRef.current.querySelectorAll("thead th")].map(
46 (cell) => cell.getBoundingClientRect().width,
47 );
48 if (widths.length) setMeasured(widths);
49 }, [measured, width, props.header]);
50 const columnWidth = props.source
51 ? 0
52 : Math.max(128, Math.min(320, (width - 56) / Math.min(props.columns, 6)));
53 const rowHeader = 56;
54 const sizes = Array.from(
55 { length: props.columns },
56 (_, column) => measured?.[column] ?? columnWidth,
57 );
58 const offsets = [0];
59 for (const size of sizes) offsets.push(offsets[offsets.length - 1]! + size);
60 const firstColumn = props.source
61 ? 0
62 : Math.max(0, sizes.findIndex((_, column) => offsets[column + 1]! > left - rowHeader) - 1);
63 const lastColumn = props.source
64 ? 1
65 : Math.min(
66 props.columns,
67 offsets.findIndex((offset) => offset >= left + width - rowHeader) + 1 || props.columns,
68 );
69 const columns = Array.from(
70 { length: Math.max(0, lastColumn - firstColumn) },
71 (_, i) => firstColumn + i,
72 );
73 const offset = (column: number) => offsets[column]!;
74 const tableWidth = props.source ? "100%" : Math.max(width, offset(props.columns) + rowHeader);
75 return (
76 <div
77 ref={ref}
78 className="relative min-h-0 flex-1 overflow-x-auto contain-strict"
79 onScroll={(event) => {
80 event.currentTarget.style.setProperty(
81 "--preview-scroll-left",
82 `${event.currentTarget.scrollLeft}px`,
83 );
84 setLeft(event.currentTarget.scrollLeft);
85 }}
86 >
87 {props.header && props.columns <= 30 && !measured && width > 0 ? (
88 <table
89 ref={measureRef}
90 aria-hidden="true"
91 className="invisible absolute top-0 border-separate border-spacing-0 text-xs"
92 style={{ width: Math.max(width - rowHeader, props.columns * 128) }}
93 >
94 <thead>
95 <tr>
96 {props.header.map((cell, i) => (
97 <th
98 key={i}
99 className="min-w-32 max-w-80 border-b px-3 py-1.5 text-left font-medium whitespace-nowrap"
100 >
101 {cell}
102 </th>
103 ))}
104 </tr>
105 </thead>
106 <tbody>
107 {props
108 .getRows(0)
109 ?.slice(1, 20)
110 .map((row, i) => (
111 <tr key={i}>
112 {row.map((cell, j) => (
113 <td
114 key={j}
115 className="max-w-80 border-b px-3 py-1.5 whitespace-pre-wrap break-words tabular-nums"
116 >
117 {cell}
118 </td>
119 ))}
120 </tr>
121 ))}
122 </tbody>
123 </table>
124 ) : null}
125 {width > 0 && (!props.header || props.columns > 30 || measured) ? (
126 <div
127 role={props.source ? "region" : "table"}
128 aria-label={props.name}
129 aria-rowcount={props.count}
130 aria-colcount={props.source ? undefined : props.columns}
131 className="flex h-full min-h-0 flex-col text-xs"
132 style={{ width: tableWidth }}
133 >
134 {!props.source ? (
135 <div
136 role="row"
137 className="relative z-10 flex min-h-[29px] shrink-0 border-b border-border bg-muted/60 font-medium backdrop-blur"
138 >
139 <div className="sticky left-0 z-10 w-14 shrink-0 border-r border-border bg-background" />
140 <div style={{ width: offset(firstColumn), flexShrink: 0 }} />
141 {columns.map((column) => (
142 <Tooltip key={column}>
143 <TooltipTrigger
144 render={
145 <div
146 role="columnheader"
147 aria-colindex={column + 1}
148 className="shrink-0 overflow-hidden border-r border-border/40 px-3 py-1.5 text-ellipsis whitespace-pre"
149 style={{ width: sizes[column] }}
150 >
151 {props.header?.[column] ?? columnLabel(column)}
152 </div>
153 }
154 />
155 <TooltipPopup>{props.header?.[column] ?? columnLabel(column)}</TooltipPopup>
156 </Tooltip>
157 ))}
158 </div>
159 ) : null}
160 <ScaledRows
161 {...props}
162 columnsVisible={columns}
163 sizes={sizes}
164 rowHeader={rowHeader}
165 firstColumn={firstColumn}
166 viewportHeight={size.height - (props.source ? 0 : 29)}
167 />
168 </div>
169 ) : null}
170 </div>
171 );
173function RowPage(
174 props: Parameters<typeof VirtualTablePreview>[0] & {
175 page: number;
176 columnsVisible: number[];
177 sizes: number[];
178 rowHeader: number;
179 firstColumn: number;
180 viewportHeight: number;
181 limit?: number;
182 },
183) {
184 const rows = props.getRows(props.page);
185 // A page stays mounted while the worker fills it, preserving the scroll position.
186 const { loadPage, page } = props;
187 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Request this page's rows from the indexing worker when they are missing or incomplete.
188 useEffect(() => {
189 const expected = Math.min(PREVIEW_PAGE_ROWS, props.count - page * PREVIEW_PAGE_ROWS);
190 if (!rows || rows.length < expected) loadPage?.(page);
191 }, [rows, page, loadPage, props.count]);
192 const start = props.page * PREVIEW_PAGE_ROWS;
193 const count = Math.min(PREVIEW_PAGE_ROWS, props.count - start, props.limit ?? PREVIEW_PAGE_ROWS);
194 return (
195 <div role="rowgroup">
196 {Array.from({ length: count }, (_, local) => {
197 const row = rows?.[local];
198 const index = start + local;
199 if (props.header && index === 0) return null;
200 return (
201 <div
202 key={local}
203 data-preview-row={index}
204 role={props.source ? undefined : "row"}
205 aria-rowindex={props.source ? undefined : index + 1}
206 className={
207 props.source
208 ? `flex min-h-[29px] font-mono ${props.revealLine != null && Math.min(props.count, Math.max(1, props.revealLine)) === index + 1 ? "bg-primary/10" : ""}`
209 : `flex min-h-[29px] border-b border-border/60 ${(index - (props.header ? 1 : 0)) % 2 ? "bg-muted/30" : ""}`
210 }
211 data-preview-reveal={
212 props.revealLine != null &&
213 Math.min(props.count, Math.max(1, props.revealLine)) === index + 1
214 ? "true"
215 : undefined
216 }
217 >
218 <div
219 role={props.source ? undefined : "rowheader"}
220 className={`${props.source ? "sticky left-0" : "relative"} z-1 shrink-0 border-r border-border bg-background px-2 py-1.5 text-right font-normal text-muted-foreground tabular-nums select-none`}
221 style={{
222 width: props.rowHeader,
223 transform: props.source ? undefined : "translateX(var(--preview-scroll-left, 0px))",
224 }}
225 >
226 <span className="sticky top-0 block">{index + (props.header ? 0 : 1)}</span>
227 </div>
228 {!props.source ? (
229 <div
230 style={{
231 width: props.sizes.slice(0, props.firstColumn).reduce((a, b) => a + b, 0),
232 flexShrink: 0,
233 }}
234 />
235 ) : null}
236 {props.columnsVisible.map((column) => (
237 <div
238 key={column}
239 role={props.source ? undefined : "cell"}
240 aria-colindex={props.source ? undefined : column + 1}
241 className={
242 props.source
243 ? `min-w-0 flex-1 px-3 py-1 ${props.wrap ? "whitespace-pre-wrap break-words" : "whitespace-pre"}`
244 : "shrink-0 border-r border-border/40 px-3 py-1.5 whitespace-pre-wrap break-words tabular-nums"
245 }
246 style={props.source ? undefined : { width: props.sizes[column] }}
247 >
248 {row?.[column] ?? ""}
249 </div>
250 ))}
251 </div>
252 );
253 })}
254 </div>
255 );
257​
258function ScaledRows(props: Omit<Parameters<typeof RowPage>[0], "page">) {
259 const ref = useRef<HTMLDivElement>(null);
260 const contentRef = useRef<HTMLDivElement>(null);
261 const [layout, setLayout] = useState({ offset: 0, height: 0, rowHeight: 29 });
262 const [top, setTop] = useState(0);
263 const handledReveal = useRef<string | null>(null);
264 const pendingReveal = useRef<{ row: number; attempts: number } | null>(null);
265 const pendingEnd = useRef(false);
266 const position = { top, height: props.viewportHeight };
267 const scrollHeight = Math.min(8_000_000, props.count * 29);
268 // Chromium caps a scroll surface at 33 million pixels. Scale the track for
269 // multi-million-line logs while retaining real row heights in the viewport.
270 const headerRows = props.header ? 1 : 0;
271 const maxFirst = Math.max(0, props.count - headerRows - Math.floor(position.height / 29));
272 const scale = Math.max(1, scrollHeight - position.height) / Math.max(1, maxFirst * 29);
273 const first = Math.min(maxFirst, Math.floor(position.top / scale / 29)) + headerRows;
274 // The final mounted rows keep their measured height and scroll natively.
275 const nativeTail = first - headerRows === maxFirst;
276 const scrollModel = useRef({ scale, maxFirst, heights: [] as number[] });
277 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure native tail rows and preserve the DOM scroll position when the virtual track scale changes.
278 useLayoutEffect(() => {
279 const previous = scrollModel.current;
280 const heights = nativeTail
281 ? Array.from(contentRef.current?.querySelectorAll<HTMLElement>("[data-preview-row]") ?? [])
282 .filter((row) => Number(row.dataset.previewRow) >= first)
283 .map((row) => row.offsetHeight)
284 : [];
285 scrollModel.current = { scale, maxFirst, heights };
286 const node = ref.current;
287 if (!node || (previous.scale === scale && previous.maxFirst === maxFirst)) return;
288 const previousEnd = previous.maxFirst * 29 * previous.scale;
289 let logicalTop = Math.min(previous.maxFirst * 29, node.scrollTop / previous.scale);
290 let remaining = Math.max(0, node.scrollTop - previousEnd);
291 // Native-tail pixels cross rows of different heights before returning to the scaled track.
292 for (const height of previous.heights) {
293 logicalTop += Math.min(1, remaining / height) * 29;
294 remaining = Math.max(0, remaining - height);
295 if (!remaining) break;
296 }
297 let nativeOffset = 0;
298 remaining = Math.max(0, logicalTop / 29 - maxFirst);
299 for (const height of heights) {
300 nativeOffset += Math.min(1, remaining) * height;
301 remaining = Math.max(0, remaining - 1);
302 if (!remaining) break;
303 }
304 node.scrollTop = Math.min(maxFirst * 29, logicalTop) * scale + nativeOffset;
305 setTop(node.scrollTop);
306 });
307 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll the DOM viewport to a requested line after its virtual track has committed.
308 useLayoutEffect(() => {
309 const node = ref.current;
310 if (props.revealLine == null) {
311 handledReveal.current = null;
312 pendingReveal.current = null;
313 return;
314 }
315 const key = `${props.revealRequestId}:${props.revealLine}`;
316 if (!node || !props.count || handledReveal.current === key) return;
317 const row = Math.min(props.count, Math.max(1, props.revealLine)) - 1;
318 node.scrollTop = Math.max(0, (row - headerRows) * 29) * scale;
319 setTop(node.scrollTop);
320 pendingEnd.current = false;
321 pendingReveal.current = { row, attempts: 0 };
322 handledReveal.current = key;
323 }, [props.revealLine, props.revealRequestId, props.count, headerRows, scale]);
324 const atStart = position.top === 0;
325 const rowHeight = () =>
326 contentRef.current?.querySelector<HTMLElement>(`[data-preview-row="${first}"]`)?.offsetHeight ||
327 29;
328 const onWheel = useEffectEvent((event: WheelEvent) => {
329 const node = ref.current;
330 if (!node || event.ctrlKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)) return;
331 const delta =
332 event.deltaY * (event.deltaMode === 1 ? 29 : event.deltaMode === 2 ? node.clientHeight : 1);
333 if (!delta) return;
334 event.preventDefault();
335 pendingEnd.current = false;
336 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / rowHeight());
337 });
338 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Install a non-passive native wheel listener so virtual scrolling can prevent the browser's default scroll.
339 useEffect(() => {
340 const node = ref.current;
341 if (!node) return;
342 const wheel = (event: WheelEvent) => onWheel(event);
343 node.addEventListener("wheel", wheel, { passive: false });
344 return () => {
345 node.removeEventListener("wheel", wheel);
346 };
347 }, []);
348 const page = Math.floor(first / PREVIEW_PAGE_ROWS);
349 const visibleEnd = (first % PREVIEW_PAGE_ROWS) + Math.ceil(position.height / 29) + 1;
350 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure mounted row offsets and observe content resizes to position the virtual rows against the scroll track.
351 useLayoutEffect(() => {
352 if (atStart) return;
353 const node = contentRef.current;
354 if (!node) return;
355 const update = () => {
356 const row = node.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
357 const offset = row ? row.getBoundingClientRect().top - node.getBoundingClientRect().top : 0;
358 const height = node.clientHeight;
359 const rowHeight = row?.offsetHeight || 29;
360 setLayout((old) =>
361 old.offset === offset && old.height === height && old.rowHeight === rowHeight
362 ? old
363 : { offset, height, rowHeight },
364 );
365 };
366 update();
367 return observeResize(node, update);
368 }, [first, atStart]);
369 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Correct the DOM scroll position once a requested worker row has loaded and its actual bounds are measurable.
370 useLayoutEffect(() => {
371 const pending = pendingReveal.current;
372 const node = ref.current;
373 const row =
374 pending &&
375 contentRef.current?.querySelector<HTMLElement>(`[data-preview-row="${pending.row}"]`);
376 if (
377 !pending ||
378 !node ||
379 !row ||
380 !props.getRows(Math.floor(pending.row / PREVIEW_PAGE_ROWS))?.[pending.row % PREVIEW_PAGE_ROWS]
381 )
382 return;
383 const content = contentRef.current!;
384 const firstRow = content.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
385 if (
386 !atStart &&
387 (layout.height !== content.clientHeight ||
388 layout.offset !==
389 (firstRow
390 ? firstRow.getBoundingClientRect().top - content.getBoundingClientRect().top
391 : 0))
392 )
393 return;
394 const bounds = row.getBoundingClientRect();
395 const viewport = node.getBoundingClientRect();
396 const delta =
397 bounds.top < viewport.top
398 ? bounds.top - viewport.top
399 : Math.min(bounds.bottom, bounds.top + viewport.height) > viewport.bottom
400 ? Math.min(bounds.bottom, bounds.top + viewport.height) - viewport.bottom
401 : 0;
402 if (Math.abs(delta) < 1 || pending.attempts++ >= 8) {
403 pendingReveal.current = null;
404 return;
405 }
406 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / Math.max(29, bounds.height));
407 setTop(node.scrollTop);
408 });
409 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Complete End-key scrolling after the final worker row has loaded and its DOM layout has settled.
410 useLayoutEffect(() => {
411 const node = ref.current;
412 const content = contentRef.current;
413 if (!pendingEnd.current || !nativeTail || !node || !content || !props.count) return;
414 const last = props.count - 1;
415 if (!props.getRows(Math.floor(last / PREVIEW_PAGE_ROWS))?.[last % PREVIEW_PAGE_ROWS]) return;
416 const row = content.querySelector<HTMLElement>(`[data-preview-row="${last}"]`);
417 const firstRow = content.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
418 if (
419 !row ||
420 (!atStart &&
421 (layout.height !== content.clientHeight ||
422 layout.offset !==
423 (firstRow
424 ? firstRow.getBoundingClientRect().top - content.getBoundingClientRect().top
425 : 0)))
426 )
427 return;
428 node.scrollTop = node.scrollHeight;
429 setTop(node.scrollTop);
430 if (Math.abs(row.getBoundingClientRect().bottom - node.getBoundingClientRect().bottom) < 1)
431 pendingEnd.current = false;
432 });
433 return (
434 <div
435 ref={ref}
436 tabIndex={0}
437 className="min-h-0 flex-1 overflow-auto"
438 onKeyDown={(event) => {
439 const node = event.currentTarget;
440 const delta =
441 event.key === "ArrowDown"
442 ? 29
443 : event.key === "ArrowUp"
444 ? -29
445 : event.key === "PageDown"
446 ? node.clientHeight
447 : event.key === "PageUp"
448 ? -node.clientHeight
449 : null;
450 if (delta !== null) {
451 pendingEnd.current = false;
452 event.preventDefault();
453 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / rowHeight());
454 } else if (event.key === "Home" || event.key === "End") {
455 event.preventDefault();
456 pendingEnd.current = event.key === "End";
457 pendingReveal.current = null;
458 node.scrollTop = event.key === "Home" ? 0 : node.scrollHeight;
459 setTop(node.scrollTop);
460 }
461 }}
462 onScroll={(event) => setTop(event.currentTarget.scrollTop)}
463 >
464 <div className="relative" style={{ height: scrollHeight }}>
465 <div
466 ref={contentRef}
467 className="absolute inset-x-0"
468 style={{
469 top:
470 maxFirst === 0
471 ? 0
472 : nativeTail
473 ? maxFirst * scale * 29 - layout.offset
474 : position.top +
475 (atStart
476 ? 0
477 : -layout.offset - ((position.top / scale / 29) % 1) * layout.rowHeight),
478 }}
479 >
480 {Array.from(
481 {
482 length: Math.min(
483 Math.ceil(visibleEnd / PREVIEW_PAGE_ROWS),
484 Math.ceil(props.count / PREVIEW_PAGE_ROWS) - page,
485 ),
486 },
487 (_, offset) => (
488 <RowPage
489 key={page + offset}
490 {...props}
491 page={page + offset}
492 limit={visibleEnd - offset * PREVIEW_PAGE_ROWS}
493 />
494 ),
495 )}
496 </div>
497 </div>
498 </div>
499 );
501​
502function columnLabel(index: number): string {
503 let label = "";
504 for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26))
505 label = String.fromCharCode(65 + ((value - 1) % 26)) + label;
506 return label;