-
Notifications
You must be signed in to change notification settings - Fork 320
/
search-page.js
177 lines (150 loc) · 4.71 KB
/
search-page.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/* globals searchNodes */
import lunr from 'lunr'
import resultsTemplate from './handlebars/templates/search-results.handlebars'
import { qs, escapeHtmlEntities, isBlank, getQueryParamByName, getProjectNameAndVersion } from './helpers'
import { setSearchInputValue } from './sidebar/sidebar-search'
const EXCERPT_RADIUS = 80
const SEARCH_CONTAINER_SELECTOR = '#search'
/**
* Performs a full-text search within the documentation
* for the query in URL params and renders the result.
*
* Activates only on the `/search.html` page.
*/
export function initialize () {
if (window.location.pathname.endsWith('/search.html')) {
const query = getQueryParamByName('q')
search(query)
}
}
function search (value) {
if (isBlank(value)) {
renderResults({ value })
} else {
setSearchInputValue(value)
const index = getIndex()
try {
const results = searchResultsToDecoratedSearchNodes(index.search(value))
renderResults({ value, results })
} catch (error) {
renderResults({ value, errorMessage: error.message })
}
}
}
function renderResults ({ value, results, errorMessage }) {
const searchContainer = qs(SEARCH_CONTAINER_SELECTOR)
const resultsHtml = resultsTemplate({ value, results, errorMessage })
searchContainer.innerHTML = resultsHtml
}
function getIndex () {
const cachedIndex = loadIndex()
if (cachedIndex) { return cachedIndex }
const index = createIndex()
saveIndex(index)
return index
}
function loadIndex () {
try {
const serializedIndex = sessionStorage.getItem(indexStorageKey())
if (serializedIndex) {
registerElixirTokenFunction()
return lunr.Index.load(JSON.parse(serializedIndex))
} else {
return null
}
} catch (error) {
console.error('Failed to load index: ', error)
return null
}
}
function saveIndex (index) {
try {
const serializedIndex = JSON.stringify(index)
sessionStorage.setItem(indexStorageKey(), serializedIndex)
} catch (error) {
console.error('Failed to save index: ', error)
}
}
function indexStorageKey () {
return `index:${getProjectNameAndVersion()}`
}
function createIndex () {
return lunr(function () {
this.ref('ref')
this.field('title', { boost: 3 })
this.field('doc')
this.metadataWhitelist = ['position']
this.pipeline.remove(lunr.stopWordFilter)
this.use(elixirTokenSplitter)
searchNodes.forEach(searchNode => {
this.add(searchNode)
})
})
}
function elixirTokenSplitter (builder) {
registerElixirTokenFunction()
builder.pipeline.before(lunr.stemmer, elixirTokenFunction)
builder.searchPipeline.before(lunr.stemmer, elixirTokenFunction)
}
function elixirTokenFunction (token) {
const tokens = token
.toString()
.split(/\.|\/|_/)
.map(part => {
return token.clone().update(() => part)
})
if (tokens.length > 1) {
return [...tokens, token]
}
return tokens
}
function registerElixirTokenFunction () {
return lunr.Pipeline.registerFunction(elixirTokenFunction, 'elixirTokenSplitter')
}
function searchResultsToDecoratedSearchNodes (results) {
return results
// If the docs are regenerated without changing its version,
// a reference may have been doc'ed false in the code but
// still available in the cached index, so we skip it here.
.filter(result => getSearchNodeByRef(result.ref))
.map(result => {
const searchNode = getSearchNodeByRef(result.ref)
const metadata = result.matchData.metadata
return {
...searchNode,
metadata,
excerpts: getExcerpts(searchNode, metadata)
}
})
}
function getSearchNodeByRef (ref) {
return searchNodes.find(searchNode => searchNode.ref === ref) || null
}
function getExcerpts (searchNode, metadata) {
const { doc } = searchNode
const searchTerms = Object.keys(metadata)
const excerpts =
searchTerms
.filter(term => 'doc' in metadata[term])
.map(term => {
return metadata[term].doc.position
.map(([sliceStart, sliceLength]) => excerpt(doc, sliceStart, sliceLength))
})
.reduce((xs, ys) => xs.concat(ys), []) // flatten
if (excerpts.length === 0) {
const beginning = doc.slice(0, EXCERPT_RADIUS * 2) + (EXCERPT_RADIUS * 2 < doc.length ? '...' : '')
return [beginning]
}
return excerpts.slice(0, 1)
}
function excerpt (doc, sliceStart, sliceLength) {
const startPos = Math.max(sliceStart - EXCERPT_RADIUS, 0)
const endPos = Math.min(sliceStart + sliceLength + EXCERPT_RADIUS, doc.length)
return [
startPos > 0 ? '...' : '',
doc.slice(startPos, sliceStart),
'<em>' + escapeHtmlEntities(doc.slice(sliceStart, sliceStart + sliceLength)) + '</em>',
doc.slice(sliceStart + sliceLength, endPos),
endPos < doc.length ? '...' : ''
].join('')
}