website-theme/assets/js/search.js

165 lines
4.2 KiB
JavaScript
Raw Normal View History

2019-03-24 11:41:16 -04:00
var lunrIndex
var lunrResult
var pagesIndex
2018-10-08 06:37:58 -04:00
2019-03-24 13:02:50 -04:00
var bigramTokeniser = function (obj, metadata) {
if (obj == null || obj == undefined) {
return []
}
if (Array.isArray(obj)) {
return obj.map(function (t) {
return new lunr.Token(
lunr.utils.asString(t).toLowerCase(),
lunr.utils.clone(metadata)
)
})
}
var str = obj.toString().trim().toLowerCase(),
tokens = []
for(var i = 0; i <= str.length - 2; i++) {
var tokenMetadata = lunr.utils.clone(metadata) || {}
tokenMetadata["position"] = [i, i + 2]
tokenMetadata["index"] = tokens.length
tokens.push(
new lunr.Token (
str.slice(i, i + 2),
tokenMetadata
)
)
}
return tokens
}
var queryNgramSeparator = function (query) {
var str = query.toString().trim().toLowerCase(),
tokens = []
for(var i = 0; i <= str.length - 2; i++) {
tokens.push(str.slice(i, i + 2))
}
return tokens.join(' ')
}
2018-10-08 06:37:58 -04:00
/**
2019-03-24 11:41:16 -04:00
* Preparation for using lunr.js
2018-10-08 06:37:58 -04:00
*/
2019-03-24 11:41:16 -04:00
function initLunr () {
2018-10-08 06:37:58 -04:00
$.getJSON('index.json').done(function (index) {
2019-03-24 11:41:16 -04:00
pagesIndex = index
lunrIndex = lunr(function () {
2019-03-24 13:02:50 -04:00
this.tokenizer = bigramTokeniser
this.pipeline.reset()
2019-03-24 11:41:16 -04:00
this.ref('ref')
this.field('title', { boost: 10 })
this.field('body')
this.metadataWhitelist = ['position']
for (var page of pagesIndex) {
this.add(page)
}
})
2018-10-08 06:37:58 -04:00
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error
console.error('Error getting Hugo index flie:', err)
})
}
2019-03-24 11:41:16 -04:00
/**
* Searching pages using lunr
* @param {String} query Query string for searching
* @return {Object[]} Array of search results
*/
function search (query) {
2019-03-24 13:02:50 -04:00
lunrResult = lunrIndex.search(queryNgramSeparator(query))
2019-03-24 11:41:16 -04:00
return lunrResult.map(function (result) {
return pagesIndex.filter(function (page) {
return page.ref === result.ref
})[0]
})
}
2018-10-08 06:37:58 -04:00
/**
* Setup UI for Search
*/
function initUI () {
// Clear query when clear icon is clicked
$('#searchBoxIcon').click(function () {
2019-03-23 03:18:03 -04:00
$('#searchBoxInput').val('')
$('#searchBoxInput').trigger('keyup')
2018-10-08 06:37:58 -04:00
})
// Event when chenging query
2019-03-23 03:18:03 -04:00
$('#searchBoxInput').keyup(function () {
2018-10-08 06:37:58 -04:00
var $searchResults = $('#searchResults')
2019-03-24 11:41:16 -04:00
var query = $(this).val()
2018-10-08 06:37:58 -04:00
// Icon switching
if (query.length) {
$('#searchBoxIcon').attr('src', '/img/clear.png')
$('#searchBoxIcon').css('cursor', 'pointer')
} else {
$('#searchBoxIcon').attr('src', '/img/search.png')
$('#searchBoxIcon').css('cursor', 'default')
}
// Only trigger a search when 2 chars. at least have been provided
if (query.length < 2) {
$searchResults.hide()
return
}
// Display search results
2019-03-24 11:41:16 -04:00
renderResults(search(query))
2018-10-08 06:37:58 -04:00
$searchResults.show()
})
// Emit keyup event for when the query is already setted with browser back etc.
2019-03-23 03:18:03 -04:00
$('#searchBoxInput').trigger('keyup')
2018-10-08 06:37:58 -04:00
}
/**
* Rendering search results
* @param {Object[]} results Array of search results
*/
function renderResults (results) {
var $searchResults = $('#searchResults')
2019-03-23 03:18:03 -04:00
var query = $('#searchBoxInput').val()
2019-03-24 11:41:16 -04:00
var BODY_LENGTH = 100
2018-10-08 06:37:58 -04:00
var MAX_PAGES = 10
// Clear search result
$searchResults.empty()
// Show message when results is empty
if (!results.length) {
$searchResults.append('<div class="searchResultPage">No results found for query "' + query + '"</div>')
return
}
// Only show the ten first results
results.slice(0, MAX_PAGES).forEach(function (result, idx) {
var $searchResultPage = $('<div class="searchResultPage">')
2019-03-24 11:41:16 -04:00
var metadata = lunrResult[idx].matchData.metadata
var matchPosition = metadata[Object.keys(metadata)[0]].body ? metadata[Object.keys(metadata)[0]].body.position[0][0] : 0
var bodyStartPosition = (matchPosition - (BODY_LENGTH / 2) > 0) ? matchPosition - (BODY_LENGTH / 2) : 0
2018-10-08 06:37:58 -04:00
$searchResultPage.append('<a class="searchResultTitle" href="' + result.ref + '">' + result.title + '</a>')
2019-03-24 11:41:16 -04:00
$searchResultPage.append('<div class="searchResultBody">' + result.body.substr(bodyStartPosition, BODY_LENGTH) + '</div>')
2018-10-08 06:37:58 -04:00
$searchResults.append($searchResultPage)
// Highlight keyword
$('#searchResults').mark(query)
})
}
2019-03-24 11:41:16 -04:00
initLunr()
2018-10-08 06:37:58 -04:00
$(function () {
initUI()
})