hugo-theme-stack-stars/assets/ts/search.tsx

226 lines
5.7 KiB
TypeScript
Raw Normal View History

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