Skip to content

Commit

Permalink
fix: only intercept links we recognize
Browse files Browse the repository at this point in the history
  • Loading branch information
mikaelkaron committed Jun 21, 2019
1 parent 65818f3 commit b983848
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
5 changes: 5 additions & 0 deletions packages/stencil-xstate-router/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions packages/stencil-xstate-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,8 @@
"peerDependencies": {
"navigo": "^7.1.2",
"xstate": "^4.6.1"
},
"dependencies": {
"route-recognizer": "^0.3.4"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ import {
RouterInterpreterOptions,
StateRenderer
} from '../xstate-router/types';
import RouteRecognizer from 'route-recognizer';

@Component({
tag: 'xstate-router-navigo',
shadow: false
})
export class XstateRouterNavigo implements ComponentInterface {
@State() router: Navigo;
@State() private routes = new RouteRecognizer();
@State() private router: Navigo;

/**
* An XState machine
Expand Down Expand Up @@ -90,10 +92,17 @@ export class XstateRouterNavigo implements ComponentInterface {
// that the link has a `href` attribute
el.hasAttribute('href')
) {
// stop default click action
event.preventDefault();
// navigate to the url
this.router.navigate(el.getAttribute('href'));
// normalize href attribute
const href = el
.getAttribute('href')
.replace(new RegExp(`^${this.hash}`), '');
// check if we recognize this url
if (this.routes.recognize(href)) {
// stop default click action
event.preventDefault();
// navigate to the url
this.router.navigate(href);
}
}
}

Expand All @@ -105,8 +114,6 @@ export class XstateRouterNavigo implements ComponentInterface {
route={(routes, send) =>
routes
? routes
// https://github.com/krasimir/navigo/pull/39
.sort((a, b) => b.path.length - a.path.length)
// map paths to unsubscribe callbacks
.map(({ path }) => {
const handler = (params: Record<string, any>) =>
Expand All @@ -115,6 +122,8 @@ export class XstateRouterNavigo implements ComponentInterface {
path,
params
});
// add path to this.routes
this.routes.add([{ path, handler }]);
// subscribe path to history changes
this.router.on(path, handler);
// return unsubscribe handler
Expand Down

0 comments on commit b983848

Please sign in to comment.