Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

17.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import {
  cn,
  HStack,
  Table,
  Tbody,
  Td,
  Th,
  Thead,
  Tr,
  useEscape,
  useMount,
  VStack
} from "@carbon/react";
import { clamp } from "@carbon/utils";
import { Trans } from "@lingui/react/macro";
import type { ColumnDef, ColumnOrderState } from "@tanstack/react-table";
import {
  flexRender,
  getCoreRowModel,
  useReactTable
} from "@tanstack/react-table";
import { useCallback, useEffect, useRef, useState } from "react";
import { LuCirclePlus } from "react-icons/lu";
import type {
  EditableTableCellComponent,
  Position
} from "~/components/Editable";
import { useVirtualRows } from "~/components/Table/useVirtualRows";
import { Row } from "./components";
import { getAccessorKey, updateNestedProperty } from "./utils";

// Used until a row is measured: a body cell is `h-11`.
const ESTIMATED_ROW_HEIGHT = 44;
// The header row sits above the rows inside the same scroller. Its `Tr` is
// `h-10`, but every `Th` is `h-11`, and a table row is as tall as its tallest
// cell.
const HEADER_HEIGHT = 44;
const OVERSCAN = 3;

interface GridProps<T extends object> {
  canEdit?: boolean;
  columns: ColumnDef<T>[];
  contained?: boolean;
  data: T[];
  defaultColumnOrder?: string[];
  defaultColumnVisibility?: Record<string, boolean>;
  editableComponents?: Record<string, EditableTableCellComponent<T>>;
  /**
   * Lock individual rows: a row this returns `false` for renders its editable
   * columns as plain, non-editable cells (no ring, no pencil, no editor), the
   * same as every cell does under `canEdit={false}`. For lists that mix rows a
   * user may still change with rows a status has locked. Defaults to every
   * row being editable.
   */
  isRowEditable?: (row: T) => boolean;
  /**
   * Cap the grid's height in pixels. The rows then scroll inside the grid under
   * a pinned header, and only the rows in view (plus the selected one) are
   * rendered — for lists that can run to hundreds of rows. Without it every
   * row is rendered and the grid is as tall as its rows.
   */
  maxHeight?: number;

  withNewRow?: boolean;
  withSimpleSorting?: boolean;
  onDataChange?: (data: T[]) => void;
  onEditRow?: (row: T) => void;
  onNewRow?: () => void;
}

const Grid = <T extends object>({
  canEdit = true,
  columns,
  contained = true,
  data,
  editableComponents,
  isRowEditable,
  maxHeight,
  defaultColumnOrder,
  defaultColumnVisibility,
  withSimpleSorting = true,
  onDataChange,
  onEditRow,
  onNewRow
}: GridProps<T>) => {
  const tableContainerRef = useRef<HTMLDivElement>(null);

  /* Data for Optimistic Updates */
  const [internalData, setInternalData] = useState<T[]>(data);
  useEffect(() => {
    setInternalData(data);
  }, [data]);

  /* Column Visibility */
  const [columnVisibility, setColumnVisibility] = useState(
    defaultColumnVisibility ?? {}
  );

  /* Column Ordering */
  const [columnOrder, setColumnOrder] = useState<ColumnOrderState>(
    defaultColumnOrder ?? []
  );

  const table = useReactTable({
    data: internalData,
    columns: columns,
    state: {
      columnVisibility,
      columnOrder
    },
    onColumnVisibilityChange: setColumnVisibility,
    onColumnOrderChange: setColumnOrder,
    getCoreRowModel: getCoreRowModel(),
    meta: {
      // These are not part of the standard API, but are accessible via table.options.meta
      editableComponents,
      updateData: (rowIndex, updates) => {
        setInternalData((previousData) => {
          const newData = previousData.map((row, index) => {
            if (index === rowIndex) {
              return Object.entries(updates).reduce(
                (newRow, [columnId, value]) => {
                  if (columnId.includes("_") && !(columnId in newRow)) {
                    updateNestedProperty(newRow, columnId, value);
                    return newRow;
                  } else {
                    return {
                      ...newRow,
                      [columnId]: value
                    };
                  }
                },
                row
              );
            }
            return row;
          });

          onDataChange?.(newData);

          return newData;
        });
      }
    }
  });

  const [isEditing, setIsEditing] = useState(false);
  const [selectedCell, setSelectedCell] = useState<Position>(null);

  // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
  const focusOnSelectedCell = useCallback(() => {
    if (selectedCell == null) return;
    const cell = tableContainerRef.current?.querySelector(
      `[data-row="${selectedCell.row}"][data-column="${selectedCell.column}"]`
    ) as HTMLDivElement;
    if (cell) cell.focus();
  }, [selectedCell, tableContainerRef]);

  useEscape(() => {
    setIsEditing(false);
    focusOnSelectedCell();
  });

  const onSelectedCellChange = useCallback(
    (position: Position) => {
      if (
        selectedCell == null ||
        position == null ||
        selectedCell.row !== position?.row ||
        selectedCell.column !== position.column
      )
        setSelectedCell(position);
    },
    [selectedCell]
  );

  const isColumnEditable = useCallback(
    (selectedColumn: number) => {
      const tableColumns = [
        ...table.getLeftVisibleLeafColumns(),
        ...table.getCenterVisibleLeafColumns()
      ];

      const column = tableColumns[selectedColumn];
      if (!column) return false;

      const accessorKey = getAccessorKey(column.columnDef);
      return (
        accessorKey && editableComponents && accessorKey in editableComponents
      );
    },
    [table, editableComponents]
  );

  // A cell is editable when its column has an editor AND its row is not locked.
  const isCellEditable = useCallback(
    (rowIndex: number, column: number) => {
      if (!isColumnEditable(column)) return false;
      if (!isRowEditable) return true;
      const row = table.getRowModel().rows[rowIndex];
      return row ? isRowEditable(row.original) : false;
    },
    [isColumnEditable, isRowEditable, table]
  );

  const onCellClick = useCallback(
    (row: number, column: number) => {
      // ignore row select checkbox column
      if (column === -1) return;
      // Editable cells enter edit mode on a single click (the editable input
      // then auto-focuses and selects its text), instead of select-then-click.
      if (isCellEditable(row, column)) {
        onSelectedCellChange({ row, column });
        setIsEditing(true);
        return;
      }
      setIsEditing(false);
      onSelectedCellChange({ row, column });
    },
    [isCellEditable, onSelectedCellChange]
  );

  const onCellUpdate = useCallback(
    (rowIndex: number) => (updates: Record<string, unknown>) =>
      table.options.meta?.updateData
        ? table.options.meta?.updateData(rowIndex, updates)
        : undefined,
    [table]
  );

  const onKeyDown = useCallback(
    (event: React.KeyboardEvent<HTMLDivElement>) => {
      if (!selectedCell) return;

      const { code, shiftKey } = event;

      const commandCodes: {
        [key: string]: [number, number];
      } = {
        Tab: [0, 1],
        Enter: [1, 0]
      };

      const navigationCodes: {
        [key: string]: [number, number];
      } = {
        ArrowRight: [0, 1],
        ArrowLeft: [0, -1],
        ArrowDown: [1, 0],
        ArrowUp: [-1, 0]
      };

      const lastRow = table.getRowModel().rows.length - 1;
      const lastColumn = table.getVisibleLeafColumns().length - 1;

      const navigate = (
        delta: [number, number],
        tabWrap = false
      ): [number, number] => {
        const x0 = selectedCell?.column || 0;
        const y0 = selectedCell?.row || 0;

        let x1 = x0 + delta[1];
        let y1 = y0 + delta[0];

        if (tabWrap) {
          if (delta[1] > 0) {
            // wrap to the next row if we're on the last column
            if (x1 > lastColumn) {
              x1 = 0;
              y1 += 1;
            }
            // don't wrap to the next row if we're on the last row
            if (y1 > lastRow) {
              x1 = x0;
              y1 = y0;
            }
          } else {
            // reverse tab wrap
            if (x1 < 0) {
              x1 = lastColumn;
              y1 -= 1;
            }

            if (y1 < 0) {
              x1 = x0;
              y1 = y0;
            }
          }
        } else {
          x1 = clamp(x1, 0, lastColumn);
        }

        y1 = clamp(y1, 0, lastRow);

        return [x1, y1];
      };

      if (code in commandCodes) {
        event.preventDefault();

        if (
          canEdit &&
          !isEditing &&
          code === "Enter" &&
          !shiftKey &&
          isCellEditable(selectedCell.row, selectedCell.column)
        ) {
          setIsEditing(true);
          return;
        }

        let direction = commandCodes[code];

        if (shiftKey) direction = [-direction[0], -direction[1]];
        const [x1, y1] = navigate(direction, code === "Tab");

        // Commit any in-flight edit before navigating. Editors (NumberField,
        // DatePicker, etc.) commit their value on blur — without this, Tab's
        // preventDefault keeps focus on the input until it unmounts and the
        // onChange never fires, silently dropping the typed value.
        if (
          isEditing &&
          document.activeElement instanceof HTMLElement &&
          document.activeElement !== document.body
        ) {
          document.activeElement.blur();
        }

        setSelectedCell({
          row: y1,
          column: x1
        });
        // On Tab, carry edit mode into the next editable cell so typing
        // continues naturally. Otherwise (Enter) drop out of edit mode.
        if (isEditing) {
          const carryEdit = Boolean(
            canEdit && code === "Tab" && isCellEditable(y1, x1)
          );
          setIsEditing(carryEdit);
        }
      } else if (code in navigationCodes) {
        // arrow key navigation should't work if we're editing
        if (isEditing) return;
        event.preventDefault();
        const [x1, y1] = navigate(navigationCodes[code], code === "Tab");
        setIsEditing(false);
        setSelectedCell({
          row: y1,
          column: x1
        });
        // any other key (besides shift) activates editing
        // if the column is editable and a cell is selected
      } else if (
        !["ShiftLeft", "ShiftRight"].includes(code) &&
        !isEditing &&
        selectedCell &&
        isCellEditable(selectedCell.row, selectedCell.column)
      ) {
        setIsEditing(true);
      }
    },
    [canEdit, isCellEditable, isEditing, selectedCell, table]
  );

  // reset the selected cell when the table data changes
  // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
  useEffect(() => {
    setSelectedCell(null);
  }, [columnOrder, columnVisibility]);

  useMount(() => {
    setColumnOrder(table.getAllLeafColumns().map((column) => column.id));
  });

  const rows = table.getRowModel().rows;

  /* Row virtualization (only with `maxHeight`) */
  const isVirtual = maxHeight !== undefined;

  // The selected row stays rendered when it scrolls out of view: it holds the
  // keyboard focus and, mid-edit, the open editor. Dropping it would lose both.
  const selectedRow = selectedCell?.row;
  const keepSelectedRow = useCallback(() => selectedRow, [selectedRow]);

  const { virtualizer: rowVirtualizer, renderRows } = useVirtualRows({
    enabled: isVirtual,
    count: rows.length,
    getScrollElement: () => tableContainerRef.current,
    getItemKey: (index) => rows[index]?.id ?? index,
    estimateSize: () => ESTIMATED_ROW_HEIGHT,
    overscan: OVERSCAN,
    scrollMargin: HEADER_HEIGHT,
    keepIndex: keepSelectedRow,
    // The scroller is not measured until after the first render; without this
    // that render would draw no rows at all.
    initialHeight: maxHeight ?? 0
  });

  const renderRow = (row: (typeof rows)[number], virtualIndex?: number) => (
    <Row
      key={row.id}
      editableComponents={
        canEdit && (isRowEditable?.(row.original) ?? true)
          ? editableComponents
          : {}
      }
      isEditing={isEditing}
      selectedCell={selectedCell}
      row={row}
      rowIsSelected={selectedCell?.row === row.index}
      rowRef={isVirtual ? rowVirtualizer.measureElement : undefined}
      virtualIndex={virtualIndex}
      withRowBorder={isVirtual}
      onCellClick={onCellClick}
      onCellUpdate={onCellUpdate}
      onEditRow={onEditRow}
    />
  );

  // The rows in view, with an empty row standing in for each run of rows that
  // is not rendered, so the scrollbar and every row's position stay true.
  const renderVirtualRows = () => {
    const columnCount = table.getVisibleLeafColumns().length;
    return renderRows(
      (index) => renderRow(rows[index]!, index),
      (key, height) => (
        <tr key={key} aria-hidden>
          <td colSpan={columnCount} style={{ height, padding: 0 }} />
        </tr>
      )
    );
  };

  // In a virtualized grid "New" sits under the scroller, always in view, so
  // adding a row never means scrolling to the end of a long list first. The
  // added row lands at the end, out of view, so the grid scrolls to it.
  const awaitedRowCount = useRef<number | null>(null);
  const onNewRowClick = () => {
    awaitedRowCount.current = rows.length + 1;
    onNewRow?.();
  };
  useEffect(() => {
    const awaited = awaitedRowCount.current;
    awaitedRowCount.current = null;
    if (awaited === rows.length) {
      rowVirtualizer.scrollToIndex(rows.length - 1, { align: "end" });
    }
  }, [rows.length, rowVirtualizer]);

  return (
    <VStack
      spacing={0}
      className={cn(
        "h-full w-full",
        // The frame the table's own wrapper would otherwise draw: here it has
        // to go around the scroller and the "New" button under it.
        isVirtual && !contained && "overflow-hidden rounded-md border"
      )}
    >
      <div
        className={cn(
          "w-full h-full overflow-x-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent max-md:scroll-fade-x",
          contained ? "" : "relative",
          isVirtual && "overflow-y-auto"
        )}
        style={
          isVirtual ? { maxHeight, scrollPaddingTop: HEADER_HEIGHT } : undefined
        }
        ref={tableContainerRef}
        onKeyDown={onKeyDown}
      >
        <Table
          full={contained || isVirtual}
          className={cn(
            !contained && !isVirtual && "border w-full",
            // Automatic layout sizes columns from the rows that are rendered,
            // and virtualization swaps those rows while scrolling, so every
            // column changed width under the cursor. Fixed layout takes the
            // widths from the header (`header.getSize()`) alone.
            isVirtual && "table-fixed"
          )}
        >
          <Thead
            className={cn(
              "sticky top-0 z-10",
              // Rows scroll under the pinned header, so it must be opaque.
              isVirtual && "bg-card"
            )}
          >
            {table.getHeaderGroups().map((headerGroup) => (
              <Tr key={headerGroup.id} className="h-10">
                {headerGroup.headers.map((header) => {
                  const accessorKey = getAccessorKey(header.column.columnDef);

                  const sortable =
                    withSimpleSorting &&
                    accessorKey &&
                    !accessorKey.endsWith(".id") &&
                    header.column.columnDef.enableSorting !== false;

                  return (
                    <Th
                      key={header.id}
                      colSpan={header.colSpan}
                      className={cn(
                        "border-r border-border px-4 py-3 whitespace-nowrap text-sm",
                        sortable && "cursor-pointer"
                      )}
                      style={{
                        width: header.getSize()
                      }}
                    >
                      {header.isPlaceholder ? null : (
                        <div className="flex justify-start items-center text-xs text-zinc-500">
                          {flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                        </div>
                      )}
                    </Th>
                  );
                })}
              </Tr>
            ))}
          </Thead>
          <Tbody>
            {isVirtual
              ? renderVirtualRows()
              : rows.map((row) => renderRow(row))}
            {rows.length === 0 && !onNewRow && (
              <Tr className="h-10 hover:bg-muted/50">
                <Td colSpan={24}>
                  <p className="text-muted-foreground text-center w-full">
                    <Trans>No Data</Trans>
                  </p>
                </Td>
              </Tr>
            )}
            {onNewRow && !isVirtual && (
              <Tr
                onClick={onNewRow}
                className="cursor-pointer h-10 hover:bg-muted/50 border-t"
              >
                <Td colSpan={24}>
                  <HStack className="items-center h-6">
                    <LuCirclePlus className="text-muted-foreground h-4 w-4" />
                    <span>
                      <Trans>New</Trans>
                    </span>
                  </HStack>
                </Td>
              </Tr>
            )}
          </Tbody>
        </Table>
      </div>
      {onNewRow && isVirtual && (
        <button
          type="button"
          onClick={onNewRowClick}
          className="flex h-11 w-full items-center space-x-2 border-t border-border px-6 text-sm hover:bg-muted/50"
        >
          <LuCirclePlus className="text-muted-foreground h-4 w-4" />
          <span>
            <Trans>New</Trans>
          </span>
        </button>
      )}
    </VStack>
  );
};

export default Grid;