@braineet/ui
Version:
Braineet design system
84 lines (79 loc) • 2.79 kB
JavaScript
/* eslint-disable no-continue */
/* eslint-disable no-plusplus */
import React from 'react';
import { StyledPageButton, StyledButton, StyledBreak } from './styles';
import { jsx as _jsx } from "react/jsx-runtime";
export var PageButtons = function PageButtons(_ref) {
var pages = _ref.pages,
activePage = _ref.activePage,
onChange = _ref.onChange;
var createPage = function createPage(pageIndex) {
var isActivePage = parseInt(activePage, 10) === parseInt(pageIndex, 10);
return /*#__PURE__*/_jsx(StyledPageButton, {
children: /*#__PURE__*/_jsx(StyledButton, {
color: isActivePage ? 'brand' : 'black',
styleType: isActivePage ? 'solid' : 'ghost',
isActivePage: isActivePage,
onClick: function onClick(event) {
return onChange(event, pageIndex);
},
children: pageIndex.toString()
})
}, "page-" + pageIndex);
};
var createGap = function createGap(pageIndex) {
return /*#__PURE__*/_jsx(StyledBreak, {
children: "..."
}, "gap-" + pageIndex);
};
var renderButtons = function renderButtons(totalPages, currentPage) {
var buttons = [];
for (var pageIndex = 1; pageIndex <= totalPages; pageIndex++) {
// Always display the current page
if (pageIndex === currentPage) {
buttons.push(createPage(pageIndex));
continue;
}
// Always display the first and last page
if (pageIndex === 1 || pageIndex === totalPages) {
buttons.push(createPage(pageIndex));
continue;
}
// Display pages used for padding around the current page
if (pageIndex >= currentPage - 2 && pageIndex <= currentPage + 2) {
buttons.push(createPage(pageIndex));
continue;
}
// Handle case where front gap should not be displayed
if (currentPage <= 2 + 3 && pageIndex <= 2 * 2 + 3) {
buttons.push(createPage(pageIndex));
continue;
}
// Handle case where back gap should not be displayed
if (currentPage >= totalPages - 2 - 2 && pageIndex >= totalPages - 2 * 2 - 4) {
buttons.push(createPage(pageIndex));
continue;
}
// Render Gap and determine next starting pageIndex
if (pageIndex < currentPage) {
buttons.push(createGap(pageIndex));
if (currentPage >= totalPages - 2 - 2) {
pageIndex = totalPages - 2 * 2 - 3;
} else {
pageIndex = currentPage - 2 - 1;
}
} else {
buttons.push(createGap(pageIndex));
pageIndex = totalPages - 1;
}
}
return buttons;
};
return /*#__PURE__*/_jsx(StyledPageButton, {
children: renderButtons(pages, activePage)
});
};
PageButtons.defaultProps = {
activePage: undefined
};
export default PageButtons;