OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-web-ui / web / js / router.js

41 lines · javascript ref:
/**
 * Browser-side SPA Router
 *
 * Hash-based routing shared across P2P apps.
 * Each app registers its own pages.
 *
 * Usage:
 *   import { createRouter } from './router.js'
 *   const router = createRouter(document.getElementById('app'))
 *   router.add(/^\/$/, pageHome)
 *   router.add(/^\/repos\/([^/]+)$/, pageRepo)
 *   router.start()
 */

export function createRouter (container) {
  const routes = []

  function add (pattern, handler) {
    routes.push({ pattern, handler })
  }

  function navigate () {
    const hash = window.location.hash.slice(1) || '/'
    for (const r of routes) {
      const match = hash.match(r.pattern)
      if (match) {
        r.handler(container, ...match.slice(1))
        return
      }
    }
    container.innerHTML = '<div class="error">404 — Page not found</div>'
  }

  function start () {
    window.addEventListener('hashchange', navigate)
    navigate()
  }

  return { add, start, navigate }
}