coryd.dev/src/pages/static/search.html

258 lines
8.5 KiB
HTML

---
title: Search
permalink: /search/index.html
description: Search through posts and other content on my site.
---
<h2 class="page-title">Search</h2>
<p>You can find <a href="/posts">posts</a>, <a href="/links">links</a>, <a href="/music/#artists">artists</a>, genres, <a href="/watching#movies">movies</a>, <a href="/watching#tv">shows</a> and <a href="/reading">books</a> via the field below (though it only surfaces movies and shows I've watched and books I've written something about). <a href="/tags">You can also browse my tags list</a>.</p>
{% render "static/blocks/top-tags.liquid"
label:"Top tags"
tags:topTags.tags
%}
<noscript>
<p><mark>If you're seeing this it means that you've (quite likely) disabled JavaScript (that's a totally valid choice!).</mark> You can search for anything on my site using the form below, but your query will be routed through <a href="https://duckduckgo.com">DuckDuckGo</a>.</p>
<p><mark>Type something in and hit enter.</mark></p>
</noscript>
<form class="search__form" action="https://duckduckgo.com" method="get">
<input
class="search__form--input"
placeholder="Search"
type="search"
name="q"
autocomplete="off"
autofocus
onkeydown="return event.key !== 'Enter'"
/>
<details>
<summary>Filter by type</summary>
<fieldset class="search__form--type">
<label>
<input class="article" type="checkbox" name="section" value="post" checked />
post
</label>
<label>
<input class="music" type="checkbox" name="section" value="artist" checked />
artist
</label>
<label>
<input class="music" type="checkbox" name="section" value="genre" checked />
genre
</label>
<label>
<input class="books" type="checkbox" name="section" value="book" checked />
book
</label>
<label>
<input class="movies" type="checkbox" name="section" value="movie" checked />
movie
</label>
<label>
<input class="tv" type="checkbox" name="section" value="show" checked />
show
</label>
</fieldset>
</details>
<input
class="search__form--fallback"
type="hidden"
name="sites"
value="coryd.dev"
/>
</form>
<div class="search__results client-side"></div>
<button class="search__load-more client-side" style="display: none">
Load More
</button>
<script src="/assets/scripts/components/minisearch.js"></script>
<script src="/assets/scripts/components/minisearch.js"></script>
<script>
window.addEventListener("load", () => {
(() => {
if (typeof MiniSearch === "undefined") return;
const SELECTORS = {
form: ".search__form",
fallback: ".search__form--fallback",
input: ".search__form--input",
results: ".search__results",
loadMore: ".search__load-more",
checkboxes: '.search__form--type input[type="checkbox"]',
};
const miniSearch = new MiniSearch({
fields: ["title", "description", "tags", "section"],
idField: "id",
storeFields: [
"id",
"title",
"url",
"description",
"section",
"tags",
"total_plays",
],
searchOptions: {
fields: ["title", "tags"],
prefix: true,
fuzzy: 0.3,
combineWith: "OR",
boost: { title: 5, tags: 2, description: 1 },
},
});
const $form = document.querySelector(SELECTORS.form);
const $fallback = document.querySelector(SELECTORS.fallback);
const $input = document.querySelector(SELECTORS.input);
const $results = document.querySelector(SELECTORS.results);
const $loadMoreButton = document.querySelector(SELECTORS.loadMore);
const $sectionCheckboxes = document.querySelectorAll(SELECTORS.checkboxes);
$form.removeAttribute("action");
$form.removeAttribute("method");
if ($fallback) $fallback.remove();
const PAGE_SIZE = 10;
let currentPage = 1;
let currentResults = [];
let total = 0;
let debounceTimeout;
let isLoading = false;
const resultIds = new Set();
const generateResultHTML = ({ title, url, description, type, tags, genre_name, genre_url, total_plays }) => `
<article class="search__results--result">
<h3 class="${type}">
<a href="${url}">${title}</a>
${type === "music" && total_plays > 0 ? ` <mark>${total_plays} plays</mark>` : ""}
</h3>
${type !== "music" && tags && tags.length
? `<div class="tags tags-small ${type}">
${tags.map(
(tag) =>
`<a href="/tags/${encodeURIComponent(tag.toLowerCase())}">#${tag.toLowerCase()}</a>`
).join(' ')}
</div>`
: ''}
${type === "music" && genre_name && genre_url
? `<div class="tags tags-small ${type}">
<a href="${genre_url}">${genre_name}</a>
</div>`
: ''}
<p>${description}</p>
</article>
`;
const setLoadMoreButton = (isLoading) => {
$loadMoreButton.disabled = isLoading;
$loadMoreButton.textContent = isLoading ? "Loading..." : "Load More";
};
const showLoadingMessage = () => {
$results.innerHTML = '<article class="search__results--loading">Searching...</article>';
$results.style.display = "block";
};
const renderSearchResults = (results) => {
$results.innerHTML = results.length
? results.map(generateResultHTML).join("")
: '<article class="search__results--no-results">No results found.</article>';
$results.style.display = "block";
};
const appendSearchResults = (results) => {
const newResultsHTML = results.map(generateResultHTML).join("");
$results.insertAdjacentHTML("beforeend", newResultsHTML);
};
const getSelectedSections = () => Array.from($sectionCheckboxes).filter((cb) => cb.checked).map((cb) => cb.value);
const loadSearchIndex = async (query, sections, page) => {
isLoading = true;
setLoadMoreButton(true);
try {
const sectionQuery = sections.join(",");
const response = await fetch(
`https://www.coryd.dev/api/search.php?q=${encodeURIComponent(
query,
)}&section=${sectionQuery}&page=${page}&pageSize=${PAGE_SIZE}`,
);
const data = await response.json();
total = data.total || 0;
const formattedResults = (data.results || []).map((item) => ({
...item,
id: item.result_id,
}));
miniSearch.removeAll();
miniSearch.addAll(formattedResults);
return formattedResults;
} catch (error) {
console.error("Error fetching search data:", error);
return [];
} finally {
isLoading = false;
setLoadMoreButton(false);
}
};
const updateSearchResults = (results) => {
if (currentPage === 1) {
renderSearchResults(results);
} else {
appendSearchResults(results);
}
$loadMoreButton.style.display = currentPage * PAGE_SIZE < total ? "block" : "none";
};
const handleSearch = async () => {
const query = $input.value.trim();
if (!query) {
renderSearchResults([]);
$loadMoreButton.style.display = "none";
return;
}
showLoadingMessage();
$loadMoreButton.style.display = "none";
const results = await loadSearchIndex(query, getSelectedSections(), 1);
currentPage = 1;
currentResults = results;
resultIds.clear();
results.forEach((r) => resultIds.add(r.id));
updateSearchResults(results);
};
$input.addEventListener("input", () => {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(handleSearch, 300);
});
$sectionCheckboxes.forEach((cb) => cb.addEventListener("change", handleSearch));
$loadMoreButton.addEventListener("click", async () => {
if (isLoading) return;
currentPage++;
const nextResults = await loadSearchIndex($input.value.trim(), getSelectedSections(), currentPage);
const filteredResults = nextResults.filter((item) => {
if (resultIds.has(item.id)) return false;
resultIds.add(item.id);
return true;
});
currentResults = [...currentResults, ...filteredResults];
updateSearchResults(filteredResults);
});
})();
});
</script>