chore: search cleanup

This commit is contained in:
Cory Dransfeldt 2024-10-19 21:28:08 -07:00
parent fca18da3f7
commit 2f9534562a
No known key found for this signature in database
3 changed files with 77 additions and 200 deletions

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.5.17", "version": "1.5.18",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.5.17", "version": "1.5.18",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@cdransf/api-text": "^1.5.0", "@cdransf/api-text": "^1.5.0",

View file

@ -1,6 +1,6 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.5.17", "version": "1.5.18",
"description": "The source for my personal site. Built using 11ty (and other tools).", "description": "The source for my personal site. Built using 11ty (and other tools).",
"type": "module", "type": "module",
"engines": { "engines": {

View file

@ -1,96 +1,4 @@
window.addEventListener("load", () => { window.addEventListener("load", () => {
// menu keyboard controls
(() => {
const menuInput = document.getElementById("menu-toggle");
const menuButtonContainer = document.querySelector(
".menu-button-container"
);
const menuItems = document.querySelectorAll(".menu-primary li");
menuButtonContainer.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
menuInput.checked = !menuInput.checked;
}
});
menuItems.forEach((item) => {
item.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
item.querySelector("a").click();
}
});
});
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && menuInput.checked) menuInput.checked = false;
});
})();
// modal keyboard controls and scroll management
(() => {
const modalInputs = document.querySelectorAll(".modal-input");
if (!modalInputs) return;
const toggleBodyScroll = (disableScroll) => {
if (disableScroll) {
document.body.style.overflow = "hidden";
} else {
document.body.style.overflow = "";
}
};
const checkModals = () => {
let isAnyModalOpen = false;
modalInputs.forEach((modalInput) => {
if (modalInput.checked) isAnyModalOpen = true;
});
toggleBodyScroll(isAnyModalOpen);
};
modalInputs.forEach((modalInput) => {
modalInput.addEventListener("change", checkModals);
});
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
modalInputs.forEach((modalInput) => {
if (modalInput.checked) modalInput.checked = false;
});
toggleBodyScroll(false);
}
});
checkModals();
})();
// text toggle for media pages
(() => {
const button = document.querySelector("[data-toggle-button]");
const content = document.querySelector("[data-toggle-content]");
const text = document.querySelectorAll("[data-toggle-content] p");
const minHeight = 500; // this needs to match the height set on [data-toggle-content].text-toggle-hidden in text-toggle.css
const interiorHeight = Array.from(text).reduce(
(acc, node) => acc + node.scrollHeight,
0
);
if (!button || !content || !text) return;
if (interiorHeight < minHeight) {
content.classList.remove("text-toggle-hidden");
button.style.display = "none";
return;
}
button.addEventListener("click", () => {
const isHidden = content.classList.toggle("text-toggle-hidden");
button.textContent = isHidden ? "Show more" : "Show less";
});
})();
// search logic
(() => { (() => {
if (typeof MiniSearch === "undefined") return; if (typeof MiniSearch === "undefined") return;
@ -113,14 +21,14 @@ window.addEventListener("load", () => {
boost: { title: 5, tags: 2, description: 1 }, boost: { title: 5, tags: 2, description: 1 },
}, },
}); });
const $form = document.querySelector(".search__form"); const $form = document.querySelector(".search__form");
const $input = document.querySelector(".search__form--input"); const $input = document.querySelector(".search__form--input");
const $fallback = document.querySelector(".search__form--fallback"); const $results = document.querySelector(".search__results");
const $loadMoreButton = document.querySelector(".search__load-more");
const $typeCheckboxes = document.querySelectorAll( const $typeCheckboxes = document.querySelectorAll(
'.search__form--type input[type="checkbox"]' '.search__form--type input[type="checkbox"]'
); );
const $results = document.querySelector(".search__results");
const $loadMoreButton = document.querySelector(".search__load-more");
$form.removeAttribute("action"); $form.removeAttribute("action");
$form.removeAttribute("method"); $form.removeAttribute("method");
@ -130,24 +38,21 @@ window.addEventListener("load", () => {
let currentPage = 1; let currentPage = 1;
let currentResults = []; let currentResults = [];
let total = 0; let total = 0;
let resultsById = {};
let debounceTimeout;
const parseMarkdown = (markdown) => { const parseMarkdown = (markdown) =>
if (!markdown) return ""; markdown
return markdown ? markdown
.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>") .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
.replace(/\*(.*?)\*/g, "<em>$1</em>") .replace(/\*(.*?)\*/g, "<em>$1</em>")
.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>') .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
.replace(/\n/g, "<br>") .replace(/\n/g, "<br>")
.replace(/[#*_~`]/g, ""); .replace(/[#*_~`]/g, "")
}; : "";
const truncateDescription = (markdown, maxLength = 150) => { const truncateDescription = (markdown, maxLength = 150) => {
const htmlDescription = parseMarkdown(markdown); const plainText =
const tempDiv = document.createElement("div"); new DOMParser().parseFromString(parseMarkdown(markdown), "text/html")
tempDiv.innerHTML = htmlDescription; .body.textContent || "";
const plainText = tempDiv.textContent || tempDiv.innerText || "";
return plainText.length > maxLength return plainText.length > maxLength
? `${plainText.substring(0, maxLength)}...` ? `${plainText.substring(0, maxLength)}...`
: plainText; : plainText;
@ -159,80 +64,44 @@ window.addEventListener("load", () => {
: title; : title;
const renderSearchResults = (results) => { const renderSearchResults = (results) => {
if (results.length > 0) {
const resultHTML = results const resultHTML = results
.map(({ title, url, description, type, total_plays }) => { .map(
const truncatedDesc = truncateDescription(description); ({ title, url, description, type, total_plays }) => `
const formattedTitle =
type === "artist" && total_plays !== undefined
? formatArtistTitle(title, total_plays)
: title;
return `
<li class="search__results--result"> <li class="search__results--result">
<a href="${url}"> <a href="${url}">
<h3>${formattedTitle}</h3> <h3>${
type === "artist" && total_plays
? formatArtistTitle(title, total_plays)
: title
}</h3>
</a> </a>
<p>${truncatedDesc}</p> <p>${truncateDescription(description)}</p>
</li> </li>
`; `
}) )
.join(""); .join("");
$results.innerHTML = resultHTML;
$results.style.display = "block";
} else {
$results.innerHTML = $results.innerHTML =
resultHTML ||
'<li class="search__results--no-results">No results found.</li>'; '<li class="search__results--no-results">No results found.</li>';
$results.style.display = "block"; $results.style.display = "block";
}
}; };
const appendSearchResults = (results) => { const loadSearchIndex = async (query, types, page) => {
const newResults = results
.map(({ title, url, description, type, total_plays }) => {
const truncatedDesc = truncateDescription(description);
const formattedTitle =
type === "artist" && total_plays !== undefined
? formatArtistTitle(title, total_plays)
: title;
return `
<li class="search__results--result">
<a href="${url}"><h3>${formattedTitle}</h3></a>
<p>${truncatedDesc}</p>
</li>
`;
})
.join("");
$results.insertAdjacentHTML("beforeend", newResults);
};
const loadSearchIndex = async (query = "", types = [], page = 1) => {
const typeQuery = types.join(",");
try { try {
const typeQuery = types.join(",");
const response = await fetch( const response = await fetch(
`https://coryd.dev/api/search?q=${query}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}` `https://coryd.dev/api/search?q=${query}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}`
); );
const index = await response.json(); const { results, total: newTotal } = await response.json();
const results = index.results || []; total = newTotal;
total = index.total || results.length;
const formattedResults = results.map((item) => ({ const formattedResults = results.map((item) => ({
...item, ...item,
id: item.result_id, id: item.result_id,
})); }));
resultsById = formattedResults.reduce((acc, item) => {
acc[item.id] = item;
return acc;
}, {});
miniSearch.removeAll(); miniSearch.removeAll();
miniSearch.addAll(formattedResults); miniSearch.addAll(formattedResults);
return formattedResults; return formattedResults;
} catch (error) { } catch (error) {
console.error("Error fetching search data:", error); console.error("Error fetching search data:", error);
@ -242,8 +111,8 @@ window.addEventListener("load", () => {
const getSelectedTypes = () => const getSelectedTypes = () =>
Array.from($typeCheckboxes) Array.from($typeCheckboxes)
.filter((checkbox) => checkbox.checked) .filter((cb) => cb.checked)
.map((checkbox) => checkbox.value); .map((cb) => cb.value);
const updateSearchResults = (results) => { const updateSearchResults = (results) => {
if (currentPage === 1) { if (currentPage === 1) {
@ -251,43 +120,52 @@ window.addEventListener("load", () => {
} else { } else {
appendSearchResults(results); appendSearchResults(results);
} }
$loadMoreButton.style.display =
const moreResultsToShow = currentPage * PAGE_SIZE < total; currentPage * PAGE_SIZE < total ? "block" : "none";
$loadMoreButton.style.display = moreResultsToShow ? "block" : "none";
}; };
$input.addEventListener("input", () => { const appendSearchResults = (results) => {
const query = $input.value.trim(); const newResultsHTML = results
clearTimeout(debounceTimeout); .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) { if (!query) {
renderSearchResults([]); renderSearchResults([]);
$loadMoreButton.style.display = "none"; $loadMoreButton.style.display = "none";
return; return;
} }
debounceTimeout = setTimeout(async () => {
const results = await loadSearchIndex(query, getSelectedTypes(), 1); const results = await loadSearchIndex(query, getSelectedTypes(), 1);
currentResults = results; currentResults = results;
currentPage = 1; currentPage = 1;
updateSearchResults(results);
};
updateSearchResults(currentResults); $input.addEventListener("input", () => {
}, 300); clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(handleSearch, 300);
}); });
$typeCheckboxes.forEach((checkbox) => { $typeCheckboxes.forEach((cb) =>
checkbox.addEventListener("change", async () => { cb.addEventListener("change", handleSearch)
const results = await loadSearchIndex(
$input.value.trim(),
getSelectedTypes(),
1
); );
currentResults = results;
currentPage = 1;
updateSearchResults(currentResults);
});
});
$loadMoreButton.addEventListener("click", async () => { $loadMoreButton.addEventListener("click", async () => {
currentPage++; currentPage++;
@ -297,7 +175,6 @@ window.addEventListener("load", () => {
currentPage currentPage
); );
currentResults = [...currentResults, ...nextResults]; currentResults = [...currentResults, ...nextResults];
updateSearchResults(nextResults); updateSearchResults(nextResults);
}); });
})(); })();