Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support hash router #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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