|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- import { h, Component } from 'preact';
-
- class WBPagination extends Component {
- renderVisiblePages(numPages, activePage, chunkSize, onPageChanged, getPageUrl) {
- let visible = {};
-
- let begActChnk = activePage - Math.floor(chunkSize / 2);
- let endActChnk = activePage + Math.floor(chunkSize / 2) + 1;
- for (let i = Math.max(0, begActChnk); i < Math.min(numPages, endActChnk); i++)
- visible[i] = true;
-
- for (let i = 0; i < Math.min(numPages, chunkSize); i++)
- visible[i] = true;
-
- for (let i = Math.max(numPages - chunkSize, 0); i < numPages; i++)
- visible[i] = true;
-
- visible = Object.keys(visible).map(n => Number(n));
- visible.sort((a, b) => (a - b));
-
- let res = [];
- let prev = 0;
-
- res.push((
- <li class={ activePage === 0 ? "page-item disabled" : "page-item" }>
- <a class="page-link" href={ getPageUrl(activePage - 1) }
- onclick={ e => this.changePage(e, activePage - 1) }>Previous</a>
- </li>
- ));
-
- for (let idx = 0; idx < visible.length; idx++) {
- let i = visible[idx];
- let capturePrev = prev;
- if (i > prev + 1)
- res.push((
- <li class="page-item">
- <a class="page-link" href={ getPageUrl(Math.round((i + capturePrev) / 2)) }
- onclick={ e => this.changePage(e, Math.round((i + capturePrev) / 2)) }>...</a>
- </li>
- ));
- prev = i;
-
- res.push((
- <li class={ i === activePage ? "page-item active" : "page-item" }>
- <a class="page-link" href={ getPageUrl(i) }
- onclick={ e => this.changePage(e, i) }>{ i + 1 }</a>
- </li>
- ));
- }
-
- res.push((
- <li class={ activePage >= numPages - 1 ? "page-item disabled" : "page-item" }>
- <a class="page-link" href={ getPageUrl(activePage + 1) }
- onclick={ e => this.changePage(e, activePage + 1) }>Next</a>
- </li>
- ));
-
- return res;
- }
-
- changePage(e, pageIdx) {
- if (this.props.onPageChanged) {
- e.preventDefault();
- this.props.onPageChanged(pageIdx);
- }
- }
-
- render({ numPages, activePage, chunkSize, onPageChanged, getPageUrl }) {
- return (
- <nav aria-label="Pagination">
- <ul class="pagination">
- { this.renderVisiblePages(numPages, activePage, chunkSize, onPageChanged, getPageUrl) }
- </ul>
- </nav>
- );
- }
- }
-
- WBPagination.defaultProps = {
- 'chunkSize': 5,
- 'getPageUrl': () => ('#')
- };
-
- export default WBPagination;
|