Guest User

Untitled

a guest
Jan 25th, 2026
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useEffect, useMemo, useRef, useState } from "react";
  2. import { useReactTable, getCoreRowModel, getSortedRowModel, flexRender } from "@tanstack/react-table";
  3. import { useVirtualizer } from "@tanstack/react-virtual";
  4. import { bindRowScroll, getRowMetrics } from "../scrolling.js";
  5.  
  6. function normalizeHeaderStyle(style) {
  7.   if (!style) return undefined;
  8.   const next = {};
  9.   Object.entries(style).forEach(([key, value]) => {
  10.     if (key === "--ag-header-background-color") {
  11.       next.background = value;
  12.       return;
  13.     }
  14.     if (key === "color" && String(value).includes("--ag-header-foreground-color")) {
  15.       next.color = "var(--app-header-text)";
  16.       return;
  17.     }
  18.     next[key] = value;
  19.   });
  20.   return next;
  21. }
  22.  
  23. /**
  24.  * TanStack Table + react-virtual using a real <table> with colgroup for aligned widths.
  25.  * Layout mimics the existing JS app: sticky header, horizontal scroll, ellipsis cells.
  26.  */
  27. export function DataGrid({ rows, columns }) {
  28.   const [selectedId, setSelectedId] = useState(null);
  29.   const [sorting, setSorting] = useState([]);
  30.   const scrollRef = useRef(null);
  31.   const tableRef = useRef(null);
  32.  
  33.   const data = useMemo(() => rows, [rows]);
  34.   const cols = useMemo(
  35.     () => (columns || []).map(col => ({ ...col, size: col.size || col.width || 160 })),
  36.     [columns]
  37.   );
  38.  
  39.   const table = useReactTable({
  40.     data,
  41.     columns: cols,
  42.     state: { sorting },
  43.     onSortingChange: setSorting,
  44.     getCoreRowModel: getCoreRowModel(),
  45.     getSortedRowModel: getSortedRowModel()
  46.   });
  47.  
  48.   const leafColumns = table.getAllLeafColumns();
  49.   const totalWidth = useMemo(
  50.     () => leafColumns.reduce((sum, col) => sum + (col.getSize() || 160), 0),
  51.     [leafColumns]
  52.   );
  53.  
  54.   const rowVirtualizer = useVirtualizer({
  55.     count: table.getRowModel().rows.length,
  56.     getScrollElement: () => scrollRef.current,
  57.     estimateSize: () => {
  58.       const metrics = getRowMetrics();
  59.       if (metrics.rowStride) {
  60.         return metrics.rowStride;
  61.       }
  62.       const raw = getComputedStyle(document.documentElement).getPropertyValue("--app-row-height-px");
  63.       const parsed = Number.parseFloat(raw);
  64.       return Number.isFinite(parsed) && parsed > 0 ? parsed : 26;
  65.     },
  66.     overscan: 12
  67.   });
  68.  
  69.   const virtualRows = rowVirtualizer.getVirtualItems();
  70.   const totalSize = rowVirtualizer.getTotalSize();
  71.   const paddingTop = virtualRows.length ? virtualRows[0].start : 0;
  72.   const paddingBottom = virtualRows.length ? totalSize - (virtualRows[virtualRows.length - 1].end) : 0;
  73.   const metricsRefreshRef = useRef(false);
  74.  
  75.   const headerCellProps = header => {
  76.     const meta = header.column.columnDef.meta || {};
  77.     const className = meta.headerClass && meta.headerClass.length ? meta.headerClass.join(" ") : "";
  78.     const style = normalizeHeaderStyle(meta.headerStyle);
  79.     return { className, style };
  80.   };
  81.  
  82.   const rowHeight = useMemo(() => {
  83.     const raw = getComputedStyle(document.documentElement).getPropertyValue("--app-row-height-px");
  84.     const parsed = Number.parseFloat(raw);
  85.     return Number.isFinite(parsed) && parsed > 0 ? parsed : 26;
  86.   }, []);
  87.  
  88.   useEffect(() => {
  89.     const gridEl = scrollRef.current;
  90.     const gridTable = tableRef.current;
  91.     if (!gridEl || !gridTable) {
  92.       return;
  93.     }
  94.     const log = message => {
  95.       if (window.classifier3 && window.classifier3.log) {
  96.         window.classifier3.log(message);
  97.       }
  98.     };
  99.     bindRowScroll({
  100.       gridEl,
  101.       gridTable,
  102.       scheduleVirtualRender: () => rowVirtualizer.measure(),
  103.       log,
  104.       getCurrentMod: null
  105.     });
  106.     const refreshTimer = setTimeout(() => {
  107.       if (gridEl && gridEl._rowScrollApi && typeof gridEl._rowScrollApi.refresh === "function") {
  108.         gridEl._rowScrollApi.refresh();
  109.       }
  110.     }, 0);
  111.     return () => clearTimeout(refreshTimer);
  112.   }, [rowVirtualizer]);
  113.  
  114.   useEffect(() => {
  115.     if (metricsRefreshRef.current || virtualRows.length === 0) {
  116.       return;
  117.     }
  118.     const gridEl = scrollRef.current;
  119.     if (!gridEl || !gridEl._rowScrollApi || typeof gridEl._rowScrollApi.refresh !== "function") {
  120.       return;
  121.     }
  122.     metricsRefreshRef.current = true;
  123.     const log = message => {
  124.       if (window.classifier3 && window.classifier3.log) {
  125.         window.classifier3.log(message);
  126.       }
  127.     };
  128.     log("[scroll-debug] metrics-trigger reason=virtual-rows-ready");
  129.     gridEl._rowScrollApi.refresh();
  130.   }, [virtualRows]);
  131.  
  132.  
  133.   return (
  134.     <div className="grid-card">
  135.       <div className="grid-scroll" ref={scrollRef}>
  136.         <table
  137.           ref={tableRef}
  138.           className="data-table"
  139.           style={{ minWidth: `${totalWidth}px`, width: `${totalWidth}px` }}
  140.         >
  141.           <colgroup>
  142.             {leafColumns.map(col => (
  143.               <col key={col.id} style={{ width: `${col.getSize() || 160}px` }} />
  144.             ))}
  145.           </colgroup>
  146.           <thead>
  147.             {table.getHeaderGroups().map(headerGroup => (
  148.               <tr
  149.                 key={headerGroup.id}
  150.                 className={headerGroup.depth === 0 ? "header-group-row" : "header-field-row"}
  151.               >
  152.                 {headerGroup.headers.map(header => (
  153.                   <th
  154.                     key={header.id}
  155.                     colSpan={header.colSpan}
  156.                     {...headerCellProps(header)}
  157.                     onClick={header.column.getCanSort() ? header.column.getToggleSortingHandler() : undefined}
  158.                     className={[
  159.                       header.column.getCanSort() ? "sortable" : "",
  160.                       headerCellProps(header).className
  161.                     ].filter(Boolean).join(" ")}
  162.                   >
  163.                     {header.isPlaceholder ? null : (
  164.                       <span className="header-label">
  165.                         {flexRender(header.column.columnDef.header, header.getContext())}
  166.                         {header.column.getIsSorted() ? (
  167.                           <span className="sort-indicator">
  168.                             {header.column.getIsSorted() === "desc" ? "▼" : "▲"}
  169.                           </span>
  170.                         ) : (
  171.                           <span className="sort-indicator sort-indicator-hidden">▲</span>
  172.                         )}
  173.                       </span>
  174.                     )}
  175.                   </th>
  176.                 ))}
  177.               </tr>
  178.             ))}
  179.           </thead>
  180.           <tbody>
  181.             {paddingTop > 0 ? (
  182.               <tr className="virtual-spacer" style={{ height: `${paddingTop}px` }}>
  183.                 <td colSpan={leafColumns.length} />
  184.               </tr>
  185.             ) : null}
  186.             {virtualRows.map(virtualRow => {
  187.               const row = table.getRowModel().rows[virtualRow.index];
  188.               return (
  189.                 <tr
  190.                   key={row.id}
  191.                   className={selectedId === row.id ? "selected" : ""}
  192.                   style={{ height: `${rowHeight}px` }}
  193.                   onClick={() => setSelectedId(row.id)}
  194.                 >
  195.                   {row.getVisibleCells().map(cell => (
  196.                     <td key={cell.id} title={cell.getValue() ?? ""}>
  197.                       {flexRender(cell.column.columnDef.cell, cell.getContext())}
  198.                     </td>
  199.                   ))}
  200.                 </tr>
  201.               );
  202.             })}
  203.             {paddingBottom > 0 ? (
  204.               <tr className="virtual-spacer" style={{ height: `${paddingBottom}px` }}>
  205.                 <td colSpan={leafColumns.length} />
  206.               </tr>
  207.             ) : null}
  208.           </tbody>
  209.         </table>
  210.       </div>
  211.     </div>
  212.   );
  213. }
  214.  
Advertisement
Add Comment
Please, Sign In to add comment