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

VirtualTablePreview.tsx

813 lines31.7 KB

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