From dda0a0eab19457598b71f2b2b2f978b09d3f95c7 Mon Sep 17 00:00:00 2001 From: Alex Shpak Date: Mon, 15 Jul 2019 18:25:21 +0200 Subject: Start work on search feature with lunr --- assets/book.scss | 18 ++++++++++++++++++ assets/search.js | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 assets/search.js (limited to 'assets') diff --git a/assets/book.scss b/assets/book.scss index 9edc86a..8a94551 100644 --- a/assets/book.scss +++ b/assets/book.scss @@ -137,6 +137,23 @@ ul.pagination { display: none; } +.book-search { + border: 0; + border-bottom: $padding-1 solid $gray-200; + outline: none; + // padding: $padding-4 $padding-8 $padding-4 $padding-16+$padding-4; + padding: $padding-4 $padding-8 $padding-4 0; + margin-bottom: $padding-4; + width: 100%; + + // background: url("svg/search.svg") left center no-repeat; + // background-size: $padding-16; + + &:focus { + border-bottom-color: $body-font-color; + } +} + .book-toc { flex: 0 0 $toc-width; font-size: $font-size-12; @@ -211,6 +228,7 @@ aside nav, @media screen and (max-width: $sm-breakpoint) { .book-menu { margin-left: -$menu-width; + font-size: $font-size-base; } .book-header { diff --git a/assets/search.js b/assets/search.js new file mode 100644 index 0000000..84e522a --- /dev/null +++ b/assets/search.js @@ -0,0 +1,41 @@ +addEventListener("load", function() { + let input = document.querySelector("#book-search"); + let results = document.querySelector("#book-search-results"); + + Promise.all([ + loadScript("{{ "lunr.min.js" | relURL }}"), + loadScript("{{ "index.json" | relURL }}") + ]).then(enableLunr); + + function enableLunr() { + results.idx = lunr(function() { + this.ref('href') + this.field('title') + this.field('content') + + window.lunrData.forEach(function (page) { + this.add(page) + }, this) + }); + input.addEventListener("keyup", search); + } + + function search() { + if (input.value) { + var hits = results.idx.search(`${input.value}*`); + results.innerHTML = JSON.stringify(hits); + } else { + results.innerHTML = ''; + } + } + + function loadScript(src) { + return new Promise(function(resolve, reject) { + let script = document.createElement('script'); + script.src = src; + script.onload = () => resolve(script); + + document.head.append(script); + }); + } +}); -- cgit v1.2.3