Skip to content

Commit

Permalink
Merge branch 'fix-base-tag-hashHistory-createHref' of https://github.…
Browse files Browse the repository at this point in the history
…com/microbouji/history into microbouji-fix-base-tag-hashHistory-createHref
  • Loading branch information
mjackson committed Sep 12, 2019
2 parents 90561da + 288fc42 commit 27a8986
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 5 deletions.
34 changes: 34 additions & 0 deletions modules/__tests__/HashHistory-base-test.js
@@ -0,0 +1,34 @@
import expect from 'expect';
import { createHashHistory } from 'history';

describe('a hash history on a page with a <base> tag', () => {
let history, base;
beforeEach(() => {
base = document.createElement('base');
base.setAttribute('href', '/prefix');

document.head.appendChild(base);

history = createHashHistory();
});

afterEach(() => {
document.head.removeChild(base);
});

it('knows how to create hrefs', () => {
const hashIndex = window.location.href.indexOf('#');
const upToHash =
hashIndex === -1
? window.location.href
: window.location.href.slice(0, hashIndex);

const href = history.createHref({
pathname: '/the/path',
search: '?the=query',
hash: '#the-hash'
});

expect(href).toEqual(upToHash + '#/the/path?the=query#the-hash');
});
});
17 changes: 12 additions & 5 deletions modules/createHashHistory.js
Expand Up @@ -34,6 +34,11 @@ const HashPathCoders = {
}
};

function stripHash(url) {
const hashIndex = url.indexOf('#');
return hashIndex === -1 ? url : url.slice(0, hashIndex);
}

function getHashPath() {
// We can't use window.location.hash here because it's not
// consistent across browsers - Firefox will pre-decode it!
Expand All @@ -47,10 +52,7 @@ function pushHashPath(path) {
}

function replaceHashPath(path) {
const hashIndex = window.location.href.indexOf('#');
window.location.replace(
window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + '#' + path
);
window.location.replace(stripHash(window.location.href) + '#' + path);
}

function createHashHistory(props = {}) {
Expand Down Expand Up @@ -179,7 +181,12 @@ function createHashHistory(props = {}) {
// Public interface

function createHref(location) {
return '#' + encodePath(basename + createPath(location));
const baseTag = document.querySelector('base');
let href = '';
if (baseTag && baseTag.getAttribute('href')) {
href = stripHash(window.location.href);
}
return href + '#' + encodePath(basename + createPath(location));
}

function push(path, state) {
Expand Down

0 comments on commit 27a8986

Please sign in to comment.