fix(search): add lazy input

This commit is contained in:
qingwei.li
2017-02-19 15:25:36 +08:00
parent 3b127a161c
commit bf593a77ad
2 changed files with 13 additions and 11 deletions

View File

@@ -81,13 +81,7 @@ function bindEvents () {
const $search = dom.find('div.search')
const $input = dom.find($search, 'input')
const $panel = dom.find($search, '.results-panel')
// Prevent to Fold sidebar
dom.on($search, 'click',
e => e.target.tagName !== 'A' && e.stopPropagation())
dom.on($input, 'input', e => {
const value = e.target.value.trim()
const doSearch = function (value) {
if (!value) {
$panel.classList.remove('show')
$panel.innerHTML = ''
@@ -96,7 +90,6 @@ function bindEvents () {
const matchs = search(value)
let html = ''
matchs.forEach(post => {
html += `<div class="matching-post">
<h2><a href="${post.url}">${post.title}</a></h2>
@@ -106,6 +99,15 @@ function bindEvents () {
$panel.classList.add('show')
$panel.innerHTML = html || '<p class="empty">No Results!</p>'
}
let timeId
// Prevent to Fold sidebar
dom.on($search, 'click',
e => e.target.tagName !== 'A' && e.stopPropagation())
dom.on($input, 'input', e => {
clearTimeout(timeId)
timeId = setTimeout(_ => doSearch(e.target.value.trim()), 200)
})
}

View File

@@ -82,14 +82,14 @@ export function search (keywords) {
const postContent = post.body && post.body.trim()
const postUrl = post.slug || ''
if (postTitle !== '' && postContent !== '') {
if (postTitle && postContent) {
keywords.forEach((keyword, i) => {
const regEx = new RegExp(keyword, 'gi')
let indexTitle = -1
let indexContent = -1
indexTitle = postTitle.search(regEx)
indexContent = postContent.search(regEx)
indexTitle = postTitle && postTitle.search(regEx)
indexContent = postContent && postContent.search(regEx)
if (indexTitle < 0 && indexContent < 0) {
isMatch = false