feat(search): design consistency with other feed/content aggregation lists
This commit is contained in:
parent
f2bca309f5
commit
276b6cb81b
9 changed files with 152 additions and 129 deletions
|
@ -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 ? "§ions={$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
10
package-lock.json
generated
|
@ -1,12 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "coryd.dev",
|
"name": "coryd.dev",
|
||||||
"version": "9.1.8",
|
"version": "9.2.2",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "coryd.dev",
|
"name": "coryd.dev",
|
||||||
"version": "9.1.8",
|
"version": "9.2.2",
|
||||||
"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": {
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "coryd.dev",
|
"name": "coryd.dev",
|
||||||
"version": "9.1.8",
|
"version": "9.2.2",
|
||||||
"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": {
|
||||||
|
|
|
@ -1,12 +1,15 @@
|
||||||
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,
|
||||||
title text,
|
title text,
|
||||||
description text,
|
description text,
|
||||||
tags text,
|
tags text[],
|
||||||
genre_name text,
|
genre_name text,
|
||||||
genre_url text,
|
genre_url text,
|
||||||
|
section text,
|
||||||
type text,
|
type text,
|
||||||
total_plays text,
|
total_plays text,
|
||||||
rank real,
|
rank real,
|
||||||
|
@ -20,20 +23,21 @@ BEGIN
|
||||||
s.url,
|
s.url,
|
||||||
s.title,
|
s.title,
|
||||||
s.description,
|
s.description,
|
||||||
array_to_string(s.tags, ', ') AS tags,
|
s.tags,
|
||||||
s.genre_name,
|
s.genre_name,
|
||||||
s.genre_url,
|
s.genre_url,
|
||||||
|
s.section,
|
||||||
s.type,
|
s.type,
|
||||||
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;
|
||||||
|
|
|
@ -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,
|
CONCAT(COALESCE(ar.emoji, ar.genre_emoji, '🎧'), ' ', ar.genre_name) AS 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
|
||||||
|
|
|
@ -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);
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -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);
|
||||||
|
|
|
@ -3,5 +3,5 @@
|
||||||
{%- for tag in tags -%}
|
{%- for tag in tags -%}
|
||||||
<a href="/tags/{{ tag | downcase | url_encode }}">#{{ tag | downcase }}</a>
|
<a href="/tags/{{ tag | downcase | url_encode }}">#{{ tag | downcase }}</a>
|
||||||
{%- endfor -%}
|
{%- endfor -%}
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
|
@ -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>
|
||||||
|
@ -59,25 +59,34 @@ description: Search through posts and other content on my site.
|
||||||
value="coryd.dev"
|
value="coryd.dev"
|
||||||
/>
|
/>
|
||||||
</form>
|
</form>
|
||||||
<ul class="search__results client-side"></ul>
|
<div class="search__results client-side"></div>
|
||||||
<button class="search__load-more client-side" style="display: none">
|
<button class="search__load-more client-side" style="display: none">
|
||||||
Load More
|
Load More
|
||||||
</button>
|
</button>
|
||||||
<script src="/assets/scripts/components/minisearch.js"></script>
|
<script src="/assets/scripts/components/minisearch.js"></script>
|
||||||
|
<script src="/assets/scripts/components/minisearch.js"></script>
|
||||||
<script>
|
<script>
|
||||||
window.addEventListener("load", () => {
|
window.addEventListener("load", () => {
|
||||||
(() => {
|
(() => {
|
||||||
if (typeof MiniSearch === "undefined") return;
|
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({
|
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",
|
||||||
],
|
],
|
||||||
|
@ -89,13 +98,12 @@ description: Search through posts and other content on my site.
|
||||||
boost: { title: 5, tags: 2, description: 1 },
|
boost: { title: 5, tags: 2, description: 1 },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const $form = document.querySelector(SELECTORS.form);
|
||||||
const $form = document.querySelector(".search__form");
|
const $fallback = document.querySelector(SELECTORS.fallback);
|
||||||
const $fallback = document.querySelector(".search__form--fallback");
|
const $input = document.querySelector(SELECTORS.input);
|
||||||
const $input = document.querySelector(".search__form--input");
|
const $results = document.querySelector(SELECTORS.results);
|
||||||
const $results = document.querySelector(".search__results");
|
const $loadMoreButton = document.querySelector(SELECTORS.loadMore);
|
||||||
const $loadMoreButton = document.querySelector(".search__load-more");
|
const $sectionCheckboxes = document.querySelectorAll(SELECTORS.checkboxes);
|
||||||
const $typeCheckboxes = document.querySelectorAll('.search__form--type input[type="checkbox"]');
|
|
||||||
|
|
||||||
$form.removeAttribute("action");
|
$form.removeAttribute("action");
|
||||||
$form.removeAttribute("method");
|
$form.removeAttribute("method");
|
||||||
|
@ -103,11 +111,13 @@ description: Search through posts and other content on my site.
|
||||||
if ($fallback) $fallback.remove();
|
if ($fallback) $fallback.remove();
|
||||||
|
|
||||||
const PAGE_SIZE = 10;
|
const PAGE_SIZE = 10;
|
||||||
|
|
||||||
let currentPage = 1;
|
let currentPage = 1;
|
||||||
let currentResults = [];
|
let currentResults = [];
|
||||||
let total = 0;
|
let total = 0;
|
||||||
let debounceTimeout;
|
let debounceTimeout;
|
||||||
let isLoading = false;
|
let isLoading = false;
|
||||||
|
|
||||||
const parseMarkdown = (markdown) =>
|
const parseMarkdown = (markdown) =>
|
||||||
markdown
|
markdown
|
||||||
? markdown
|
? markdown
|
||||||
|
@ -125,56 +135,58 @@ description: Search through posts and other content on my site.
|
||||||
? `${plainText.substring(0, maxLength)}...`
|
? `${plainText.substring(0, maxLength)}...`
|
||||||
: plainText;
|
: plainText;
|
||||||
};
|
};
|
||||||
const renderSearchResults = (results) => {
|
const generateResultHTML = ({ title, url, description, type, tags, genre_name, genre_url, total_plays }) => `
|
||||||
const resultHTML = results
|
<article class="search__results--result">
|
||||||
.map(
|
<h3 class="${type}">
|
||||||
({ title, url, description, type, total_plays }) => `
|
|
||||||
<li class="search__results--result">
|
|
||||||
<h3>
|
|
||||||
<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>
|
||||||
|
${type !== "music" && tags && tags.length
|
||||||
|
? `<div class="tags ${type}">
|
||||||
|
${tags.map(
|
||||||
|
(tag) =>
|
||||||
|
`<a href="/tags/${encodeURIComponent(tag.toLowerCase())}">#${tag.toLowerCase()}</a>`
|
||||||
|
).join(' ')}
|
||||||
|
</div>`
|
||||||
|
: ''}
|
||||||
|
${type === "music" && genre_name && genre_url
|
||||||
|
? `<div class="tags ${type}">
|
||||||
|
<a href="${genre_url}">${genre_name}</a>
|
||||||
|
</div>`
|
||||||
|
: ''}
|
||||||
<p>${truncateDescription(description)}</p>
|
<p>${truncateDescription(description)}</p>
|
||||||
</li>
|
</article>
|
||||||
`,
|
`;
|
||||||
)
|
const setLoadMoreButton = (isLoading) => {
|
||||||
.join("");
|
$loadMoreButton.disabled = isLoading;
|
||||||
|
$loadMoreButton.textContent = isLoading ? "Loading..." : "Load More";
|
||||||
$results.innerHTML = resultHTML || '<li class="search__results--no-results">No results found.</li>';
|
};
|
||||||
|
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";
|
$results.style.display = "block";
|
||||||
};
|
};
|
||||||
const appendSearchResults = (results) => {
|
const appendSearchResults = (results) => {
|
||||||
const newResultsHTML = results
|
const newResultsHTML = results.map(generateResultHTML).join("");
|
||||||
.map(
|
|
||||||
({ title, url, description, type, total_plays }) => `
|
|
||||||
<li class="search__results--result">
|
|
||||||
<h3>
|
|
||||||
<a href="${url}">${title}</a>
|
|
||||||
${
|
|
||||||
type === "artist" && total_plays > 0
|
|
||||||
? ` <mark>${total_plays} plays</mark>`
|
|
||||||
: ""
|
|
||||||
}
|
|
||||||
</h3>
|
|
||||||
<p>${truncateDescription(description)}</p>
|
|
||||||
</li>
|
|
||||||
`,
|
|
||||||
)
|
|
||||||
.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($sectionCheckboxes).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.textContent = "Loading...";
|
setLoadMoreButton(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const typeQuery = types.join(",");
|
const sectionQuery = 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,
|
||||||
)}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}`,
|
)}§ion=${sectionQuery}&page=${page}&pageSize=${PAGE_SIZE}`,
|
||||||
);
|
);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
|
@ -195,8 +207,8 @@ description: Search through posts and other content on my site.
|
||||||
return [];
|
return [];
|
||||||
} finally {
|
} finally {
|
||||||
isLoading = false;
|
isLoading = false;
|
||||||
$loadMoreButton.disabled = false;
|
|
||||||
$loadMoreButton.textContent = "Load More";
|
setLoadMoreButton(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -206,8 +218,8 @@ description: Search through posts and other content on my site.
|
||||||
} else {
|
} else {
|
||||||
appendSearchResults(results);
|
appendSearchResults(results);
|
||||||
}
|
}
|
||||||
$loadMoreButton.style.display =
|
|
||||||
currentPage * PAGE_SIZE < total ? "block" : "none";
|
$loadMoreButton.style.display = currentPage * PAGE_SIZE < total ? "block" : "none";
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSearch = async () => {
|
const handleSearch = async () => {
|
||||||
|
@ -215,17 +227,15 @@ description: Search through posts and other content on my site.
|
||||||
|
|
||||||
if (!query) {
|
if (!query) {
|
||||||
renderSearchResults([]);
|
renderSearchResults([]);
|
||||||
|
|
||||||
$loadMoreButton.style.display = "none";
|
$loadMoreButton.style.display = "none";
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$results.innerHTML = '<li class="search__results--loading">Searching...</li>';
|
showLoadingMessage();
|
||||||
$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;
|
||||||
|
@ -235,17 +245,18 @@ description: Search through posts and other content on my site.
|
||||||
|
|
||||||
$input.addEventListener("input", () => {
|
$input.addEventListener("input", () => {
|
||||||
clearTimeout(debounceTimeout);
|
clearTimeout(debounceTimeout);
|
||||||
|
|
||||||
debounceTimeout = setTimeout(handleSearch, 300);
|
debounceTimeout = setTimeout(handleSearch, 300);
|
||||||
});
|
});
|
||||||
|
|
||||||
$typeCheckboxes.forEach((cb) => cb.addEventListener("change", handleSearch));
|
$sectionCheckboxes.forEach((cb) => cb.addEventListener("change", handleSearch));
|
||||||
|
|
||||||
$loadMoreButton.addEventListener("click", async () => {
|
$loadMoreButton.addEventListener("click", async () => {
|
||||||
if (isLoading) return;
|
if (isLoading) return;
|
||||||
|
|
||||||
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];
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue