Skip to content

Commit

Permalink
A working relative links implementation (with test) that only account…
Browse files Browse the repository at this point in the history
…s for links in a document (not `route("./foo")`). See #138.
  • Loading branch information
developit committed Apr 18, 2017
1 parent 315be7c commit 0e68437
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
27 changes: 9 additions & 18 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,11 @@ function routeTo(url) {


function routeFromLink(node) {
// only valid elements
if (!node || !node.getAttribute) return;

let href = node.getAttribute('href'),
target = node.getAttribute('target');

// ignore links with targets and non-path URLs
if (!href || !href.match(/^\//g) || (target && !target.match(/^_?self$/i))) return;
// ignore invalid & external links:
if (!node || node.protocol!==location.protocol || node.host!==location.host || (node.target && !node.target.match(/^_?self$/i))) return;

// attempt to route, if no match simply cede control to browser
return route(href);
return route(node.pathname + node.search + node.hash);
}


Expand Down Expand Up @@ -117,12 +111,9 @@ function delegateLinkHandler(e) {

let t = e.target;
do {
if (String(t.nodeName).toUpperCase()==='A' && t.getAttribute('href') && isPreactElement(t)) {
if (t.hasAttribute('native')) return;
if (String(t.nodeName).toUpperCase()==='A' && t.pathname && isPreactElement(t) && !t.hasAttribute('native') && routeFromLink(t)) {
// if link is handled by the router, prevent browser defaults
if (routeFromLink(t)) {
return prevent(e);
}
return prevent(e);
}
} while ((t=t.parentNode));
}
Expand All @@ -131,13 +122,13 @@ function delegateLinkHandler(e) {
let eventListenersInitialized = false;

function initEventListeners() {
if (eventListenersInitialized){
return;
}
if (eventListenersInitialized) return;

if (typeof addEventListener==='function') {
if (!customHistory) {
addEventListener('popstate', () => routeTo(getCurrentUrl()));
addEventListener('popstate', () => {
routeTo(getCurrentUrl());
});
}
addEventListener('click', delegateLinkHandler);
}
Expand Down
16 changes: 16 additions & 0 deletions test/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,22 @@ describe('dom', () => {
route('/foo');
expect(routerRef.base.outerHTML).to.eql('<p>bar is </p>');
});

it('should support relative links', () => {
class A {
render() {
return <a href="two">go</a>;
}
}
history.replaceState(null, null, '/foo/one');
mount(
<Router>
<A default />
</Router>
);
scratch.querySelector('a').click();
expect(location.pathname).to.equal('/foo/two');
});
});

describe('preact-router/match', () => {
Expand Down

0 comments on commit 0e68437

Please sign in to comment.