IF YOU WOULD LIKE TO GET AN ACCOUNT, please write an email to s dot adaszewski at gmail dot com. User accounts are meant only to report issues and/or generate pull requests. This is a purpose-specific Git hosting for ADARED projects. Thank you for your understanding!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.4KB

  1. import { h, Component } from 'preact';
  2. class WBPagination extends Component {
  3. renderVisiblePages(numPages, activePage, chunkSize, onPageChanged, getPageUrl) {
  4. let visible = {};
  5. let begActChnk = activePage - Math.floor(chunkSize / 2);
  6. let endActChnk = activePage + Math.floor(chunkSize / 2) + 1;
  7. for (let i = Math.max(0, begActChnk); i < Math.min(numPages, endActChnk); i++)
  8. visible[i] = true;
  9. for (let i = 0; i < Math.min(numPages, chunkSize); i++)
  10. visible[i] = true;
  11. for (let i = Math.max(numPages - chunkSize, 0); i < numPages; i++)
  12. visible[i] = true;
  13. visible = Object.keys(visible).map(n => Number(n));
  14. visible.sort((a, b) => (a - b));
  15. let res = [];
  16. let prev = 0;
  17. res.push((
  18. <li class={ activePage === 0 ? "page-item disabled" : "page-item" }>
  19. <a class="page-link" href={ getPageUrl(activePage - 1) }
  20. onclick={ e => this.changePage(e, activePage - 1) }>Previous</a>
  21. </li>
  22. ));
  23. for (let idx in visible) {
  24. let i = visible[idx];
  25. if (i > prev + 1)
  26. res.push((
  27. <li class="page-item">
  28. <a class="page-link" href={ getPageUrl(i - 1) }
  29. onclick={ e => this.changePage(e, i - 1) }>...</a>
  30. </li>
  31. ));
  32. prev = i;
  33. res.push((
  34. <li class={ i === activePage ? "page-item active" : "page-item" }>
  35. <a class="page-link" href={ getPageUrl(i) }
  36. onclick={ e => this.changePage(e, i) }>{ i + 1 }</a>
  37. </li>
  38. ));
  39. }
  40. res.push((
  41. <li class={ activePage >= numPages - 1 ? "page-item disabled" : "page-item" }>
  42. <a class="page-link" href={ getPageUrl(activePage + 1) }
  43. onclick={ e => this.changePage(e, activePage + 1) }>Next</a>
  44. </li>
  45. ));
  46. return res;
  47. }
  48. changePage(e, pageIdx) {
  49. if (this.props.onPageChanged) {
  50. e.preventDefault();
  51. this.props.onPageChanged(pageIdx);
  52. }
  53. }
  54. render({ numPages, activePage, chunkSize, onPageChanged, getPageUrl }) {
  55. return (
  56. <nav aria-label="Pagination">
  57. <ul class="pagination">
  58. { this.renderVisiblePages(numPages, activePage, chunkSize, onPageChanged, getPageUrl) }
  59. </ul>
  60. </nav>
  61. );
  62. }
  63. }
  64. WBPagination.defaultProps = {
  65. 'chunkSize': 5,
  66. 'getPageUrl': () => ('#')
  67. };
  68. export default WBPagination;