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

VirtualTablePreview.tsx

954 lines37.7 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​
336function ScaledRows(
337 props: Omit<Parameters<typeof RowPage>[0], "page" | "rowHeights"> & {
338 hasHorizontalOverflow: boolean;
339 },
340) {
341 const ref = useRef<HTMLDivElement>(null);
342 const contentRef = useRef<HTMLDivElement>(null);
343 const rowProbeRef = useRef<HTMLDivElement>(null);
344 const rowHeightCacheRef = useRef<{
345 key: string;
346 entries: Map<number, CachedRowHeight>;
347 }>({ key: "", entries: new Map() });
348 const [rowHeights, setRowHeights] = useState<{
349 key: string;
350 heights: ReadonlyMap<number, number>;
351 }>({ key: "", heights: new Map() });
352 const [, setRowMeasureTick] = useState(0);
353 const typographyKey = useClientSettings(
354 (settings) => `${settings.fontFamilySans}:${settings.fontSizeInterface}`,
355 );
356 const [layout, setLayout] = useState({ offset: 0, height: 0, rowHeight: 29 });
357 const [top, setTop] = useState(0);
358 const pendingReveal = useRef<PendingReveal | null>(null);
359 const pendingEnd = useRef<number | null>(null);
360 const positionKey = useContext(PreviewPositionKey);
361 const savedPosition = savedRowPositions.get(positionKey);
362 const handledReveal = useRef<string | null>(savedPosition?.revealKey ?? null);
363 const pendingRestore = useRef(savedPosition?.position);
364 const position = { top, height: props.viewportHeight };
365 const scrollHeight = Math.min(8_000_000, props.count * 29);
366 // Chromium caps a scroll surface at 33 million pixels. Scale the track for
367 // multi-million-line logs while retaining real row heights in the viewport.
368 const headerRows = props.header ? 1 : 0;
369 const maxFirst = Math.max(0, props.count - headerRows - Math.floor(position.height / 29));
370 const scale = Math.max(1, scrollHeight - position.height) / Math.max(1, maxFirst * 29);
371 const first = Math.min(maxFirst, Math.floor(position.top / scale / 29)) + headerRows;
372 // The final mounted rows keep their measured height and scroll natively.
373 const nativeTail = first - headerRows === maxFirst;
374 const scrollModel = useRef<ScrollModel>({ scale, maxFirst, heights: [] });
375 // 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.
376 useLayoutEffect(() => {
377 const previous = scrollModel.current;
378 const heights = nativeTail
379 ? Array.from(contentRef.current?.querySelectorAll<HTMLElement>("[data-preview-row]") ?? [])
380 .filter((row) => Number(row.dataset.previewRow) >= first)
381 .map((row) => row.offsetHeight)
382 : [];
383 scrollModel.current = { scale, maxFirst, heights };
384 const node = ref.current;
385 if (!node || (previous.scale === scale && previous.maxFirst === maxFirst)) return;
386 pendingReveal.current = pendingRevealAt(node, pendingReveal.current);
387 pendingEnd.current = pendingEndAt(node, pendingEnd.current);
388 // Native-tail pixels cross rows of different heights before returning to the scaled track.
389 const logicalTop = logicalScrollTop(node.scrollTop, previous);
390 let nativeOffset = 0;
391 let remaining = Math.max(0, logicalTop / 29 - maxFirst);
392 for (const height of heights) {
393 nativeOffset += Math.min(1, remaining) * height;
394 remaining = Math.max(0, remaining - 1);
395 if (!remaining) break;
396 }
397 node.scrollTop = Math.min(maxFirst * 29, logicalTop) * scale + nativeOffset;
398 if (pendingEnd.current !== null) pendingEnd.current = node.scrollTop;
399 const reveal = pendingReveal.current;
400 if (reveal?.expectedTop !== undefined) reveal.expectedTop = node.scrollTop;
401 setTop(node.scrollTop);
402 });
403 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll the DOM viewport to a requested line after its virtual track has committed.
404 useLayoutEffect(() => {
405 const node = ref.current;
406 if (props.revealLine == null) {
407 if (!props.indexing) handledReveal.current = null;
408 pendingReveal.current = null;
409 return;
410 }
411 const key = `${props.revealRequestId}:${props.revealLine}`;
412 if (!node || !props.count || handledReveal.current === key) return;
413 pendingRestore.current = undefined;
414 const row = Math.min(props.count, Math.max(1, props.revealLine)) - 1;
415 node.scrollTop = Math.max(0, (row - headerRows) * 29) * scale;
416 setTop(node.scrollTop);
417 pendingEnd.current = null;
418 pendingReveal.current = { row, attempts: 0 };
419 handledReveal.current = key;
420 }, [props.indexing, props.revealLine, props.revealRequestId, props.count, headerRows, scale]);
421 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Return a reopened file to its saved row once that row has streamed in.
422 useLayoutEffect(() => {
423 const saved = pendingRestore.current;
424 const node = ref.current;
425 if (saved === undefined || !node) return;
426 if (saved === "end" ? props.indexing : saved >= props.count) return;
427 pendingRestore.current = undefined;
428 node.scrollTop =
429 saved === "end" ? node.scrollHeight : Math.max(0, (saved - headerRows) * 29) * scale;
430 setTop(node.scrollTop);
431 if (saved === "end") pendingEnd.current = node.scrollTop;
432 else
433 pendingReveal.current = {
434 row: saved,
435 attempts: 0,
436 expectedTop: saved > maxFirst + headerRows ? node.scrollTop : undefined,
437 };
438 }, [props.count, props.indexing, headerRows, maxFirst, scale]);
439 const atStart = position.top === 0;
440 const rowHeight = () =>
441 contentRef.current?.querySelector<HTMLElement>(`[data-preview-row="${first}"]`)?.offsetHeight ||
442 29;
443 const onWheel = useEffectEvent((event: WheelEvent) => {
444 const node = ref.current;
445 if (!node || event.ctrlKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)) return;
446 const delta =
447 event.deltaY * (event.deltaMode === 1 ? 29 : event.deltaMode === 2 ? node.clientHeight : 1);
448 if (!delta) return;
449 event.preventDefault();
450 pendingEnd.current = null;
451 if (pendingReveal.current?.expectedTop !== undefined) pendingReveal.current = null;
452 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / rowHeight());
453 });
454 // 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.
455 useEffect(() => {
456 const node = ref.current;
457 if (!node) return;
458 const wheel = (event: WheelEvent) => onWheel(event);
459 node.addEventListener("wheel", wheel, { passive: false });
460 return () => {
461 node.removeEventListener("wheel", wheel);
462 };
463 }, []);
464 const page = Math.floor(first / PREVIEW_PAGE_ROWS);
465 const visibleEnd = (first % PREVIEW_PAGE_ROWS) + Math.ceil(position.height / 29) + 1;
466 const sizesKey = `${props.sizes.join(",")}|${typographyKey}`;
467 const pageCount = Math.min(
468 Math.ceil(visibleEnd / PREVIEW_PAGE_ROWS),
469 Math.ceil(props.count / PREVIEW_PAGE_ROWS) - page,
470 );
471 // 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.
472 useLayoutEffect(() => {
473 const probe = rowProbeRef.current;
474 if (!props.hasHorizontalOverflow || !probe) return;
475 const probeStyle = getComputedStyle(probe);
476 const cacheKey = `${sizesKey}|${probeStyle.font}`;
477 if (rowHeightCacheRef.current.key !== cacheKey) {
478 rowHeightCacheRef.current = { key: cacheKey, entries: new Map() };
479 }
480 const cache = rowHeightCacheRef.current.entries;
481 const mountedIndices: number[] = [];
482 const uncached: Array<{ index: number; row: readonly string[] }> = [];
483 for (let pageOffset = 0; pageOffset < pageCount; pageOffset++) {
484 const currentPage = page + pageOffset;
485 const rows = props.getRows(currentPage);
486 if (!rows) continue;
487 const start = currentPage * PREVIEW_PAGE_ROWS;
488 const limit = visibleEnd - pageOffset * PREVIEW_PAGE_ROWS;
489 const count = Math.min(PREVIEW_PAGE_ROWS, props.count - start, limit);
490 for (let local = 0; local < count; local++) {
491 const index = start + local;
492 if (props.header && index === 0) continue;
493 const row = rows[local];
494 if (!row) continue;
495 mountedIndices.push(index);
496 const existing = cache.get(index);
497 if (existing && (existing.row === row || sameRowCells(existing.row, row))) {
498 existing.row = row;
499 } else {
500 uncached.push({ index, row });
501 }
502 }
503 }
504 let hasRemainingUncached = false;
505 if (uncached.length > 0) {
506 const fontSize = Number.parseFloat(probeStyle.fontSize) || 12;
507 const lineHeight = Number.parseFloat(probeStyle.lineHeight) || fontSize * 1.333;
508 const { measured, remaining } = measureRowsFullHeight(
509 probe,
510 uncached,
511 props.columns,
512 props.sizes,
513 fontSize,
514 lineHeight,
515 MAX_SYNC_SCAN_CHARS,
516 );
517 hasRemainingUncached = remaining;
518 for (const [index, entry] of measured) cache.set(index, entry);
519 if (cache.size > MAX_CACHED_ROW_HEIGHTS) {
520 const keep = new Set(mountedIndices);
521 for (const key of cache.keys()) {
522 if (cache.size <= MAX_CACHED_ROW_HEIGHTS) break;
523 if (!keep.has(key)) cache.delete(key);
524 }
525 }
526 }
527 const next = new Map<number, number>();
528 for (const index of mountedIndices) {
529 const height = cache.get(index)?.height;
530 if (height && height > BASE_ROW_HEIGHT) next.set(index, height);
531 }
532 setRowHeights((old) =>
533 old.key === cacheKey && sameRowHeightMap(old.heights, next)
534 ? old
535 : { key: cacheKey, heights: next },
536 );
537 if (hasRemainingUncached) {
538 const frameId = requestAnimationFrame(() => setRowMeasureTick((tick) => tick + 1));
539 return () => cancelAnimationFrame(frameId);
540 }
541 return undefined;
542 });
543 const activeRowHeights =
544 props.hasHorizontalOverflow && rowHeights.key.startsWith(`${sizesKey}|`)
545 ? rowHeights.heights
546 : undefined;
547 function tailRowsReady(last: number) {
548 for (let index = first; index <= last; index++) {
549 if (!props.getRows(Math.floor(index / PREVIEW_PAGE_ROWS))?.[index % PREVIEW_PAGE_ROWS])
550 return false;
551 if (props.hasHorizontalOverflow) {
552 const measured = rowHeightCacheRef.current.entries.get(index);
553 if (!measured || (activeRowHeights?.get(index) ?? BASE_ROW_HEIGHT) !== measured.height)
554 return false;
555 }
556 }
557 return true;
558 }
559 // 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.
560 useLayoutEffect(() => {
561 if (atStart) return;
562 const node = contentRef.current;
563 if (!node) return;
564 const update = () => {
565 const row = node.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
566 const offset = row ? row.getBoundingClientRect().top - node.getBoundingClientRect().top : 0;
567 const height = node.clientHeight;
568 const rowHeight = row?.offsetHeight || 29;
569 setLayout((old) =>
570 old.offset === offset && old.height === height && old.rowHeight === rowHeight
571 ? old
572 : { offset, height, rowHeight },
573 );
574 };
575 update();
576 return observeResize(node, update);
577 }, [first, atStart]);
578 // 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.
579 useLayoutEffect(() => {
580 const node = ref.current;
581 if (!node) return;
582 const pending = pendingRevealAt(node, pendingReveal.current);
583 pendingReveal.current = pending;
584 if (!pending) return;
585 const alignStart = pending.expectedTop !== undefined;
586 const row = contentRef.current?.querySelector<HTMLElement>(
587 `[data-preview-row="${pending.row}"]`,
588 );
589 if (
590 !row ||
591 !props.getRows(Math.floor(pending.row / PREVIEW_PAGE_ROWS))?.[pending.row % PREVIEW_PAGE_ROWS]
592 )
593 return;
594 if (alignStart && !tailRowsReady(pending.row)) return;
595 const content = contentRef.current!;
596 const firstRow = content.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
597 if (
598 !atStart &&
599 (layout.height !== content.clientHeight ||
600 layout.offset !==
601 (firstRow
602 ? firstRow.getBoundingClientRect().top - content.getBoundingClientRect().top
603 : 0))
604 )
605 return;
606 const bounds = row.getBoundingClientRect();
607 const viewport = node.getBoundingClientRect();
608 const delta =
609 alignStart || bounds.top < viewport.top
610 ? bounds.top - viewport.top
611 : Math.min(bounds.bottom, bounds.top + viewport.height) > viewport.bottom
612 ? Math.min(bounds.bottom, bounds.top + viewport.height) - viewport.bottom
613 : 0;
614 if (Math.abs(delta) < 1 || pending.attempts++ >= 8) {
615 pendingReveal.current = null;
616 return;
617 }
618 const before = node.scrollTop;
619 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / Math.max(29, bounds.height));
620 if (Math.abs(node.scrollTop - before) < 1) pendingReveal.current = null;
621 else if (alignStart) pending.expectedTop = node.scrollTop;
622 setTop(node.scrollTop);
623 });
624 // 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.
625 useLayoutEffect(() => {
626 const node = ref.current;
627 const content = contentRef.current;
628 if (!node) return;
629 pendingEnd.current = pendingEndAt(node, pendingEnd.current);
630 if (pendingEnd.current === null || !nativeTail || !content || !props.count) return;
631 const last = props.count - 1;
632 if (!props.getRows(Math.floor(last / PREVIEW_PAGE_ROWS))?.[last % PREVIEW_PAGE_ROWS]) return;
633 const row = content.querySelector<HTMLElement>(`[data-preview-row="${last}"]`);
634 const firstRow = content.querySelector<HTMLElement>(`[data-preview-row="${first}"]`);
635 if (
636 !row ||
637 (!atStart &&
638 (layout.height !== content.clientHeight ||
639 layout.offset !==
640 (firstRow
641 ? firstRow.getBoundingClientRect().top - content.getBoundingClientRect().top
642 : 0)))
643 )
644 return;
645 node.scrollTop = node.scrollHeight;
646 setTop(node.scrollTop);
647 pendingEnd.current =
648 Math.abs(row.getBoundingClientRect().bottom - node.getBoundingClientRect().bottom) < 1 &&
649 tailRowsReady(last)
650 ? null
651 : node.scrollTop;
652 });
653 return (
654 <div
655 ref={ref}
656 tabIndex={0}
657 className="min-h-0 flex-1 overflow-auto"
658 onKeyDown={(event) => {
659 const node = event.currentTarget;
660 const delta =
661 event.key === "ArrowDown"
662 ? 29
663 : event.key === "ArrowUp"
664 ? -29
665 : event.key === "PageDown"
666 ? node.clientHeight
667 : event.key === "PageUp"
668 ? -node.clientHeight
669 : event.key === " " &&
670 event.target === node &&
671 !event.defaultPrevented &&
672 !(event.altKey || event.ctrlKey || event.metaKey)
673 ? (event.shiftKey ? -1 : 1) * node.clientHeight
674 : null;
675 if (delta !== null) {
676 pendingEnd.current = null;
677 if (pendingReveal.current?.expectedTop !== undefined) pendingReveal.current = null;
678 event.preventDefault();
679 node.scrollTop += delta * (nativeTail ? 1 : (scale * 29) / rowHeight());
680 } else if (event.key === "Home" || event.key === "End") {
681 event.preventDefault();
682 pendingReveal.current = null;
683 node.scrollTop = event.key === "Home" ? 0 : node.scrollHeight;
684 pendingEnd.current = event.key === "End" ? node.scrollTop : null;
685 setTop(node.scrollTop);
686 }
687 }}
688 onScroll={(event) => {
689 const node = event.currentTarget;
690 const scrolled = node.scrollTop;
691 setTop(scrolled);
692 pendingRestore.current = undefined;
693 const atEnd = scrolled > 0 && node.scrollHeight - node.clientHeight - scrolled <= 1;
694 // Native scrolling can move away from the last offset written by the End effects.
695 pendingEnd.current = pendingEndAt(node, pendingEnd.current);
696 pendingReveal.current = pendingRevealAt(node, pendingReveal.current);
697 savedRowPositions.set(positionKey, {
698 position:
699 atEnd && !props.indexing
700 ? "end"
701 : Math.min(
702 props.count - 1,
703 Math.floor(logicalScrollTop(scrolled, scrollModel.current) / 29) + headerRows,
704 ),
705 revealKey: handledReveal.current,
706 });
707 }}
708 >
709 <div className="relative" style={{ height: scrollHeight }}>
710 {!props.source ? (
711 <div
712 ref={rowProbeRef}
713 aria-hidden="true"
714 className="pointer-events-none invisible absolute top-0 left-0 h-0 w-0 overflow-hidden"
715 />
716 ) : null}
717 <div
718 ref={contentRef}
719 className="absolute inset-x-0"
720 style={{
721 top:
722 maxFirst === 0
723 ? 0
724 : nativeTail
725 ? maxFirst * scale * 29 - layout.offset
726 : position.top +
727 (atStart
728 ? 0
729 : -layout.offset - ((position.top / scale / 29) % 1) * layout.rowHeight),
730 }}
731 >
732 {Array.from({ length: pageCount }, (_, offset) => (
733 <RowPage
734 key={page + offset}
735 {...props}
736 page={page + offset}
737 rowHeights={activeRowHeights}
738 limit={visibleEnd - offset * PREVIEW_PAGE_ROWS}
739 />
740 ))}
741 </div>
742 </div>
743 </div>
744 );
746​
747const BASE_ROW_HEIGHT = 29;
748const CELL_HORIZONTAL_INSET = 25;
749const CELL_VERTICAL_INSET = 13;
750const MAX_MEASURED_CELLS_PER_ROW = 16;
751// Wider than any common glyph, so estimates never undercount lines.
752const MAX_GLYPH_WIDTH_EM = 1.35;
753const MAX_CACHED_ROW_HEIGHTS = 512;
754const MAX_SYNC_SCAN_CHARS = 128_000;
755const PROBE_CELL_CLASS_NAME =
756 "box-border border-r border-b border-transparent px-3 py-1.5 whitespace-pre-wrap break-words tabular-nums";
757​
758interface CachedRowHeight {
759 row: readonly string[];
760 height: number;
762​
763interface RowCellCandidate {
764 readonly column: number;
765 readonly text: string;
766 readonly upperLines: number;
768​
769/** Conservative greedy word-wrap upper bound on rendered lines without native text shaping. */
770function estimateUpperLines(text: string, innerWidth: number, fontSize: number): number {
771 const length = text.length;
772 let lines = 1;
773 let lineWidth = 0;
774 let wordWidth = 0;
775 for (let index = 0; index < length; index++) {
776 const code = text.charCodeAt(index);
777 if (code === 10 || code === 13) {
778 if (code === 13 && index + 1 < length && text.charCodeAt(index + 1) === 10) index++;
779 if (wordWidth > 0) {
780 if (lineWidth > 0 && lineWidth + wordWidth > innerWidth) lines++;
781 wordWidth = 0;
782 }
783 lines++;
784 lineWidth = 0;
785 continue;
786 }
787 if (code === 32 || code === 9) {
788 const spaceWidth = (code === 9 ? 4.5 : 0.38) * fontSize;
789 if (wordWidth > 0) {
790 if (lineWidth > 0 && lineWidth + wordWidth > innerWidth) {
791 lines++;
792 lineWidth = wordWidth;
793 } else {
794 lineWidth += wordWidth;
795 }
796 wordWidth = 0;
797 }
798 lineWidth += spaceWidth;
799 if (lineWidth > innerWidth) {
800 lines++;
801 lineWidth = 0;
802 }
803 continue;
804 }
805 const charWidth = MAX_GLYPH_WIDTH_EM * fontSize;
806 wordWidth += charWidth;
807 if (wordWidth > innerWidth) {
808 if (lineWidth > 0) {
809 lines++;
810 lineWidth = 0;
811 }
812 lines++;
813 wordWidth = charWidth;
814 }
815 }
816 if (wordWidth > 0 && lineWidth > 0 && lineWidth + wordWidth > innerWidth) lines++;
817 return lines;
819​
820function collectRowHeightCandidates(
821 row: readonly string[],
822 columns: number,
823 sizes: readonly number[],
824 fontSize: number,
825): { candidates: RowCellCandidate[]; scannedChars: number } {
826 const candidates: RowCellCandidate[] = [];
827 const limit = Math.min(columns, row.length);
828 const maxGlyphWidth = fontSize * MAX_GLYPH_WIDTH_EM;
829 let scannedChars = 0;
830 for (let column = 0; column < limit; column++) {
831 const text = row[column];
832 if (!text) continue;
833 const width = sizes[column];
834 if (!width) continue;
835 const innerWidth = Math.max(1, width - CELL_HORIZONTAL_INSET);
836 const hasControlWhitespace = text.includes("\n") || text.includes("\r") || text.includes("\t");
837 if (!hasControlWhitespace && text.length * maxGlyphWidth <= innerWidth) continue;
838 scannedChars += text.length;
839 const upperLines = estimateUpperLines(text, innerWidth, fontSize);
840 if (!hasControlWhitespace && upperLines <= 1) continue;
841 candidates.push({ column, text, upperLines });
842 }
843 if (candidates.length > MAX_MEASURED_CELLS_PER_ROW) {
844 candidates.sort((left, right) => right.upperLines - left.upperLines);
845 }
846 return { candidates, scannedChars };
848​
849function measureProbeEntries(
850 probe: HTMLElement,
851 entries: ReadonlyArray<{ index: number; column: number; text: string }>,
852 sizes: readonly number[],
853 results: Map<number, CachedRowHeight>,
854): void {
855 if (entries.length === 0) return;
856 const fragment = document.createDocumentFragment();
857 const nodes: Array<{ index: number; node: HTMLDivElement }> = [];
858 for (const entry of entries) {
859 const node = document.createElement("div");
860 node.className = PROBE_CELL_CLASS_NAME;
861 node.style.width = `${sizes[entry.column]}px`;
862 node.textContent = entry.text;
863 fragment.append(node);
864 nodes.push({ index: entry.index, node });
865 }
866 probe.replaceChildren(fragment);
867 for (const { index, node } of nodes) {
868 const height = node.getBoundingClientRect().height;
869 const current = results.get(index);
870 if (current && height > current.height) current.height = height;
871 }
872 probe.replaceChildren();
874​
875function measureRowsFullHeight(
876 probe: HTMLElement,
877 rows: ReadonlyArray<{ index: number; row: readonly string[] }>,
878 columns: number,
879 sizes: readonly number[],
880 fontSize: number,
881 lineHeight: number,
882 maxScanChars: number,
883): { measured: Map<number, CachedRowHeight>; remaining: boolean } {
884 const measured = new Map<number, CachedRowHeight>();
885 const firstPassEntries: Array<{ index: number; column: number; text: string }> = [];
886 const overflowRows: Array<{ index: number; candidates: RowCellCandidate[] }> = [];
887 let scannedChars = 0;
888 let remaining = false;
889 for (const { index, row } of rows) {
890 if (measured.size > 0 && scannedChars >= maxScanChars) {
891 remaining = true;
892 break;
893 }
894 const collected = collectRowHeightCandidates(row, columns, sizes, fontSize);
895 scannedChars += collected.scannedChars;
896 measured.set(index, { row, height: BASE_ROW_HEIGHT });
897 const firstBatchCount = Math.min(collected.candidates.length, MAX_MEASURED_CELLS_PER_ROW);
898 for (let candidateIndex = 0; candidateIndex < firstBatchCount; candidateIndex++) {
899 const candidate = collected.candidates[candidateIndex]!;
900 firstPassEntries.push({ index, column: candidate.column, text: candidate.text });
901 }
902 if (collected.candidates.length > MAX_MEASURED_CELLS_PER_ROW) {
903 overflowRows.push({ index, candidates: collected.candidates });
904 }
905 }
906 measureProbeEntries(probe, firstPassEntries, sizes, measured);
907 if (overflowRows.length > 0) {
908 const secondPassEntries: Array<{ index: number; column: number; text: string }> = [];
909 for (const { index, candidates } of overflowRows) {
910 const bestHeight = measured.get(index)?.height ?? BASE_ROW_HEIGHT;
911 const measuredLines = Math.max(
912 1,
913 Math.floor((bestHeight - CELL_VERTICAL_INSET + 0.5) / lineHeight),
914 );
915 for (
916 let candidateIndex = MAX_MEASURED_CELLS_PER_ROW;
917 candidateIndex < candidates.length;
918 candidateIndex++
919 ) {
920 const candidate = candidates[candidateIndex]!;
921 if (candidate.upperLines <= measuredLines) break;
922 secondPassEntries.push({ index, column: candidate.column, text: candidate.text });
923 }
924 }
925 measureProbeEntries(probe, secondPassEntries, sizes, measured);
926 }
927 return { measured, remaining };
929​
930function sameRowCells(left: readonly string[], right: readonly string[]): boolean {
931 if (left.length !== right.length) return false;
932 for (let index = 0; index < left.length; index++) {
933 if (left[index] !== right[index]) return false;
934 }
935 return true;
937​
938function sameRowHeightMap(
939 left: ReadonlyMap<number, number>,
940 right: ReadonlyMap<number, number>,
941): boolean {
942 if (left.size !== right.size) return false;
943 for (const [index, height] of left) {
944 if (right.get(index) !== height) return false;
945 }
946 return true;
948​
949function columnLabel(index: number): string {
950 let label = "";
951 for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26))
952 label = String.fromCharCode(65 + ((value - 1) % 26)) + label;
953 return label;