infoalloggi-monorepo/apps/infoalloggi/src/providers/StorageTableProvider.tsx

69 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-08-04 17:45:44 +02:00
import type { Table } from "@tanstack/react-table";
import {
2025-08-28 18:27:07 +02:00
createContext,
type ReactNode,
useCallback,
useContext,
useState,
2025-08-04 17:45:44 +02:00
} from "react";
2025-10-24 16:10:59 +02:00
import type { FileMetadataWithAdmin } from "~/server/services/storage.service";
2025-08-28 18:27:07 +02:00
2025-10-24 16:10:59 +02:00
type TData = FileMetadataWithAdmin;
2025-08-04 17:45:44 +02:00
export type StorageTable = Table<TData>;
const StorageTableContext = createContext<{
2025-08-28 18:27:07 +02:00
table: StorageTable | undefined;
setTable: (table: StorageTable | undefined) => void;
2025-10-24 16:10:59 +02:00
selectedRows: TData[];
2025-08-28 18:27:07 +02:00
cb_onStateChange: () => void;
2025-08-04 17:45:44 +02:00
}>({
2025-08-29 16:18:32 +02:00
cb_onStateChange: () => {},
selectedRows: [],
2025-08-28 18:27:07 +02:00
setTable: () => {},
2025-08-29 16:18:32 +02:00
table: undefined,
2025-08-04 17:45:44 +02:00
});
export const StorageTableProvider = ({ children }: { children: ReactNode }) => {
2025-08-28 18:27:07 +02:00
const [table, setTable] = useState<StorageTable | undefined>(undefined);
2025-08-04 17:45:44 +02:00
2025-10-24 16:10:59 +02:00
const [selectedRows, setSelectedRows] = useState<TData[]>([]);
2025-08-04 17:45:44 +02:00
2025-08-28 18:27:07 +02:00
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;
},
[],
);
2025-10-24 16:10:59 +02:00
setSelectedRows(selected);
2025-08-28 18:27:07 +02:00
}
}, [table]);
2025-08-04 17:45:44 +02:00
2025-08-28 18:27:07 +02:00
return (
<StorageTableContext.Provider
2025-08-29 16:18:32 +02:00
value={{ cb_onStateChange, selectedRows, setTable, table }}
2025-08-28 18:27:07 +02:00
>
{children}
</StorageTableContext.Provider>
);
2025-08-04 17:45:44 +02:00
};
export const useStorageTable = () => {
2025-08-28 18:27:07 +02:00
const context = useContext(StorageTableContext);
if (!context) {
throw new Error(
"useStorageTable must be used within a StorageTableProvider",
);
}
return context;
2025-08-04 17:45:44 +02:00
};