@trellixio/roaster-coffee
Version:
Beans' product component library
52 lines (51 loc) • 1.89 kB
JavaScript
import { useContext, useCallback } from 'react';
import { SELECT_ALL_ITEMS, SelectionType, } from './types';
import { TableContext, TableRowContext, TableSelectionChangeContext } from './context';
export function useTableSelectionChange() {
const onSelectionChange = useContext(TableSelectionChangeContext);
if (!onSelectionChange) {
throw new Error(`Missing TableProvider context`);
}
return onSelectionChange;
}
export function useTableRow() {
const tableRow = useContext(TableRowContext);
if (!tableRow) {
throw new Error(`Missing TableProvider context`);
}
return tableRow;
}
export function useTableValue() {
const table = useContext(TableContext);
if (!table) {
throw new Error(`Missing TableProvider context`);
}
return table;
}
export function useBulkSelectionData({ selectedItemsCount, itemCount }) {
const selectable = Boolean(selectedItemsCount);
const selectMode = selectedItemsCount === 'All' || selectedItemsCount > 0;
let bulkSelectState = 'indeterminate';
if (!selectedItemsCount || selectedItemsCount === 0) {
bulkSelectState = undefined;
}
else if (selectedItemsCount === SELECT_ALL_ITEMS || selectedItemsCount === itemCount) {
bulkSelectState = true;
}
return {
selectMode,
bulkSelectState,
selectable,
};
}
export function useHandleBulkSelection({ onSelectionChange = () => { } }) {
const handleSelectionChange = useCallback((selectionType, selection) => {
if (selectionType === SelectionType.Single) {
onSelectionChange(SelectionType.Single, selection);
}
else if (selectionType === SelectionType.Page || selectionType === SelectionType.All) {
onSelectionChange(selectionType, SELECT_ALL_ITEMS);
}
}, [onSelectionChange]);
return handleSelectionChange;
}