2024-05-02 19:30:44 +00:00
|
|
|
// from https://stackoverflow.com/a/68213902/15458245
|
2024-05-02 18:53:19 +00:00
|
|
|
|
|
|
|
|
import { HeaderProps, Row } from "react-table";
|
|
|
|
|
|
|
|
|
|
interface GetConditionalSelectHeaderCheckboxProps {
|
|
|
|
|
/** react-table header props */
|
|
|
|
|
headerProps: React.PropsWithChildren<HeaderProps<any>>;
|
|
|
|
|
checkIfRowIsSelectable: (row: Row<any>) => boolean;
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-02 19:30:44 +00:00
|
|
|
export const getConditionalSelectHeaderCheckboxProps = ({
|
2024-05-02 18:53:19 +00:00
|
|
|
headerProps,
|
|
|
|
|
checkIfRowIsSelectable,
|
|
|
|
|
}: GetConditionalSelectHeaderCheckboxProps) => {
|
|
|
|
|
// Define if the checkbox should show as checked or indeterminate
|
2026-02-25 11:49:07 +00:00
|
|
|
const checkIfAllSelectableRowsSelected = (rows: Row<any>[]) => {
|
|
|
|
|
const selectableRows = rows.filter(checkIfRowIsSelectable);
|
|
|
|
|
return (
|
|
|
|
|
selectableRows.length > 0 && selectableRows.every((row) => row.isSelected)
|
|
|
|
|
);
|
|
|
|
|
};
|
2024-05-02 19:30:44 +00:00
|
|
|
const allSelectableRowsSelected = checkIfAllSelectableRowsSelected(
|
|
|
|
|
headerProps.rows
|
|
|
|
|
);
|
2024-05-02 18:53:19 +00:00
|
|
|
const indeterminate =
|
2024-05-02 19:30:44 +00:00
|
|
|
!allSelectableRowsSelected &&
|
|
|
|
|
headerProps.rows.some((row) => row.isSelected);
|
2024-05-02 18:53:19 +00:00
|
|
|
|
|
|
|
|
const onChange = () => {
|
|
|
|
|
if (checkIfAllSelectableRowsSelected(headerProps.rows)) {
|
|
|
|
|
headerProps.rows.forEach((row) => {
|
|
|
|
|
headerProps.toggleRowSelected(row.id, false);
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
// Otherwise select every selectable row on the page
|
2026-03-04 14:39:04 +00:00
|
|
|
headerProps.rows.forEach((row) => {
|
2024-05-02 18:53:19 +00:00
|
|
|
const rowChecked = checkIfRowIsSelectable(row);
|
|
|
|
|
headerProps.toggleRowSelected(row.id, rowChecked);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Usual checkbox props
|
|
|
|
|
const checkboxProps = headerProps.getToggleAllRowsSelectedProps();
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
...checkboxProps,
|
2024-05-02 19:30:44 +00:00
|
|
|
value: allSelectableRowsSelected,
|
2024-05-02 18:53:19 +00:00
|
|
|
indeterminate,
|
|
|
|
|
onChange,
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default { getConditionalSelectHeaderCheckboxProps };
|