Skip to content

Commit

Permalink
fixed initial context without slash 🔧
Browse files Browse the repository at this point in the history
  • Loading branch information
cinic committed May 31, 2021
1 parent 6aabae9 commit 3eee1f2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
11 changes: 11 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {createURLRouter, $context} from './index'

describe('Test router creation', () => {
it('context without /', () => {
createURLRouter({
context: 'dealer',
routes: [{path: '/', view: () => console.log('Hello')}],
})
expect($context.getState()).toBe('/dealer')
})
})
11 changes: 5 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const pushState = createEffect(
},
)

const $context = restore(changeContext, '')
export const $context = restore(changeContext, '')
const $routes = restore(addRoutes, [])
const $currentPathname = createStore('/')
export const $currentRoute = combine(
Expand Down Expand Up @@ -46,15 +46,14 @@ export function createURLRouter({
}: RouterParams): Router {
if (!Array.isArray(routes)) throw Error('routes should be an Array of Route!')

if (context) {
context.match(/^[^/]/) ? changeContext(`/${context}`) : changeContext(context)
}
const ctx = context && context.match(/^[^/]/) ? `/${context}` : context

changeContext(ctx)
addRoutes(routes)
popState(location.pathname.replace(context, ''))
popState(location.pathname.replace(ctx, ''))

window.addEventListener('popstate', (e) =>
popState((e.target as Window).location.pathname.replace(context, '')),
popState((e.target as Window).location.pathname.replace(ctx, '')),
)

return () =>
Expand Down

0 comments on commit 3eee1f2

Please sign in to comment.