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

VirtualTablePreview.tsx

970 lines38.1 KB

1/* oxlint-disable react/no-array-index-key -- Positions identify source rows and columns. */
2import { useContext, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
3import { useClientSettings } from "~/hooks/useSettings";
4import { observeResize } from "~/lib/observeResize";
5import { PREVIEW_PAGE_ROWS } from "./largeTextProtocol";
6import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip";
7import { selectRenderedContentOnSelectAll } from "./fileSurfaceChrome";
8import { createPositionMemory, PreviewPositionKey } from "./previewPosition";
9​
10const savedRowPositions = createPositionMemory<{
11 position: number | "end";
12 revealKey: string | null;
13}>();
14​
15export default function VirtualTablePreview(props: {
16 readonly name: string;
17 readonly count: number;
18 readonly columns: number;
19 readonly getRows: (page: number) => readonly (readonly string[])[] | undefined;
20 readonly loadPage?: (page: number) => void;
21 readonly indexing?: boolean;
22 readonly onCopyAll?: (clipboard: DataTransfer) => void;
23 readonly header?: readonly string[] | undefined;
24 readonly rowIndexes?: readonly number[] | undefined;
25 readonly columnIndexes?: readonly number[] | undefined;
26 readonly source?: boolean;
27 readonly wrap?: boolean;
28 readonly revealLine?: number | null;
29 readonly revealRequestId?: number;
30}) {
31 const ref = useRef<HTMLDivElement>(null);
32 const [left, setLeft] = useState(0);
33 const [size, setSize] = useState({ width: 0, height: 600 });
34 const { width } = size;
35 const widthRef = useRef(0);
36 const measureRef = useRef<HTMLTableElement>(null);
37 const [measured, setMeasured] = useState<number[] | null>(null);
38 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure the viewport before paint and observe container resizes to invalidate column measurements.
39 useLayoutEffect(() => {
40 const node = ref.current;
41 if (!node) return;
42 const update = () => {
43 const width = node.clientWidth;
44 const height = node.clientHeight;
45 setSize((old) => (old.width === width && old.height === height ? old : { width, height }));
46 if (widthRef.current !== width) {
47 widthRef.current = width;
48 setMeasured(null);
49 }
50 };
51 update();
52 return observeResize(node, update);
53 }, []);
54 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Read the browser's laid-out table column widths before displaying the virtual table.
55 useLayoutEffect(() => {
56 if (!width || !props.header || !measureRef.current || measured) return;
57 const widths = [...measureRef.current.querySelectorAll("thead th")].map(
58 (cell) => cell.getBoundingClientRect().width,
59 );
60 if (widths.length) setMeasured(widths);
61 }, [measured, width, props.header]);
62 const columnWidth = props.source
63 ? 0
64 : Math.max(128, Math.min(320, (width - 56) / Math.min(props.columns, 6)));
65 const rowHeader = 56;
66 const sizes = Array.from(
67 { length: props.columns },
68 (_, column) => measured?.[column] ?? columnWidth,
69 );
70 const offsets = [0];
71 for (const size of sizes) offsets.push(offsets[offsets.length - 1]! + size);
72 const firstColumn = props.source
73 ? 0
74 : Math.max(0, sizes.findIndex((_, column) => offsets[column + 1]! > left - rowHeader) - 1);
75 const lastColumn = props.source
76 ? 1
77 : Math.min(
78 props.columns,
79 offsets.findIndex((offset) => offset >= left + width - rowHeader) + 1 || props.columns,
80 );
81 const columns = Array.from(
82 { length: Math.max(0, lastColumn - firstColumn) },
83 (_, i) => firstColumn + i,
84 );
85 const offset = (column: number) => offsets[column]!;
86 const tableWidth = props.source ? "100%" : Math.max(width, offset(props.columns) + rowHeader);
87 const hasHorizontalOverflow = !props.source && offset(props.columns) + rowHeader > width;
88 return (
89 <div
90 ref={ref}
91 className="relative min-h-0 flex-1 overflow-x-auto contain-strict"
92 onScroll={(event) => {
93 event.currentTarget.style.setProperty(
94 "--preview-scroll-left",
95 `${event.currentTarget.scrollLeft}px`,
96 );
97 setLeft(event.currentTarget.scrollLeft);
98 }}
99 >
100 {props.header && props.columns <= 30 && !measured && width > 0 ? (
101 <table
102 ref={measureRef}
103 aria-hidden="true"
104 className="invisible absolute top-0 border-separate border-spacing-0 text-xs"
105 style={{ width: Math.max(width - rowHeader, props.columns * 128) }}
106 >
107 <thead>
108 <tr>
109 {props.header.map((cell, i) => (
110 <th
111 key={i}
112 className="min-w-32 max-w-80 border-b px-3 py-1.5 text-left font-medium whitespace-nowrap"
113 >
114 {cell}
115 </th>
116 ))}
117 </tr>
118 </thead>
119 <tbody>
120 {props
121 .getRows(0)
122 ?.slice(1, 20)
123 .map((row, i) => (
124 <tr key={i}>
125 {row.map((cell, j) => (
126 <td
127 key={j}
128 className="max-w-80 border-b px-3 py-1.5 whitespace-pre-wrap break-words tabular-nums"
129 >
130 {cell}
131 </td>
132 ))}
133 </tr>
134 ))}
135 </tbody>
136 </table>
137 ) : null}
138 {width > 0 && (!props.header || props.columns > 30 || measured) ? (
139 <div
140 role={props.source ? "region" : "table"}
141 aria-label={props.name}
142 aria-rowcount={props.count}
143 aria-colcount={props.source ? undefined : props.columns}
144 className="flex h-full min-h-0 flex-col text-xs"
145 style={{ width: tableWidth }}
146 onKeyDown={selectRenderedContentOnSelectAll}
147 onCopy={
148 props.onCopyAll
149 ? (event) => {
150 const table = event.currentTarget;
151 const selection = table.ownerDocument.getSelection();
152 if (selection?.rangeCount !== 1 || selection.isCollapsed) return;
153 const range = selection.getRangeAt(0);
154 if (
155 range.startContainer !== table ||
156 range.startOffset !== 0 ||
157 range.endContainer !== table ||
158 range.endOffset !== table.childNodes.length
159 )
160 return;
161 event.preventDefault();
162 props.onCopyAll?.(event.clipboardData);
163 }
164 : undefined
165 }
166 >
167 {!props.source ? (
168 <div
169 role="row"
170 className="relative z-10 flex min-h-[29px] shrink-0 border-b border-border bg-muted/60 font-medium backdrop-blur"
171 >
172 <div className="sticky left-0 z-10 w-14 shrink-0 border-r border-border bg-background" />
173 <div style={{ width: offset(firstColumn), flexShrink: 0 }} />
174 {columns.map((column) => (
175 <SharedTooltipTrigger
176 key={column}
177 render={
178 <div
179 role="columnheader"
180 aria-colindex={column + 1}
181 className="shrink-0 overflow-hidden border-r border-border/40 px-3 py-1.5 text-ellipsis whitespace-pre"
182 style={{ width: sizes[column] }}
183 >
184 {props.header?.[column] ??
185 columnLabel(props.columnIndexes?.[column] ?? column)}
186 </div>
187 }
188 label={
189 props.header?.[column] ?? columnLabel(props.columnIndexes?.[column] ?? column)
190 }
191 />
192 ))}
193 </div>
194 ) : null}
195 <ScaledRows
196 {...props}
197 columnsVisible={columns}
198 sizes={sizes}
199 hasHorizontalOverflow={hasHorizontalOverflow}
200 rowHeader={rowHeader}
201 firstColumn={firstColumn}
202 viewportHeight={size.height - (props.source ? 0 : 29)}
203 />
204 </div>
205 ) : null}
206 </div>
207 );
209function RowPage(
210 props: Parameters<typeof VirtualTablePreview>[0] & {
211 page: number;
212 columnsVisible: number[];
213 sizes: number[];
214 rowHeights?: ReadonlyMap<number, number> | undefined;
215 rowHeader: number;
216 firstColumn: number;
217 viewportHeight: number;
218 limit?: number;
219 },
220) {
221 const rows = props.getRows(props.page);
222 // A page stays mounted while the worker fills it, preserving the scroll position.
223 const { loadPage, page } = props;
224 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Request this page's rows from the indexing worker when they are missing or incomplete.
225 useEffect(() => {
226 const expected = Math.min(PREVIEW_PAGE_ROWS, props.count - page * PREVIEW_PAGE_ROWS);
227 if (!rows || rows.length < expected) loadPage?.(page);
228 }, [rows, page, loadPage, props.count]);
229 const start = props.page * PREVIEW_PAGE_ROWS;
230 const count = Math.min(PREVIEW_PAGE_ROWS, props.count - start, props.limit ?? PREVIEW_PAGE_ROWS);
231 return (
232 <div role="rowgroup">
233 {Array.from({ length: count }, (_, local) => {
234 const row = rows?.[local];
235 const index = start + local;
236 if (props.header && index === 0) return null;
237 const rowMinHeight = !props.source && row ? props.rowHeights?.get(index) : undefined;
238 return (
239 <div
240 key={local}
241 data-preview-row={index}
242 role={props.source ? undefined : "row"}
243 aria-rowindex={props.source ? undefined : index + 1}
244 className={
245 props.source
246 ? `flex min-h-[29px] font-mono ${props.revealLine != null && Math.min(props.count, Math.max(1, props.revealLine)) === index + 1 ? "bg-primary/10" : ""}`
247 : `flex min-h-[29px] border-b border-border/60 ${(index - (props.header ? 1 : 0)) % 2 ? "bg-muted/30" : ""}`
248 }
249 style={rowMinHeight ? { minHeight: rowMinHeight } : undefined}
250 data-preview-reveal={
251 props.revealLine != null &&
252 Math.min(props.count, Math.max(1, props.revealLine)) === index + 1
253 ? "true"
254 : undefined
255 }
256 >
257 <div
258 role={props.source ? undefined : "rowheader"}
259 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`}
260 style={{
261 width: props.rowHeader,
262 transform: props.source ? undefined : "translateX(var(--preview-scroll-left, 0px))",
263 }}
264 >
265 <span className="sticky top-0 block">
266 {(props.rowIndexes?.[index] ?? index - (props.header ? 1 : 0)) + 1}
267 </span>
268 </div>
269 {!props.source ? (
270 <div
271 style={{
272 width: props.sizes.slice(0, props.firstColumn).reduce((a, b) => a + b, 0),
273 flexShrink: 0,
274 }}
275 />
276 ) : null}
277 {props.columnsVisible.map((column) => (
278 <div
279 key={column}
280 role={props.source ? undefined : "cell"}
281 aria-colindex={props.source ? undefined : column + 1}
282 className={
283 props.source
284 ? `min-w-0 flex-1 px-3 py-1 ${props.wrap ? "whitespace-pre-wrap break-words" : "whitespace-pre"}`
285 : "shrink-0 border-r border-border/40 px-3 py-1.5 whitespace-pre-wrap break-words tabular-nums"
286 }
287 style={props.source ? undefined : { width: props.sizes[column] }}
288 >
289 {row?.[column] ?? ""}
290 </div>
291 ))}
292 </div>
293 );
294 })}
295 </div>
296 );
298​
299interface ScrollModel {
300 scale: number;
301 maxFirst: number;
302 heights: number[];
304​
305function logicalScrollTop(scrollTop: number, model: ScrollModel): number {
306 const trackEnd = model.maxFirst * 29;
307 let logicalTop = Math.min(trackEnd, scrollTop / model.scale);
308 let remaining = Math.max(0, scrollTop - trackEnd * model.scale);
309 for (const height of model.heights) {
310 if (!remaining) break;
311 logicalTop += Math.min(1, remaining / height) * 29;
312 remaining = Math.max(0, remaining - height);
313 }
314 return logicalTop;
316​
317function pendingEndAt(node: HTMLElement, expectedTop: number | null): number | null {
318 if (expectedTop === null) return null;
319 // Layout can clamp the scroll offset while the bottom stays pinned.
320 if (node.scrollHeight - node.clientHeight - node.scrollTop <= 1) return node.scrollTop;
321 return Math.abs(node.scrollTop - expectedTop) > 1 ? null : expectedTop;
323​
324interface PendingReveal {
325 row: number;
326 attempts: number;
327 expectedTop?: number | undefined;
329​
330function pendingRevealAt(node: HTMLElement, pending: PendingReveal | null): PendingReveal | null {
331 if (pending?.expectedTop === undefined) return pending;
332 const clampedTop = Math.min(pending.expectedTop, node.scrollHeight - node.clientHeight);
333 return Math.abs(node.scrollTop - clampedTop) > 1 ? null : pending;
335​
336// Other modified keys belong to the browser, OS, and app shortcuts.
337const MODIFIED_SCROLL_KEYS = new Set([
338 "Shift+ ",
339 "Alt+ArrowDown",
340 "Alt+ArrowUp",
341 "Control+Home",
342 "Control+End",
343]);
344​
345function ScaledRows(
346 props: Omit<Parameters<typeof RowPage>[0], "page" | "rowHeights"> & {
347 hasHorizontalOverflow: boolean;
348 },
349) {
350 const ref = useRef<HTMLDivElement>(null);
351 const contentRef = useRef<HTMLDivElement>(null);
352 const rowProbeRef = useRef<HTMLDivElement>(null);
353 const rowHeightCacheRef = useRef<{
354 key: string;
355 entries: Map<number, CachedRowHeight>;
356 }>({ key: "", entries: new Map() });
357 const [rowHeights, setRowHeights] = useState<{
358 key: string;
359 heights: ReadonlyMap<number, number>;
360 }>({ key: "", heights: new Map() });
361 const [, setRowMeasureTick] = useState(0);
362 const typographyKey = useClientSettings(
363 (settings) => `${settings.fontFamilySans}:${settings.fontSizeInterface}`,
364 );
365 const [layout, setLayout] = useState({ offset: 0, height: 0, rowHeight: 29 });
366 const [top, setTop] = useState(0);
367 const pendingReveal = useRef<PendingReveal | null>(null);
368 const pendingEnd = useRef<number | null>(null);
369 const positionKey = useContext(PreviewPositionKey);
370 const savedPosition = savedRowPositions.get(positionKey);
371 const handledReveal = useRef<string | null>(savedPosition?.revealKey ?? null);
372 const pendingRestore = useRef(savedPosition?.position);
373 const position = { top, height: props.viewportHeight };
374 const scrollHeight = Math.min(8_000_000, props.count * 29);
375 // Chromium caps a scroll surface at 33 million pixels. Scale the track for
376 // multi-million-line logs while retaining real row heights in the viewport.
377 const headerRows = props.header ? 1 : 0;
378 const maxFirst = Math.max(0, props.count - headerRows - Math.floor(position.height / 29));
379 const scale = Math.max(1, scrollHeight - position.height) / Math.max(1, maxFirst * 29);
380 const first = Math.min(maxFirst, Math.floor(position.top / scale / 29)) + headerRows;
381 // The final mounted rows keep their measured height and scroll natively.
382 const nativeTail = first - headerRows === maxFirst;
383 const scrollModel = useRef<ScrollModel>({ scale, maxFirst, heights: [] });
384 // 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.
385 useLayoutEffect(() => {
386 const previous = scrollModel.current;
387 const heights = nativeTail
388 ? Array.from(contentRef.current?.querySelectorAll<HTMLElement>("[data-preview-row]") ?? [])
389 .filter((row) => Number(row.dataset.previewRow) >= first)
390 .map((row) => row.offsetHeight)
391 : [];
392 scrollModel.current = { scale, maxFirst, heights };
393 const node = ref.current;
394 if (!node || (previous.scale === scale && previous.maxFirst === maxFirst)) return;
395 pendingReveal.current = pendingRevealAt(node, pendingReveal.current);
396 pendingEnd.current = pendingEndAt(node, pendingEnd.current);
397 // Native-tail pixels cross rows of different heights before returning to the scaled track.
398 const logicalTop = logicalScrollTop(node.scrollTop, previous);
399 let nativeOffset = 0;
400 let remaining = Math.max(0, logicalTop / 29 - maxFirst);
401 for (const height of heights) {
402 nativeOffset += Math.min(1, remaining) * height;
403 remaining = Math.max(0, remaining - 1);
404 if (!remaining) break;
405 }
406 node.scrollTop = Math.min(maxFirst * 29, logicalTop) * scale + nativeOffset;
407 if (pendingEnd.current !== null) pendingEnd.current = node.scrollTop;
408 const reveal = pendingReveal.current;
409 if (reveal?.expectedTop !== undefined) reveal.expectedTop = node.scrollTop;
410 setTop(node.scrollTop);
411 });
412 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll the DOM viewport to a requested line after its virtual track has committed.
413 useLayoutEffect(() => {
414 const node = ref.current;
415 if (props.revealLine == null) {
416 if (!props.indexing) handledReveal.current = null;
417 pendingReveal.current = null;
418 return;
419 }
420 const key = `${props.revealRequestId}:${props.revealLine}`;
421 if (!node || !props.count || handledReveal.current === key) return;
422 pendingRestore.current = undefined;
423 const row = Math.min(props.count, Math.max(1, props.revealLine)) - 1;
424 node.scrollTop = Math.max(0, (row - headerRows) * 29) * scale;
425 setTop(node.scrollTop);
426 pendingEnd.current = null;
427 pendingReveal.current = { row, attempts: 0 };
428 handledReveal.current = key;
429 }, [props.indexing, props.revealLine, props.revealRequestId, props.count, headerRows, scale]);
430 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Return a reopened file to its saved row once that row has streamed in.
431 useLayoutEffect(() => {
432 const saved = pendingRestore.current;
433 const node = ref.current;
434 if (saved === undefined || !node) return;
435 if (saved === "end" ? props.indexing : saved >= props.count) return;
436 pendingRestore.current = undefined;
437 node.scrollTop =
438 saved === "end" ? node.scrollHeight : Math.max(0, (saved - headerRows) * 29) * scale;
439 setTop(node.scrollTop);
440 if (saved === "end") pendingEnd.current = node.scrollTop;
441 else
442 pendingReveal.current = {
443 row: saved,
444 attempts: 0,
445 expectedTop: saved > maxFirst + headerRows ? node.scrollTop : undefined,
446 };
447 }, [props.count, props.indexing, headerRows, maxFirst, scale]);
448 const atStart = position.top === 0;
449 const rowHeight = () =>
450 contentRef.current?.querySelector<HTMLElement>(`[data-preview-row="${first}"]`)?.offsetHeight ||
451 29;
452 const onWheel = useEffectEvent((event: WheelEvent) => {
453 const node = ref.current;
454 if (!node || event.ctrlKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)) return;
455 const delta =
456 event.deltaY * (event.deltaMode === 1 ? 29 : event.deltaMode === 2 ? node.clientHeight : 1);
457 if (!delta) return;
458 event.preventDefault();
459 pendingEnd.current = null;
460 if (pendingReveal.current?.expectedTop !== undefined) pendingReveal.current = null;
461 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / rowHeight());
462 });
463 // 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.
464 useEffect(() => {
465 const node = ref.current;
466 if (!node) return;
467 const wheel = (event: WheelEvent) => onWheel(event);
468 node.addEventListener("wheel", wheel, { passive: false });
469 return () => {
470 node.removeEventListener("wheel", wheel);
471 };
472 }, []);
473 const page = Math.floor(first / PREVIEW_PAGE_ROWS);
474 const visibleEnd = (first % PREVIEW_PAGE_ROWS) + Math.ceil(position.height / 29) + 1;
475 const sizesKey = `${props.sizes.join(",")}|${typographyKey}`;
476 const pageCount = Math.min(
477 Math.ceil(visibleEnd / PREVIEW_PAGE_ROWS),
478 Math.ceil(props.count / PREVIEW_PAGE_ROWS) - page,
479 );
480 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure mounted rows across all columns before paint so horizontal column virtualization keeps row heights and vertical scroll position stable.
481 useLayoutEffect(() => {
482 const probe = rowProbeRef.current;
483 if (!props.hasHorizontalOverflow || !probe) return;
484 const probeStyle = getComputedStyle(probe);
485 const cacheKey = `${sizesKey}|${probeStyle.font}`;
486 if (rowHeightCacheRef.current.key !== cacheKey) {
487 rowHeightCacheRef.current = { key: cacheKey, entries: new Map() };
488 }
489 const cache = rowHeightCacheRef.current.entries;
490 const mountedIndices: number[] = [];
491 const uncached: Array<{ index: number; row: readonly string[] }> = [];
492 for (let pageOffset = 0; pageOffset < pageCount; pageOffset++) {
493 const currentPage = page + pageOffset;
494 const rows = props.getRows(currentPage);
495 if (!rows) continue;
496 const start = currentPage * PREVIEW_PAGE_ROWS;
497 const limit = visibleEnd - pageOffset * PREVIEW_PAGE_ROWS;
498 const count = Math.min(PREVIEW_PAGE_ROWS, props.count - start, limit);
499 for (let local = 0; local < count; local++) {
500 const index = start + local;
501 if (props.header && index === 0) continue;
502 const row = rows[local];
503 if (!row) continue;
504 mountedIndices.push(index);
505 const existing = cache.get(index);
506 if (existing && (existing.row === row || sameRowCells(existing.row, row))) {
507 existing.row = row;
508 } else {
509 uncached.push({ index, row });
510 }
511 }
512 }
513 let hasRemainingUncached = false;
514 if (uncached.length > 0) {
515 const fontSize = Number.parseFloat(probeStyle.fontSize) || 12;
516 const lineHeight = Number.parseFloat(probeStyle.lineHeight) || fontSize * 1.333;
517 const { measured, remaining } = measureRowsFullHeight(
518 probe,
519 uncached,
520 props.columns,
521 props.sizes,
522 fontSize,
523 lineHeight,
524 MAX_SYNC_SCAN_CHARS,
525 );
526 hasRemainingUncached = remaining;
527 for (const [index, entry] of measured) cache.set(index, entry);
528 if (cache.size > MAX_CACHED_ROW_HEIGHTS) {
529 const keep = new Set(mountedIndices);
530 for (const key of cache.keys()) {
531 if (cache.size <= MAX_CACHED_ROW_HEIGHTS) break;
532 if (!keep.has(key)) cache.delete(key);
533 }
534 }
535 }
536 const next = new Map<number, number>();
537 for (const index of mountedIndices) {
538 const height = cache.get(index)?.height;
539 if (height && height > BASE_ROW_HEIGHT) next.set(index, height);
540 }
541 setRowHeights((old) =>
542 old.key === cacheKey && sameRowHeightMap(old.heights, next)
543 ? old
544 : { key: cacheKey, heights: next },
545 );
546 if (hasRemainingUncached) {
547 const frameId = requestAnimationFrame(() => setRowMeasureTick((tick) => tick + 1));
548 return () => cancelAnimationFrame(frameId);
549 }
550 return undefined;
551 });
552 const activeRowHeights =
553 props.hasHorizontalOverflow && rowHeights.key.startsWith(`${sizesKey}|`)
554 ? rowHeights.heights
555 : undefined;
556 function tailRowsReady(last: number) {
557 for (let index = first; index <= last; index++) {
558 if (!props.getRows(Math.floor(index / PREVIEW_PAGE_ROWS))?.[index % PREVIEW_PAGE_ROWS])
559 return false;
560 if (props.hasHorizontalOverflow) {
561 const measured = rowHeightCacheRef.current.entries.get(index);
562 if (!measured || (activeRowHeights?.get(index) ?? BASE_ROW_HEIGHT) !== measured.height)
563 return false;
564 }
565 }
566 return true;
567 }
568 // 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.
569 useLayoutEffect(() => {
570 if (atStart) return;
571 const node = contentRef.current;
572 if (!node) return;
573 const update = () => {
574 const row = node.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
575 const offset = row ? row.getBoundingClientRect().top - node.getBoundingClientRect().top : 0;
576 const height = node.clientHeight;
577 const rowHeight = row?.offsetHeight || 29;
578 setLayout((old) =>
579 old.offset === offset && old.height === height && old.rowHeight === rowHeight
580 ? old
581 : { offset, height, rowHeight },
582 );
583 };
584 update();
585 return observeResize(node, update);
586 }, [first, atStart]);
587 // 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.
588 useLayoutEffect(() => {
589 const node = ref.current;
590 if (!node) return;
591 const pending = pendingRevealAt(node, pendingReveal.current);
592 pendingReveal.current = pending;
593 if (!pending) return;
594 const alignStart = pending.expectedTop !== undefined;
595 const row = contentRef.current?.querySelector<HTMLElement>(
596 `[data-preview-row="${pending.row}"]`,
597 );
598 if (
599 !row ||
600 !props.getRows(Math.floor(pending.row / PREVIEW_PAGE_ROWS))?.[pending.row % PREVIEW_PAGE_ROWS]
601 )
602 return;
603 if (alignStart && !tailRowsReady(pending.row)) return;
604 const content = contentRef.current!;
605 const firstRow = content.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
606 if (
607 !atStart &&
608 (layout.height !== content.clientHeight ||
609 layout.offset !==
610 (firstRow
611 ? firstRow.getBoundingClientRect().top - content.getBoundingClientRect().top
612 : 0))
613 )
614 return;
615 const bounds = row.getBoundingClientRect();
616 const viewport = node.getBoundingClientRect();
617 const delta =
618 alignStart || bounds.top < viewport.top
619 ? bounds.top - viewport.top
620 : Math.min(bounds.bottom, bounds.top + viewport.height) > viewport.bottom
621 ? Math.min(bounds.bottom, bounds.top + viewport.height) - viewport.bottom
622 : 0;
623 if (Math.abs(delta) < 1 || pending.attempts++ >= 8) {
624 pendingReveal.current = null;
625 return;
626 }
627 const before = node.scrollTop;
628 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / Math.max(29, bounds.height));
629 if (Math.abs(node.scrollTop - before) < 1) pendingReveal.current = null;
630 else if (alignStart) pending.expectedTop = node.scrollTop;
631 setTop(node.scrollTop);
632 });
633 // 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.
634 useLayoutEffect(() => {
635 const node = ref.current;
636 const content = contentRef.current;
637 if (!node) return;
638 pendingEnd.current = pendingEndAt(node, pendingEnd.current);
639 if (pendingEnd.current === null || !nativeTail || !content || !props.count) return;
640 const last = props.count - 1;
641 if (!props.getRows(Math.floor(last / PREVIEW_PAGE_ROWS))?.[last % PREVIEW_PAGE_ROWS]) return;
642 const row = content.querySelector<HTMLElement>(`[data-preview-row="${last}"]`);
643 const firstRow = content.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
644 if (
645 !row ||
646 (!atStart &&
647 (layout.height !== content.clientHeight ||
648 layout.offset !==
649 (firstRow
650 ? firstRow.getBoundingClientRect().top - content.getBoundingClientRect().top
651 : 0)))
652 )
653 return;
654 node.scrollTop = node.scrollHeight;
655 setTop(node.scrollTop);
656 pendingEnd.current =
657 Math.abs(row.getBoundingClientRect().bottom - node.getBoundingClientRect().bottom) < 1 &&
658 tailRowsReady(last)
659 ? null
660 : node.scrollTop;
661 });
662 return (
663 <div
664 ref={ref}
665 tabIndex={0}
666 className="min-h-0 flex-1 overflow-auto"
667 onKeyDown={(event) => {
668 const modifiers =
669 (event.altKey ? "Alt+" : "") +
670 (event.ctrlKey ? "Control+" : "") +
671 (event.metaKey ? "Meta+" : "") +
672 (event.shiftKey ? "Shift+" : "");
673 if (
674 event.defaultPrevented ||
675 (modifiers && !MODIFIED_SCROLL_KEYS.has(modifiers + event.key))
676 )
677 return;
678 const node = event.currentTarget;
679 const delta =
680 event.key === "ArrowDown"
681 ? 29
682 : event.key === "ArrowUp"
683 ? -29
684 : event.key === "PageDown"
685 ? node.clientHeight
686 : event.key === "PageUp"
687 ? -node.clientHeight
688 : event.key === " " && event.target === node
689 ? (event.shiftKey ? -1 : 1) * node.clientHeight
690 : null;
691 if (delta !== null) {
692 pendingEnd.current = null;
693 if (pendingReveal.current?.expectedTop !== undefined) pendingReveal.current = null;
694 event.preventDefault();
695 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / rowHeight());
696 } else if (event.key === "Home" || event.key === "End") {
697 event.preventDefault();
698 pendingReveal.current = null;
699 node.scrollTop = event.key === "Home" ? 0 : node.scrollHeight;
700 pendingEnd.current = event.key === "End" ? node.scrollTop : null;
701 setTop(node.scrollTop);
702 }
703 }}
704 onScroll={(event) => {
705 const node = event.currentTarget;
706 const scrolled = node.scrollTop;
707 setTop(scrolled);
708 pendingRestore.current = undefined;
709 const atEnd = scrolled > 0 && node.scrollHeight - node.clientHeight - scrolled <= 1;
710 // Native scrolling can move away from the last offset written by the End effects.
711 pendingEnd.current = pendingEndAt(node, pendingEnd.current);
712 pendingReveal.current = pendingRevealAt(node, pendingReveal.current);
713 savedRowPositions.set(positionKey, {
714 position:
715 atEnd && !props.indexing
716 ? "end"
717 : Math.min(
718 props.count - 1,
719 Math.floor(logicalScrollTop(scrolled, scrollModel.current) / 29) + headerRows,
720 ),
721 revealKey: handledReveal.current,
722 });
723 }}
724 >
725 <div className="relative" style={{ height: scrollHeight }}>
726 {!props.source ? (
727 <div
728 ref={rowProbeRef}
729 aria-hidden="true"
730 className="pointer-events-none invisible absolute top-0 left-0 h-0 w-0 overflow-hidden"
731 />
732 ) : null}
733 <div
734 ref={contentRef}
735 className="absolute inset-x-0"
736 style={{
737 top:
738 maxFirst === 0
739 ? 0
740 : nativeTail
741 ? maxFirst * scale * 29 - layout.offset
742 : position.top +
743 (atStart
744 ? 0
745 : -layout.offset - ((position.top / scale / 29) % 1) * layout.rowHeight),
746 }}
747 >
748 {Array.from({ length: pageCount }, (_, offset) => (
749 <RowPage
750 key={page + offset}
751 {...props}
752 page={page + offset}
753 rowHeights={activeRowHeights}
754 limit={visibleEnd - offset * PREVIEW_PAGE_ROWS}
755 />
756 ))}
757 </div>
758 </div>
759 </div>
760 );
762​
763const BASE_ROW_HEIGHT = 29;
764const CELL_HORIZONTAL_INSET = 25;
765const CELL_VERTICAL_INSET = 13;
766const MAX_MEASURED_CELLS_PER_ROW = 16;
767// Wider than any common glyph, so estimates never undercount lines.
768const MAX_GLYPH_WIDTH_EM = 1.35;
769const MAX_CACHED_ROW_HEIGHTS = 512;
770const MAX_SYNC_SCAN_CHARS = 128_000;
771const PROBE_CELL_CLASS_NAME =
772 "box-border border-r border-b border-transparent px-3 py-1.5 whitespace-pre-wrap break-words tabular-nums";
773​
774interface CachedRowHeight {
775 row: readonly string[];
776 height: number;
778​
779interface RowCellCandidate {
780 readonly column: number;
781 readonly text: string;
782 readonly upperLines: number;
784​
785/** Conservative greedy word-wrap upper bound on rendered lines without native text shaping. */
786function estimateUpperLines(text: string, innerWidth: number, fontSize: number): number {
787 const length = text.length;
788 let lines = 1;
789 let lineWidth = 0;
790 let wordWidth = 0;
791 for (let index = 0; index < length; index++) {
792 const code = text.charCodeAt(index);
793 if (code === 10 || code === 13) {
794 if (code === 13 && index + 1 < length && text.charCodeAt(index + 1) === 10) index++;
795 if (wordWidth > 0) {
796 if (lineWidth > 0 && lineWidth + wordWidth > innerWidth) lines++;
797 wordWidth = 0;
798 }
799 lines++;
800 lineWidth = 0;
801 continue;
802 }
803 if (code === 32 || code === 9) {
804 const spaceWidth = (code === 9 ? 4.5 : 0.38) * fontSize;
805 if (wordWidth > 0) {
806 if (lineWidth > 0 && lineWidth + wordWidth > innerWidth) {
807 lines++;
808 lineWidth = wordWidth;
809 } else {
810 lineWidth += wordWidth;
811 }
812 wordWidth = 0;
813 }
814 lineWidth += spaceWidth;
815 if (lineWidth > innerWidth) {
816 lines++;
817 lineWidth = 0;
818 }
819 continue;
820 }
821 const charWidth = MAX_GLYPH_WIDTH_EM * fontSize;
822 wordWidth += charWidth;
823 if (wordWidth > innerWidth) {
824 if (lineWidth > 0) {
825 lines++;
826 lineWidth = 0;
827 }
828 lines++;
829 wordWidth = charWidth;
830 }
831 }
832 if (wordWidth > 0 && lineWidth > 0 && lineWidth + wordWidth > innerWidth) lines++;
833 return lines;
835​
836function collectRowHeightCandidates(
837 row: readonly string[],
838 columns: number,
839 sizes: readonly number[],
840 fontSize: number,
841): { candidates: RowCellCandidate[]; scannedChars: number } {
842 const candidates: RowCellCandidate[] = [];
843 const limit = Math.min(columns, row.length);
844 const maxGlyphWidth = fontSize * MAX_GLYPH_WIDTH_EM;
845 let scannedChars = 0;
846 for (let column = 0; column < limit; column++) {
847 const text = row[column];
848 if (!text) continue;
849 const width = sizes[column];
850 if (!width) continue;
851 const innerWidth = Math.max(1, width - CELL_HORIZONTAL_INSET);
852 const hasControlWhitespace = text.includes("\n") || text.includes("\r") || text.includes("\t");
853 if (!hasControlWhitespace && text.length * maxGlyphWidth <= innerWidth) continue;
854 scannedChars += text.length;
855 const upperLines = estimateUpperLines(text, innerWidth, fontSize);
856 if (!hasControlWhitespace && upperLines <= 1) continue;
857 candidates.push({ column, text, upperLines });
858 }
859 if (candidates.length > MAX_MEASURED_CELLS_PER_ROW) {
860 candidates.sort((left, right) => right.upperLines - left.upperLines);
861 }
862 return { candidates, scannedChars };
864​
865function measureProbeEntries(
866 probe: HTMLElement,
867 entries: ReadonlyArray<{ index: number; column: number; text: string }>,
868 sizes: readonly number[],
869 results: Map<number, CachedRowHeight>,
870): void {
871 if (entries.length === 0) return;
872 const fragment = document.createDocumentFragment();
873 const nodes: Array<{ index: number; node: HTMLDivElement }> = [];
874 for (const entry of entries) {
875 const node = document.createElement("div");
876 node.className = PROBE_CELL_CLASS_NAME;
877 node.style.width = `${sizes[entry.column]}px`;
878 node.textContent = entry.text;
879 fragment.append(node);
880 nodes.push({ index: entry.index, node });
881 }
882 probe.replaceChildren(fragment);
883 for (const { index, node } of nodes) {
884 const height = node.getBoundingClientRect().height;
885 const current = results.get(index);
886 if (current && height > current.height) current.height = height;
887 }
888 probe.replaceChildren();
890​
891function measureRowsFullHeight(
892 probe: HTMLElement,
893 rows: ReadonlyArray<{ index: number; row: readonly string[] }>,
894 columns: number,
895 sizes: readonly number[],
896 fontSize: number,
897 lineHeight: number,
898 maxScanChars: number,
899): { measured: Map<number, CachedRowHeight>; remaining: boolean } {
900 const measured = new Map<number, CachedRowHeight>();
901 const firstPassEntries: Array<{ index: number; column: number; text: string }> = [];
902 const overflowRows: Array<{ index: number; candidates: RowCellCandidate[] }> = [];
903 let scannedChars = 0;
904 let remaining = false;
905 for (const { index, row } of rows) {
906 if (measured.size > 0 && scannedChars >= maxScanChars) {
907 remaining = true;
908 break;
909 }
910 const collected = collectRowHeightCandidates(row, columns, sizes, fontSize);
911 scannedChars += collected.scannedChars;
912 measured.set(index, { row, height: BASE_ROW_HEIGHT });
913 const firstBatchCount = Math.min(collected.candidates.length, MAX_MEASURED_CELLS_PER_ROW);
914 for (let candidateIndex = 0; candidateIndex < firstBatchCount; candidateIndex++) {
915 const candidate = collected.candidates[candidateIndex]!;
916 firstPassEntries.push({ index, column: candidate.column, text: candidate.text });
917 }
918 if (collected.candidates.length > MAX_MEASURED_CELLS_PER_ROW) {
919 overflowRows.push({ index, candidates: collected.candidates });
920 }
921 }
922 measureProbeEntries(probe, firstPassEntries, sizes, measured);
923 if (overflowRows.length > 0) {
924 const secondPassEntries: Array<{ index: number; column: number; text: string }> = [];
925 for (const { index, candidates } of overflowRows) {
926 const bestHeight = measured.get(index)?.height ?? BASE_ROW_HEIGHT;
927 const measuredLines = Math.max(
928 1,
929 Math.floor((bestHeight - CELL_VERTICAL_INSET + 0.5) / lineHeight),
930 );
931 for (
932 let candidateIndex = MAX_MEASURED_CELLS_PER_ROW;
933 candidateIndex < candidates.length;
934 candidateIndex++
935 ) {
936 const candidate = candidates[candidateIndex]!;
937 if (candidate.upperLines <= measuredLines) break;
938 secondPassEntries.push({ index, column: candidate.column, text: candidate.text });
939 }
940 }
941 measureProbeEntries(probe, secondPassEntries, sizes, measured);
942 }
943 return { measured, remaining };
945​
946function sameRowCells(left: readonly string[], right: readonly string[]): boolean {
947 if (left.length !== right.length) return false;
948 for (let index = 0; index < left.length; index++) {
949 if (left[index] !== right[index]) return false;
950 }
951 return true;
953​
954function sameRowHeightMap(
955 left: ReadonlyMap<number, number>,
956 right: ReadonlyMap<number, number>,
957): boolean {
958 if (left.size !== right.size) return false;
959 for (const [index, height] of left) {
960 if (right.get(index) !== height) return false;
961 }
962 return true;
964​
965function columnLabel(index: number): string {
966 let label = "";
967 for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26))
968 label = String.fromCharCode(65 + ((value - 1) % 26)) + label;
969 return label;