import React, { createContext, forwardRef, RefObject, useCallback, useEffect, useRef, useState } from "react"; import equal from "react-fast-compare" // @ts-ignore import { FixedSizeList as List } from "react-window"; import useMeasure from "react-use-measure"; import { CircularProgressCenter } from "../CircularProgressCenter"; import { OnVirtualTableColumnResizeParams, VirtualTableColumn, VirtualTableFilterValues, VirtualTableProps, VirtualTableWhereFilterOp } from "./VirtualTableProps"; import { getRowHeight } from "./common"; import { VirtualTableContextProps } from "./types"; import { VirtualTableHeaderRow } from "./VirtualTableHeaderRow"; import { VirtualTableRow } from "./VirtualTableRow"; import { VirtualTableCell } from "./VirtualTableCell"; import { AssignmentIcon, CenteredView, cn, Typography } from "@firecms/ui"; const VirtualListContext = createContext>({} as any); VirtualListContext.displayName = "VirtualListContext"; type InnerElementProps = { children: React.ReactNode, style: any }; // eslint-disable-next-line react/display-name const innerElementType = forwardRef(({ children, ...rest }: InnerElementProps, ref) => { return ( {(virtualTableProps) => { const customView = virtualTableProps.customView; return ( <>
{!customView && children}
{customView &&
{customView}
} ); }}
); }) ; /** * This is a Table component that allows displaying arbitrary data, not * necessarily related to entities or properties. It is the component * that powers the entity collections but has a generic API, so it * can be reused. * * @group Components */ export const VirtualTable = React.memo>( function VirtualTable>({ data, onResetPagination, onEndReached, size = "m", columns: columnsProp, onRowClick, onColumnResize, filter: filterInput, checkFilterCombination, onFilterUpdate, sortBy, error, emptyComponent, onSortByUpdate, loading, cellRenderer, hoverRow, createFilterField, rowClassName, className, endAdornment, AddColumnComponent }: VirtualTableProps) { const sortByProperty: string | undefined = sortBy ? sortBy[0] : undefined; const currentSort: "asc" | "desc" | undefined = sortBy ? sortBy[1] : undefined; const [columns, setColumns] = useState(columnsProp); const tableRef = useRef(null); const endReachCallbackThreshold = useRef(0); useEffect(() => { setColumns(columnsProp); }, [columnsProp]); const [measureRef, bounds] = useMeasure(); const onColumnResizeInternal = useCallback((params: OnVirtualTableColumnResizeParams) => { setColumns(columns.map((column) => column.key === params.column.key ? params.column : column)); }, [columns]); const onColumnResizeEndInternal = useCallback((params: OnVirtualTableColumnResizeParams) => { setColumns(columns.map((column) => column.key === params.column.key ? params.column : column)); if (onColumnResize) { onColumnResize(params); } }, [columns, onColumnResize]); // saving the current filter as a ref as a workaround for header closure const filterRef = useRef | undefined>(); useEffect(() => { filterRef.current = filterInput; }, [filterInput]); const scrollToTop = useCallback(() => { endReachCallbackThreshold.current = 0; if (tableRef.current) { // scrollRef.current = [scrollRef.current[0], 0]; tableRef.current.scrollTo(tableRef.current?.scrollLeft, 0); } }, []); const onColumnSort = useCallback((key: string) => { const isDesc = sortByProperty === key && currentSort === "desc"; const isAsc = sortByProperty === key && currentSort === "asc"; const newSort = isAsc ? "desc" : (isDesc ? undefined : "asc"); const newSortProperty: string | undefined = isDesc ? undefined : key; const filter = filterRef.current; const newSortBy: [string, "asc" | "desc"] | undefined = newSort && newSortProperty ? [newSortProperty, newSort] : undefined; if (filter) { if (checkFilterCombination && !checkFilterCombination(filter, newSortBy)) { if (onFilterUpdate) onFilterUpdate(undefined); } } if (onResetPagination) { onResetPagination(); } if (onSortByUpdate) { onSortByUpdate(newSortBy); } scrollToTop(); }, [checkFilterCombination, currentSort, onFilterUpdate, onResetPagination, onSortByUpdate, scrollToTop, sortByProperty]); const resetSort = useCallback(() => { endReachCallbackThreshold.current = 0; if (onSortByUpdate) onSortByUpdate(undefined); }, [onSortByUpdate]); const maxScroll = Math.max((data?.length ?? 0) * getRowHeight(size) - bounds.height, 0); const onEndReachedInternal = useCallback((scrollOffset: number) => { if (onEndReached && (data?.length ?? 0) > 0 && scrollOffset > endReachCallbackThreshold.current + 600) { endReachCallbackThreshold.current = scrollOffset; onEndReached(); } }, [data?.length, onEndReached]); const onScroll = useCallback(({ scrollOffset, scrollUpdateWasRequested }: { scrollDirection: "forward" | "backward", scrollOffset: number, scrollUpdateWasRequested: boolean; }) => { if (!scrollUpdateWasRequested && (scrollOffset >= maxScroll - 600)) onEndReachedInternal(scrollOffset); }, [maxScroll, onEndReachedInternal]); const onFilterUpdateInternal = useCallback((column: VirtualTableColumn, filterForProperty?: [VirtualTableWhereFilterOp, any]) => { endReachCallbackThreshold.current = 0; const filter = filterRef.current; let newFilterValue: VirtualTableFilterValues = filter ? { ...filter } : {}; if (!filterForProperty) { delete newFilterValue[column.key]; } else { newFilterValue[column.key] = filterForProperty; } const newSortBy: [string, "asc" | "desc"] | undefined = sortByProperty && currentSort ? [sortByProperty, currentSort] : undefined; const isNewFilterCombinationValid = !checkFilterCombination || checkFilterCombination(newFilterValue, newSortBy); if (!isNewFilterCombinationValid) { newFilterValue = filterForProperty ? { [column.key]: filterForProperty } as VirtualTableFilterValues> : {}; } if (onFilterUpdate) onFilterUpdate(newFilterValue); }, [checkFilterCombination, currentSort, onFilterUpdate, sortByProperty]); const buildEmptyView = useCallback(() => { if (loading) return ; return
{emptyComponent}
; }, [emptyComponent, loading]); const empty = !loading && (data?.length ?? 0) === 0; const customView = error ? {"Error fetching data from the data source"} {error?.message && } : (empty ? buildEmptyView() : undefined); const virtualListController = { data, size, cellRenderer, columns, currentSort, onRowClick, customView, onColumnResize: onColumnResizeInternal, onColumnResizeEnd: onColumnResizeEndInternal, filter: filterRef.current, onColumnSort, onFilterUpdate: onFilterUpdateInternal, sortByProperty, hoverRow: hoverRow ?? false, createFilterField, rowClassName, endAdornment, AddColumnComponent }; // useTraceUpdate(virtualListController); return (
); }, equal ); function MemoizedList({ outerRef, width, height, itemCount, onScroll, itemSize, includeAddColumn }: { outerRef: RefObject; width: number; height: number; itemCount: number; onScroll: (params: { scrollDirection: "forward" | "backward", scrollOffset: number, scrollUpdateWasRequested: boolean; }) => void; itemSize: number; includeAddColumn?: boolean; }) { const Row = useCallback(({ index, style }: any) => { return {({ onRowClick, data, columns, size = "m", cellRenderer, hoverRow, rowClassName, endAdornment }) => { if (endAdornment && index === (data ?? []).length) { return
{endAdornment}
; } const rowData = data && data[index]; return ( {columns.map((column: VirtualTableColumn, columnIndex: number) => { const cellData = rowData && rowData[column.key]; return ; })} {includeAddColumn &&
} ); }} ; }, []); return {Row} ; } const SafeLinkRenderer: React.FC<{ text: string; }> = ({ text }) => { const urlRegex = /https?:\/\/[^\s]+/g; const htmlContent = text.replace(urlRegex, (url) => { // For each URL found, replace it with an HTML tag return `Link
`; }); return (
); };