Skip to content

Commit

Permalink
fix(url): Removes concatenation of URL with hash if it contains a hash
Browse files Browse the repository at this point in the history
FIX #53
  • Loading branch information
Alexandre Stanislawski committed Dec 28, 2015
1 parent bc12b23 commit 348df1c
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/lib/DocSearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ class DocSearch {

// Translate hits into smaller objects to be send to the template
return groupedHits.map((hit) => {
let url = hit.anchor ? `${hit.url}#${hit.anchor}` : hit.url;
let url = DocSearch.formatURL(hit);
let category = utils.getHighlightedValue(hit, 'lvl0');
let subcategory = utils.getHighlightedValue(hit, 'lvl1') || category;
let displayTitle = utils.compact([
Expand All @@ -154,6 +154,21 @@ class DocSearch {
});
}

static formatURL(hit) {
const {url, anchor} = hit;
if (url) {
const containsAnchor = url.indexOf('#') !== -1;
if (containsAnchor) return url;
else if (anchor) return `${hit.url}#${hit.anchor}`;
return url;
}
else if (anchor) return `#${hit.anchor}`;
/* eslint-disable */
console.warn('no anchor nor url for : ', JSON.stringify(hit));
/* eslint-enable */
return null;
}

static getSuggestionTemplate() {
const template = Hogan.compile(templates.suggestion);
return (suggestion) => {
Expand Down
64 changes: 64 additions & 0 deletions test/DocSearch-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,70 @@ describe('DocSearch', () => {
// Then
expect(actual[0].url).toEqual('http://foo.bar/#anchor');
});
it('should not add the anchor to the url if one is set but it is already in the URL', () => {
// Given
let input = [{
hierarchy: {
lvl0: 'Ruby',
lvl1: 'API',
lvl2: null,
lvl3: null,
lvl4: null,
lvl5: null
},
content: 'foo bar',
url: 'http://foo.bar/#anchor',
anchor: 'anchor'
}];

// When
let actual = DocSearch.formatHits(input);

// Then
expect(actual[0].url).toEqual('http://foo.bar/#anchor');
});
it('should just use the URL if no anchor is provided', () => {
// Given
let input = [{
hierarchy: {
lvl0: 'Ruby',
lvl1: 'API',
lvl2: null,
lvl3: null,
lvl4: null,
lvl5: null
},
content: 'foo bar',
url: 'http://foo.bar/'
}];

// When
let actual = DocSearch.formatHits(input);

// Then
expect(actual[0].url).toEqual(input[0].url);
});
it('should return the anchor if there is no URL', () => {
// Given
let input = [{
hierarchy: {
lvl0: 'Ruby',
lvl1: 'API',
lvl2: null,
lvl3: null,
lvl4: null,
lvl5: null
},
content: 'foo bar',
anchor: 'anchor'
}];

// When
let actual = DocSearch.formatHits(input);

// Then
expect(actual[0].url).toEqual('#' + input[0].anchor);
});
});

describe('getSuggestionTemplate', () => {
Expand Down

0 comments on commit 348df1c

Please sign in to comment.