Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useEffect, useMemo, useRef, useState } from "react";
- import { useReactTable, getCoreRowModel, getSortedRowModel, flexRender } from "@tanstack/react-table";
- import { useVirtualizer } from "@tanstack/react-virtual";
- import { bindRowScroll, getRowMetrics } from "../scrolling.js";
- function normalizeHeaderStyle(style) {
- if (!style) return undefined;
- const next = {};
- Object.entries(style).forEach(([key, value]) => {
- if (key === "--ag-header-background-color") {
- next.background = value;
- return;
- }
- if (key === "color" && String(value).includes("--ag-header-foreground-color")) {
- next.color = "var(--app-header-text)";
- return;
- }
- next[key] = value;
- });
- return next;
- }
- /**
- * TanStack Table + react-virtual using a real <table> with colgroup for aligned widths.
- * Layout mimics the existing JS app: sticky header, horizontal scroll, ellipsis cells.
- */
- export function DataGrid({ rows, columns }) {
- const [selectedId, setSelectedId] = useState(null);
- const [sorting, setSorting] = useState([]);
- const scrollRef = useRef(null);
- const tableRef = useRef(null);
- const data = useMemo(() => rows, [rows]);
- const cols = useMemo(
- () => (columns || []).map(col => ({ ...col, size: col.size || col.width || 160 })),
- [columns]
- );
- const table = useReactTable({
- data,
- columns: cols,
- state: { sorting },
- onSortingChange: setSorting,
- getCoreRowModel: getCoreRowModel(),
- getSortedRowModel: getSortedRowModel()
- });
- const leafColumns = table.getAllLeafColumns();
- const totalWidth = useMemo(
- () => leafColumns.reduce((sum, col) => sum + (col.getSize() || 160), 0),
- [leafColumns]
- );
- const rowVirtualizer = useVirtualizer({
- count: table.getRowModel().rows.length,
- getScrollElement: () => scrollRef.current,
- estimateSize: () => {
- const metrics = getRowMetrics();
- if (metrics.rowStride) {
- return metrics.rowStride;
- }
- const raw = getComputedStyle(document.documentElement).getPropertyValue("--app-row-height-px");
- const parsed = Number.parseFloat(raw);
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 26;
- },
- overscan: 12
- });
- const virtualRows = rowVirtualizer.getVirtualItems();
- const totalSize = rowVirtualizer.getTotalSize();
- const paddingTop = virtualRows.length ? virtualRows[0].start : 0;
- const paddingBottom = virtualRows.length ? totalSize - (virtualRows[virtualRows.length - 1].end) : 0;
- const metricsRefreshRef = useRef(false);
- const headerCellProps = header => {
- const meta = header.column.columnDef.meta || {};
- const className = meta.headerClass && meta.headerClass.length ? meta.headerClass.join(" ") : "";
- const style = normalizeHeaderStyle(meta.headerStyle);
- return { className, style };
- };
- const rowHeight = useMemo(() => {
- const raw = getComputedStyle(document.documentElement).getPropertyValue("--app-row-height-px");
- const parsed = Number.parseFloat(raw);
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 26;
- }, []);
- useEffect(() => {
- const gridEl = scrollRef.current;
- const gridTable = tableRef.current;
- if (!gridEl || !gridTable) {
- return;
- }
- const log = message => {
- if (window.classifier3 && window.classifier3.log) {
- window.classifier3.log(message);
- }
- };
- bindRowScroll({
- gridEl,
- gridTable,
- scheduleVirtualRender: () => rowVirtualizer.measure(),
- log,
- getCurrentMod: null
- });
- const refreshTimer = setTimeout(() => {
- if (gridEl && gridEl._rowScrollApi && typeof gridEl._rowScrollApi.refresh === "function") {
- gridEl._rowScrollApi.refresh();
- }
- }, 0);
- return () => clearTimeout(refreshTimer);
- }, [rowVirtualizer]);
- useEffect(() => {
- if (metricsRefreshRef.current || virtualRows.length === 0) {
- return;
- }
- const gridEl = scrollRef.current;
- if (!gridEl || !gridEl._rowScrollApi || typeof gridEl._rowScrollApi.refresh !== "function") {
- return;
- }
- metricsRefreshRef.current = true;
- const log = message => {
- if (window.classifier3 && window.classifier3.log) {
- window.classifier3.log(message);
- }
- };
- log("[scroll-debug] metrics-trigger reason=virtual-rows-ready");
- gridEl._rowScrollApi.refresh();
- }, [virtualRows]);
- return (
- <div className="grid-card">
- <div className="grid-scroll" ref={scrollRef}>
- <table
- ref={tableRef}
- className="data-table"
- style={{ minWidth: `${totalWidth}px`, width: `${totalWidth}px` }}
- >
- <colgroup>
- {leafColumns.map(col => (
- <col key={col.id} style={{ width: `${col.getSize() || 160}px` }} />
- ))}
- </colgroup>
- <thead>
- {table.getHeaderGroups().map(headerGroup => (
- <tr
- key={headerGroup.id}
- className={headerGroup.depth === 0 ? "header-group-row" : "header-field-row"}
- >
- {headerGroup.headers.map(header => (
- <th
- key={header.id}
- colSpan={header.colSpan}
- {...headerCellProps(header)}
- onClick={header.column.getCanSort() ? header.column.getToggleSortingHandler() : undefined}
- className={[
- header.column.getCanSort() ? "sortable" : "",
- headerCellProps(header).className
- ].filter(Boolean).join(" ")}
- >
- {header.isPlaceholder ? null : (
- <span className="header-label">
- {flexRender(header.column.columnDef.header, header.getContext())}
- {header.column.getIsSorted() ? (
- <span className="sort-indicator">
- {header.column.getIsSorted() === "desc" ? "▼" : "▲"}
- </span>
- ) : (
- <span className="sort-indicator sort-indicator-hidden">▲</span>
- )}
- </span>
- )}
- </th>
- ))}
- </tr>
- ))}
- </thead>
- <tbody>
- {paddingTop > 0 ? (
- <tr className="virtual-spacer" style={{ height: `${paddingTop}px` }}>
- <td colSpan={leafColumns.length} />
- </tr>
- ) : null}
- {virtualRows.map(virtualRow => {
- const row = table.getRowModel().rows[virtualRow.index];
- return (
- <tr
- key={row.id}
- className={selectedId === row.id ? "selected" : ""}
- style={{ height: `${rowHeight}px` }}
- onClick={() => setSelectedId(row.id)}
- >
- {row.getVisibleCells().map(cell => (
- <td key={cell.id} title={cell.getValue() ?? ""}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </td>
- ))}
- </tr>
- );
- })}
- {paddingBottom > 0 ? (
- <tr className="virtual-spacer" style={{ height: `${paddingBottom}px` }}>
- <td colSpan={leafColumns.length} />
- </tr>
- ) : null}
- </tbody>
- </table>
- </div>
- </div>
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment