Hugo-theme-stack/assets/ts/search.tsx

250 lines
6.9 KiB
TypeScript
Raw Normal View History

2020-09-26 05:40:33 -04:00
interface pageData {
title: string,
date: string,
permalink: string,
content: string,
image?: string,
preview: string,
matchCount: number
}
2020-09-26 16:50:23 -04:00
/**
* Escape HTML tags as HTML entities
* Edited from:
* @link https://stackoverflow.com/a/5499821
*/
const tagsToReplace = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
2020-10-04 09:53:27 -04:00
'"': '&quot;',
'…': '&hellip;'
2020-09-26 16:50:23 -04:00
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function replaceHTMLEnt(str) {
return str.replace(/[&<>"]/g, replaceTag);
}
2020-11-06 05:33:51 -05:00
function escapeRegExp(string) {
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
2020-09-26 05:40:33 -04:00
}
2020-11-06 05:33:51 -05:00
class Search {
private data: pageData[];
private form: HTMLFormElement;
private input: HTMLInputElement;
private list: HTMLDivElement;
private resultTitle: HTMLHeadElement;
constructor({ form, input, list, resultTitle }) {
this.form = form;
this.input = input;
this.list = list;
this.resultTitle = resultTitle;
this.handleQueryString();
this.bindQueryStringChange();
this.bindSearchForm();
2020-09-26 05:40:33 -04:00
}
2020-11-06 05:33:51 -05:00
private async searchKeywords(keywords: string[]) {
const rawData = await this.getData();
let results: pageData[] = [];
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
/// Sort keywords by their length
keywords.sort((a, b) => {
return b.length - a.length
});
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
for (const item of rawData) {
let result = {
...item,
preview: '',
matchCount: 0
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
let matched = false;
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
for (const keyword of keywords) {
if (keyword === '') continue;
2020-10-04 09:53:27 -04:00
2020-11-06 05:33:51 -05:00
const regex = new RegExp(escapeRegExp(replaceHTMLEnt(keyword)), 'gi');
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
const contentMatch = regex.exec(result.content);
regex.lastIndex = 0; /// Reset regex
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
const titleMatch = regex.exec(result.title);
regex.lastIndex = 0; /// Reset regex
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
if (titleMatch) {
result.title = result.title.replace(regex, Search.marker);
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
if (titleMatch || contentMatch) {
matched = true;
++result.matchCount;
2020-10-04 09:53:27 -04:00
2020-11-06 05:33:51 -05:00
let start = 0,
end = 100;
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
if (contentMatch) {
start = contentMatch.index - 20;
end = contentMatch.index + 80
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
if (start < 0) start = 0;
}
if (result.preview.indexOf(keyword) !== -1) {
result.preview = result.preview.replace(regex, Search.marker);
}
else {
if (start !== 0) result.preview += `[...] `;
result.preview += `${result.content.slice(start, end).replace(regex, Search.marker)} `;
}
}
}
if (matched) {
result.preview += '[...]';
results.push(result);
}
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
/** Result with more matches appears first */
return results.sort((a, b) => {
return b.matchCount - a.matchCount;
});
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
public static marker(match) {
return '<mark>' + match + '</mark>';
2020-09-26 05:40:33 -04:00
}
2020-11-06 05:33:51 -05:00
private async doSearch(keywords: string[]) {
const startTime = performance.now();
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
const results = await this.searchKeywords(keywords);
this.clear();
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
for (const item of results) {
this.list.append(Search.render(item));
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
const endTime = performance.now();
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
this.resultTitle.innerText = `${results.length} pages (${((endTime - startTime) / 1000).toPrecision(1)} seconds)`;
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
public async getData() {
if (!this.data) {
/// Not fetched yet
const jsonURL = this.form.dataset.json;
this.data = await fetch(jsonURL).then(res => res.json());
2020-09-26 05:40:33 -04:00
}
2020-11-06 05:33:51 -05:00
return this.data;
}
2020-09-26 16:50:23 -04:00
2020-11-06 05:33:51 -05:00
private bindSearchForm() {
let lastSearch = '';
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
const eventHandler = (e) => {
e.preventDefault();
const keywords = this.input.value;
2020-09-26 16:50:23 -04:00
2020-11-06 05:33:51 -05:00
Search.updateQueryString(keywords, true);
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
if (keywords === '') {
return this.clear();
2020-09-26 05:40:33 -04:00
}
2020-11-06 05:33:51 -05:00
if (lastSearch === keywords) return;
lastSearch = keywords;
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
this.doSearch(keywords.split(' '));
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
this.input.addEventListener('input', eventHandler);
this.input.addEventListener('compositionend', eventHandler);
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
private clear() {
this.list.innerHTML = '';
this.resultTitle.innerText = '';
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
private bindQueryStringChange() {
window.addEventListener('popstate', (e) => {
this.handleQueryString()
})
}
private handleQueryString() {
const pageURL = new URL(window.location.toString());
const keywords = pageURL.searchParams.get('keyword');
this.input.value = keywords;
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
if (keywords) {
this.doSearch(keywords.split(' '));
}
else {
this.clear()
2020-09-26 05:40:33 -04:00
}
}
2020-11-06 05:33:51 -05:00
private static updateQueryString(keywords: string, replaceState = false) {
const pageURL = new URL(window.location.toString());
if (keywords === '') {
pageURL.searchParams.delete('keyword')
}
else {
pageURL.searchParams.set('keyword', keywords);
}
2020-09-26 05:40:33 -04:00
2020-11-06 05:33:51 -05:00
if (replaceState) {
window.history.replaceState('', '', pageURL.toString());
}
else {
window.history.pushState('', '', pageURL.toString());
}
}
public static render(item: pageData) {
return <article>
<a href={item.permalink}>
<div class="article-details">
<h2 class="article-title" dangerouslySetInnerHTML={{ __html: item.title }}></h2>
<secion class="article-preview" dangerouslySetInnerHTML={{ __html: item.preview }}></secion>
2020-09-26 05:40:33 -04:00
</div>
2020-11-06 05:33:51 -05:00
{item.image &&
<div class="article-image">
<img src={item.image} loading="lazy" />
</div>
}
</a>
</article>;
}
2020-09-26 05:40:33 -04:00
}
2020-11-06 05:33:51 -05:00
window.addEventListener('load', () => {
setTimeout(function () {
const searchForm = document.querySelector('.search-form') as HTMLFormElement,
searchInput = searchForm.querySelector('input') as HTMLInputElement,
searchResultList = document.querySelector('.search-result--list') as HTMLDivElement,
searchResultTitle = document.querySelector('.search-result--title') as HTMLHeadingElement;
new Search({
form: searchForm,
input: searchInput,
list: searchResultList,
resultTitle: searchResultTitle
});
}, 0);
})
export default Search;