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

VirtualTablePreview.tsx

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