"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useUrlPagination = exports.paginationFromUrlParams = void 0; var _react = require("react"); var _reactRouterDom = require("react-router-dom"); var _constants = require("../common/constants"); var _use_url_params = require("./use_url_params"); /* * 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 paginationFromUrlParams = urlParams => { var _ref, _Number, _ref2; const pagination = { pageSize: _constants.MANAGEMENT_DEFAULT_PAGE_SIZE, page: 1 }; // Search params can appear multiple times in the URL, in which case the value for them, // once parsed, would be an array. In these case, we take the last value defined pagination.page = Number((_ref = Array.isArray(urlParams.page) ? urlParams.page[urlParams.page.length - 1] : urlParams.page) !== null && _ref !== void 0 ? _ref : pagination.page); pagination.pageSize = (_Number = Number((_ref2 = Array.isArray(urlParams.pageSize) ? urlParams.pageSize[urlParams.pageSize.length - 1] : urlParams.pageSize) !== null && _ref2 !== void 0 ? _ref2 : pagination.pageSize)) !== null && _Number !== void 0 ? _Number : pagination.pageSize; // If Current Page is not a valid positive integer, set it to 1 if (!Number.isFinite(pagination.page) || pagination.page < 1) { pagination.page = 1; } // if pageSize is not one of the expected page sizes, reset it to 10 (default) if (!_constants.MANAGEMENT_PAGE_SIZE_OPTIONS.includes(pagination.pageSize)) { pagination.pageSize = _constants.MANAGEMENT_DEFAULT_PAGE_SIZE; } return pagination; }; /** * Uses URL params for pagination and also persists those to the URL as they are updated */ exports.paginationFromUrlParams = paginationFromUrlParams; const useUrlPagination = () => { const location = (0, _reactRouterDom.useLocation)(); const history = (0, _reactRouterDom.useHistory)(); const { urlParams, toUrlParams } = (0, _use_url_params.useUrlParams)(); const urlPaginationParams = (0, _react.useMemo)(() => { return paginationFromUrlParams(urlParams); }, [urlParams]); const [pagination, setPagination] = (0, _react.useState)(urlPaginationParams); const setUrlPagination = (0, _react.useCallback)(({ pageSize, page }) => { history.push({ ...location, search: toUrlParams({ ...urlParams, page, pageSize }) }); }, [history, location, toUrlParams, urlParams]); (0, _react.useEffect)(() => { setPagination(prevState => { return { ...prevState, ...paginationFromUrlParams(urlParams) }; }); }, [setPagination, urlParams]); return { pagination, setPagination: setUrlPagination, pageSizeOptions: [..._constants.MANAGEMENT_PAGE_SIZE_OPTIONS] }; }; exports.useUrlPagination = useUrlPagination;