aboutsummaryrefslogtreecommitdiffhomepage
path: root/services/nuldoc/nuldoc-src/components/Pagination.ts
blob: 62e796b1663b0ff66ba40eacfbe399f2c252e294 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { elem, Element } from "../dom.ts";

type Props = {
  currentPage: number;
  totalPages: number;
  basePath: string;
};

export default function Pagination(
  { currentPage, totalPages, basePath }: Props,
): Element {
  if (totalPages <= 1) {
    return elem("div", {});
  }

  const pages = generatePageNumbers(currentPage, totalPages);

  return elem(
    "nav",
    { class: "pagination" },
    elem(
      "div",
      { class: "pagination-prev" },
      currentPage > 1
        ? elem("a", { href: pageUrlAt(basePath, currentPage - 1) }, "前へ")
        : null,
    ),
    ...pages.map((page) => {
      if (page === "...") {
        return elem("div", { class: "pagination-elipsis" }, "…");
      } else if (page === currentPage) {
        return elem(
          "div",
          { class: "pagination-page pagination-page-current" },
          elem("span", {}, String(page)),
        );
      } else {
        return elem(
          "div",
          { class: "pagination-page" },
          elem("a", { href: pageUrlAt(basePath, page) }, String(page)),
        );
      }
    }),
    elem(
      "div",
      { class: "pagination-next" },
      currentPage < totalPages
        ? elem("a", { href: pageUrlAt(basePath, currentPage + 1) }, "次へ")
        : null,
    ),
  );
}

type PageItem = number | "...";

/**
 * Generates page numbers for pagination display.
 *
 * - Always show the first page
 * - Always show the last page
 * - Always show the current page
 * - Always show the page before and after the current page
 * - If there's only one page gap between displayed pages, fill it
 * - If there are two or more pages gap between displayed pages, show ellipsis
 */
function generatePageNumbers(
  currentPage: number,
  totalPages: number,
): PageItem[] {
  const pages = new Set<number>();
  pages.add(1);
  pages.add(Math.max(1, currentPage - 1));
  pages.add(currentPage);
  pages.add(Math.min(totalPages, currentPage + 1));
  pages.add(totalPages);

  const sorted = Array.from(pages).sort((a, b) => a - b);

  const result: PageItem[] = [];
  for (let i = 0; i < sorted.length; i++) {
    if (i > 0) {
      const gap = sorted[i] - sorted[i - 1];
      if (gap === 2) {
        result.push(sorted[i - 1] + 1);
      } else if (gap > 2) {
        result.push("...");
      }
    }
    result.push(sorted[i]);
  }

  return result;
}

function pageUrlAt(basePath: string, page: number): string {
  return page === 1 ? basePath : `${basePath}${page}/`;
}