all repos — h3 @ 5109642920d0098be427f14dfd8312de4a94e176

A tiny, extremely minimalist JavaScript microframework.

example/assets/js/components/paginator.js

 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
import h3 from "../h3.js";
import store from "../store.js";

export default function Paginator() {
  const hash = window.location.hash;
  let { page, pagesize, filteredTodos } = store.get();
  let total = filteredTodos.length;
  if (hash.match(/page=(\d+)/)) {
    page = parseInt(hash.match(/page=(\d+)/)[1]);
  }
  // Recalculate page in case data is filtered.
  page = Math.min(Math.ceil(filteredTodos.length / pagesize), page) || 1;
  store.dispatch("pages/set", page);
  const pages = Math.ceil(total / pagesize) || 1;
  const previousClass = page > 1 ? ".link" : ".disabled";
  const nextClass = page < pages ? ".link" : ".disabled";
  function setPreviousPage() {
    const page = store.get('page');
    const newPage = page - 1;
    store.dispatch("pages/set", newPage);
    window.location.hash = `/?page=${newPage}`;
    store.dispatch("app/update");
  }
  function setNextPage() {
    const page = store.get('page');
    const newPage = page + 1;
    store.dispatch("pages/set", newPage);
    window.location.hash = `/?page=${newPage}`;
    store.dispatch("app/update");
  }
  return h3("div.paginator", [
    h3(
      `span.previous-page${previousClass}`,
      {
        onclick: setPreviousPage,
      },
      ["←"]
    ),
    h3("span.current-page", [`${String(page)}/${String(pages)}`]),
    h3(
      `span.next-page${nextClass}`,
      {
        onclick: setNextPage,
      },
      ["→"]
    ),
  ]);
}