Add reusable virtual table hook
This commit is contained in:
parent
3dcb0dc4ed
commit
481258484c
3 changed files with 330 additions and 52 deletions
255
src/renderer/components/virtual-table/hooks/use-virtual-table.ts
Normal file
255
src/renderer/components/virtual-table/hooks/use-virtual-table.ts
Normal file
|
@ -0,0 +1,255 @@
|
||||||
|
import {
|
||||||
|
BodyScrollEvent,
|
||||||
|
ColDef,
|
||||||
|
GetRowIdParams,
|
||||||
|
GridReadyEvent,
|
||||||
|
IDatasource,
|
||||||
|
PaginationChangedEvent,
|
||||||
|
RowDoubleClickedEvent,
|
||||||
|
RowModelType,
|
||||||
|
} from '@ag-grid-community/core';
|
||||||
|
import type { AgGridReact as AgGridReactType } from '@ag-grid-community/react/lib/agGridReact';
|
||||||
|
import { QueryKey, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import debounce from 'lodash/debounce';
|
||||||
|
import { MutableRefObject, useCallback, useMemo } from 'react';
|
||||||
|
import { generatePath, useNavigate } from 'react-router';
|
||||||
|
import { BasePaginatedResponse, LibraryItem } from '/@/renderer/api/types';
|
||||||
|
import { getColumnDefs, VirtualTableProps } from '/@/renderer/components/virtual-table';
|
||||||
|
import { SetContextMenuItems, useHandleTableContextMenu } from '/@/renderer/features/context-menu';
|
||||||
|
import { AppRoute } from '/@/renderer/router/routes';
|
||||||
|
import { ListDeterministicArgs, ListItemProps, ListTableProps } from '/@/renderer/store';
|
||||||
|
import { ListDisplayType, ServerListItem, TablePagination } from '/@/renderer/types';
|
||||||
|
|
||||||
|
export type AgGridFetchFn<TResponse, TFilter> = (
|
||||||
|
args: { filter: TFilter; limit: number; startIndex: number },
|
||||||
|
signal?: AbortSignal,
|
||||||
|
) => Promise<TResponse>;
|
||||||
|
|
||||||
|
interface UseAgGridProps<TResponse, TFilter> {
|
||||||
|
contextMenu: SetContextMenuItems;
|
||||||
|
fetch: {
|
||||||
|
filter: TFilter;
|
||||||
|
fn: AgGridFetchFn<TResponse, TFilter>;
|
||||||
|
itemCount?: number;
|
||||||
|
queryKey: (id: string, query?: Record<any, any>) => QueryKey;
|
||||||
|
server: ServerListItem | null;
|
||||||
|
};
|
||||||
|
itemCount?: number;
|
||||||
|
itemType: LibraryItem;
|
||||||
|
pageKey: string;
|
||||||
|
properties: ListItemProps<any>;
|
||||||
|
setTable: (args: { data: Partial<ListTableProps> } & ListDeterministicArgs) => void;
|
||||||
|
setTablePagination: (args: { data: Partial<TablePagination> } & ListDeterministicArgs) => void;
|
||||||
|
tableRef: MutableRefObject<AgGridReactType | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useVirtualTable = <TResponse, TFilter>({
|
||||||
|
fetch,
|
||||||
|
tableRef,
|
||||||
|
properties,
|
||||||
|
setTable,
|
||||||
|
setTablePagination,
|
||||||
|
pageKey,
|
||||||
|
itemType,
|
||||||
|
contextMenu,
|
||||||
|
itemCount,
|
||||||
|
}: UseAgGridProps<TResponse, TFilter>) => {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const isPaginationEnabled = properties.display === ListDisplayType.TABLE_PAGINATED;
|
||||||
|
|
||||||
|
const columnDefs: ColDef[] = useMemo(() => {
|
||||||
|
return getColumnDefs(properties.table.columns);
|
||||||
|
}, [properties.table.columns]);
|
||||||
|
|
||||||
|
const defaultColumnDefs: ColDef = useMemo(() => {
|
||||||
|
return {
|
||||||
|
lockPinned: true,
|
||||||
|
lockVisible: true,
|
||||||
|
resizable: true,
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const onGridSizeChange = () => {
|
||||||
|
if (properties.table.autoFit) {
|
||||||
|
tableRef?.current?.api.sizeColumnsToFit();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onGridReady = useCallback(
|
||||||
|
(params: GridReadyEvent) => {
|
||||||
|
const dataSource: IDatasource = {
|
||||||
|
getRows: async (params) => {
|
||||||
|
const limit = params.endRow - params.startRow;
|
||||||
|
const startIndex = params.startRow;
|
||||||
|
|
||||||
|
const queryKey = fetch.queryKey(fetch.server?.id || '', {
|
||||||
|
limit,
|
||||||
|
startIndex,
|
||||||
|
...fetch.filter,
|
||||||
|
});
|
||||||
|
|
||||||
|
const results = (await queryClient.fetchQuery(
|
||||||
|
queryKey,
|
||||||
|
async ({ signal }) => {
|
||||||
|
const res = await fetch.fn(
|
||||||
|
{
|
||||||
|
filter: fetch.filter,
|
||||||
|
limit,
|
||||||
|
startIndex,
|
||||||
|
},
|
||||||
|
signal,
|
||||||
|
);
|
||||||
|
|
||||||
|
return res;
|
||||||
|
},
|
||||||
|
|
||||||
|
{ cacheTime: 1000 * 60 * 1 },
|
||||||
|
)) as BasePaginatedResponse<any>;
|
||||||
|
|
||||||
|
params.successCallback(results?.items || [], results?.totalRecordCount || 0);
|
||||||
|
},
|
||||||
|
rowCount: undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
params.api.setDatasource(dataSource);
|
||||||
|
params.api.ensureIndexVisible(properties.table.scrollOffset || 0, 'top');
|
||||||
|
},
|
||||||
|
[fetch, properties.table.scrollOffset, queryClient],
|
||||||
|
);
|
||||||
|
|
||||||
|
const onPaginationChanged = useCallback(
|
||||||
|
(event: PaginationChangedEvent) => {
|
||||||
|
if (!isPaginationEnabled || !event.api) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Scroll to top of page on pagination change
|
||||||
|
const currentPageStartIndex =
|
||||||
|
properties.table.pagination.currentPage *
|
||||||
|
properties.table.pagination.itemsPerPage;
|
||||||
|
event.api?.ensureIndexVisible(currentPageStartIndex, 'top');
|
||||||
|
} catch (err) {
|
||||||
|
console.log(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTablePagination({
|
||||||
|
data: {
|
||||||
|
itemsPerPage: event.api.paginationGetPageSize(),
|
||||||
|
totalItems: event.api.paginationGetRowCount(),
|
||||||
|
totalPages: event.api.paginationGetTotalPages() + 1,
|
||||||
|
},
|
||||||
|
key: pageKey,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[
|
||||||
|
isPaginationEnabled,
|
||||||
|
setTablePagination,
|
||||||
|
pageKey,
|
||||||
|
properties.table.pagination.currentPage,
|
||||||
|
properties.table.pagination.itemsPerPage,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const onColumnMoved = useCallback(() => {
|
||||||
|
const { columnApi } = tableRef?.current || {};
|
||||||
|
const columnsOrder = columnApi?.getAllGridColumns();
|
||||||
|
|
||||||
|
if (!columnsOrder) return;
|
||||||
|
|
||||||
|
const columnsInSettings = properties.table.columns;
|
||||||
|
const updatedColumns = [];
|
||||||
|
for (const column of columnsOrder) {
|
||||||
|
const columnInSettings = columnsInSettings.find(
|
||||||
|
(c) => c.column === column.getColDef().colId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (columnInSettings) {
|
||||||
|
updatedColumns.push({
|
||||||
|
...columnInSettings,
|
||||||
|
...(!properties.table.autoFit && {
|
||||||
|
width: column.getActualWidth(),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setTable({ data: { columns: updatedColumns }, key: pageKey });
|
||||||
|
}, [pageKey, properties.table.autoFit, properties.table.columns, setTable, tableRef]);
|
||||||
|
|
||||||
|
const onColumnResized = debounce(onColumnMoved, 200);
|
||||||
|
|
||||||
|
const onBodyScrollEnd = (e: BodyScrollEvent) => {
|
||||||
|
const scrollOffset = Number((e.top / properties.table.rowHeight).toFixed(0));
|
||||||
|
setTable({ data: { scrollOffset }, key: pageKey });
|
||||||
|
};
|
||||||
|
|
||||||
|
const onCellContextMenu = useHandleTableContextMenu(itemType, contextMenu);
|
||||||
|
|
||||||
|
const defaultTableProps: Partial<VirtualTableProps> = useMemo(() => {
|
||||||
|
return {
|
||||||
|
alwaysShowHorizontalScroll: true,
|
||||||
|
autoFitColumns: properties.table.autoFit,
|
||||||
|
blockLoadDebounceMillis: 200,
|
||||||
|
getRowId: (data: GetRowIdParams<any>) => data.data.id,
|
||||||
|
infiniteInitialRowCount: itemCount || 100,
|
||||||
|
pagination: isPaginationEnabled,
|
||||||
|
paginationAutoPageSize: isPaginationEnabled,
|
||||||
|
paginationPageSize: properties.table.pagination.itemsPerPage || 100,
|
||||||
|
paginationProps: isPaginationEnabled
|
||||||
|
? {
|
||||||
|
pageKey,
|
||||||
|
pagination: properties.table.pagination,
|
||||||
|
setPagination: setTablePagination,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
rowBuffer: 20,
|
||||||
|
rowHeight: properties.table.rowHeight || 40,
|
||||||
|
rowModelType: 'infinite' as RowModelType,
|
||||||
|
suppressRowDrag: true,
|
||||||
|
};
|
||||||
|
}, [
|
||||||
|
isPaginationEnabled,
|
||||||
|
itemCount,
|
||||||
|
pageKey,
|
||||||
|
properties.table.autoFit,
|
||||||
|
properties.table.pagination,
|
||||||
|
properties.table.rowHeight,
|
||||||
|
setTablePagination,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const onRowDoubleClicked = useCallback(
|
||||||
|
(e: RowDoubleClickedEvent) => {
|
||||||
|
switch (itemType) {
|
||||||
|
case LibraryItem.ALBUM:
|
||||||
|
navigate(generatePath(AppRoute.LIBRARY_ALBUMS_DETAIL, { albumId: e.data.id }));
|
||||||
|
break;
|
||||||
|
case LibraryItem.ARTIST:
|
||||||
|
navigate(
|
||||||
|
generatePath(AppRoute.LIBRARY_ARTISTS_DETAIL, { artistId: e.data.id }),
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case LibraryItem.PLAYLIST:
|
||||||
|
navigate(generatePath(AppRoute.PLAYLISTS_DETAIL, { playlistId: e.data.id }));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[itemType, navigate],
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
columnDefs,
|
||||||
|
defaultColumnDefs,
|
||||||
|
onBodyScrollEnd,
|
||||||
|
onCellContextMenu,
|
||||||
|
onColumnMoved,
|
||||||
|
onColumnResized,
|
||||||
|
onGridReady,
|
||||||
|
onGridSizeChange,
|
||||||
|
onPaginationChanged,
|
||||||
|
onRowDoubleClicked,
|
||||||
|
...defaultTableProps,
|
||||||
|
};
|
||||||
|
};
|
|
@ -1,4 +1,3 @@
|
||||||
/* eslint-disable import/no-cycle */
|
|
||||||
import { Ref, forwardRef, useRef, useEffect, useCallback, useMemo } from 'react';
|
import { Ref, forwardRef, useRef, useEffect, useCallback, useMemo } from 'react';
|
||||||
import type {
|
import type {
|
||||||
ICellRendererParams,
|
ICellRendererParams,
|
||||||
|
@ -19,6 +18,7 @@ import { useClickOutside, useMergedRef } from '@mantine/hooks';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import relativeTime from 'dayjs/plugin/relativeTime';
|
import relativeTime from 'dayjs/plugin/relativeTime';
|
||||||
import formatDuration from 'format-duration';
|
import formatDuration from 'format-duration';
|
||||||
|
import { AnimatePresence } from 'framer-motion';
|
||||||
import { generatePath } from 'react-router';
|
import { generatePath } from 'react-router';
|
||||||
import styled from 'styled-components';
|
import styled from 'styled-components';
|
||||||
import { AlbumArtistCell } from '/@/renderer/components/virtual-table/cells/album-artist-cell';
|
import { AlbumArtistCell } from '/@/renderer/components/virtual-table/cells/album-artist-cell';
|
||||||
|
@ -29,9 +29,10 @@ import { GenreCell } from '/@/renderer/components/virtual-table/cells/genre-cell
|
||||||
import { GenericTableHeader } from '/@/renderer/components/virtual-table/headers/generic-table-header';
|
import { GenericTableHeader } from '/@/renderer/components/virtual-table/headers/generic-table-header';
|
||||||
import { AppRoute } from '/@/renderer/router/routes';
|
import { AppRoute } from '/@/renderer/router/routes';
|
||||||
import { PersistedTableColumn } from '/@/renderer/store/settings.store';
|
import { PersistedTableColumn } from '/@/renderer/store/settings.store';
|
||||||
import { TableColumn } from '/@/renderer/types';
|
import { TableColumn, TablePagination as TablePaginationType } from '/@/renderer/types';
|
||||||
import { FavoriteCell } from '/@/renderer/components/virtual-table/cells/favorite-cell';
|
import { FavoriteCell } from '/@/renderer/components/virtual-table/cells/favorite-cell';
|
||||||
import { RatingCell } from '/@/renderer/components/virtual-table/cells/rating-cell';
|
import { RatingCell } from '/@/renderer/components/virtual-table/cells/rating-cell';
|
||||||
|
import { TablePagination } from '/@/renderer/components/virtual-table/table-pagination';
|
||||||
|
|
||||||
export * from './table-config-dropdown';
|
export * from './table-config-dropdown';
|
||||||
export * from './table-pagination';
|
export * from './table-pagination';
|
||||||
|
@ -352,10 +353,15 @@ export const getColumnDefs = (columns: PersistedTableColumn[]) => {
|
||||||
return columnDefs;
|
return columnDefs;
|
||||||
};
|
};
|
||||||
|
|
||||||
interface VirtualTableProps extends AgGridReactProps {
|
export interface VirtualTableProps extends AgGridReactProps {
|
||||||
autoFitColumns?: boolean;
|
autoFitColumns?: boolean;
|
||||||
autoHeight?: boolean;
|
autoHeight?: boolean;
|
||||||
deselectOnClickOutside?: boolean;
|
deselectOnClickOutside?: boolean;
|
||||||
|
paginationProps?: {
|
||||||
|
pageKey: string;
|
||||||
|
pagination: TablePaginationType;
|
||||||
|
setPagination: any;
|
||||||
|
};
|
||||||
transparentHeader?: boolean;
|
transparentHeader?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -370,6 +376,7 @@ export const VirtualTable = forwardRef(
|
||||||
onNewColumnsLoaded,
|
onNewColumnsLoaded,
|
||||||
onGridReady,
|
onGridReady,
|
||||||
onGridSizeChanged,
|
onGridSizeChanged,
|
||||||
|
paginationProps,
|
||||||
...rest
|
...rest
|
||||||
}: VirtualTableProps,
|
}: VirtualTableProps,
|
||||||
ref: Ref<AgGridReactType | null>,
|
ref: Ref<AgGridReactType | null>,
|
||||||
|
@ -453,40 +460,54 @@ export const VirtualTable = forwardRef(
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TableWrapper
|
<>
|
||||||
ref={deselectRef}
|
<TableWrapper
|
||||||
className={
|
ref={deselectRef}
|
||||||
transparentHeader
|
className={
|
||||||
? 'ag-header-transparent ag-theme-alpine-dark'
|
transparentHeader
|
||||||
: 'ag-theme-alpine-dark'
|
? 'ag-header-transparent ag-theme-alpine-dark'
|
||||||
}
|
: 'ag-theme-alpine-dark'
|
||||||
>
|
}
|
||||||
<AgGridReact
|
>
|
||||||
ref={mergedRef}
|
<AgGridReact
|
||||||
animateRows
|
ref={mergedRef}
|
||||||
maintainColumnOrder
|
animateRows
|
||||||
suppressAsyncEvents
|
maintainColumnOrder
|
||||||
suppressContextMenu
|
suppressAsyncEvents
|
||||||
suppressCopyRowsToClipboard
|
suppressContextMenu
|
||||||
suppressMoveWhenRowDragging
|
suppressCopyRowsToClipboard
|
||||||
suppressPaginationPanel
|
suppressMoveWhenRowDragging
|
||||||
suppressScrollOnNewData
|
suppressPaginationPanel
|
||||||
blockLoadDebounceMillis={200}
|
suppressScrollOnNewData
|
||||||
cacheBlockSize={300}
|
blockLoadDebounceMillis={200}
|
||||||
cacheOverflowSize={1}
|
cacheBlockSize={300}
|
||||||
defaultColDef={defaultColumnDefs}
|
cacheOverflowSize={1}
|
||||||
enableCellChangeFlash={false}
|
defaultColDef={defaultColumnDefs}
|
||||||
headerHeight={36}
|
enableCellChangeFlash={false}
|
||||||
rowBuffer={30}
|
headerHeight={36}
|
||||||
rowSelection="multiple"
|
rowBuffer={30}
|
||||||
{...rest}
|
rowSelection="multiple"
|
||||||
onColumnMoved={handleColumnMoved}
|
{...rest}
|
||||||
onGridReady={handleGridReady}
|
onColumnMoved={handleColumnMoved}
|
||||||
onGridSizeChanged={handleGridSizeChanged}
|
onGridReady={handleGridReady}
|
||||||
onModelUpdated={handleModelUpdated}
|
onGridSizeChanged={handleGridSizeChanged}
|
||||||
onNewColumnsLoaded={handleNewColumnsLoaded}
|
onModelUpdated={handleModelUpdated}
|
||||||
/>
|
onNewColumnsLoaded={handleNewColumnsLoaded}
|
||||||
</TableWrapper>
|
/>
|
||||||
|
{paginationProps && (
|
||||||
|
<AnimatePresence
|
||||||
|
presenceAffectsLayout
|
||||||
|
initial={false}
|
||||||
|
mode="wait"
|
||||||
|
>
|
||||||
|
<TablePagination
|
||||||
|
{...paginationProps}
|
||||||
|
tableRef={tableRef}
|
||||||
|
/>
|
||||||
|
</AnimatePresence>
|
||||||
|
)}
|
||||||
|
</TableWrapper>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
|
@ -29,17 +29,17 @@ export type ListKey = keyof ListState['item'] | string;
|
||||||
|
|
||||||
type FilterType = AlbumListFilter | SongListFilter | AlbumArtistListFilter;
|
type FilterType = AlbumListFilter | SongListFilter | AlbumArtistListFilter;
|
||||||
|
|
||||||
type ListTableProps = {
|
export type ListTableProps = {
|
||||||
pagination: TablePagination;
|
pagination: TablePagination;
|
||||||
scrollOffset: number;
|
scrollOffset: number;
|
||||||
} & DataTableProps;
|
} & DataTableProps;
|
||||||
|
|
||||||
type ListGridProps = {
|
export type ListGridProps = {
|
||||||
itemsPerRow?: number;
|
itemsPerRow?: number;
|
||||||
scrollOffset?: number;
|
scrollOffset?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
type ItemProps<TFilter = any> = {
|
export type ListItemProps<TFilter = any> = {
|
||||||
display: ListDisplayType;
|
display: ListDisplayType;
|
||||||
filter: TFilter;
|
filter: TFilter;
|
||||||
grid?: ListGridProps;
|
grid?: ListGridProps;
|
||||||
|
@ -48,31 +48,33 @@ type ItemProps<TFilter = any> = {
|
||||||
|
|
||||||
export interface ListState {
|
export interface ListState {
|
||||||
detail: {
|
detail: {
|
||||||
[key: string]: Omit<ItemProps<any>, 'display'>;
|
[key: string]: Omit<ListItemProps<any>, 'display'>;
|
||||||
};
|
};
|
||||||
item: {
|
item: {
|
||||||
album: ItemProps<AlbumListFilter>;
|
album: ListItemProps<AlbumListFilter>;
|
||||||
albumArtist: ItemProps<AlbumArtistListFilter>;
|
albumArtist: ListItemProps<AlbumArtistListFilter>;
|
||||||
albumDetail: ItemProps<any>;
|
albumDetail: ListItemProps<any>;
|
||||||
song: ItemProps<SongListFilter>;
|
song: ListItemProps<SongListFilter>;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
type DeterministicArgs = { key: ListKey };
|
export type ListDeterministicArgs = { key: ListKey };
|
||||||
|
|
||||||
export interface ListSlice extends ListState {
|
export interface ListSlice extends ListState {
|
||||||
_actions: {
|
_actions: {
|
||||||
getFilter: (args: { id?: string; itemType: LibraryItem; key?: string }) => FilterType;
|
getFilter: (args: { id?: string; itemType: LibraryItem; key?: string }) => FilterType;
|
||||||
resetFilter: () => void;
|
resetFilter: () => void;
|
||||||
setDisplayType: (args: { data: ListDisplayType } & DeterministicArgs) => void;
|
setDisplayType: (args: { data: ListDisplayType } & ListDeterministicArgs) => void;
|
||||||
setFilter: (
|
setFilter: (
|
||||||
args: { data: Partial<FilterType>; itemType: LibraryItem } & DeterministicArgs,
|
args: { data: Partial<FilterType>; itemType: LibraryItem } & ListDeterministicArgs,
|
||||||
) => FilterType;
|
) => FilterType;
|
||||||
setGrid: (args: { data: Partial<ListGridProps> } & DeterministicArgs) => void;
|
setGrid: (args: { data: Partial<ListGridProps> } & ListDeterministicArgs) => void;
|
||||||
setStore: (data: Partial<ListSlice>) => void;
|
setStore: (data: Partial<ListSlice>) => void;
|
||||||
setTable: (args: { data: Partial<ListTableProps> } & DeterministicArgs) => void;
|
setTable: (args: { data: Partial<ListTableProps> } & ListDeterministicArgs) => void;
|
||||||
setTableColumns: (args: { data: PersistedTableColumn[] } & DeterministicArgs) => void;
|
setTableColumns: (args: { data: PersistedTableColumn[] } & ListDeterministicArgs) => void;
|
||||||
setTablePagination: (args: { data: Partial<TablePagination> } & DeterministicArgs) => void;
|
setTablePagination: (
|
||||||
|
args: { data: Partial<TablePagination> } & ListDeterministicArgs,
|
||||||
|
) => void;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Reference in a new issue