├── .editorconfig ├── .gitignore ├── .nojekyll ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── code-of-conduct.md ├── docs ├── index.html └── js │ └── demo.js ├── package-lock.json ├── package.json ├── rollup.config.ts ├── src ├── demo.tsx ├── react-pagination-hook.ts └── type-utils.ts ├── test └── react-pagination-hook.test.ts ├── tools ├── gh-pages-publish.ts └── semantic-release-prepare.ts ├── tsconfig.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | #root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | max_line_length = 100 10 | indent_size = 2 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | .DS_Store 5 | *.log 6 | .vscode 7 | .idea 8 | dist 9 | compiled 10 | .awcache 11 | .rpt2_cache 12 | -------------------------------------------------------------------------------- /.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eliseumds/react-pagination-hook/267970ff99a0da07af5dc19e8f7a88c77e182f27/.nojekyll -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | cache: 3 | directories: 4 | - "~/.npm" 5 | notifications: 6 | email: false 7 | node_js: 8 | - '8' 9 | - '10' 10 | - '12' 11 | script: npm run test:prod 12 | jobs: 13 | include: 14 | - stage: deploy 15 | node_js: '12' 16 | script: npm run lint && npm run build 17 | deploy: 18 | - provider: pages 19 | skip_cleanup: true 20 | github_token: "$GH_TOKEN" 21 | keep_history: true 22 | verbose: true 23 | on: 24 | branch: master 25 | - provider: releases 26 | api_key: "$GH_TOKEN" 27 | skip_cleanup: true 28 | on: 29 | tags: true 30 | branch: master 31 | - provider: npm 32 | email: eliseumds@gmail.com 33 | api_key: 34 | secure: jxiN7JX1CFt/MLLZcLZPlTxhP7iCnTdyf5u3k23RVkGModpmFtObFn8xBRpLueDeLBXQFMiwhzhWjJbHWcSEvfGfbOseC5Yzk31cM+XxkjHgm+m94MVwWJyc7mAvePWlMKQM6LNiDij6xgf1CR89RiFJ/7zIZAQm366bfFFWSXfv3MU8LUERJfa7Mf9ZSoK2etCs0gdrMpOyyYu7CKVCfOK3rIzi+uf9zC2solDgkt4nEUyswF2XLkeC6943wV2VvsMrLoS1JDeDaFleuSOcvs/eAmHtDVvOLN3wdFN32CQj/OD0bSlzffyX6SC76m4OF8dSkbUoIR/S5CPRFavvMYQ6weTFKjNvvU6s8FLBR0+Zq7PShMJu7+iJJan9NlMdbQNyBGqqjQNZ9FG1+OCu+x1DPZvIM4PaMOKkDF7B8x4sxwG2fL2riZSkQ88vEHxvL8m/94/81fITJenOVK34mZ4kp6ixUWjiIELBv4ye/rXCcsKdT9phSne6XozzJTZQmDO8IOJQSMRSxsCoWuagsGGLH1tOdOOlCzMm8UJvDMay/TDqu6suLxRu7vil4TTX4FlejOAA1GYIlkS7s6f3mVmD3PzH0HEiDHpjcolAbVUrZVFCe5LMiok2Q1P6c8iWy1pi1uzPJjZCLmMAEyvaG8OM8ST6nYpUo4ZOfZG6WWI= 35 | on: 36 | tags: true 37 | branch: master 38 | 39 | branches: 40 | except: 41 | - "/^v\\d+\\.\\d+\\.\\d+$/" 42 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We're really glad you're reading this, because we need volunteer developers to help this project come to fruition. 👏 2 | 3 | ## Instructions 4 | 5 | These steps will guide you through contributing to this project: 6 | 7 | - Fork the repo 8 | - Clone it and install dependencies 9 | 10 | git clone https://github.com/YOUR-USERNAME/typescript-library-starter 11 | npm install 12 | 13 | Keep in mind that after running `npm install` the git repo is reset. So a good way to cope with this is to have a copy of the folder to push the changes, and the other to try them. 14 | 15 | Make and commit your changes. Make sure the commands npm run build and npm run test:prod are working. 16 | 17 | Finally send a [GitHub Pull Request](https://github.com/alexjoverm/typescript-library-starter/compare?expand=1) with a clear list of what you've done (read more [about pull requests](https://help.github.com/articles/about-pull-requests/)). Make sure all of your commits are atomic (one feature per commit). 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Eliseu dos Santos 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Welcome to react-pagination-hook 👋

2 |

3 | 4 | 5 | Documentation 6 | 7 | 8 | Maintenance 9 | 10 | 11 | License: MIT 12 | 13 |

14 | 15 | > A React hook that helps you render a paginator (with TypeScript support) 16 | 17 | ### 🏠 [See a demo](https://eliseumds.github.com/react-pagination-hook/docs) 18 | 19 | ## Prerequisites 20 | 21 | - react >=16.8.0 22 | 23 | ## Install 24 | 25 | ```sh 26 | npm install react-pagination-hook --save 27 | ``` 28 | 29 | ## API 30 | 31 | The hook returns the following object: 32 | 33 | ```ts 34 | { 35 | activePage: number; 36 | isFirst: boolean; 37 | isLast: boolean; 38 | hasPrevious: boolean; 39 | hasNext: boolean; 40 | visiblePieces: PaginatorPiece[]; 41 | goToPage: (pageNumber: number) => void; 42 | } 43 | ``` 44 | 45 | And a *PaginatorPiece* is either of the following objects: 46 | 47 | ```ts 48 | { type: 'previous', pageNumber: number, isDisabled: boolean } 49 | // or 50 | { type: 'next', pageNumber: number, isDisabled: boolean } 51 | // or 52 | { type: 'page-number', pageNumber: number } 53 | // or 54 | { type: 'ellipsis' } 55 | ``` 56 | 57 | ## Usage 58 | 59 | You can use this hook to develop your own pagination component. [Check out the demo](https://eliseumds.github.com/react-pagination-hook/docs) 60 | 61 | ## Author 62 | 63 | 👤 **Eliseu dos Santos <eliseumds@gmail.com>** 64 | 65 | * Twitter: [@eliseumds](https://twitter.com/eliseumds) 66 | * Github: [@eliseumds](https://github.com/eliseumds) 67 | 68 | ## 🤝 Contributing 69 | 70 | Contributions, issues and feature requests are welcome !
Feel free to check [issues page](https://github.com/eliseumds/react-pagination-hook/issues). 71 | 72 | ## Show your support 73 | 74 | Give a ⭐️ if this project helped you! 75 | 76 | ## 📝 License 77 | 78 | Copyright © 2019 [Eliseu dos Santos <eliseumds@gmail.com>](https://github.com/eliseumds).
79 | This project is [MIT](https://github.com/eliseumds/react-pagination-hook/blob/master/LICENSE) licensed. 80 | 81 | *** 82 | 83 | _This project was bootstraped with [typescript-library-starter](https://github.com/alexjoverm/typescript-library-starter)_ 84 | 85 | _This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_ 86 | -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at alexjovermorales@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | react-pagination-hook 8 | 9 | 10 | 11 | 12 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /docs/js/demo.js: -------------------------------------------------------------------------------- 1 | (function (global, factory) { 2 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('react'), require('react-dom')) : 3 | typeof define === 'function' && define.amd ? define(['react', 'react-dom'], factory) : 4 | (global = global || self, factory(global.React, global.ReactDOM)); 5 | }(this, function (React, ReactDOM) { 'use strict'; 6 | 7 | var React__default = 'default' in React ? React['default'] : React; 8 | ReactDOM = ReactDOM && ReactDOM.hasOwnProperty('default') ? ReactDOM['default'] : ReactDOM; 9 | 10 | /*! ***************************************************************************** 11 | Copyright (c) Microsoft Corporation. All rights reserved. 12 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 13 | this file except in compliance with the License. You may obtain a copy of the 14 | License at http://www.apache.org/licenses/LICENSE-2.0 15 | 16 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 18 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 19 | MERCHANTABLITY OR NON-INFRINGEMENT. 20 | 21 | See the Apache Version 2.0 License for specific language governing permissions 22 | and limitations under the License. 23 | ***************************************************************************** */ 24 | 25 | var __assign = function() { 26 | __assign = Object.assign || function __assign(t) { 27 | for (var s, i = 1, n = arguments.length; i < n; i++) { 28 | s = arguments[i]; 29 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; 30 | } 31 | return t; 32 | }; 33 | return __assign.apply(this, arguments); 34 | }; 35 | 36 | function computeVisiblePieces(activePage, config) { 37 | var numberOfPages = config.numberOfPages, maxButtons = config.maxButtons, showEllipsis = config.showEllipsis, padding = config.padding; 38 | var visiblePieces = []; 39 | if (numberOfPages <= maxButtons) { 40 | for (var page = 1; page <= numberOfPages; page++) { 41 | visiblePieces.push({ type: 'page-number', pageNumber: page }); 42 | } 43 | return visiblePieces; 44 | } 45 | var lowerLimit = activePage; 46 | var upperLimit = activePage; 47 | visiblePieces.push({ 48 | type: 'previous', 49 | pageNumber: Math.max(1, activePage - 1), 50 | isDisabled: activePage === 1, 51 | }); 52 | // From https://gist.github.com/keon/5380f81393ad98ec19e6 53 | for (var i = 1; i < maxButtons && i < numberOfPages;) { 54 | if (lowerLimit > 1) { 55 | lowerLimit--; 56 | i++; 57 | } 58 | if (i < maxButtons && upperLimit < numberOfPages) { 59 | upperLimit++; 60 | i++; 61 | } 62 | } 63 | if (lowerLimit > 1) { 64 | visiblePieces.push({ type: 'page-number', pageNumber: 1 }); 65 | visiblePieces.push({ type: 'ellipsis' }); 66 | } 67 | for (var i = lowerLimit; i <= upperLimit; i++) { 68 | visiblePieces.push({ type: 'page-number', pageNumber: i }); 69 | } 70 | if (activePage < numberOfPages - 2) { 71 | visiblePieces.push({ type: 'ellipsis' }); 72 | visiblePieces.push({ type: 'page-number', pageNumber: numberOfPages }); 73 | } 74 | visiblePieces.push({ 75 | type: 'next', 76 | pageNumber: Math.min(numberOfPages, activePage + 1), 77 | isDisabled: activePage === numberOfPages, 78 | }); 79 | return visiblePieces; 80 | } 81 | function usePagination(_config) { 82 | if (typeof _config !== 'object') { 83 | throw new TypeError("usePagination(config): config must be an object. Go " + typeof _config + " instead"); 84 | } 85 | var config = __assign({ maxButtons: 5, padding: 2 }, _config); 86 | var _a = React.useState(config.initialPage), activePage = _a[0], setActivePage = _a[1]; 87 | var numberOfPages = config.numberOfPages; 88 | var isFirst = activePage === 1; 89 | var isLast = activePage === numberOfPages; 90 | var hasPrevious = numberOfPages > 1 && activePage > 1; 91 | var hasNext = activePage < numberOfPages; 92 | var visiblePieces = computeVisiblePieces(activePage, config); 93 | var goToPage = React.useCallback(function (pageNumber) { 94 | setActivePage(pageNumber); 95 | }, []); 96 | React.useEffect(function () { 97 | if (config.initialPage !== activePage) { 98 | setActivePage(config.initialPage); 99 | } 100 | }, [config.initialPage]); 101 | return { 102 | activePage: activePage, 103 | isFirst: isFirst, 104 | isLast: isLast, 105 | hasPrevious: hasPrevious, 106 | hasNext: hasNext, 107 | visiblePieces: visiblePieces, 108 | goToPage: goToPage, 109 | }; 110 | } 111 | 112 | var SOURCE_DEMO = "\nconst pagination = usePagination({\n initialPage: %INITIAL_PAGE%,\n numberOfPages: %NUMBER_OF_PAGES%,\n maxButtons: %MAX_BUTTONS%,\n});\n\n// render however you like\n".trim(); 113 | function Demo() { 114 | var _a = React__default.useState(1), initialPage = _a[0], setInitialPage = _a[1]; 115 | var _b = React__default.useState(10), numberOfPages = _b[0], setNumberOfPages = _b[1]; 116 | var _c = React__default.useState(5), maxButtons = _c[0], setMaxButtons = _c[1]; 117 | React__default.useEffect(function () { 118 | if (initialPage > numberOfPages) { 119 | setInitialPage(numberOfPages); 120 | } 121 | }, [initialPage, numberOfPages]); 122 | React__default.useEffect(function () { 123 | if (maxButtons > numberOfPages) { 124 | setMaxButtons(numberOfPages); 125 | } 126 | }, [maxButtons, numberOfPages]); 127 | var _d = usePagination({ initialPage: initialPage, numberOfPages: numberOfPages, maxButtons: maxButtons }), activePage = _d.activePage, visiblePieces = _d.visiblePieces, goToPage = _d.goToPage; 128 | return (React__default.createElement("div", { className: "container" }, 129 | React__default.createElement("h1", null, "react-pagination-hook demo"), 130 | React__default.createElement("div", { className: "row" }, 131 | React__default.createElement("div", { className: "col-md-2" }, "Initial page:"), 132 | React__default.createElement("div", null, 133 | React__default.createElement("input", { type: "range", value: initialPage, min: 1, max: numberOfPages, onChange: function (event) { return setInitialPage(Number(event.target.value)); } }), 134 | initialPage)), 135 | React__default.createElement("div", { className: "row" }, 136 | React__default.createElement("div", { className: "col-md-2" }, "Number of pages:"), 137 | React__default.createElement("div", null, 138 | React__default.createElement("input", { type: "range", value: numberOfPages, min: 1, max: 100, onChange: function (event) { return setNumberOfPages(Number(event.target.value)); } }), 139 | numberOfPages)), 140 | React__default.createElement("div", { className: "row" }, 141 | React__default.createElement("div", { className: "col-md-2" }, "Max buttons:"), 142 | React__default.createElement("div", null, 143 | React__default.createElement("input", { type: "range", value: maxButtons, min: 1, max: 10, onChange: function (event) { return setMaxButtons(Number(event.target.value)); } }), 144 | maxButtons)), 145 | React__default.createElement("pre", null, 146 | React__default.createElement("code", null, SOURCE_DEMO 147 | .replace('%INITIAL_PAGE%', String(initialPage)) 148 | .replace('%NUMBER_OF_PAGES%', String(numberOfPages)) 149 | .replace('%MAX_BUTTONS%', String(maxButtons)))), 150 | React__default.createElement("div", { style: { display: 'flex' } }, visiblePieces.map(function (visiblePiece, index) { 151 | var key = visiblePiece.type + "-" + index; 152 | if (visiblePiece.type === 'ellipsis') { 153 | return React__default.createElement("div", { key: key, style: { lineHeight: '48px' } }, "..."); 154 | } 155 | var pageNumber = visiblePiece.pageNumber; 156 | var onClick = function () { return goToPage(pageNumber); }; 157 | if (visiblePiece.type === 'page-number') { 158 | var isActive = pageNumber === activePage; 159 | var className = isActive ? 'primary' : ''; 160 | return React__default.createElement("button", { key: key, onClick: onClick, className: className }, pageNumber); 161 | } 162 | return React__default.createElement("button", { key: key, disabled: visiblePiece.isDisabled, onClick: onClick }, visiblePiece.type === 'next' ? '>' : '<'); 163 | })), 164 | React__default.createElement("hr", null), 165 | React__default.createElement("p", { style: { textAlign: 'right' } }, 166 | React__default.createElement("a", { href: "https://github.com/eliseumds/react-pagination-hook/tree/master/src/demo.tsx", target: "_blank" }, "Click here"), 167 | " to see the code for this demo"))); 168 | } 169 | ReactDOM.render(React__default.createElement(Demo, null), document.getElementById('demo-container')); 170 | 171 | })); 172 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-pagination-hook", 3 | "version": "0.0.2", 4 | "description": "A React hook that helps you render a paginator", 5 | "keywords": [ 6 | "react", 7 | "hook", 8 | "pagination", 9 | "paginator" 10 | ], 11 | "main": "dist/react-pagination-hook.umd.js", 12 | "module": "dist/react-pagination-hook.es.js", 13 | "typings": "dist/types/react-pagination-hook.d.ts", 14 | "files": [ 15 | "dist" 16 | ], 17 | "author": "Eliseu dos Santos ", 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/eliseumds/react-pagination-hook" 21 | }, 22 | "homepage": "https://github.com/eliseumds/react-pagination-hook#readme", 23 | "bugs": { 24 | "url": "https://github.com/eliseumds/react-pagination-hook/issues" 25 | }, 26 | "license": "MIT", 27 | "engines": { 28 | "node": ">=6.0.0" 29 | }, 30 | "scripts": { 31 | "lint": "tslint --project tsconfig.json -t codeFrame 'src/**/*.ts' 'test/**/*.ts'", 32 | "prebuild": "rimraf dist", 33 | "build": "tsc --module commonjs && rollup -c rollup.config.ts", 34 | "start": "rollup -c rollup.config.ts -w", 35 | "test": "jest --coverage", 36 | "test:watch": "jest --coverage --watch", 37 | "test:prod": "npm run test -- --no-cache", 38 | "deploy-docs": "ts-node tools/gh-pages-publish", 39 | "commit": "git-cz", 40 | "semantic-release": "semantic-release", 41 | "semantic-release-prepare": "ts-node tools/semantic-release-prepare", 42 | "precommit": "lint-staged", 43 | "prepush": "npm run test:prod && npm run build", 44 | "commitmsg": "commitlint -E HUSKY_GIT_PARAMS" 45 | }, 46 | "lint-staged": { 47 | "{src,test}/**/*.ts": [ 48 | "prettier --write", 49 | "git add" 50 | ] 51 | }, 52 | "config": { 53 | "commitizen": { 54 | "path": "node_modules/cz-conventional-changelog" 55 | } 56 | }, 57 | "jest": { 58 | "transform": { 59 | ".(ts|tsx)": "ts-jest" 60 | }, 61 | "testEnvironment": "node", 62 | "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 63 | "moduleFileExtensions": [ 64 | "ts", 65 | "tsx", 66 | "js" 67 | ], 68 | "coveragePathIgnorePatterns": [ 69 | "/node_modules/", 70 | "/test/", 71 | "demo" 72 | ], 73 | "coverageThreshold": { 74 | "global": { 75 | "branches": 90, 76 | "functions": 95, 77 | "lines": 95, 78 | "statements": 95 79 | } 80 | }, 81 | "collectCoverageFrom": [ 82 | "src/*.{js,ts}" 83 | ] 84 | }, 85 | "prettier": { 86 | "tabWidth": 2, 87 | "semi": true, 88 | "singleQuote": true, 89 | "trailingComma": "es5" 90 | }, 91 | "commitlint": { 92 | "extends": [ 93 | "@commitlint/config-conventional" 94 | ] 95 | }, 96 | "peerDependencies": { 97 | "react": "^16.8.0", 98 | "react-dom": "^16.8.0" 99 | }, 100 | "devDependencies": { 101 | "@commitlint/cli": "8.0.0", 102 | "@commitlint/config-conventional": "8.0.0", 103 | "@types/jest": "24.0.14", 104 | "@types/node": "12.0.8", 105 | "@types/react": "^16.8.19", 106 | "@types/react-dom": "^16.8.4", 107 | "colors": "1.3.3", 108 | "commitizen": "3.1.1", 109 | "cross-env": "5.2.0", 110 | "cz-conventional-changelog": "2.1.0", 111 | "husky": "2.4.1", 112 | "jest": "24.8.0", 113 | "jest-config": "24.8.0", 114 | "lint-staged": "8.2.0", 115 | "prettier": "1.18.2", 116 | "prompt": "1.0.0", 117 | "react": "^16.8.6", 118 | "react-dom": "^16.8.6", 119 | "react-hooks-testing-library": "^0.5.1", 120 | "react-test-renderer": "^16.8.6", 121 | "replace-in-file": "4.1.0", 122 | "rimraf": "2.6.3", 123 | "rollup": "1.15.2", 124 | "rollup-plugin-sourcemaps": "0.4.2", 125 | "rollup-plugin-typescript2": "0.21.1", 126 | "semantic-release": "^15.13.16", 127 | "shelljs": "0.8.3", 128 | "ts-jest": "24.0.2", 129 | "ts-node": "8.2.0", 130 | "tslint": "5.17.0", 131 | "tslint-config-prettier": "1.18.0", 132 | "tslint-config-standard": "8.0.1", 133 | "typescript": "3.5.1" 134 | }, 135 | "dependencies": {} 136 | } 137 | -------------------------------------------------------------------------------- /rollup.config.ts: -------------------------------------------------------------------------------- 1 | import sourceMaps from 'rollup-plugin-sourcemaps' 2 | import typescript from 'rollup-plugin-typescript2' 3 | 4 | const pkg = require('./package.json') 5 | 6 | const libraryName = 'react-pagination-hook' 7 | 8 | const globals = { 9 | 'react': 'React', 10 | 'react-dom': 'ReactDOM', 11 | }; 12 | const sharedConfig = { 13 | external: ['react', 'react-dom'], 14 | watch: { 15 | include: 'src/**', 16 | }, 17 | plugins: [ 18 | typescript({ useTsconfigDeclarationDir: true }), 19 | sourceMaps(), 20 | ], 21 | }; 22 | 23 | export default [ 24 | { 25 | ...sharedConfig, 26 | input: `src/demo.tsx`, 27 | output: { 28 | file: 'docs/js/demo.js', 29 | format: 'umd', 30 | globals, 31 | }, 32 | }, 33 | { 34 | ...sharedConfig, 35 | input: `src/${libraryName}.ts`, 36 | output: [ 37 | { file: pkg.main, name: libraryName, format: 'umd', sourcemap: true, globals }, 38 | { file: pkg.module, format: 'es', sourcemap: true, globals }, 39 | ], 40 | } 41 | ]; 42 | -------------------------------------------------------------------------------- /src/demo.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import { usePagination } from './react-pagination-hook'; 4 | 5 | const SOURCE_DEMO = ` 6 | const pagination = usePagination({ 7 | initialPage: %INITIAL_PAGE%, 8 | numberOfPages: %NUMBER_OF_PAGES%, 9 | maxButtons: %MAX_BUTTONS%, 10 | }); 11 | 12 | // render however you like 13 | `.trim(); 14 | 15 | function Demo() { 16 | const [initialPage, setInitialPage] = React.useState(1); 17 | const [numberOfPages, setNumberOfPages] = React.useState(10); 18 | const [maxButtons, setMaxButtons] = React.useState(5); 19 | 20 | React.useEffect(() => { 21 | if (initialPage > numberOfPages) { 22 | setInitialPage(numberOfPages); 23 | } 24 | }, [initialPage, numberOfPages]); 25 | 26 | React.useEffect(() => { 27 | if (maxButtons > numberOfPages) { 28 | setMaxButtons(numberOfPages); 29 | } 30 | }, [maxButtons, numberOfPages]); 31 | 32 | const { 33 | activePage, 34 | visiblePieces, 35 | goToPage, 36 | } = usePagination({ initialPage, numberOfPages, maxButtons }); 37 | 38 | return ( 39 |
40 |

react-pagination-hook demo

41 |
42 |
Initial page:
43 |
44 | setInitialPage(Number(event.target.value))} /> 45 | {initialPage} 46 |
47 |
48 |
49 |
Number of pages:
50 |
51 | setNumberOfPages(Number(event.target.value))} /> 52 | {numberOfPages} 53 |
54 |
55 |
56 |
Max buttons:
57 |
58 | setMaxButtons(Number(event.target.value))} /> 59 | {maxButtons} 60 |
61 |
62 |
 63 |         
 64 |           {SOURCE_DEMO
 65 |             .replace('%INITIAL_PAGE%', String(initialPage))
 66 |             .replace('%NUMBER_OF_PAGES%', String(numberOfPages))
 67 |             .replace('%MAX_BUTTONS%', String(maxButtons))}
 68 |         
 69 |       
70 |
71 | {visiblePieces.map((visiblePiece, index) => { 72 | const key = `${visiblePiece.type}-${index}`; 73 | 74 | if (visiblePiece.type === 'ellipsis') { 75 | return
...
; 76 | } 77 | 78 | const { pageNumber } = visiblePiece; 79 | const onClick = () => goToPage(pageNumber); 80 | 81 | if (visiblePiece.type === 'page-number') { 82 | const isActive = pageNumber === activePage; 83 | const className = isActive ? 'primary' : ''; 84 | 85 | return ; 86 | } 87 | 88 | return ; 91 | })} 92 |
93 | 94 |
95 | 96 |

97 | Click here to see the code for this demo 98 |

99 |
100 | ); 101 | } 102 | 103 | ReactDOM.render( 104 | , 105 | document.getElementById('demo-container') 106 | ) 107 | -------------------------------------------------------------------------------- /src/react-pagination-hook.ts: -------------------------------------------------------------------------------- 1 | import { useCallback, useState, useEffect } from 'react'; 2 | import { AugmentedRequired } from './type-utils'; 3 | 4 | export type ConfigArg = { 5 | numberOfPages: number; 6 | initialPage: number; 7 | maxButtons?: number; 8 | }; 9 | 10 | type Config = AugmentedRequired; 11 | 12 | export type PaginatorPiece = 13 | | { 14 | type: 'previous' | 'next'; 15 | pageNumber: number; 16 | isDisabled: boolean; 17 | } 18 | | { 19 | pageNumber: number; 20 | type: 'page-number'; 21 | } 22 | | { 23 | type: 'ellipsis'; 24 | }; 25 | 26 | export interface State { 27 | activePage: number; 28 | isFirst: boolean; 29 | isLast: boolean; 30 | hasPrevious: boolean; 31 | hasNext: boolean; 32 | visiblePieces: PaginatorPiece[]; 33 | goToPage: (pageNumber: number) => void; 34 | } 35 | 36 | function computeVisiblePieces(activePage: number, config: Config): PaginatorPiece[] { 37 | const { numberOfPages, maxButtons } = config; 38 | const visiblePieces: PaginatorPiece[] = []; 39 | 40 | if (numberOfPages <= maxButtons) { 41 | for (let page = 1; page <= numberOfPages; page++) { 42 | visiblePieces.push({ type: 'page-number', pageNumber: page }); 43 | } 44 | 45 | return visiblePieces; 46 | } 47 | 48 | let lowerLimit = activePage; 49 | let upperLimit = activePage; 50 | 51 | visiblePieces.push({ 52 | type: 'previous', 53 | pageNumber: Math.max(1, activePage - 1), 54 | isDisabled: activePage === 1, 55 | }); 56 | 57 | // From https://gist.github.com/keon/5380f81393ad98ec19e6 58 | for (let i = 1; i < maxButtons && i < numberOfPages; ) { 59 | if (lowerLimit > 1) { 60 | lowerLimit--; 61 | i++; 62 | } 63 | 64 | if (i < maxButtons && upperLimit < numberOfPages) { 65 | upperLimit++; 66 | i++; 67 | } 68 | } 69 | 70 | if (lowerLimit > 1 && lowerLimit !== upperLimit) { 71 | visiblePieces.push({ type: 'page-number', pageNumber: 1 }); 72 | visiblePieces.push({ type: 'ellipsis' }); 73 | } 74 | 75 | for (let i = lowerLimit; i <= upperLimit; i++) { 76 | visiblePieces.push({ type: 'page-number', pageNumber: i }); 77 | } 78 | 79 | if (activePage < numberOfPages - 2) { 80 | visiblePieces.push({ type: 'ellipsis' }); 81 | visiblePieces.push({ type: 'page-number', pageNumber: numberOfPages }); 82 | } 83 | 84 | visiblePieces.push({ 85 | type: 'next', 86 | pageNumber: Math.min(numberOfPages, activePage + 1), 87 | isDisabled: activePage === numberOfPages, 88 | }); 89 | 90 | return visiblePieces; 91 | } 92 | 93 | export function usePagination(_config: ConfigArg) { 94 | if (typeof _config !== 'object') { 95 | throw new TypeError( 96 | `usePagination(config): config must be an object. Go ${typeof _config} instead` 97 | ); 98 | } 99 | 100 | const config: Config = { maxButtons: 5, ..._config }; 101 | 102 | if (config.initialPage > config.numberOfPages) { 103 | config.initialPage = config.numberOfPages; 104 | } 105 | 106 | if (config.maxButtons > config.numberOfPages) { 107 | config.maxButtons = config.numberOfPages; 108 | } 109 | 110 | const [activePage, setActivePage] = useState(config.initialPage); 111 | const { numberOfPages } = config; 112 | const isFirst = activePage === 1; 113 | const isLast = activePage === numberOfPages; 114 | const hasPrevious = numberOfPages > 1 && activePage > 1; 115 | const hasNext = activePage < numberOfPages; 116 | const visiblePieces = computeVisiblePieces(activePage, config); 117 | const goToPage = useCallback(pageNumber => { 118 | setActivePage(pageNumber); 119 | }, []); 120 | 121 | useEffect(() => { 122 | if (config.initialPage !== activePage) { 123 | setActivePage(config.initialPage); 124 | } 125 | }, [config.initialPage]); 126 | 127 | return { 128 | activePage, 129 | isFirst, 130 | isLast, 131 | hasPrevious, 132 | hasNext, 133 | visiblePieces, 134 | goToPage, 135 | }; 136 | } 137 | -------------------------------------------------------------------------------- /src/type-utils.ts: -------------------------------------------------------------------------------- 1 | // From https://github.com/piotrwitek/utility-types/blob/b83fe212836284d03b5e725352d6fa947b49ca2b/src/mapped-types.ts#L599-L618 2 | export type AugmentedRequired = Omit & 3 | Required>; 4 | -------------------------------------------------------------------------------- /test/react-pagination-hook.test.ts: -------------------------------------------------------------------------------- 1 | import { act, renderHook } from 'react-hooks-testing-library'; 2 | import { usePagination, PaginatorPiece } from '../src/react-pagination-hook'; 3 | 4 | // "!previous:1 1 2 3 ... 100 next:4" >> [ 5 | // { type: 'previous', pageNumber: 1, isDisabled: true }, 6 | // { type: 'page-number', pageNumber: 1 }, 7 | // { type: 'page-number', pageNumber: 2 }, 8 | // { type: 'page-number', pageNumber: 3 }, 9 | // { type: 'ellipsis' }, 10 | // { type: 'page-number', pageNumber: 100 }, 11 | // { type: 'next', pageNumber: 4, isDisabled: false }, 12 | // ] 13 | function buildExpectation(fullExpression: string): PaginatorPiece[] { 14 | return fullExpression 15 | .trim() 16 | .split(' ') 17 | .map(expression => { 18 | if (/^\d+$/.test(expression)) { 19 | return { type: 'page-number', pageNumber: Number(expression) }; 20 | } 21 | 22 | if (expression === '...') { 23 | return { type: 'ellipsis' }; 24 | } 25 | 26 | const matches = expression.match(/^([\!]*(previous|next))\:(\d+)$/); 27 | 28 | if (matches) { 29 | const bits = matches[0].split(':'); 30 | let type: 'previous' | 'next'; 31 | let pageNumber: number = Number(bits[1]); 32 | let isDisabled: boolean = false; 33 | 34 | if (bits[0].startsWith('!')) { 35 | isDisabled = true; 36 | type = bits[0].slice(1) as any; 37 | } else { 38 | type = bits[0] as any; 39 | } 40 | 41 | return { type, pageNumber, isDisabled }; 42 | } 43 | 44 | throw new TypeError(`buildExpectation(arg): invalid expression "${expression}"`); 45 | }); 46 | } 47 | 48 | describe('react-pagination-hook', () => { 49 | test('is defined', () => { 50 | expect(typeof usePagination).toBe('function'); 51 | }); 52 | 53 | test('break without required properties', () => { 54 | const hook1 = renderHook(() => usePagination(undefined as any)); 55 | expect(hook1.result.error).toBeInstanceOf(TypeError); 56 | 57 | const hook2 = renderHook(() => usePagination(1 as any)); 58 | expect(hook2.result.error).toBeInstanceOf(TypeError); 59 | }); 60 | 61 | test('prevents out-of-range initial page', () => { 62 | const hook = renderHook(() => 63 | usePagination({ 64 | initialPage: 99, // << higher than numberOfPages 65 | numberOfPages: 10, 66 | }) 67 | ); 68 | 69 | expect(hook.result.current.activePage).toBe(10); 70 | }); 71 | 72 | describe('with basic config', () => { 73 | const hook = renderHook( 74 | (props: { initialPage: number }) => 75 | usePagination({ 76 | numberOfPages: 10, 77 | maxButtons: 3, 78 | initialPage: props.initialPage, 79 | }), 80 | { 81 | initialProps: { 82 | initialPage: 1, 83 | }, 84 | } 85 | ); 86 | 87 | test('return initial state on initial render', () => { 88 | expect(hook.result.current.activePage).toBe(1); 89 | expect(hook.result.current.isFirst).toBe(true); 90 | expect(hook.result.current.isLast).toBe(false); 91 | expect(hook.result.current.hasPrevious).toBe(false); 92 | expect(hook.result.current.hasNext).toBe(true); 93 | expect(typeof hook.result.current.goToPage).toBe('function'); 94 | 95 | const expectation = '!previous:1 1 2 3 ... 10 next:2'; 96 | 97 | expect(hook.result.current.visiblePieces).toStrictEqual(buildExpectation(expectation)); 98 | }); 99 | 100 | test('navigate to the second page', () => { 101 | act(() => { 102 | hook.result.current.goToPage(2); 103 | }); 104 | 105 | expect(hook.result.current.activePage).toBe(2); 106 | expect(hook.result.current.isFirst).toBe(false); 107 | expect(hook.result.current.isLast).toBe(false); 108 | expect(hook.result.current.hasPrevious).toBe(true); 109 | expect(hook.result.current.hasNext).toBe(true); 110 | 111 | const expectation = 'previous:1 1 2 3 ... 10 next:3'; 112 | 113 | expect(hook.result.current.visiblePieces).toStrictEqual(buildExpectation(expectation)); 114 | }); 115 | 116 | test('rerender with initialPage as the last one', () => { 117 | hook.rerender({ initialPage: 10 }); 118 | 119 | expect(hook.result.current.activePage).toBe(10); 120 | expect(hook.result.current.isFirst).toBe(false); 121 | expect(hook.result.current.isLast).toBe(true); 122 | expect(hook.result.current.hasPrevious).toBe(true); 123 | expect(hook.result.current.hasNext).toBe(false); 124 | 125 | const expectation = 'previous:9 1 ... 8 9 10 !next:10'; 126 | 127 | expect(hook.result.current.visiblePieces).toStrictEqual(buildExpectation(expectation)); 128 | }); 129 | }); 130 | 131 | test('few pages', () => { 132 | const hook = renderHook(() => 133 | usePagination({ 134 | numberOfPages: 5, 135 | maxButtons: 10, 136 | initialPage: 1, 137 | }) 138 | ); 139 | 140 | const expectation = '1 2 3 4 5'; 141 | 142 | expect(hook.result.current.visiblePieces).toStrictEqual(buildExpectation(expectation)); 143 | }); 144 | 145 | test('maximum 1 button', () => { 146 | const hook = renderHook(() => 147 | usePagination({ 148 | numberOfPages: 3, 149 | maxButtons: 1, 150 | initialPage: 1, 151 | }) 152 | ); 153 | 154 | expect(hook.result.current.visiblePieces).toStrictEqual( 155 | buildExpectation('!previous:1 1 next:2') 156 | ); 157 | 158 | act(() => { 159 | hook.result.current.goToPage(2); 160 | }); 161 | 162 | expect(hook.result.current.visiblePieces).toStrictEqual( 163 | buildExpectation('previous:1 2 next:3') 164 | ); 165 | 166 | act(() => { 167 | hook.result.current.goToPage(3); 168 | }); 169 | 170 | expect(hook.result.current.visiblePieces).toStrictEqual( 171 | buildExpectation('previous:2 3 !next:3') 172 | ); 173 | }); 174 | }); 175 | -------------------------------------------------------------------------------- /tools/gh-pages-publish.ts: -------------------------------------------------------------------------------- 1 | const { cd, exec, echo, touch } = require('shelljs') 2 | const { existsSync, readFileSync } = require('fs') 3 | const url = require('url') 4 | 5 | if (!existsSync('./docs/js/demo.js')) { 6 | throw new Error('tools/gh-pages-publish: run "npm run build" before'); 7 | } 8 | 9 | let repoUrl 10 | let pkg = JSON.parse(readFileSync('package.json') as any) 11 | if (typeof pkg.repository === 'object') { 12 | if (!pkg.repository.hasOwnProperty('url')) { 13 | throw new Error('URL does not exist in repository section') 14 | } 15 | repoUrl = pkg.repository.url 16 | } else { 17 | repoUrl = pkg.repository 18 | } 19 | 20 | let parsedUrl = url.parse(repoUrl) 21 | let repository = (parsedUrl.host || '') + (parsedUrl.path || '') 22 | let ghToken = process.env.GH_TOKEN 23 | 24 | echo(`Deploying docs to ${repository}`) 25 | exec('git config user.name "TravisCI"') 26 | exec('git config user.email "travis@travis-ci.org') 27 | exec('git checkout gh-pages') 28 | exec('git add .') // add whatever files were generated by the build script 29 | exec('git commit -m "docs(docs): update gh-pages. Travis build $TRAVIS_BUILD_NUMBER"') 30 | exec(`git remote add origin-pages https://${ghToken}@${repository} > /dev/null 2>&1`) 31 | exec('git push --quiet --set-upstream origin-pages gh-pages'); 32 | echo('Docs deployed!!') 33 | -------------------------------------------------------------------------------- /tools/semantic-release-prepare.ts: -------------------------------------------------------------------------------- 1 | const path = require("path") 2 | const { fork } = require("child_process") 3 | const colors = require("colors") 4 | 5 | const { readFileSync, writeFileSync } = require("fs") 6 | const pkg = JSON.parse( 7 | readFileSync(path.resolve(__dirname, "..", "package.json")) 8 | ) 9 | 10 | pkg.scripts.prepush = "npm run test:prod && npm run build" 11 | pkg.scripts.commitmsg = "commitlint -E HUSKY_GIT_PARAMS" 12 | 13 | writeFileSync( 14 | path.resolve(__dirname, "..", "package.json"), 15 | JSON.stringify(pkg, null, 2) 16 | ) 17 | 18 | // Call husky to set up the hooks 19 | fork(path.resolve(__dirname, "..", "node_modules", "husky", "lib", "installer", 'bin'), ['install']) 20 | 21 | console.log() 22 | console.log(colors.green("Done!!")) 23 | console.log() 24 | 25 | if (pkg.repository.url.trim()) { 26 | console.log(colors.cyan("Now run:")) 27 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 28 | console.log(colors.cyan(" semantic-release-cli setup")) 29 | console.log() 30 | console.log( 31 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 32 | ) 33 | console.log() 34 | console.log( 35 | colors.gray( 36 | 'Note: Make sure "repository.url" in your package.json is correct before' 37 | ) 38 | ) 39 | } else { 40 | console.log( 41 | colors.red( 42 | 'First you need to set the "repository.url" property in package.json' 43 | ) 44 | ) 45 | console.log(colors.cyan("Then run:")) 46 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 47 | console.log(colors.cyan(" semantic-release-cli setup")) 48 | console.log() 49 | console.log( 50 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 51 | ) 52 | } 53 | 54 | console.log() 55 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "es5", 5 | "module":"es2015", 6 | "lib": ["es2015", "es2016", "es2017", "dom"], 7 | "strict": true, 8 | "sourceMap": true, 9 | "declaration": true, 10 | "allowSyntheticDefaultImports": true, 11 | "experimentalDecorators": true, 12 | "emitDecoratorMetadata": true, 13 | "esModuleInterop": true, 14 | "declarationDir": "dist/types", 15 | "outDir": "dist/lib", 16 | "jsx": "react", 17 | "typeRoots": [ 18 | "typings", 19 | "node_modules/@types" 20 | ] 21 | }, 22 | "include": [ 23 | "src" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint-config-standard", 4 | "tslint-config-prettier" 5 | ], 6 | "rules": { 7 | "strict-type-predicates": false 8 | } 9 | } 10 | --------------------------------------------------------------------------------