Created
June 5, 2017 12:32
-
-
Save Polvista/b19054c705859cef8e38c70de4cf29f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const patchLinks = (stateService: StateService) => { | |
document.body.addEventListener('click', (event) => { | |
if(event.ctrlKey || event.metaKey || event.which == 2) | |
return; | |
let elm = event.target as HTMLElement; | |
while (elm.nodeName.toLowerCase() !== 'a') { | |
if (elm === document.body || !(elm = elm.parentElement)) | |
return; | |
} | |
let href = (elm as HTMLAnchorElement).href; | |
href = href.replace(/^https?:\/\//, '').replace('www.', '').replace(window.location.host, ''); | |
if(!href || elm.getAttribute('target') || /^\s*(javascript|mailto):/i.test(href) || href.startsWith('#') || href.startsWith('/#') || !href.startsWith('/')) | |
return; | |
event.preventDefault(); | |
const { path, search, hash } = LinksUtils.parseUrl(href); | |
const stateDecl = stateService.get() | |
.map(state => ({state, params: state.$$state().url.exec(path, search, hash)})) | |
.find(stateDecl => stateDecl.params != null); | |
if(stateDecl) | |
stateService.go(stateDecl.state.name, stateDecl.params); | |
}); | |
} |
This won't work if you click an element inside an anchor though, e.g. <a href="..."><div>Click me</div></a>
, because elm
will be the <div>
element. To solve this I used:
const nearestAnchor = event
.composedPath()
.find(element => (element as HTMLElement).tagName === "A");
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is
LinkUtils
here?