import { TableCellStylesType } from "../attributes"; import { useTableStore } from "../store"; interface UseCellStyleControlOptions { styleKey: keyof TableCellStylesType; defaultValue: T; hasValue: (value: T) => boolean; label: string; labelSelected?: string; } interface CellStyleControlProps { value: T; hasValue: () => boolean; onChange: (value: T) => void; onDeselect: () => void; label: string; } export function useCellStyleControl({ styleKey, defaultValue, hasValue: hasValueFn, label, labelSelected, }: UseCellStyleControlOptions): CellStyleControlProps { const selectedCells = useTableStore(state => state.selectedCells); const cellDefaults = useTableStore(state => state.cellDefaults.styles); const getCellStyle = useTableStore(state => state.getCellStyle); const updateCellStyles = useTableStore(state => state.updateCellStyles); const updateCellGlobalStyles = useTableStore( state => state.updateCellGlobalStyles ); const firstSelectedCellStyle = selectedCells.length > 0 ? getCellStyle(selectedCells[0]) || {} : {}; const value = selectedCells.length > 0 && firstSelectedCellStyle[styleKey] ? ((firstSelectedCellStyle[styleKey] as T) ?? defaultValue) : (cellDefaults[styleKey] as T); const hasValue = () => { if (selectedCells.length > 0) { const cellValue = firstSelectedCellStyle[styleKey] as T; return cellValue ? hasValueFn(cellValue) : false; } else { const globalValue = cellDefaults[styleKey] as T; return hasValueFn(globalValue); } }; const computedLabel = selectedCells.length > 0 && labelSelected ? labelSelected : label; const onChange = (newValue: T) => { if (selectedCells.length > 0) { selectedCells.forEach(coord => { updateCellStyles(coord, { [styleKey]: newValue, } as Partial); }); } else { updateCellGlobalStyles({ [styleKey]: newValue, } as Partial); } }; const onDeselect = () => { if (selectedCells.length > 0) { selectedCells.forEach(coord => { updateCellStyles(coord, { [styleKey]: defaultValue, } as Partial); }); } else { updateCellGlobalStyles({ [styleKey]: defaultValue, } as Partial); } }; return { value, hasValue, onChange, onDeselect, label: computedLabel, }; }