import type { Table } from "@tanstack/react-table"; import { createContext, type ReactNode, useCallback, useContext, useState, } from "react"; import type { Storageindex, StorageindexId, } from "~/schemas/public/Storageindex"; type TData = { id: StorageindexId; filename: string | null; ext: string | null; created_at: Date; from_admin: boolean; actions: string; expires_at: Date | null; }; export type StorageTable = Table; const StorageTableContext = createContext<{ table: StorageTable | undefined; setTable: (table: StorageTable | undefined) => void; selectedRows: Storageindex[]; cb_onStateChange: () => void; }>({ cb_onStateChange: () => {}, selectedRows: [], setTable: () => {}, table: undefined, }); export const StorageTableProvider = ({ children }: { children: ReactNode }) => { const [table, setTable] = useState(undefined); const [selectedRows, setSelectedRows] = useState([]); 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.map((r) => ({ created_at: r.created_at, expires_at: r.expires_at, ext: r.ext, filename: r.filename, from_admin: r.from_admin, id: r.id, })), ); } }, [table]); return ( {children} ); }; export const useStorageTable = () => { const context = useContext(StorageTableContext); if (!context) { throw new Error( "useStorageTable must be used within a StorageTableProvider", ); } return context; };