import React, { useState } from "react"; import { MRT_TableInstance, MRT_Column } from "material-react-table"; import { IconButton, Popover, TextField, Box, Divider, Switch, Typography, Button, } from "@mui/material"; import ShowHideColumns from "../../assets/TableIcons/ShowHideColumns"; interface Props { table: MRT_TableInstance; } export function ShowHideColumnsMenu({ table }: Props) { const [anchorEl, setAnchorEl] = useState(null); const [search, setSearch] = useState(""); const handleOpen = (event: React.MouseEvent) => setAnchorEl(event.currentTarget); const handleClose = () => { setAnchorEl(null); setSearch(""); }; const columnVisibility = table.getState().columnVisibility; const columnMatchesSearch = (col: MRT_Column, term: string): boolean => { if (!term) return true; const searchTerm = term.toLowerCase(); const headerText = col.columnDef.header?.toString().toLowerCase() ?? ""; if (headerText.includes(searchTerm)) return true; return (col.columns ?? []).some((child) => columnMatchesSearch(child as MRT_Column, term) ); }; const toggleColumn = (colId: string, value: boolean) => table.setColumnVisibility({ ...columnVisibility, [colId]: value }); const toggleGroup = (group: MRT_Column, value: boolean) => { const updates: Record = {}; group.getLeafColumns().forEach((leaf) => (updates[leaf.id] = value)); updates[group.id] = value; table.setColumnVisibility({ ...columnVisibility, ...updates }); }; const renderColumnGroup = (col: MRT_Column, level = 0) => { if (!columnMatchesSearch(col, search)) return null; const subCols = col.columns ?? []; const hasChildren = subCols.length > 0; if (hasChildren) { const groupVisible = col .getLeafColumns() .some((leaf) => columnVisibility[leaf.id] ?? true); return ( {col.columnDef.header?.toString() || "Group"} toggleGroup(col, e.target.checked)} /> {subCols .filter((child) => { const childCol = child as MRT_Column; return (childCol.columns?.length ?? 0) > 0 || !!childCol.columnDef.header; }) .map((child) => renderColumnGroup(child as MRT_Column, level + 1))} ); } if (!col.columnDef.header) return null; return ( {col.columnDef.header?.toString()} toggleColumn(col.id, e.target.checked)} /> ); }; const hideableLeafCols = table.getAllLeafColumns().filter((c) => c.getCanHide()); const allLeafHidden = hideableLeafCols.every( (c) => (columnVisibility[c.id] ?? true) === false ); const allLeafVisible = hideableLeafCols.every( (c) => (columnVisibility[c.id] ?? true) === true ); return ( <> setSearch(e.target.value)} sx={{ mb: 1, "& .MuiOutlinedInput-root": { borderRadius: "8px" }, }} /> {table .getAllColumns() .filter((col) => col.getCanHide()) .map((col) => renderColumnGroup(col))} ); }