infoalloggi-monorepo/apps/infoalloggi/src/providers/StorageTableProvider.tsx
2026-05-19 18:42:34 +02:00

68 lines
1.6 KiB
TypeScript

import type { Table } from "@tanstack/react-table";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useState,
} from "react";
import type { FileMetadataWithAdmin } from "~/server/services/storage.service";
type TData = FileMetadataWithAdmin;
export type StorageTableType = Table<TData>;
const StorageTableContext = createContext<{
table: StorageTableType | undefined;
setTable: (table: StorageTableType | undefined) => void;
selectedRows: TData[];
cb_onStateChange: () => void;
}>({
cb_onStateChange: () => {},
selectedRows: [],
setTable: () => {},
table: undefined,
});
export const StorageTableProvider = ({ children }: { children: ReactNode }) => {
const [table, setTable] = useState<StorageTableType | undefined>(undefined);
const [selectedRows, setSelectedRows] = useState<TData[]>([]);
const cb_onStateChange = useCallback(() => {
if (table) {
const rowSelection = table.getState().rowSelection;
const data = table.getCoreRowModel().rowsById;
const selected = Object.keys(rowSelection).reduce(
(acc: TData[], rowId) => {
const row = data[rowId];
if (row && rowSelection[rowId]) {
acc.push(row.original);
}
return acc;
},
[],
);
setSelectedRows(selected);
}
}, [table]);
return (
<StorageTableContext.Provider
value={{ cb_onStateChange, selectedRows, setTable, table }}
>
{children}
</StorageTableContext.Provider>
);
};
export const useStorageTable = () => {
const context = useContext(StorageTableContext);
if (!context) {
throw new Error(
"useStorageTable must be used within a StorageTableProvider",
);
}
return context;
};