"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useTable = useTable; var _react = require("react"); var _public = require("@kbn/kibana-utils-plugin/public"); var _table = require("../../components/table"); var _constants = require("../../../common/constants"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ const PAGE_SIZE_OPTIONS = [5, 10, 20, 50]; const DEFAULT_PAGINATION = { pageSize: 20, initialPageSize: 20, pageIndex: 0, initialPageIndex: 0, pageSizeOptions: PAGE_SIZE_OPTIONS, totalItemCount: 0 }; const getPaginationInitialState = page => { const pagination = DEFAULT_PAGINATION; if (page) { pagination.initialPageSize = page.size; pagination.pageSize = page.size; pagination.initialPageIndex = page.index; pagination.pageIndex = page.index; } return { ...pagination, pageSizeOptions: PAGE_SIZE_OPTIONS }; }; function useTable(storageKey) { const storage = new _public.Storage(window.localStorage); const getLocalStorageData = (0, _table.euiTableStorageGetter)(storageKey); const setLocalStorageData = (0, _table.euiTableStorageSetter)(storageKey); const storageData = getLocalStorageData(storage); // get initial state from localstorage const [pagination, setPagination] = (0, _react.useState)(getPaginationInitialState(storageData.page)); const updateTotalItemCount = (0, _react.useCallback)(num => { // only update pagination state if different if (num === pagination.totalItemCount) return; setPagination({ ...pagination, totalItemCount: num }); }, [setPagination, pagination]); // get initial state from localStorage const [sorting, setSorting] = (0, _react.useState)(storageData.sort || { sort: { field: 'name', direction: _constants.EUI_SORT_ASCENDING } }); const [query, setQuery] = (0, _react.useState)(''); const onTableChange = ({ page, sort, queryText }) => { setPagination({ ...pagination, ...{ initialPageSize: page.size, pageSize: page.size, initialPageIndex: page.index, pageIndex: page.index, pageSizeOptions: PAGE_SIZE_OPTIONS } }); setSorting({ sort }); setLocalStorageData(storage, { page, sort: { sort } }); setQuery(queryText); }; const getPaginationRouteOptions = (0, _react.useCallback)(() => { if (!pagination || !sorting) { return {}; } return { pagination: { size: pagination.pageSize, index: pagination.pageIndex }, ...sorting, queryText: query }; }, [pagination, query, sorting]); const getPaginationTableProps = () => { return { sorting, pagination, onTableChange }; }; return { getPaginationRouteOptions, getPaginationTableProps, updateTotalItemCount }; }