UNPKG

@hitachivantara/uikit-react-core

Version:

Core React components for the NEXT Design System.

81 lines (80 loc) 2.64 kB
import { useMemo } from "react"; import { useTable, usePagination, useExpanded, useSortBy, useResizeColumns } from "react-table"; import { DefaultCell } from "../renderers/DefaultCell.js"; import { useHvTableStyles } from "./useHvTableStyles.js"; const 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; } const uniqueKeys = Object.keys(Object.assign({}, ...data)); return uniqueKeys.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 ); const indexOfHvTableStylesPlugin = plugins.findIndex( (plugin) => plugin.pluginName === "useHvTableStyles" ); if (indexOfHvTableStylesPlugin === -1) { plugins.push(useHvTableStyles); } return useTable( { data, columns, defaultColumn: { Cell: DefaultCell }, ...others }, useHvTableSetup, ...plugins ); } export { useHvTable };