diff --git a/src/lib/DocSearch.js b/src/lib/DocSearch.js index a1bdf0503..f9fdd5108 100644 --- a/src/lib/DocSearch.js +++ b/src/lib/DocSearch.js @@ -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([ @@ -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) => { diff --git a/test/DocSearch-test.js b/test/DocSearch-test.js index 7b3a96491..7bcac3d84 100644 --- a/test/DocSearch-test.js +++ b/test/DocSearch-test.js @@ -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', () => {