From a3376d1ad133455b73ca893e222c1aec89ae6d44 Mon Sep 17 00:00:00 2001 From: amzrk2 Date: Mon, 15 Jun 2020 23:50:54 +0800 Subject: Update searching based on Fuse.js --- assets/js/fuji.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'assets/js') diff --git a/assets/js/fuji.js b/assets/js/fuji.js index b72c30e..d1be458 100644 --- a/assets/js/fuji.js +++ b/assets/js/fuji.js @@ -83,3 +83,40 @@ document.querySelector('.btn .btn-toggle-mode').addEventListener('click', () => } } }); + +// search by fuse.js +function searchAll(key, index) { + let fuse = new Fuse(index, { + keys: ['title', 'tags'], + }); + let result = fuse.search(key); + console.log(result); + if (result.length > 0) { + document.getElementById('search-result').innerHTML = template('search-result-template', result); + } +} + +let urlParams = new URLSearchParams(window.location.search); // get params from URL +if (urlParams.has('search')) { + let key = urlParams.get('search'); // get search keyword + document.querySelector('.search-input input').setAttribute('value', key); + // get search index from json + let xhr = new XMLHttpRequest(); + xhr.open('GET', '/index.json', true); + xhr.responseType = 'json'; + xhr.onerror = function (e) { + console.error(`${xhr.status} ${xhr.statusText}`); + }; + xhr.onload = function () { + if (xhr.readyState === 4) { + if (xhr.status === 200) { + // use index json to search + console.log(xhr.response); + searchAll(key, xhr.response); + } else { + console.error(`${xhr.status} ${xhr.statusText}`); + } + } + }; + xhr.send(null); +} -- cgit v1.2.3