feat(search): design consistency with other feed/content aggregation lists

This commit is contained in:
Cory Dransfeldt 2025-06-10 10:31:50 -07:00
parent f2bca309f5
commit 3b36c4bfca
No known key found for this signature in database
8 changed files with 84 additions and 74 deletions

View file

@ -18,13 +18,13 @@ class SearchHandler extends BaseHandler
{ {
try { try {
$query = $this->validateAndSanitizeQuery($_GET["q"] ?? null); $query = $this->validateAndSanitizeQuery($_GET["q"] ?? null);
$types = $this->validateAndSanitizeTypes($_GET["type"] ?? ""); $sections = $this->validateAndSanitizeSections($_GET["section"] ?? "");
$page = isset($_GET["page"]) ? intval($_GET["page"]) : 1; $page = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
$pageSize = isset($_GET["pageSize"]) ? intval($_GET["pageSize"]) : 10; $pageSize = isset($_GET["pageSize"]) ? intval($_GET["pageSize"]) : 10;
$offset = ($page - 1) * $pageSize; $offset = ($page - 1) * $pageSize;
$cacheKey = $this->generateCacheKey($query, $types, $page, $pageSize); $cacheKey = $this->generateCacheKey($query, $sections, $page, $pageSize);
$results = []; $results = [];
$results = $this->getCachedResults($cacheKey) ?? $this->fetchSearchResults($query, $types, $pageSize, $offset); $results = $this->getCachedResults($cacheKey) ?? $this->fetchSearchResults($query, $sections, $pageSize, $offset);
if (empty($results) || empty($results["data"])) { if (empty($results) || empty($results["data"])) {
$this->sendResponse(["results" => [], "total" => 0, "page" => $page, "pageSize" => $pageSize], 200); $this->sendResponse(["results" => [], "total" => 0, "page" => $page, "pageSize" => $pageSize], 200);
@ -61,38 +61,38 @@ class SearchHandler extends BaseHandler
return $query; return $query;
} }
private function validateAndSanitizeTypes(string $rawTypes): ?array private function validateAndSanitizeSections(string $rawSections): ?array
{ {
$allowedTypes = ["post", "artist", "genre", "book", "movie", "show"]; $allowedSections = ["post", "artist", "genre", "book", "movie", "show"];
if (empty($rawTypes)) return null; if (empty($rawSections)) return null;
$types = array_map( $sections = array_map(
fn($type) => strtolower( fn($section) => strtolower(
trim(htmlspecialchars($type, ENT_QUOTES, "UTF-8")) trim(htmlspecialchars($section, ENT_QUOTES, "UTF-8"))
), ),
explode(",", $rawTypes) explode(",", $rawSections)
); );
$invalidTypes = array_diff($types, $allowedTypes); $invalidSections = array_diff($sections, $allowedSections);
if (!empty($invalidTypes)) throw new Exception("Invalid 'type' parameter. Unsupported types: " . implode(", ", $invalidTypes)); if (!empty($invalidSections)) throw new Exception("Invalid 'section' parameter. Unsupported sections: " . implode(", ", $invalidSections));
return $types; return $sections;
} }
private function fetchSearchResults( private function fetchSearchResults(
string $query, string $query,
?array $types, ?array $sections,
int $pageSize, int $pageSize,
int $offset int $offset
): array { ): array {
$typesParam = $types && count($types) > 0 ? "%7B" . implode(",", $types) . "%7D" : ""; $sectionsParam = $sections && count($sections) > 0 ? "%7B" . implode(",", $sections) . "%7D" : "";
$endpoint = "rpc/search_optimized_index"; $endpoint = "rpc/search_optimized_index";
$queryString = $queryString =
"search_query=" . "search_query=" .
urlencode($query) . urlencode($query) .
"&page_size={$pageSize}&page_offset={$offset}" . "&page_size={$pageSize}&page_offset={$offset}" .
($typesParam ? "&types={$typesParam}" : ""); ($sectionsParam ? "&sections={$sectionsParam}" : "");
$data = $this->makeRequest("GET", "{$endpoint}?{$queryString}"); $data = $this->makeRequest("GET", "{$endpoint}?{$queryString}");
$total = count($data) > 0 ? $data[0]["total_count"] : 0; $total = count($data) > 0 ? $data[0]["total_count"] : 0;
$results = array_map(function ($item) { $results = array_map(function ($item) {
@ -105,16 +105,16 @@ class SearchHandler extends BaseHandler
private function generateCacheKey( private function generateCacheKey(
string $query, string $query,
?array $types, ?array $sections,
int $page, int $page,
int $pageSize int $pageSize
): string { ): string {
$typesKey = $types ? implode(",", $types) : "all"; $sectionsKey = $sections ? implode(",", $sections) : "all";
return sprintf( return sprintf(
"search:%s:types:%s:page:%d:pageSize:%d", "search:%s:sections:%s:page:%d:pageSize:%d",
md5($query), md5($query),
$typesKey, $sectionsKey,
$page, $page,
$pageSize $pageSize
); );

10
package-lock.json generated
View file

@ -1,12 +1,12 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "9.1.8", "version": "9.2.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "coryd.dev", "name": "coryd.dev",
"version": "9.1.8", "version": "9.2.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"minisearch": "^7.1.2", "minisearch": "^7.1.2",
@ -1577,9 +1577,9 @@
} }
}, },
"node_modules/fdir": { "node_modules/fdir": {
"version": "6.4.5", "version": "6.4.6",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.5.tgz", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz",
"integrity": "sha512-4BG7puHpVsIYxZUbiUE3RqGloLaSSwzYie5jvasC4LWuBWzZawynvYouhjbQKw2JuIGYdm0DzIxl8iVidKlUEw==", "integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peerDependencies": { "peerDependencies": {

View file

@ -1,6 +1,6 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "9.1.8", "version": "9.2.0",
"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,4 +1,6 @@
CREATE OR REPLACE FUNCTION search_optimized_index(search_query text, page_size integer, page_offset integer, types text[]) DROP FUNCTION IF EXISTS search_optimized_index(text, integer, integer, text[]);
CREATE FUNCTION search_optimized_index(search_query text, page_size integer, page_offset integer, sections text[])
RETURNS TABLE( RETURNS TABLE(
result_id integer, result_id integer,
url text, url text,
@ -7,7 +9,7 @@ CREATE OR REPLACE FUNCTION search_optimized_index(search_query text, page_size i
tags text, tags text,
genre_name text, genre_name text,
genre_url text, genre_url text,
type text, section text,
total_plays text, total_plays text,
rank real, rank real,
total_count bigint total_count bigint
@ -23,17 +25,17 @@ BEGIN
array_to_string(s.tags, ', ') AS tags, array_to_string(s.tags, ', ') AS tags,
s.genre_name, s.genre_name,
s.genre_url, s.genre_url,
s.type, s.section,
s.total_plays, s.total_plays,
ts_rank_cd(to_tsvector('english', s.title || ' ' || s.description || array_to_string(s.tags, ' ')), plainto_tsquery('english', search_query)) AS rank, ts_rank_cd(to_tsvector('english', s.title || ' ' || s.description || array_to_string(s.tags, ' ')), plainto_tsquery('english', search_query)) AS rank,
COUNT(*) OVER() AS total_count COUNT(*) OVER() AS total_count
FROM FROM
optimized_search_index s optimized_search_index s
WHERE(types IS NULL WHERE(sections IS NULL
OR s.type = ANY(types)) OR s.section = ANY(sections))
AND plainto_tsquery('english', search_query) @@ to_tsvector('english', s.title || ' ' || s.description || array_to_string(s.tags, ' ')) AND plainto_tsquery('english', search_query) @@ to_tsvector('english', s.title || ' ' || s.description || array_to_string(s.tags, ' '))
ORDER BY ORDER BY
s.type = 'post' DESC, s.section = 'post' DESC,
s.content_date DESC NULLS LAST, s.content_date DESC NULLS LAST,
rank DESC rank DESC
LIMIT page_size OFFSET page_offset; LIMIT page_size OFFSET page_offset;

View file

@ -1,37 +1,38 @@
CREATE OR REPLACE VIEW optimized_search_index AS CREATE OR REPLACE VIEW optimized_search_index AS
WITH search_data AS ( WITH search_data AS (
SELECT SELECT
'post' AS type, p.title,
CONCAT('📝 ', p.title) AS title,
p.url::TEXT AS url, p.url::TEXT AS url,
p.description AS description, p.description AS description,
p.tags, p.tags,
NULL AS genre_name, NULL AS genre_name,
NULL AS genre_url, NULL AS genre_url,
NULL::TEXT AS total_plays, NULL::TEXT AS total_plays,
p.date AS content_date p.date AS content_date,
'article' AS type,
'post' AS section
FROM FROM
optimized_posts p optimized_posts p
UNION ALL UNION ALL
SELECT SELECT
'link' AS type, CONCAT(l.title, ' via ', l.name) AS title,
CONCAT('🔗 ', l.title, ' via ', l.name) AS title,
l.link::TEXT AS url, l.link::TEXT AS url,
l.description AS description, l.description AS description,
l.tags, l.tags,
NULL AS genre_name, NULL AS genre_name,
NULL AS genre_url, NULL AS genre_url,
NULL::TEXT AS total_plays, NULL::TEXT AS total_plays,
l.date AS content_date l.date AS content_date,
'link' AS type,
'link' AS section
FROM FROM
optimized_links l optimized_links l
UNION ALL UNION ALL
SELECT SELECT
'book' AS type,
CASE WHEN b.rating IS NOT NULL THEN CASE WHEN b.rating IS NOT NULL THEN
CONCAT('📖 ', b.title, ' (', b.rating, ')') CONCAT(b.title, ' (', b.rating, ')')
ELSE ELSE
CONCAT('📖 ', b.title) b.title
END AS title, END AS title,
b.url::TEXT AS url, b.url::TEXT AS url,
b.description AS description, b.description AS description,
@ -39,58 +40,62 @@ WITH search_data AS (
NULL AS genre_name, NULL AS genre_name,
NULL AS genre_url, NULL AS genre_url,
NULL::TEXT AS total_plays, NULL::TEXT AS total_plays,
b.date_finished AS content_date b.date_finished AS content_date,
'books' AS type,
'book' AS section
FROM FROM
optimized_books b optimized_books b
WHERE WHERE
LOWER(b.status) = 'finished' LOWER(b.status) = 'finished'
UNION ALL UNION ALL
SELECT SELECT
'artist' AS type, ar.name AS title,
CONCAT(COALESCE(ar.emoji, ar.genre_emoji, '🎧'), ' ', ar.name) AS title,
ar.url::TEXT AS url, ar.url::TEXT AS url,
ar.description AS description, ar.description AS description,
ARRAY[ar.genre_name] AS tags, ARRAY[ar.genre_name] AS tags,
ar.genre_name, ar.genre_name,
ar.genre_slug AS genre_url, ar.genre_slug AS genre_url,
TO_CHAR(ar.total_plays::NUMERIC, 'FM999,999,999,999') AS total_plays, TO_CHAR(ar.total_plays::NUMERIC, 'FM999,999,999,999') AS total_plays,
NULL AS content_date NULL AS content_date,
'music' AS type,
'artist' AS section
FROM FROM
optimized_artists ar optimized_artists ar
UNION ALL UNION ALL
SELECT SELECT
'genre' AS type, g.name AS title,
CONCAT(COALESCE(g.emoji, '🎵'), ' ', g.name) AS title,
g.url::TEXT AS url, g.url::TEXT AS url,
g.description AS description, g.description AS description,
NULL AS tags, NULL AS tags,
g.name AS genre_name, g.name AS genre_name,
g.url AS genre_url, g.url AS genre_url,
NULL::TEXT AS total_plays, g.total_plays AS total_plays,
NULL AS content_date NULL AS content_date,
'music' AS type,
'genre' AS section
FROM FROM
optimized_genres g optimized_genres g
UNION ALL UNION ALL
SELECT SELECT
'show' AS type, CONCAT(s.title, ' (', s.year, ')') AS title,
CONCAT('📺 ', s.title, ' (', s.year, ')') AS title,
s.url::TEXT AS url, s.url::TEXT AS url,
s.description AS description, s.description AS description,
s.tags, s.tags,
NULL AS genre_name, NULL AS genre_name,
NULL AS genre_url, NULL AS genre_url,
NULL::TEXT AS total_plays, NULL::TEXT AS total_plays,
s.last_watched_at AS content_date s.last_watched_at AS content_date,
'tv' AS type,
'show' AS section
FROM FROM
optimized_shows s optimized_shows s
WHERE WHERE
s.last_watched_at IS NOT NULL s.last_watched_at IS NOT NULL
UNION ALL UNION ALL
SELECT SELECT
'movie' AS type,
CASE CASE
WHEN m.rating IS NOT NULL THEN CONCAT('🎬 ', m.title, ' (', m.rating, ')') WHEN m.rating IS NOT NULL THEN CONCAT(m.title, ' (', m.rating, ')')
ELSE CONCAT('🎬 ', m.title, ' (', m.year, ')') ELSE CONCAT(m.title, ' (', m.year, ')')
END AS title, END AS title,
m.url::TEXT AS url, m.url::TEXT AS url,
m.description AS description, m.description AS description,
@ -98,7 +103,9 @@ WITH search_data AS (
NULL AS genre_name, NULL AS genre_name,
NULL AS genre_url, NULL AS genre_url,
NULL::TEXT AS total_plays, NULL::TEXT AS total_plays,
m.last_watched AS content_date m.last_watched AS content_date,
'movies' AS type,
'movie' AS section
FROM FROM
optimized_movies m optimized_movies m
WHERE WHERE

View file

@ -179,7 +179,4 @@
/* dialogs */ /* dialogs */
--dialog-overlay-background: light-dark(#ffffffbf, #000000bf); --dialog-overlay-background: light-dark(#ffffffbf, #000000bf);
/* input accent color */
accent-color: var(--accent-color);
} }

View file

@ -3,6 +3,10 @@
opacity: .5; opacity: .5;
} }
input {
accent-color: var(--section-color, var(--accent-color));
}
input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]), input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]),
textarea { textarea {
width: var(--sizing-full); width: var(--sizing-full);

View file

@ -27,27 +27,27 @@ description: Search through posts and other content on my site.
<summary>Filter by type</summary> <summary>Filter by type</summary>
<fieldset class="search__form--type"> <fieldset class="search__form--type">
<label> <label>
<input type="checkbox" name="type" value="post" checked /> <input class="article" type="checkbox" name="section" value="post" checked />
post post
</label> </label>
<label> <label>
<input type="checkbox" name="type" value="artist" checked /> <input class="music" type="checkbox" name="section" value="artist" checked />
artist artist
</label> </label>
<label> <label>
<input type="checkbox" name="type" value="genre" checked /> <input class="music" type="checkbox" name="section" value="genre" checked />
genre genre
</label> </label>
<label> <label>
<input type="checkbox" name="type" value="book" checked /> <input class="books" type="checkbox" name="section" value="book" checked />
book book
</label> </label>
<label> <label>
<input type="checkbox" name="type" value="movie" checked /> <input class="movies" type="checkbox" name="section" value="movie" checked />
movie movie
</label> </label>
<label> <label>
<input type="checkbox" name="type" value="show" checked /> <input class="tv" type="checkbox" name="section" value="show" checked />
show show
</label> </label>
</fieldset> </fieldset>
@ -70,14 +70,14 @@ description: Search through posts and other content on my site.
if (typeof MiniSearch === "undefined") return; if (typeof MiniSearch === "undefined") return;
const miniSearch = new MiniSearch({ const miniSearch = new MiniSearch({
fields: ["title", "description", "tags", "type"], fields: ["title", "description", "tags", "section"],
idField: "id", idField: "id",
storeFields: [ storeFields: [
"id", "id",
"title", "title",
"url", "url",
"description", "description",
"type", "section",
"tags", "tags",
"total_plays", "total_plays",
], ],
@ -130,9 +130,9 @@ description: Search through posts and other content on my site.
.map( .map(
({ title, url, description, type, total_plays }) => ` ({ title, url, description, type, total_plays }) => `
<li class="search__results--result"> <li class="search__results--result">
<h3> <h3 class="${type}">
<a href="${url}">${title}</a> <a href="${url}">${title}</a>
${type === "artist" && total_plays > 0 ? ` <mark>${total_plays} plays</mark>` : ""} ${type === "music" && total_plays > 0 ? ` <mark>${total_plays} plays</mark>` : ""}
</h3> </h3>
<p>${truncateDescription(description)}</p> <p>${truncateDescription(description)}</p>
</li> </li>
@ -163,14 +163,14 @@ description: Search through posts and other content on my site.
.join(""); .join("");
$results.insertAdjacentHTML("beforeend", newResultsHTML); $results.insertAdjacentHTML("beforeend", newResultsHTML);
}; };
const getSelectedTypes = () => Array.from($typeCheckboxes).filter((cb) => cb.checked).map((cb) => cb.value); const getSelectedSections = () => Array.from($typeCheckboxes).filter((cb) => cb.checked).map((cb) => cb.value);
const loadSearchIndex = async (query, types, page) => { const loadSearchIndex = async (query, sections, page) => {
isLoading = true; isLoading = true;
$loadMoreButton.disabled = true; $loadMoreButton.disabled = true;
$loadMoreButton.textContent = "Loading..."; $loadMoreButton.textContent = "Loading...";
try { try {
const typeQuery = types.join(","); const typeQuery = sections.join(",");
const response = await fetch( const response = await fetch(
`https://www.coryd.dev/api/search.php?q=${encodeURIComponent( `https://www.coryd.dev/api/search.php?q=${encodeURIComponent(
query, query,
@ -225,7 +225,7 @@ description: Search through posts and other content on my site.
$results.style.display = "block"; $results.style.display = "block";
$loadMoreButton.style.display = "none"; $loadMoreButton.style.display = "none";
const results = await loadSearchIndex(query, getSelectedTypes(), 1); const results = await loadSearchIndex(query, getSelectedSections(), 1);
currentResults = results; currentResults = results;
currentPage = 1; currentPage = 1;
@ -245,7 +245,7 @@ description: Search through posts and other content on my site.
currentPage++; currentPage++;
const nextResults = await loadSearchIndex($input.value.trim(), getSelectedTypes(), currentPage); const nextResults = await loadSearchIndex($input.value.trim(), getSelectedSections(), currentPage);
currentResults = [...currentResults, ...nextResults]; currentResults = [...currentResults, ...nextResults];