UNPKG

@hitachivantara/uikit-react-core

Version:
57 lines (56 loc) 2.43 kB
import { DefaultCell } from "../renderers/DefaultCell.js"; import { useHvTableStyles } from "./useHvTableStyles.js"; import { useMemo } from "react"; import { useExpanded, usePagination, useResizeColumns, useSortBy, useTable } from "react-table"; //#region src/Table/hooks/useHvTable.ts var toTitleCase = (str) => { return str.replace(/([^A-Z])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().replace(/(^\w|\b\w)/g, (m) => m.toUpperCase()).replace(/\s+/g, " ").trim(); }; function useDefaultData(data) { return useMemo(() => { return data || []; }, [data]); } function useDefaultColumns(data, columns) { return useMemo(() => { if (columns != null) return columns; return Object.keys(Object.assign({}, ...data)).filter((key) => !["subRows", "subComponent"].includes(key)).map((key) => ({ accessor: key, Header: toTitleCase(key) })); }, [columns, data]); } function ensureCorePluginInstallation(plugins, hvPluginName, corePluginToInstall) { const indexOfCorePlugin = plugins.findIndex((plugin) => plugin.pluginName === corePluginToInstall.pluginName); const indexOfHvPlugin = plugins.findIndex((plugin) => plugin.pluginName === hvPluginName); if (indexOfHvPlugin !== -1 && (indexOfCorePlugin === -1 || indexOfCorePlugin > indexOfHvPlugin)) { if (indexOfCorePlugin > -1) plugins.splice(indexOfCorePlugin, 1); plugins.splice(indexOfHvPlugin, 0, corePluginToInstall); } } function useInstanceHook(instance) { const { rowsById } = instance; Object.assign(instance, { initialRowsById: rowsById }); } function useHvTableSetup(hooks) { hooks.useInstance.push(useInstanceHook); } useHvTableSetup.pluginName = "useHvTableSetup"; function useHvTable(options, ...plugins) { const { data: dataProp, columns: columnsProp, ...others } = options; const data = useDefaultData(dataProp); const columns = useDefaultColumns(data, columnsProp); ensureCorePluginInstallation(plugins, "useHvPagination", usePagination); ensureCorePluginInstallation(plugins, "useHvRowExpand", useExpanded); ensureCorePluginInstallation(plugins, "useHvSortBy", useSortBy); ensureCorePluginInstallation(plugins, "useHvResizeColumns", useResizeColumns); if (plugins.findIndex((plugin) => plugin.pluginName === "useHvTableStyles") === -1) plugins.push(useHvTableStyles); return useTable({ data, columns, defaultColumn: { Cell: DefaultCell }, ...others }, useHvTableSetup, ...plugins); } //#endregion export { useHvTable };