UNPKG

@excentone/spfx-react

Version:

Contains custom ReactJs components and hooks intended to use when developing SharePoint Framework (SPFx) Web components.

74 lines (72 loc) 2.98 kB
import { isFunction } from "@excentone/spfx-utilities"; import { useCallback, useEffect, useMemo, useState } from "react"; /** * `useCachedListColumns` is a custom hook to easily use columns and modify its state (e.g. sorting). * @param columnDefinitions The column definitions. * @returns A tuple that contains the state of the columns and operations to alter its state. */ export const useDetailsListColumns = (columnDefinitions, options) => { const defaultOptions = useMemo(() => ({ sortColumnsExcept: [], showOnlyDashboardViewColumns: false }), []); const { onColumnSorted, sortColumnsExcept, showOnlyDashboardViewColumns } = useMemo(() => ({ ...defaultOptions, ...options }), [options]); const [columns, setColumns] = useState([]); const sortColumn = useCallback((_, { key, isSorted, isSortedDescending }) => setColumns(prev => { const next = [...prev.map(col => { if (col.key !== key || (isSorted && !isSortedDescending)) { col.isSorted = null; col.isSortedDescending = null; } else { col.isSorted = true; col.isSortedDescending = !isSortedDescending; } return col; })]; return next; }), [setColumns]); const initColumns = useCallback(() => { const filterColumnsForDashboardViewOnly = (col) => showOnlyDashboardViewColumns ? !col.hideInDashboardView : true; const tryFilterColumnByShowColumn = (col) => col.showColumn ? isFunction(col.showColumn) ? col.showColumn(col) : col.showColumn : true; const tryApplySorting = (col) => { if (!sortColumnsExcept.includes(col.key)) { col.onColumnClick = sortColumn; } return col; }; setColumns(columnDefinitions .filter(filterColumnsForDashboardViewOnly) .filter(tryFilterColumnByShowColumn) .map(tryApplySorting)); }, [setColumns, columnDefinitions, sortColumn, showOnlyDashboardViewColumns, sortColumnsExcept]); const clearSorting = useCallback(() => setColumns(prev => [...prev.map(col => ({ ...col, isSorted: null, isSortedDescending: null }))]), [setColumns]); const tryInvokeEvent = useCallback(() => { if (columns && columns.length && isFunction(onColumnSorted)) { onColumnSorted(columns.find(col => col.isSorted)); } }, [columns, onColumnSorted]); useEffect(tryInvokeEvent, [columns]); useEffect(initColumns, [showOnlyDashboardViewColumns, sortColumnsExcept]); return [ columns, { clearSorting, sortedColumn: () => columns.find(col => col.isSorted), } ]; }; //# sourceMappingURL=useDetailsListColumns.js.map