Skip to content

Commit

Permalink
feat: add support hash router
Browse files Browse the repository at this point in the history
  • Loading branch information
lexich committed Nov 29, 2021
1 parent 2036c48 commit cb63cd5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
4 changes: 3 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,11 @@ export interface Router<AppPages extends Pages = Pages>
* ```
*
* @param routes URL patterns.
* @param options (Optional) { hash?: boolean }
*/
export function createRouter<AppPages extends Pages>(
routes: Routes<AppPages>
routes: Routes<AppPages>,
options?: { hash?: boolean }
): Router<AppPages>

/**
Expand Down
22 changes: 15 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { atom, onMount } from 'nanostores'

export function createRouter(routes) {
export function createRouter(routes, options) {
let router = atom()
let isHashRouter = options && options.hash;

let getPathname = isHashRouter
? () => location.hash.replace(/^#\/?/, '')
: () => location.pathname

router.routes = Object.keys(routes).map(name => {
let value = routes[name]
if (typeof value === 'string') {
Expand Down Expand Up @@ -75,20 +81,21 @@ export function createRouter(routes) {
}

let popstate = () => {
let page = parse(location.pathname)
let page = parse(getPathname())
if (page !== false) set(page)
}

if (typeof window !== 'undefined' && typeof location !== 'undefined') {
onMount(router, () => {
let page = parse(location.pathname)
let page = parse(getPathname())
if (page !== false) set(page)
document.body.addEventListener('click', click)
window.addEventListener('popstate', popstate)
let eventName = isHashRouter ? 'hashchange' : 'popstate'
window.addEventListener(eventName, popstate)
return () => {
prev = undefined
document.body.removeEventListener('click', click)
window.removeEventListener('popstate', popstate)
window.removeEventListener(eventName, popstate)
}
})
} else {
Expand All @@ -99,10 +106,11 @@ export function createRouter(routes) {
let page = parse(path)
if (page !== false) {
if (typeof history !== 'undefined') {
let pageFix = isHashRouter ? '#' + path : path
if (redirect) {
history.replaceState(null, null, path)
history.replaceState(null, null, pageFix)
} else {
history.pushState(null, null, path)
history.pushState(null, null, pageFix)
}
}
set(page)
Expand Down

0 comments on commit cb63cd5

Please sign in to comment.