chore: modularize search; deduplicate helpers

This commit is contained in:
Cory Dransfeldt 2024-11-28 13:26:55 -08:00
parent d2ad1147b3
commit 643aa242ff
No known key found for this signature in database
7 changed files with 224 additions and 254 deletions

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.4.0", "version": "1.5.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.4.0", "version": "1.5.0",
"dependencies": { "dependencies": {
"@astrojs/check": "0.9.4", "@astrojs/check": "0.9.4",
"@astrojs/cloudflare": "^11.2.0", "@astrojs/cloudflare": "^11.2.0",

View file

@ -1,7 +1,7 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"type": "module", "type": "module",
"version": "1.4.0", "version": "1.5.0",
"scripts": { "scripts": {
"dev": "astro dev", "dev": "astro dev",
"start": "astro dev", "start": "astro dev",

View file

@ -0,0 +1,29 @@
<form class="search__form" action="https://duckduckgo.com" method="get">
<input
class="search__form--input"
placeholder="Search"
type="search"
name="q"
autocomplete="off"
autofocus
/>
<details>
<summary class="highlight-text">Filter by type</summary>
<fieldset class="search__form--type">
{["post", "link", "artist", "genre", "book", "movie", "show"].map(type => (
<label>
<input type="checkbox" name="type" value={type} checked />
{type.charAt(0).toUpperCase() + type.slice(1)}
</label>
))}
</fieldset>
</details>
<input
class="search__form--fallback"
type="hidden"
name="sites"
value="coryd.dev"
/>
</form>
<ul class="search__results client-side"></ul>
<button class="search__load-more client-side" style="display:none">Load More</button>

View file

@ -0,0 +1,21 @@
<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="/books">books</a> via the field below (though it only surfaces
movies and shows I've watched and books I've written something about).
</p>
<noscript>
<p>
<strong class="highlight-text"
>If you're seeing this it means that you've (quite likely) disabled
JavaScript (that's a totally valid choice!).</strong
> 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>
<strong class="highlight-text">Type something in and hit enter.</strong>
</p>
</noscript>

View file

@ -0,0 +1,164 @@
<script>
import MiniSearch from "minisearch";
import { sanitizeContent, htmlTruncate, md } from "@utils/helpers/general.js";
window.addEventListener("load", () => {
(() => {
const miniSearch = new MiniSearch({
fields: ["title", "description", "tags", "type"],
idField: "id",
storeFields: [
"id",
"title",
"url",
"description",
"type",
"tags",
"total_plays",
],
searchOptions: {
fields: ["title", "tags"],
prefix: true,
fuzzy: 0.1,
boost: { title: 5, tags: 2, description: 1 },
},
});
const $form = document.querySelector(".search__form");
const $fallback = document.querySelector(".search__form--fallback");
const $input = document.querySelector(".search__form--input");
const $results = document.querySelector(".search__results");
const $loadMoreButton = document.querySelector(".search__load-more");
const $typeCheckboxes = document.querySelectorAll(
'.search__form--type input[type="checkbox"]'
);
$form.removeAttribute("action");
$form.removeAttribute("method");
if ($fallback) $fallback.remove();
const PAGE_SIZE = 10;
let currentPage = 1;
let currentResults = [];
let total = 0;
let debounceTimeout;
const renderSearchResults = (results) => {
const resultHTML = results
.map(
({ title, url, description, type, total_plays }) => `
<li class="search__results--result">
<h3>
<a href="${url}">${title}</a>
${
type === "artist" && total_plays > 0
? ` <strong class="highlight-text">${total_plays} plays</strong>`
: ""
}
</h3>
<p>${htmlTruncate(sanitizeContent(md(description)))}</p>
</li>
`
)
.join("");
$results.innerHTML =
resultHTML ||
'<li class="search__results--no-results">No results found.</li>';
$results.style.display = "block";
};
const loadSearchIndex = async (query, types, page) => {
try {
const typeQuery = types.join(",");
const response = await fetch(
`https://coryd.dev/api/search?q=${query}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}`
);
const { results, total: newTotal } = await response.json();
total = newTotal;
const formattedResults = 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 [];
}
};
const getSelectedTypes = () =>
Array.from($typeCheckboxes)
.filter((cb) => cb.checked)
.map((cb) => cb.value);
const updateSearchResults = (results) => {
if (currentPage === 1) {
renderSearchResults(results);
} else {
appendSearchResults(results);
}
$loadMoreButton.style.display =
currentPage * PAGE_SIZE < total ? "block" : "none";
};
const appendSearchResults = (results) => {
const newResultsHTML = results
.map(
({ title, url, description, type, total_plays }) => `
<li class="search__results--result">
<h3>
<a href="${url}">${title}</a>
${
type === "artist" && total_plays > 0
? ` <strong class="highlight-text">${total_plays} plays</strong>`
: ""
}
</h3>
<p>${htmlTruncate(sanitizeContent(md(description)))}</p>
</li>
`
)
.join("");
$results.insertAdjacentHTML("beforeend", newResultsHTML);
};
const handleSearch = async () => {
const query = $input.value.trim();
if (!query) {
renderSearchResults([]);
$loadMoreButton.style.display = "none";
return;
}
const results = await loadSearchIndex(query, getSelectedTypes(), 1);
currentResults = results;
currentPage = 1;
updateSearchResults(results);
};
$input.addEventListener("input", () => {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(handleSearch, 200);
});
$typeCheckboxes.forEach((cb) =>
cb.addEventListener("change", handleSearch)
);
$loadMoreButton.addEventListener("click", async () => {
currentPage++;
const nextResults = await loadSearchIndex(
$input.value.trim(),
getSelectedTypes(),
currentPage
);
currentResults = [...currentResults, ...nextResults];
updateSearchResults(nextResults);
});
})();
});
</script>

View file

@ -109,7 +109,7 @@ const pageDescription = md(description);
<noscript> <noscript>
<style> <style>
.client-side { .client-side {
display: none; display: none !important;
} }
</style> </style>
</noscript> </noscript>

View file

@ -1,5 +1,8 @@
--- ---
import Layout from "@layouts/Layout.astro"; import Layout from "@layouts/Layout.astro";
import SearchIntro from "@components/search/SearchIntro.astro"
import SearchForm from "@components/search/SearchForm.astro"
import SearchLogic from "@components/search/SearchLogic.astro"
import AddonLinks from "@components/blocks/links/AddonLinks.astro"; import AddonLinks from "@components/blocks/links/AddonLinks.astro";
import { getPopularPosts } from "@utils/getPopularPosts.js"; import { getPopularPosts } from "@utils/getPopularPosts.js";
import { fetchAllPosts } from "@data/posts.js"; import { fetchAllPosts } from "@data/posts.js";
@ -24,255 +27,8 @@ const description =
description={description} description={description}
currentUrl={Astro.url.pathname} currentUrl={Astro.url.pathname}
> >
<h2 class="page-title">Search</h2> <SearchIntro />
<p> <SearchForm />
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="/books">books</a> via the field below (though it only surfaces
movies and shows I've watched and books I've written something about).
</p>
<noscript>
<p>
<strong class="highlight-text"
>If you're seeing this it means that you've (quite likely) disabled
JavaScript (that's a totally valid choice!).</strong
> 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>
<strong class="highlight-text">Type something in and hit enter.</strong>
</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
/>
<details>
<summary class="highlight-text">Filter by type</summary>
<fieldset class="search__form--type">
<label
><input type="checkbox" name="type" value="post" checked /> Posts</label
>
<label
><input type="checkbox" name="type" value="link" checked /> Links</label
>
<label
><input type="checkbox" name="type" value="artist" checked /> Artists</label
>
<label
><input type="checkbox" name="type" value="genre" checked /> Genres</label
>
<label
><input type="checkbox" name="type" value="book" checked /> Books</label
>
<label
><input type="checkbox" name="type" value="movie" checked /> Movies</label
>
<label
><input type="checkbox" name="type" value="show" checked /> Shows</label
>
</fieldset>
</details>
<input
class="search__form--fallback"
type="hidden"
name="sites"
value="coryd.dev"
/>
</form>
<ul class="search__results"></ul>
<button class="search__load-more" style="display:none">Load More</button>
<AddonLinks popularPosts={popularPosts} links={links} /> <AddonLinks popularPosts={popularPosts} links={links} />
</Layout> </Layout>
<script> <SearchLogic />
import MiniSearch from "minisearch";
window.addEventListener("load", () => {
(() => {
const miniSearch = new MiniSearch({
fields: ["title", "description", "tags", "type"],
idField: "id",
storeFields: [
"id",
"title",
"url",
"description",
"type",
"tags",
"total_plays",
],
searchOptions: {
fields: ["title", "tags"],
prefix: true,
fuzzy: 0.1,
boost: { title: 5, tags: 2, description: 1 },
},
});
const $form = document.querySelector(".search__form");
const $fallback = document.querySelector(".search__form--fallback");
const $input = document.querySelector(".search__form--input");
const $results = document.querySelector(".search__results");
const $loadMoreButton = document.querySelector(".search__load-more");
const $typeCheckboxes = document.querySelectorAll(
'.search__form--type input[type="checkbox"]'
);
$form.removeAttribute("action");
$form.removeAttribute("method");
if ($fallback) $fallback.remove();
const PAGE_SIZE = 10;
let currentPage = 1;
let currentResults = [];
let total = 0;
let debounceTimeout;
const parseMarkdown = (markdown) =>
markdown
? markdown
.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
.replace(/\*(.*?)\*/g, "<em>$1</em>")
.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
.replace(/\n/g, "<br>")
.replace(/[#*_~`]/g, "")
: "";
const truncateDescription = (markdown, maxLength = 150) => {
const plainText =
new DOMParser().parseFromString(parseMarkdown(markdown), "text/html")
.body.textContent || "";
return plainText.length > maxLength
? `${plainText.substring(0, maxLength)}...`
: plainText;
};
const formatArtistTitle = (title, totalPlays) =>
totalPlays > 0
? `${title} <strong class="highlight-text">${totalPlays} plays</strong>`
: title;
const renderSearchResults = (results) => {
const resultHTML = results
.map(
({ title, url, description, type, total_plays }) => `
<li class="search__results--result">
<a href="${url}">
<h3>${
type === "artist" && total_plays
? formatArtistTitle(title, total_plays)
: title
}</h3>
</a>
<p>${truncateDescription(description)}</p>
</li>
`
)
.join("");
$results.innerHTML =
resultHTML ||
'<li class="search__results--no-results">No results found.</li>';
$results.style.display = "block";
};
const loadSearchIndex = async (query, types, page) => {
try {
const typeQuery = types.join(",");
const response = await fetch(
`https://coryd.dev/api/search?q=${query}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}`
);
const { results, total: newTotal } = await response.json();
total = newTotal;
const formattedResults = 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 [];
}
};
const getSelectedTypes = () =>
Array.from($typeCheckboxes)
.filter((cb) => cb.checked)
.map((cb) => cb.value);
const updateSearchResults = (results) => {
if (currentPage === 1) {
renderSearchResults(results);
} else {
appendSearchResults(results);
}
$loadMoreButton.style.display =
currentPage * PAGE_SIZE < total ? "block" : "none";
};
const appendSearchResults = (results) => {
const newResultsHTML = results
.map(
({ title, url, description, type, total_plays }) => `
<li class="search__results--result">
<a href="${url}">
<h3>${
type === "artist" && total_plays
? formatArtistTitle(title, total_plays)
: title
}</h3>
</a>
<p>${truncateDescription(description)}</p>
</li>
`
)
.join("");
$results.insertAdjacentHTML("beforeend", newResultsHTML);
};
const handleSearch = async () => {
const query = $input.value.trim();
if (!query) {
renderSearchResults([]);
$loadMoreButton.style.display = "none";
return;
}
const results = await loadSearchIndex(query, getSelectedTypes(), 1);
currentResults = results;
currentPage = 1;
updateSearchResults(results);
};
$input.addEventListener("input", () => {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(handleSearch, 300);
});
$typeCheckboxes.forEach((cb) =>
cb.addEventListener("change", handleSearch)
);
$loadMoreButton.addEventListener("click", async () => {
currentPage++;
const nextResults = await loadSearchIndex(
$input.value.trim(),
getSelectedTypes(),
currentPage
);
currentResults = [...currentResults, ...nextResults];
updateSearchResults(nextResults);
});
})();
});
</script>