2022-01-17 05:53:32 +00:00
|
|
|
import {
|
|
|
|
Context,
|
|
|
|
createContext,
|
|
|
|
ReactNode,
|
|
|
|
useCallback,
|
|
|
|
useContext,
|
|
|
|
useMemo,
|
|
|
|
useState,
|
|
|
|
} from 'react';
|
2022-01-04 12:16:09 +00:00
|
|
|
|
|
|
|
import { useLocalStorage } from '@/portainer/hooks/useLocalStorage';
|
|
|
|
|
2022-08-11 04:33:29 +00:00
|
|
|
interface TableSettingsContextInterface<T> {
|
2022-01-04 12:16:09 +00:00
|
|
|
settings: T;
|
|
|
|
setTableSettings(partialSettings: Partial<T>): void;
|
|
|
|
setTableSettings(mutation: (settings: T) => T): void;
|
|
|
|
}
|
|
|
|
|
|
|
|
const TableSettingsContext = createContext<TableSettingsContextInterface<
|
|
|
|
Record<string, unknown>
|
|
|
|
> | null>(null);
|
2022-09-20 18:14:24 +00:00
|
|
|
TableSettingsContext.displayName = 'TableSettingsContext';
|
2022-01-04 12:16:09 +00:00
|
|
|
|
|
|
|
export function useTableSettings<T>() {
|
|
|
|
const Context = getContextType<T>();
|
|
|
|
|
|
|
|
const context = useContext(Context);
|
|
|
|
|
|
|
|
if (context === null) {
|
|
|
|
throw new Error('must be nested under TableSettingsProvider');
|
|
|
|
}
|
|
|
|
|
|
|
|
return context;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface ProviderProps<T> {
|
|
|
|
children: ReactNode;
|
|
|
|
defaults?: T;
|
|
|
|
storageKey: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function TableSettingsProvider<T>({
|
|
|
|
children,
|
|
|
|
defaults,
|
|
|
|
storageKey,
|
|
|
|
}: ProviderProps<T>) {
|
|
|
|
const Context = getContextType<T>();
|
|
|
|
|
|
|
|
const [storage, setStorage] = useLocalStorage<T>(
|
|
|
|
keyBuilder(storageKey),
|
|
|
|
defaults as T
|
|
|
|
);
|
|
|
|
|
|
|
|
const [settings, setTableSettings] = useState(storage);
|
|
|
|
|
2022-01-17 05:53:32 +00:00
|
|
|
const handleChange = useCallback(
|
|
|
|
(mutation: Partial<T> | ((settings: T) => T)): void => {
|
|
|
|
setTableSettings((settings) => {
|
|
|
|
const newTableSettings =
|
|
|
|
mutation instanceof Function
|
|
|
|
? mutation(settings)
|
|
|
|
: { ...settings, ...mutation };
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2022-01-17 05:53:32 +00:00
|
|
|
setStorage(newTableSettings);
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2022-01-17 05:53:32 +00:00
|
|
|
return newTableSettings;
|
|
|
|
});
|
|
|
|
},
|
|
|
|
[setStorage]
|
|
|
|
);
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2022-01-17 05:53:32 +00:00
|
|
|
const contextValue = useMemo(
|
|
|
|
() => ({
|
|
|
|
settings,
|
|
|
|
setTableSettings: handleChange,
|
|
|
|
}),
|
|
|
|
[settings, handleChange]
|
|
|
|
);
|
|
|
|
|
|
|
|
return <Context.Provider value={contextValue}>{children}</Context.Provider>;
|
2022-01-04 12:16:09 +00:00
|
|
|
|
|
|
|
function keyBuilder(key: string) {
|
|
|
|
return `datatable_TableSettings_${key}`;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function getContextType<T>() {
|
2022-01-17 05:53:32 +00:00
|
|
|
return TableSettingsContext as unknown as Context<
|
2022-01-04 12:16:09 +00:00
|
|
|
TableSettingsContextInterface<T>
|
|
|
|
>;
|
|
|
|
}
|