• Stars
    star
    140
  • Rank 261,473 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 3 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate a sequence of numbers for use in a pagination system, the clever way.

JavaScript Pagination Sequence Generator

JavaScript Pagination Sequence Generator

Generate a sequence of numbers for use in a Pagination Component, the clever way.

Installation

npm i @bramus/pagination-sequence

Usage / Example

This library comes as an ES Module and exposes a function/algorithm to generate an array of pagination entries.

import { generate } from '@bramus/pagination-sequence';

const sequence = generate(67, 74);
// ~> [1, 2, '…', 65, 66, 67, 68, 69, '…', 73, 74]

Alternatively you can use generateFromObj which accepts a configuration Object as an argument:

import { generateFromObj } from '@bramus/pagination-sequence';

const sequence = generateFromObj({
    curPage: 67,
    numPages: 74,
});
// ~> [1, 2, '…', 65, 66, 67, 68, 69, '…', 73, 74]

Note that this is a Framework Agnostic library: the generated array is not rendered in any way but, instead, must be fed into your own Pagination Component for rendering.

πŸ’‘ Looking for some Pagination Component inspiration? See Integration Examples below to see how to use this with the JavaScript Framework Du Jourβ„’.

API

generate()

The exposed generate function has the following API:

generate(curPage, numPages, numPagesAtEdges = 2, numPagesAroundCurrent = 2, glue = '…');

Parameters:

  • curPage: The current active page
  • numPages: The total number of pages
  • numPagesAtEdges (default: 2): Number of pages to show on the outer edges.
  • numPagesAroundCurrent (default: 2): Number of pages to show around the active page.
  • glue (default: '…'): The string to show when there's a gap

generateFromObj()

The generateFromObj function accepts one single opts object. Its members are all of the parameters described above. Default values are set where possible.

const { 
    curPage = 1,
    numPages = 1,
    numPagesAtEdges = 2,
    numPagesAroundCurrent = 2,
    glue = '…',
} = opts;

Principles

The algorithm is opinionated and follows these principles:

  • Stable Output

    When generating a sequence, it will always generate the same amount of entries, for any curPage value. When viewing a page at the edge of a series, this can result in numPagesAtEdges being ignored.

    For example: Instead of having generate(2, 12, 1, 1) return 01-[02]-03-..-12 (5 entries), it will return 01-[02]-03-04-05-..-12 (7 entries). This is a deliberate choice because generate(7, 12, 1, 1) will also return 7 entries: 01-..-06-[07]-08-..-12.

    With a stable amount of entries being generated, the output will also be visually stable when rendered on screen.

  • Always include links to the edges

    The algorithm will always include links to the first and last page.

    For Example: when looking at page 25 of 50, the algorithm will include a link to page 1 and page 50.

  • No unnecessary gaps

    When the algorithm detects a gap that's only β€œ1 item wide”, it will replace that gap with the actual number.

    For Example: A foolish take on generate(4, 9, 1, 1), would generate 01-..-03-[04]-05-..-09. The algorithm corrects the first gap to 02 and will return 01-02-03-[04]-05-..-09 instead.

Integration Examples

React

πŸ”— Try it online: https://codepen.io/bramus/pen/NWaxNKQ

import React from "react";
import ReactDOM from "react-dom";
import { generate } from "@bramus/pagination-sequence";

const BASE_URL = '#';

const PaginationEntry = ({ value, onEntryClick = null, label = null, title = null, isCurrent = false, isDisabled = false, ...props }) => {
    label ??= value;
    title ??= `Go to page ${value}`;

    const onClick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        
        e.target.blur();
        
        if (onEntryClick) {
            onEntryClick(value);
        }
    }
        
    if (value == '…') {
        return (
            <li data-pagination-ellipsis {...props}><span>{label}</span></li>
        );
    }

    if (isDisabled) {
        return (
            <li data-pagination-disabled {...props}><span>{label}</span></li>
        );
    }

    if (isCurrent) {
        props['data-pagination-current'] = true;
    }

    return (
        <li {...props}>
            <a href={`${BASE_URL}/page/${value}`} title={title} onClick={onClick}>{label}</a>
        </li>
    );
}

const Pagination = ({ curPage, numPages, numPagesAtEdges = 2, numPagesAroundCurrent = 2, onEntryClick = null }) => {
    const sequence = generate(curPage, numPages, numPagesAtEdges, numPagesAroundCurrent);
    // console.log(sequence);

    return (
        <ul className="pagination">
            <PaginationEntry data-pagination-first onEntryClick={onEntryClick} value={1} title="Go to First Page" label="&laquo;" isDisabled={curPage === 1} />
            <PaginationEntry data-pagination-prev onEntryClick={onEntryClick} value={curPage-1} title="Go to Previous Page" label="&lsaquo;" isDisabled={curPage === 1} />
            {sequence.map((val, idx) => 
                <PaginationEntry key={`page-${(val == '…') ? `…-${idx}` : val}`} onEntryClick={onEntryClick} value={val} isCurrent={val == curPage} />
            )}
            <PaginationEntry data-pagination-next onEntryClick={onEntryClick} value={curPage+1} title="Go to Next Page" label="&rsaquo;" isDisabled={curPage === numPages} />
            <PaginationEntry data-pagination-next onEntryClick={onEntryClick} value={numPages} title="Go to Last Page" label="&raquo;" isDisabled={curPage === numPages} />
        </ul>
    );
}

ReactDOM.render(
    <Pagination curPage={25} numPages={50} onEntryClick={(val) => { console.log(val)}} />,
    document.getElementById('root')
);

License

@bramus/pagination-sequence is released under the MIT public license. See the enclosed LICENSE for details.

Other Language Implementations

Looking for an implementation in another programming language?

More Repositories

1

react-native-maps-directions

Directions Component for `react-native-maps`
JavaScript
1,219
star
2

router

A lightweight and simple object oriented PHP Router
PHP
1,085
star
3

mixed-content-scan

Scan your HTTPS-enabled website for Mixed Content
PHP
522
star
4

photoshop-google-maps-tile-cutter

PS_Bramus.GoogleMapsTileCutter - A Photoshop script that cuts image tiles from any image for direct use with Google Maps
JavaScript
201
star
5

monolog-colored-line-formatter

Colored/ANSI Line Formatter for Monolog
PHP
132
star
6

freshinstall

Automatically configure and install software onto your new Mac
Shell
106
star
7

composer-autocomplete

Bash/Shell autocompletion for Composer
94
star
8

mastodon-redirector

View Mastodon profiles on your Mastodon instance
JavaScript
93
star
9

ansi-php

ANSI Control Functions and ANSI Control Sequences (Colors, Erasing, etc.) for PHP CLI Apps
PHP
89
star
10

specificity

JavaScript Package to calculate the Specificity of CSS Selectors
JavaScript
68
star
11

viewport-resize-behavior

Viewport vs Virtual Keyboard Resize Behavior Explainer
45
star
12

simple-rest-api-explorer

A simple way to showcasing and exploring all endpoints of your RESTful API.
JavaScript
37
star
13

mercator-puzzle-redux

Dynamic take on the original Mercator Puzzle by Google
HTML
37
star
14

scroll-driven-animations-debugger-extension

Browser extension to debug Scroll-Driven Animations
36
star
15

ion-drawer-vertical

A vertical drawer for Ionic 1
JavaScript
35
star
16

sda-utilities

Collection of utility functions for use with Scroll-Driven Animations
JavaScript
28
star
17

style-observer

MutationObserver for CSS
TypeScript
26
star
18

view-transitions-demos

HTML
20
star
19

react-native-maps-directions-example

Example app that uses react-native-maps-directions
Java
20
star
20

ws2-sws-course-materials

Course materials for the course Serverside Webscripting, part of the Professional Bachelor ICT study programme.
PHP
13
star
21

chrome-dark-mode-toggle

Real control over Light Mode / Dark Mode on a per-site basis!
13
star
22

web-dev-rss

Cloudflare Worker that generates RSS Feeds for web.dev
JavaScript
12
star
23

webhid-elgato-stream-deck-daft-punk-soundboard

WebHID Demo: Elgato Stream Deck Daft Punk Soundboard
JavaScript
12
star
24

bramus_cssextras

bramus_cssextras is a plugin for TinyMCE which enables the usage of CSS classes and CSS ids on any HTML element within TinyMCE. Together with an external CSS file, set via the TinyMCE content_css setting, bramus_cssextras bridges the (visual) gap between the content entered through TinyMCE and the actual output
JavaScript
12
star
25

ria-course-materials

Course materials for the course Web & Mobile Development (formerly Rich Internet Applications), part of the Professional Bachelor ICT study programme.
JavaScript
12
star
26

ws1-sws-course-materials

Course materials for the course Serverside Webscripting, part of the Professional Bachelor ICT study programme.
PHP
11
star
27

css-houdini-voronoi

A CSS Houdini Paint Worklet that draws a Voronoi Diagram as a background image
JavaScript
10
star
28

google-maps-polygon-moveto

Programmatically move a google.maps.Polygon to a new google.maps.LatLng using Google Maps V3
JavaScript
9
star
29

js-range

JavaScript
7
star
30

ws2-sws-fiddles-silex

Silex Code Examples/Fiddles
PHP
7
star
31

css-houdini-circles

A CSS Houdini PaintWorklet to draw background circles.
JavaScript
7
star
32

PS_BRAMUS.TextConvert

PSD2TXT and TXT2PSD for the masses!
JavaScript
6
star
33

enumeration

Yet Another Enumeration Implementation for PHP
PHP
5
star
34

chrome-for-developers-rss

Cloudflare Worker that generates RSS Feeds for developer.chrome.com
JavaScript
4
star
35

wec-web-ui-summit-2023-demos

WEC Web UI Summit 2023 Demos
HTML
4
star
36

reflection

A library that tries to make PHP's built-in Reflection better.
PHP
3
star
37

github-toggle-chrome-extension

Quickly toggle between a GitHub Repo and its GitHub Pages
JavaScript
3
star
38

jquery_classdata

jQuery ClassData is a jQuery plugin that allows you to access and manipulate data saved in the class property of DOM-elements in a nice and easy to use way.
JavaScript
3
star
39

js-pagination-sequence-demos

Demos that use @bramus/pagination-sequence
JavaScript
2
star
40

css-selector-benchmark

CSS Selector Benchmarks, using PerfTestRunner and Puppeteer
HTML
2
star
41

wmd-course-materials

Course materials for the course Web & Mobile Development, part of the Professional Bachelor ICT study programme.
JavaScript
2
star
42

yummy

A self hosted Delicious (with del.icio.us import)
PHP
1
star
43

meetingzone

Find a meeting time across timezones
JavaScript
1
star
44

gcloud-kms-scripts

A collection of scripts here to help interact with Google's Cloud Key Management Service (KMS)
Shell
1
star
45

tokenphrase

TokenPhrase is a PHP class that generates unique phrases for you to use in your app as tokens
PHP
1
star
46

terraform-gcloud-event-cloud-function

Terraform deploy a local folder to a Google Cloud Function that can be triggered via an Event
HCL
1
star
47

remix-example-app

JavaScript
1
star
48

parcel-css-demo

JavaScript
1
star
49

bramus_cssextras-demo

Demo for bramus_cssextras (https://github.com/bramus/bramus_cssextras) | bramus_cssextras is a plugin for TinyMCE which enables the usage of CSS classes and CSS ids on any HTML element within TinyMCE. Together with an external CSS file, set via the TinyMCE content_css setting, bramus_cssextras bridges the (visual) gap between the content entered through TinyMCE and the actual output
1
star