Skip to content

Commit

Permalink
Integrate searcher.js into `book.js 💐
Browse files Browse the repository at this point in the history
  • Loading branch information
CoralPink committed Dec 18, 2023
1 parent 5b55318 commit cc9b245
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 164 deletions.
1 change: 1 addition & 0 deletions .github/workflows/gh-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ jobs:
rm book/elasticlunr.min.js
rm book/highlight.css
rm book/highlight.js
rm book/searcher.js
rm book/tomorrow-night.css
rm book/css/variables.css
rm book/mark.min.js
Expand Down
1 change: 1 addition & 0 deletions debug.sh
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ mdbook build --dest-dir commentary
#rm commentary/elasticlunr.min.js
#rm commentary/highlight.css
#rm commentary/highlight.js
#rm commentary/searcher.js
#rm commentary/tomorrow-night.css
#rm commentary/css/variables.css
#rm commentary/mark.min.js
Expand Down
156 changes: 138 additions & 18 deletions js/book.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,147 @@
import wasmInit, { attribute_external_links } from './wasm_book.js';

import { codeBlock } from './codeblock.js';
import './sidebar.js';
import wasmInit, { attribute_external_links, SearchResult } from './wasm_book.js';

import Finder from './finder.js';
import Mark from 'mark.js';
import TableOfContents from './table-of-contents.js';
import ThemeSelector from './theme-selector.js';

import './sidebar.js';
const ELEM_BAR = document.getElementById('searchbar');
const ELEM_WRAPPER = document.getElementById('search-wrapper');
const ELEM_RESULTS = document.getElementById('searchresults');
const ELEM_ICON = document.getElementById('search-toggle');

wasmInit()
.then(() => {
attribute_external_links();
})
.catch(e => {
console.error(`Error Attribute external links: ${e}`);
const ELEM_HEADER = document.getElementById('searchresults-header');
const ELEM_OUTER = document.getElementById('searchresults-outer');

const resultMarker = new Mark(ELEM_RESULTS);

let searchResult;
let finder;

// Eventhandler for keyevents while the searchbar is focused
const keyUpHandler = () => {
const term = ELEM_BAR.value.trim();

if (term === '') {
ELEM_OUTER.classList.add('hidden');
return;
}

const results = finder.search(term);

ELEM_RESULTS.innerHTML = '';
ELEM_HEADER.innerText = `${results.length} search results for : ${term}`;

for (const result of results) {
searchResult.append_search_result(result.ref, result.doc.body, result.doc.breadcrumbs, term);
}

resultMarker.mark(decodeURIComponent(term).split(' '), {
accuracy: 'complementary',
exclude: ['a'],
});

ELEM_OUTER.classList.remove('hidden');
};

const showSearch = () => {
ELEM_WRAPPER.classList.remove('hidden');
ELEM_ICON.setAttribute('aria-expanded', 'true');
ELEM_BAR.select();
};

const hiddenSearch = () => {
ELEM_WRAPPER.classList.add('hidden');
ELEM_ICON.setAttribute('aria-expanded', 'false');
};

// On reload or browser history backwards/forwards events, parse the url and do search or mark
const doSearchOrMarkFromUrl = () => {
const param = new URLSearchParams(globalThis.location.search).get('highlight');

if (!param) {
return;
}
const term = decodeURIComponent(param);
ELEM_BAR.value = term;

const marker = new Mark(document.getElementById('main'));
marker.mark(term.split(' '), {
accuracy: 'complementary',
});

document.addEventListener(
'DOMContentLoaded',
() => {
codeBlock();
for (const x of document.querySelectorAll('mark')) {
x.addEventListener('mousedown', marker.unmark, { once: true, passive: true });
}
};

const searchInit = async root => {
globalThis.search = globalThis.search || {};
globalThis.search.hasFocus = () => ELEM_BAR === document.activeElement;

try {
const [config, _] = await Promise.all([
fetch(`${root}searchindex.json`).then(response => response.json()),
wasmInit(),
]);

searchResult = new SearchResult(root, config.results_options.teaser_word_count, config.doc_urls);
finder = new Finder(config.index.documentStore.docs, config.results_options.limit_results);

attribute_external_links();
} catch (e) {
console.error(`Error during initialization: ${e}`);
console.log('The search function is disabled.');
ELEM_ICON.classList.add('hidden');
return;
}

ELEM_BAR.addEventListener('keyup', keyUpHandler, { once: false, passive: true });
ELEM_ICON.addEventListener(
'mouseup',
() => (ELEM_WRAPPER.classList.contains('hidden') ? showSearch() : hiddenSearch()),
{ once: false, passive: true },
);

document.addEventListener(
'keyup',
e => {
if (ELEM_WRAPPER.classList.contains('hidden')) {
switch (e.key) {
case '/':
case 's':
case 'S':
showSearch();
break;
}
return;
}

if (e.key === 'Escape') {
hiddenSearch();
}
},
{ once: false, passive: true },
);

// Suppress "submit" events so the page doesn't reload when the user presses Enter
document.addEventListener('submit', e => e.preventDefault(), { once: false, passive: false });
};

(() => {
document.addEventListener(
'DOMContentLoaded',
() => {
codeBlock();

new TableOfContents();
new ThemeSelector();

new TableOfContents();
new ThemeSelector();
},
{ once: true, passive: true },
);
doSearchOrMarkFromUrl();
searchInit(document.getElementById('bookjs').dataset.pathtoroot);
},
{ once: true, passive: true },
);
})();
2 changes: 1 addition & 1 deletion js/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ console.info(`[INFO]: 👩🏼‍🍳 I'm going to bake ${CLR_BC}bun${CLR_RESET}
const start = performance.now();

const result = await Bun.build({
entrypoints: ['./book.js', './hl-worker.js', './searcher.js', './serviceworker.js'],
entrypoints: ['./book.js', './hl-worker.js', './serviceworker.js'],
outdir: './dist',
minify: true,
});
Expand Down
138 changes: 0 additions & 138 deletions js/searcher.js

This file was deleted.

3 changes: 1 addition & 2 deletions js/serviceworker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
const CACHE_VERSION = 'v0.14.0';
const CACHE_VERSION = 'v0.15.0';
const CACHE_LIST = [
'/commentary/book.js',
'/commentary/hl-worker.js',
'/commentary/searcher.js',
'/commentary/wasm_book_bg.wasm',

'/commentary/css/style.css',
Expand Down
7 changes: 2 additions & 5 deletions theme/index.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,7 @@
<link rel="stylesheet" href="{{ path_to_root }}fonts/fonts.css" async>
{{#each additional_css}}<link rel="stylesheet" href="{{ ../path_to_root }}{{ this }}" async>{{/each}}

<script defer type="module" src="{{ path_to_root }}book.js"></script>
{{#if search_js}}
<script defer type="module" src="{{ path_to_root }}searcher.js" id="searcher" data-pathtoroot="{{ path_to_root }}"></script>
{{/if}}
{{#each additional_js}}<script async src="{{ ../path_to_root }}{{this}}"></script>{{/each}}
<script defer type="module" src="{{ path_to_root }}book.js" id = "bookjs" data-pathtoroot="{{ path_to_root }}"></script>
{{#each additional_js}}<script defer src="{{ ../path_to_root }}{{this}}"></script>{{/each}}
</body>
</html>

0 comments on commit cc9b245

Please sign in to comment.