chore: search cleanup

This commit is contained in:
Cory Dransfeldt 2024-10-19 15:42:51 -07:00
parent d518b752ea
commit cb1ddafaf6
No known key found for this signature in database
4 changed files with 266 additions and 248 deletions

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.5.5", "version": "1.5.6",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "coryd.dev", "name": "coryd.dev",
"version": "1.5.5", "version": "1.5.6",
"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.5", "version": "1.5.6",
"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,260 +1,269 @@
window.addEventListener('load', () => { window.addEventListener("load", () => {
// menu keyboard controls // menu keyboard controls
;(() => { (() => {
const menuInput = document.getElementById('menu-toggle') const menuInput = document.getElementById("menu-toggle");
const menuButtonContainer = document.querySelector('.menu-button-container') const menuButtonContainer = document.querySelector(
const menuItems = document.querySelectorAll('.menu-primary li') ".menu-button-container"
);
const menuItems = document.querySelectorAll(".menu-primary li");
menuButtonContainer.addEventListener('keydown', (e) => { menuButtonContainer.addEventListener("keydown", (e) => {
if (e.key === 'Enter' || e.key === ' ') { if (e.key === "Enter" || e.key === " ") {
e.preventDefault() e.preventDefault();
menuInput.checked = !menuInput.checked menuInput.checked = !menuInput.checked;
} }
}) });
menuItems.forEach((item) => { menuItems.forEach((item) => {
item.addEventListener('keydown', (e) => { item.addEventListener("keydown", (e) => {
if (e.key === 'Enter' || e.key === ' ') { if (e.key === "Enter" || e.key === " ") {
e.preventDefault() e.preventDefault();
item.querySelector('a').click() item.querySelector("a").click();
} }
}) });
}) });
document.addEventListener('keydown', (e) => { document.addEventListener("keydown", (e) => {
if (e.key === 'Escape' && menuInput.checked) menuInput.checked = false if (e.key === "Escape" && menuInput.checked) menuInput.checked = false;
}) });
})() })();
// modal keyboard controls and scroll management // modal keyboard controls and scroll management
;(() => { (() => {
const modalInputs = document.querySelectorAll('.modal-input') const modalInputs = document.querySelectorAll(".modal-input");
if (!modalInputs) return if (!modalInputs) return;
const toggleBodyScroll = (disableScroll) => { const toggleBodyScroll = (disableScroll) => {
if (disableScroll) { if (disableScroll) {
document.body.style.overflow = 'hidden' document.body.style.overflow = "hidden";
} else { } else {
document.body.style.overflow = '' document.body.style.overflow = "";
} }
} };
const checkModals = () => { const checkModals = () => {
let isAnyModalOpen = false let isAnyModalOpen = false;
modalInputs.forEach((modalInput) => { modalInputs.forEach((modalInput) => {
if (modalInput.checked) isAnyModalOpen = true if (modalInput.checked) isAnyModalOpen = true;
}) });
toggleBodyScroll(isAnyModalOpen) toggleBodyScroll(isAnyModalOpen);
} };
modalInputs.forEach((modalInput) => { modalInputs.forEach((modalInput) => {
modalInput.addEventListener('change', checkModals) modalInput.addEventListener("change", checkModals);
}) });
document.addEventListener('keydown', (e) => { document.addEventListener("keydown", (e) => {
if (e.key === 'Escape') { if (e.key === "Escape") {
modalInputs.forEach((modalInput) => { modalInputs.forEach((modalInput) => {
if (modalInput.checked) modalInput.checked = false if (modalInput.checked) modalInput.checked = false;
}) });
toggleBodyScroll(false) toggleBodyScroll(false);
} }
}) });
checkModals() checkModals();
})() })();
// text toggle for media pages // text toggle for media pages
;(() => { (() => {
const button = document.querySelector('[data-toggle-button]') const button = document.querySelector("[data-toggle-button]");
const content = document.querySelector('[data-toggle-content]') const content = document.querySelector("[data-toggle-content]");
const text = document.querySelectorAll('[data-toggle-content] p') 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 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) const interiorHeight = Array.from(text).reduce(
(acc, node) => acc + node.scrollHeight,
0
);
if (!button || !content || !text) return if (!button || !content || !text) return;
if (interiorHeight < minHeight) { if (interiorHeight < minHeight) {
content.classList.remove('text-toggle-hidden') content.classList.remove("text-toggle-hidden");
button.style.display = 'none' button.style.display = "none";
return return;
} }
button.addEventListener('click', () => { button.addEventListener("click", () => {
const isHidden = content.classList.toggle('text-toggle-hidden') const isHidden = content.classList.toggle("text-toggle-hidden");
button.textContent = isHidden ? 'Show more' : 'Show less' button.textContent = isHidden ? "Show more" : "Show less";
}) });
})() })();
// search logic // search logic
;(() => { (() => {
if (!MiniSearch || !document.querySelector('.search__form')) return if (!MiniSearch || !document.querySelector(".search__form--input")) return;
const miniSearch = new MiniSearch({ const miniSearch = new MiniSearch({
fields: ['title', 'description', 'tags', 'type'], fields: ["title", "description", "tags", "type"],
idField: 'id', });
storeFields: ['id', 'title', 'url', 'description', 'type', 'tags', 'total_plays'], const $form = document.querySelector(".search__form");
searchOptions: { const $input = document.querySelector(".search__form--input");
boost: { title: 2, tags: 1.5 }, const $fallback = document.querySelector(".search__form--fallback");
prefix: true, const $typeCheckboxes = document.querySelectorAll(
fuzzy: 0.3, '.search__form--type input[type="checkbox"]'
}, );
}) const $results = document.querySelector(".search__results");
const $loadMoreButton = document.querySelector(".search__load-more");
const $form = document.querySelector('.search__form') $form.removeAttribute("action");
const $input = document.querySelector('.search__form--input') $form.removeAttribute("method");
const $typeCheckboxes = document.querySelectorAll('.search__form--type input[type="checkbox"]') if ($fallback) $fallback.remove();
const $results = document.querySelector('.search__results')
const $loadMoreButton = document.querySelector('.search__load-more')
const PAGE_SIZE = 10 const PAGE_SIZE = 10;
let currentPage = 1 let currentPage = 1;
let currentResults = [] let currentResults = [];
let totalResults = 0 let total = 0;
let resultsById = {} let resultsById = {};
let debounceTimeout let debounceTimeout;
const parseMarkdown = (markdown = '') => const parseMarkdown = (markdown) => {
markdown if (!markdown) return "";
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') return markdown
.replace(/\*(.*?)\*/g, '<em>$1</em>') .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
.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 htmlDescription = parseMarkdown(markdown);
const tempDiv = document.createElement('div') const tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlDescription tempDiv.innerHTML = htmlDescription;
const plainText = tempDiv.textContent || tempDiv.innerText || '' const plainText = tempDiv.textContent || tempDiv.innerText || "";
return plainText.length > maxLength ? `${plainText.substring(0, maxLength)}...` : plainText return plainText.length > maxLength
} ? `${plainText.substring(0, maxLength)}...`
: plainText;
};
const formatArtistTitle = (title, totalPlays) => const formatArtistTitle = (title, totalPlays) =>
totalPlays > 0 ? `${title} <strong class="highlight-text">${totalPlays} plays</strong>` : title totalPlays > 0
? `${title} <strong class="highlight-text">${totalPlays} plays</strong>`
: title;
const updateLoadMoreButton = () => { const renderSearchResults = (results) => {
const moreResultsToShow = currentPage * PAGE_SIZE < totalResults if (results.length > 0) {
$loadMoreButton.style.display = moreResultsToShow ? 'block' : 'none' const resultHTML = results
} .map(({ title, url, description, type, total_plays }) => {
const truncatedDesc = truncateDescription(description);
const formattedTitle =
type === "artist" && total_plays !== undefined
? formatArtistTitle(title, total_plays)
: title;
const renderSearchResults = results => { return `
const resultHTML = results.map(({ title, url, description, type, total_plays }) => { <li class="search__results--result">
const truncatedDesc = truncateDescription(description) <a href="${url}">
const formattedTitle = type === 'artist' && total_plays !== undefined <h3>${formattedTitle}</h3>
? formatArtistTitle(title, total_plays) </a>
: title <p>${truncatedDesc}</p>
</li>
`;
})
.join("");
return ` $results.innerHTML = resultHTML;
<li class="search__results--result"> $results.style.display = "block";
<a href="${url}"> } else {
<h3>${formattedTitle}</h3> $results.innerHTML =
</a> '<li class="search__results--no-results">No results found.</li>';
<p>${truncatedDesc}</p> $results.style.display = "block";
</li> }
` };
}).join('')
$results.innerHTML = resultHTML || '<li class="search__results--no-results">No results found.</li>' const appendSearchResults = (results) => {
$results.style.display = 'block' 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;
const appendSearchResults = results => { return `
const resultHTML = results.map(({ title, url, description, type, total_plays }) => { <li class="search__results--result">
const truncatedDesc = truncateDescription(description) <a href="${url}"><h3>${formattedTitle}</h3></a>
const formattedTitle = type === 'artist' && total_plays !== undefined <p>${truncatedDesc}</p>
? formatArtistTitle(title, total_plays) </li>
: title `;
})
.join("");
$results.insertAdjacentHTML("beforeend", newResults);
};
return ` const loadSearchIndex = async (query = "", types = []) => {
<li class="search__results--result"> const typeQuery = types.join(",");
<a href="${url}"><h3>${formattedTitle}</h3></a>
<p>${truncatedDesc}</p>
</li>
`
}).join('')
$results.insertAdjacentHTML('beforeend', resultHTML)
}
const loadSearchIndex = async (query = '', types = [], page = 1) => {
const typeQuery = types.join(',')
try { try {
const response = await fetch(`http://localhost:8787/api/search?q=${query}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}`) const response = await fetch(
const index = await response.json() `https://coryd.dev/api/search?q=${query}&type=${typeQuery}&page=${currentPage}&pageSize=${PAGE_SIZE}`
);
const index = await response.json();
const results = index.results || [];
const results = index.results || [] total = index.total || results.length;
totalResults = index.total || 0
if (!Array.isArray(results)) throw new Error('Expected results to be an array')
resultsById = results.reduce((acc, item) => { resultsById = results.reduce((acc, item) => {
acc[item.id] = item acc[item.id] = item;
return acc return acc;
}, {}) }, {});
if (page === 1) { miniSearch.removeAll();
miniSearch.removeAll() miniSearch.addAll(results);
miniSearch.addAll(results)
}
return results currentResults = results;
return resultsById;
} catch (error) { } catch (error) {
console.error('Error fetching search data:', error) console.error("Error fetching search data:", error);
return [] return {};
} }
} };
const getSearchResults = query =>
miniSearch.search(query).map(({ id }) => resultsById[id])
.filter(result => getSelectedTypes().includes(result.type))
const getSelectedTypes = () => const getSelectedTypes = () =>
Array.from($typeCheckboxes) Array.from($typeCheckboxes)
.filter(checkbox => checkbox.checked) .filter((checkbox) => checkbox.checked)
.map(checkbox => checkbox.value) .map((checkbox) => checkbox.value);
const handleInputEvent = async () => { $input.addEventListener("input", () => {
const query = $input.value.trim() const query = $input.value.trim();
clearTimeout(debounceTimeout) clearTimeout(debounceTimeout);
if (!query) { if (!query) {
renderSearchResults([]) renderSearchResults([]);
$loadMoreButton.style.display = 'none' $loadMoreButton.style.display = "none";
return return;
} }
debounceTimeout = setTimeout(async () => { debounceTimeout = setTimeout(async () => {
const results = await loadSearchIndex(query, getSelectedTypes(), 1) await loadSearchIndex(query, getSelectedTypes());
currentResults = results currentPage = 1;
currentPage = 1
renderSearchResults(getResultsForPage(currentPage)) renderSearchResults(getResultsForPage(currentPage));
updateLoadMoreButton() $loadMoreButton.style.display = total > PAGE_SIZE ? "block" : "none";
}, 300) }, 300);
} });
const handleCheckboxChange = async () => { $typeCheckboxes.forEach((checkbox) => {
const results = await loadSearchIndex($input.value.trim(), getSelectedTypes(), 1) checkbox.addEventListener("change", async () => {
currentResults = results await loadSearchIndex($input.value.trim(), getSelectedTypes());
currentPage = 1 currentPage = 1;
renderSearchResults(getResultsForPage(currentPage)) renderSearchResults(getResultsForPage(currentPage));
updateLoadMoreButton() $loadMoreButton.style.display = total > PAGE_SIZE ? "block" : "none";
} });
});
const handleLoadMoreClick = async () => { $loadMoreButton.addEventListener("click", () => {
currentPage++ currentPage++;
const nextResults = await loadSearchIndex($input.value.trim(), getSelectedTypes(), currentPage) const nextResults = getResultsForPage(currentPage);
appendSearchResults(nextResults) appendSearchResults(nextResults);
updateLoadMoreButton() $loadMoreButton.style.display =
} currentPage * PAGE_SIZE < total ? "block" : "none";
});
const getResultsForPage = page => const getResultsForPage = (page) =>
currentResults.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE) currentResults.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
})();
$input.addEventListener('input', handleInputEvent) });
$typeCheckboxes.forEach(checkbox => checkbox.addEventListener('change', handleCheckboxChange))
$loadMoreButton.addEventListener('click', handleLoadMoreClick)
})()
})

View file

@ -1,47 +1,55 @@
import { createClient } from '@supabase/supabase-js' import { createClient } from "@supabase/supabase-js";
export default { export default {
async fetch(request, env) { async fetch(request, env) {
const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_KEY) const allowedOrigin = "https://coryd.dev";
const origin = request.headers.get("Origin") || "";
const referer = request.headers.get("Referer") || "";
const { searchParams } = new URL(request.url) if (!origin.startsWith(allowedOrigin) && !referer.startsWith(allowedOrigin))
const query = searchParams.get('q') || '' return new Response("Forbidden", { status: 403 });
const types = searchParams.get('type')?.split(',') || []
const page = parseInt(searchParams.get('page') || '1', 10) const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_KEY);
const pageSize = parseInt(searchParams.get('pageSize') || '10', 10) const { searchParams } = new URL(request.url);
const offset = (page - 1) * pageSize const query = searchParams.get("q") || "";
const types = searchParams.get("type")?.split(",") || [];
const page = parseInt(searchParams.get("page") || "1", 10);
const pageSize = parseInt(searchParams.get("pageSize") || "10", 10);
const offset = (page - 1) * pageSize;
try { try {
let supabaseQuery = supabase let supabaseQuery = supabase
.from('optimized_search_index') .from("optimized_search_index")
.select( .select(
'id, title, description, url, tags, type, total_plays, genre_name, genre_url', "id, title, description, url, tags, type, total_plays, genre_name, genre_url",
{ count: 'exact' } { count: "exact" }
) )
.range(offset, offset + pageSize - 1) .range(offset, offset + pageSize - 1);
if (types.length > 0) supabaseQuery = supabaseQuery.in('type', types) if (types.length > 0) supabaseQuery = supabaseQuery.in("type", types);
if (query) { if (query) {
const queryLower = `%${query.toLowerCase()}%` const queryLower = `%${query.toLowerCase()}%`;
supabaseQuery = supabaseQuery.or( supabaseQuery = supabaseQuery.or(
`title.ilike.${queryLower},description.ilike.${queryLower}` `title.ilike.${queryLower},description.ilike.${queryLower}`
) );
} }
const { data, error, count } = await supabaseQuery const { data, error, count } = await supabaseQuery;
if (error) { if (error) {
console.error('Supabase query error:', error) console.error("Supabase query error:", error);
return new Response(JSON.stringify({ error: 'Error fetching data' }), { status: 500 }) return new Response(JSON.stringify({ error: "Error fetching data" }), {
status: 500,
});
} }
if (!data || data.length === 0) { if (!data || data.length === 0) {
console.warn('No results found.') console.warn("No results found.");
return new Response( return new Response(
JSON.stringify({ results: [], total: 0, page, pageSize }), JSON.stringify({ results: [], total: 0, page, pageSize }),
{ headers: { 'Content-Type': 'application/json' } } { headers: { "Content-Type": "application/json" } }
) );
} }
return new Response( return new Response(
@ -53,14 +61,15 @@ export default {
}), }),
{ {
headers: { headers: {
'Content-Type': 'application/json', "Content-Type": "application/json",
'Access-Control-Allow-Origin': '*',
}, },
} }
) );
} catch (error) { } catch (error) {
console.error('Unexpected error:', error) console.error("Unexpected error:", error);
return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 }) return new Response(JSON.stringify({ error: "Internal Server Error" }), {
status: 500,
});
} }
}, },
} };