@@ -3,20 +3,20 @@ import { atom, onMount } from 'nanostores'
3
3
export function createRouter ( routes , opts = { } ) {
4
4
let router = atom ( )
5
5
router . routes = Object . keys ( routes ) . map ( name => {
6
- let value = routes [ name ]
6
+ let pattern = routes [ name ]
7
7
8
- if ( typeof value !== 'string' ) {
9
- return [ name , ...[ value ] . flat ( ) ]
8
+ if ( typeof pattern !== 'string' ) {
9
+ return [ name , ...[ pattern ] . flat ( ) ]
10
10
}
11
11
12
- value = value . replace ( / \/ $ / g, '' ) || '/'
12
+ pattern = pattern . replace ( / \/ $ / g, '' ) || '/'
13
13
14
- let pattern = value
14
+ let regexp = pattern
15
15
. replace ( / [ \s ! # $ ( ) + , . : < = ? [ \\ \] ^ { | } ] / g, '\\$&' )
16
16
. replace ( / \/ \\ : ( \w + ) \\ \? / g, '(?:/(?<$1>(?<=/)[^/]+))?' )
17
17
. replace ( / \/ \\ : ( \w + ) / g, '/(?<$1>[^/]+)' )
18
18
19
- return [ name , RegExp ( '^' + pattern + '$' , 'i' ) , null , value ]
19
+ return [ name , RegExp ( '^' + regexp + '$' , 'i' ) , null , pattern ]
20
20
} )
21
21
22
22
let prev
@@ -29,8 +29,8 @@ export function createRouter(routes, opts = {}) {
29
29
let path = opts . search ? url . pathname + url . search : url . pathname
30
30
path = path . replace ( / \/ ( $ | \? ) / , '$1' ) || '/'
31
31
32
- for ( let [ route , pattern , callback ] of router . routes ) {
33
- let match = path . match ( pattern )
32
+ for ( let [ route , regexp , callback ] of router . routes ) {
33
+ let match = path . match ( regexp )
34
34
if ( match ) {
35
35
return {
36
36
hash : url . hash ,
@@ -71,7 +71,7 @@ export function createRouter(routes, opts = {}) {
71
71
router . open ( link . href )
72
72
if ( hashChanged ) {
73
73
location . hash = link . hash
74
- if ( link . hash === '' || link . hash === '#' ) {
74
+ if ( ! link . hash || link . hash === '#' ) {
75
75
window . dispatchEvent ( new HashChangeEvent ( 'hashchange' ) )
76
76
}
77
77
}
@@ -135,20 +135,19 @@ export function getPagePath(router, name, params, search) {
135
135
}
136
136
let path = route [ 3 ]
137
137
. replace ( / \/ : \w + \? / g, i => {
138
- let param = params ? params [ i . slice ( 2 ) . slice ( 0 , - 1 ) ] : null
138
+ let param = params && params [ i . slice ( 2 , - 1 ) ]
139
139
if ( param ) {
140
140
return '/' + encodeURIComponent ( param )
141
141
} else {
142
142
return ''
143
143
}
144
144
} )
145
145
. replace ( / \/ : \w + / g, i => '/' + encodeURIComponent ( params [ i . slice ( 2 ) ] ) )
146
- let postfix = ''
147
146
if ( search ) {
148
- postfix = '' + new URLSearchParams ( search )
149
- if ( postfix ) postfix = '?' + postfix
147
+ let postfix = '' + new URLSearchParams ( search )
148
+ if ( postfix ) return path + '?' + postfix
150
149
}
151
- return ( path || '/' ) + postfix
150
+ return path
152
151
}
153
152
154
153
export function openPage ( router , name , params , search ) {
0 commit comments