feat(search.html): update to disable and show loading state w/load more button; improve fuzzy search + debounce

This commit is contained in:
Cory Dransfeldt 2025-05-29 10:03:35 -07:00
parent 63db0cf32a
commit 8a6e84cb35
No known key found for this signature in database
35 changed files with 119 additions and 395 deletions

View file

@ -3,11 +3,12 @@
namespace App\Classes;
require __DIR__ . "/BaseHandler.php";
require __DIR__ . '/../../server/utils/init.php';
abstract class ApiHandler extends BaseHandler
{
protected function ensureCliAccess(): void
{
if (php_sapi_name() !== 'cli' && $_SERVER['REQUEST_METHOD'] !== 'POST') $this->sendErrorResponse("Not Found", 404);
if (php_sapi_name() !== 'cli' && $_SERVER['REQUEST_METHOD'] !== 'POST') redirectTo404();
}
}

View file

@ -8,10 +8,7 @@
$isValidId = is_string($id) && preg_match('/^[a-f0-9\-]{36}$/', $id);
$isValidClass = is_string($class) && preg_match('/^w\d{2,4}$/', $class);
if (!$isValidId || !$isValidClass) {
header("Location: /404", true, 302);
exit;
}
if (!$isValidId || !$isValidClass) redirectTo404();
$cdnUrl = "https://cdn.coryd.dev/$id.$extension?class=$class";
$ch = curl_init($cdnUrl);

View file

@ -7,8 +7,7 @@
"guzzlehttp/guzzle": "^7.9",
"kaoken/markdown-it-php": "^14.1",
"sokil/php-isocodes": "^4.2",
"sokil/php-isocodes-db-only": "^4.0",
"voku/html-min": "^4.5"
"sokil/php-isocodes-db-only": "^4.0"
},
"scripts": {
"start": [

215
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "9998c1c4f0bcc7d5e58abc25de979750",
"content-hash": "6f62ebb63bb51c04310e829e19beeab5",
"packages": [
{
"name": "guzzlehttp/guzzle",
@ -686,71 +686,6 @@
},
"time": "2024-02-02T08:24:43+00:00"
},
{
"name": "symfony/css-selector",
"version": "v7.3.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/css-selector.git",
"reference": "601a5ce9aaad7bf10797e3663faefce9e26c24e2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/css-selector/zipball/601a5ce9aaad7bf10797e3663faefce9e26c24e2",
"reference": "601a5ce9aaad7bf10797e3663faefce9e26c24e2",
"shasum": ""
},
"require": {
"php": ">=8.2"
},
"type": "library",
"autoload": {
"psr-4": {
"Symfony\\Component\\CssSelector\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Jean-François Simon",
"email": "jeanfrancois.simon@sensiolabs.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Converts CSS selectors to XPath expressions",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/css-selector/tree/v7.3.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-25T14:21:43+00:00"
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.6.0",
@ -817,154 +752,6 @@
}
],
"time": "2024-09-25T14:21:43+00:00"
},
{
"name": "voku/html-min",
"version": "4.5.1",
"source": {
"type": "git",
"url": "https://github.com/voku/HtmlMin.git",
"reference": "872dac444652d30791ca5d0c23fbe1e6b9cab5bc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/voku/HtmlMin/zipball/872dac444652d30791ca5d0c23fbe1e6b9cab5bc",
"reference": "872dac444652d30791ca5d0c23fbe1e6b9cab5bc",
"shasum": ""
},
"require": {
"ext-dom": "*",
"php": ">=7.0.0",
"voku/simple_html_dom": "~4.8.5"
},
"require-dev": {
"phpunit/phpunit": "~6.0 || ~7.0 || ~9.0"
},
"type": "library",
"autoload": {
"psr-4": {
"voku\\": "src/voku/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Lars Moelleken",
"homepage": "https://www.moelleken.org/"
}
],
"description": "HTML Compressor and Minifier",
"homepage": "https://github.com/voku/HtmlMin",
"keywords": [
"compress",
"compression",
"compressor",
"html",
"minifier"
],
"support": {
"issues": "https://github.com/voku/HtmlMin/issues",
"source": "https://github.com/voku/HtmlMin/tree/4.5.1"
},
"funding": [
{
"url": "https://www.paypal.me/moelleken",
"type": "custom"
},
{
"url": "https://github.com/voku",
"type": "github"
},
{
"url": "https://www.patreon.com/voku",
"type": "patreon"
}
],
"time": "2024-05-25T08:01:45+00:00"
},
{
"name": "voku/simple_html_dom",
"version": "4.8.10",
"source": {
"type": "git",
"url": "https://github.com/voku/simple_html_dom.git",
"reference": "716822ed52ed3a1881542be07a786270de390e99"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/voku/simple_html_dom/zipball/716822ed52ed3a1881542be07a786270de390e99",
"reference": "716822ed52ed3a1881542be07a786270de390e99",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-libxml": "*",
"ext-simplexml": "*",
"php": ">=7.0.0",
"symfony/css-selector": "~3.0 || ~4.0 || ~5.0 || ~6.0 || ~7.0"
},
"require-dev": {
"phpunit/phpunit": "~6.0 || ~7.0 || ~9.0"
},
"suggest": {
"voku/portable-utf8": "If you need e.g. UTF-8 fixed output."
},
"type": "library",
"autoload": {
"psr-4": {
"voku\\helper\\": "src/voku/helper/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "dimabdc",
"email": "support@titor.ru",
"homepage": "https://github.com/dimabdc",
"role": "Developer"
},
{
"name": "Lars Moelleken",
"homepage": "https://www.moelleken.org/",
"role": "Fork-Maintainer"
}
],
"description": "Simple HTML DOM package.",
"homepage": "https://github.com/voku/simple_html_dom",
"keywords": [
"HTML Parser",
"dom",
"php dom"
],
"support": {
"issues": "https://github.com/voku/simple_html_dom/issues",
"source": "https://github.com/voku/simple_html_dom/tree/4.8.10"
},
"funding": [
{
"url": "https://www.paypal.me/moelleken",
"type": "custom"
},
{
"url": "https://github.com/voku",
"type": "github"
},
{
"url": "https://www.patreon.com/voku",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/voku/simple_html_dom",
"type": "tidelift"
}
],
"time": "2024-07-03T16:05:14+00:00"
}
],
"packages-dev": [],

View file

@ -38,4 +38,5 @@ export default {
return `${string}s${trailing ? `${trailing}` : ''}`;
},
jsonEscape: (string) => JSON.stringify(string),
regexEscape: (string) => string.replace(/[.*+?^${}()[]\\]/g, '\\$&')
};

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "coryd.dev",
"version": "8.0.4",
"version": "8.2.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "coryd.dev",
"version": "8.0.4",
"version": "8.2.2",
"license": "MIT",
"dependencies": {
"minisearch": "^7.1.2",

View file

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

View file

@ -43,7 +43,7 @@
decoding="async"
width="' . $width . '"
height="' . $height . '"
/>';
>';
echo '</div>';
echo $closeLink;
}

View file

@ -7,7 +7,7 @@ function renderTags(array $tags): void {
foreach ($tags as $tag) {
$slug = strtolower(trim($tag));
echo '<a href="/tags/' . htmlspecialchars($slug) . '">#' . htmlspecialchars($slug) . '</a>';
echo '<a href="/tags/' . rawurlencode($slug) . '">#' . htmlspecialchars($slug) . '</a>';
}
echo '</div>';

View file

@ -36,7 +36,7 @@ permalink: "{{ feed.permalink }}.xml"
{%- endif -%}
<description><![CDATA[
{%- if feedItem.image -%}
<img src="{{ feedItem.image | encodeAmp }}?class=w800" alt="Image from {{ feedItem.title }}" />
<img src="{{ feedItem.image | encodeAmp }}?class=w800" alt="Image from {{ feedItem.title }}">
{%- endif -%}
{%- if feedItem.content -%}
{{ feedItem.content | markdown | convertRelativeLinks: globals.url }}

View file

@ -14,4 +14,4 @@
decoding="async"
width="720"
height="480"
/>
>

View file

@ -1,9 +1,12 @@
{%- for block in blocks -%}
{%- case block.type -%}
{%- when "youtube_player" -%}
{% render "blocks/youtube-player.liquid",
url:block.url
{%- when "calendar_banner" -%}
{% render "blocks/banners/calendar.liquid",
url:block.url,
text:block.text
%}
{%- when "divider" -%}
{{ block.markup | markdown }}
{%- when "forgejo_banner" -%}
{% render "blocks/banners/forgejo.liquid",
url:block.url
@ -12,6 +15,14 @@
{% render "blocks/banners/github.liquid",
url:block.url
%}
{%- when "hero" -%}
{% render "blocks/hero.liquid",
globals:globals,
image:block.image,
alt:block.alt
%}
{%- when "markdown" -%}
{{ block.text | markdown }}
{%- when "npm_banner" -%}
{% render "blocks/banners/npm.liquid",
url:block.url,
@ -22,15 +33,9 @@
url:block.url,
text:block.text
%}
{%- when "hero" -%}
{% render "blocks/hero.liquid",
globals:globals,
image:block.image,
alt:block.alt
{%- when "youtube_player" -%}
{% render "blocks/youtube-player.liquid",
url:block.url
%}
{%- when "markdown" -%}
{{ block.text | markdown }}
{%- when "divider" -%}
{{ block.markup | markdown }}
{%- endcase -%}
{%- endfor -%}

View file

@ -4,7 +4,6 @@
require __DIR__ . "/../../server/utils/init.php";
use App\Classes\ArtistFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
@ -21,7 +20,6 @@
$page = $artist;
extract(setupPageMetadata($page, $requestUri));
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");

View file

@ -4,7 +4,6 @@
require __DIR__ . "/../../server/utils/init.php";
use App\Classes\BookFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
@ -22,7 +21,6 @@
$globals = $page["globals"];
extract(setupPageMetadata($page, $requestUri));
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");

View file

@ -4,7 +4,6 @@
require __DIR__ . "/../../server/utils/init.php";
use App\Classes\GenreFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
@ -21,8 +20,6 @@
$globals = $page["globals"];
extract(setupPageMetadata($page, $requestUri));
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");

View file

@ -4,7 +4,6 @@
require __DIR__ . "/../../server/utils/init.php";
use App\Classes\MovieFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
@ -22,7 +21,6 @@
$globals = $page["globals"];
extract(setupPageMetadata($page, $requestUri));
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");

View file

@ -4,7 +4,6 @@
require __DIR__ . "/../../server/utils/init.php";
use App\Classes\ShowFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
@ -22,7 +21,6 @@
$globals = $page["globals"];
extract(setupPageMetadata($page, $requestUri));
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");

View file

@ -5,7 +5,6 @@
use App\Classes\TagFetcher;
use App\Classes\GlobalsFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
@ -63,7 +62,6 @@
];
extract(setupPageMetadata($page, $requestUri));
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");

View file

@ -6,10 +6,10 @@
"
sizes="(max-width: 450px) 100px, 200px"
class="icon" src="{{ globals.avatar_header }}?class=w100&v={% appVersion %}"
alt="{{ globals.site_name }}"
alt="An avatar representing {{ globals.site_name }}"
width="100"
height="145"
/>
>
<span>Cory</span> <span>Dransfeldt</span>
{%- endcapture -%}
<section class="main-title">

View file

@ -37,7 +37,7 @@
decoding="async"
width="{{ width }}"
height="{{ height }}"
/>
>
</div>
</a>
{%- endfor -%}

View file

@ -15,7 +15,7 @@
decoding="async"
width="64"
height="64"
/>
>
</a>
<div class="meta-text">
<a class="title" href="{{ item.chart.url }}">{{ item.chart.title }}</a>

View file

@ -83,23 +83,22 @@ Redirect {{ redirect.status_code | default: "301" }} {{ redirect.source_url }} {
</FilesMatch>
{% endfor %}
{%- assign userAgents = "" -%}
{% for robot in robots -%}
{%- for userAgent in robot.user_agents -%}
{%- if userAgent != "*" and userAgent != "NaN" -%}
{%- assign userAgents = userAgents | append: userAgent %}
{%- unless forloop.last -%}
{%- assign userAgents = userAgents | append: "|" -%}
{%- endunless -%}
{%- assign escapedAgents = "" -%}
{%- for robot in robots -%}
{%- for agent in robot.user_agents -%}
{%- if agent != "*" and agent != "NaN" -%}
{%- assign escaped = agent | regexEscape -%}
{%- assign escapedAgents = escapedAgents | append: escaped | append: "|" -%}
{%- endif -%}
{%- endfor -%}
{%- endfor %}
{% if userAgents != "" or referers != "" -%}
RewriteCond %{HTTP_USER_AGENT} "{{ userAgents }}" [NC]
{%- endfor -%}
{%- assign userAgentsRegex = escapedAgents | slice: 0, escapedAgents.size | rstrip: "|" -%}
{% if userAgentsRegex != "" %}
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "{{ userAgentsRegex }}" [NC]
RewriteCond %{REQUEST_URI} !^/robots\.txt$ [NC]
RewriteRule .* /403/index.html [L,R=403]
{%- endif %}
RewriteRule ^.*$ - [F,L]
{% endif %}
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

View file

@ -10,7 +10,7 @@ schema: artist
class="media-image"
srcset="
<?= htmlspecialchars($artist["image"]) ?>?class=w200&type=webp 200w,
<?= htmlspecialchars($artist["image"]) ?>?class=w600&type=webp 400w,
<?= htmlspecialchars($artist["image"]) ?>?class=w400&type=webp 400w,
<?= htmlspecialchars($artist["image"]) ?>?class=w800&type=webp 800w
"
sizes="(max-width: 450px) 200px,
@ -21,7 +21,7 @@ schema: artist
decoding="async"
width="200"
height="200"
/>
>
<div class="media-meta">
<h2 class="page-title"><?= htmlspecialchars($artist["name"]) ?></h2>
<span class="sub-meta country">{% tablericon "map-pin" %} <?= htmlspecialchars(
@ -111,13 +111,3 @@ schema: artist
<?php renderMediaGrid($artist["albums"]); ?>
<?php endif; ?>
</article>
<?php
$html = ob_get_clean();
$htmlMin = new HtmlMin();
$htmlMin->doOptimizeAttributes(true);
$htmlMin->doRemoveComments(true);
$htmlMin->doSumUpWhitespace(true);
$htmlMin->doRemoveWhitespaceAroundTags(true);
$htmlMin->doOptimizeViaHtmlDomParser(false);
echo $htmlMin->minify($html);
?>

View file

@ -22,7 +22,7 @@ schema: book
decoding="async"
width="200"
height="307"
/>
>
<div class="media-meta">
<h2 class="page-title"><?= htmlspecialchars($book["title"]) ?></h2>
<?php if (!empty($book["tags"])): ?>
@ -67,13 +67,3 @@ schema: book
<?= parseMarkdown($book["description"]) ?>
<?php endif; ?>
</article>
<?php
$html = ob_get_clean();
$htmlMin = new HtmlMin();
$htmlMin->doOptimizeAttributes(true);
$htmlMin->doRemoveComments(true);
$htmlMin->doSumUpWhitespace(true);
$htmlMin->doRemoveWhitespaceAroundTags(true);
$htmlMin->doOptimizeViaHtmlDomParser(false);
echo $htmlMin->minify($html);
?>

View file

@ -45,13 +45,3 @@ schema: genre
<button data-toggle-button>Show more</button>
<?php endif; ?>
</article>
<?php
$html = ob_get_clean();
$htmlMin = new HtmlMin();
$htmlMin->doOptimizeAttributes(true);
$htmlMin->doRemoveComments(true);
$htmlMin->doSumUpWhitespace(true);
$htmlMin->doRemoveWhitespaceAroundTags(true);
$htmlMin->doOptimizeViaHtmlDomParser(false);
echo $htmlMin->minify($html);
?>

View file

@ -20,7 +20,7 @@ schema: movie
decoding="async"
width="256"
height="180"
/>
>
<div class="media-meta">
<h2 class="page-title"><?= htmlspecialchars($movie["title"]) ?> (<?= htmlspecialchars($movie["year"]) ?>)</h2>
<?php if (!empty($movie["tags"])): ?>
@ -63,13 +63,3 @@ schema: movie
<?= parseMarkdown($movie["description"]) ?>
<?php endif; ?>
</article>
<?php
$html = ob_get_clean();
$htmlMin = new HtmlMin();
$htmlMin->doOptimizeAttributes(true);
$htmlMin->doRemoveComments(true);
$htmlMin->doSumUpWhitespace(true);
$htmlMin->doRemoveWhitespaceAroundTags(true);
$htmlMin->doOptimizeViaHtmlDomParser(false);
echo $htmlMin->minify($html);
?>

View file

@ -20,7 +20,7 @@ schema: show
decoding="async"
width="256"
height="180"
/>
>
<div class="media-meta">
<h2 class="page-title"><?= htmlspecialchars($show["title"]) ?> (<?= htmlspecialchars($show["year"]) ?>)</h2>
<?php if (!empty($show["tags"])): ?>
@ -60,13 +60,3 @@ schema: show
<?= parseMarkdown($show["description"]) ?>
<?php endif; ?>
</article>
<?php
$html = ob_get_clean();
$htmlMin = new HtmlMin();
$htmlMin->doOptimizeAttributes(true);
$htmlMin->doRemoveComments(true);
$htmlMin->doSumUpWhitespace(true);
$htmlMin->doRemoveWhitespaceAroundTags(true);
$htmlMin->doOptimizeViaHtmlDomParser(false);
echo $htmlMin->minify($html);
?>

View file

@ -38,13 +38,3 @@ schema: tags
</article>
<?php endforeach; ?>
<?php renderPaginator($pagination, $totalPages); ?>
<?php
$html = ob_get_clean();
$htmlMin = new HtmlMin();
$htmlMin->doOptimizeAttributes(true);
$htmlMin->doRemoveComments(true);
$htmlMin->doSumUpWhitespace(true);
$htmlMin->doRemoveWhitespaceAroundTags(true);
$htmlMin->doOptimizeViaHtmlDomParser(false);
echo $htmlMin->minify($html);
?>

View file

@ -37,7 +37,7 @@ updated: "now"
decoding="async"
width="200"
height="307"
/>
>
</a>
<div class="media-meta">
<a href="{{ book.url }}">

View file

@ -40,7 +40,7 @@ schema: blog
decoding="async"
width="200"
height="auto"
/>
>
{%- endif -%}
{{ post.content | markdown }}
{% render "blocks/index.liquid",

View file

@ -23,7 +23,7 @@ excludeFromSitemap: true
decoding="async"
width="720"
height="480"
/>
>
</div>
<div>
<h2 style="text-align:center">403</h2>

View file

@ -23,7 +23,7 @@ excludeFromSitemap: true
decoding="async"
width="720"
height="480"
/>
>
</div>
<h2 style="text-align:center">404</h2>
<p style="text-align:center">What kind of idiots do you have working here?</p>

View file

@ -23,7 +23,7 @@ excludeFromSitemap: true
decoding="async"
width="720"
height="480"
/>
>
</div>
<div style="text-align:center">
<h2>429</h2>

View file

@ -23,7 +23,7 @@ excludeFromSitemap: true
decoding="async"
width="720"
height="480"
/>
>
</div>
<div style="text-align:center">
<h2>500</h2>

View file

@ -84,7 +84,8 @@ description: Search through posts and other content on my site.
searchOptions: {
fields: ["title", "tags"],
prefix: true,
fuzzy: 0.1,
fuzzy: 0.3,
combineWith: "OR",
boost: { title: 5, tags: 2, description: 1 },
},
});
@ -94,12 +95,11 @@ description: Search through posts and other content on my site.
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"]',
);
const $typeCheckboxes = document.querySelectorAll('.search__form--type input[type="checkbox"]');
$form.removeAttribute("action");
$form.removeAttribute("method");
if ($fallback) $fallback.remove();
const PAGE_SIZE = 10;
@ -107,7 +107,7 @@ description: Search through posts and other content on my site.
let currentResults = [];
let total = 0;
let debounceTimeout;
let isLoading = false;
const parseMarkdown = (markdown) =>
markdown
? markdown
@ -117,7 +117,6 @@ description: Search through posts and other content on my site.
.replace(/\n/g, "<br>")
.replace(/[#*_~`]/g, "")
: "";
const truncateDescription = (markdown, maxLength = 225) => {
const plainText =
new DOMParser().parseFromString(parseMarkdown(markdown), "text/html")
@ -126,12 +125,29 @@ description: Search through posts and other content on my site.
? `${plainText.substring(0, maxLength)}...`
: plainText;
};
const renderSearchResults = (results) => {
const resultHTML = results
.map(
({ title, url, description, type, total_plays }) => `
<li class="search__results--result">
<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.innerHTML = resultHTML || '<li class="search__results--no-results">No results found.</li>';
$results.style.display = "block";
};
const appendSearchResults = (results) => {
const newResultsHTML = results
.map(
({ title, url, description, type, total_plays }) => `
<li class="search__results--result">
<h3>
<a href="${url}">${title}</a>
${
@ -140,45 +156,50 @@ description: Search through posts and other content on my site.
: ""
}
</h3>
<p>${truncateDescription(description)}</p>
</li>
`,
<p>${truncateDescription(description)}</p>
</li>
`,
)
.join("");
$results.innerHTML =
resultHTML ||
'<li class="search__results--no-results">No results found.</li>';
$results.style.display = "block";
$results.insertAdjacentHTML("beforeend", newResultsHTML);
};
const getSelectedTypes = () => Array.from($typeCheckboxes).filter((cb) => cb.checked).map((cb) => cb.value);
const loadSearchIndex = async (query, types, page) => {
isLoading = true;
$loadMoreButton.disabled = true;
$loadMoreButton.textContent = "Loading...";
try {
const typeQuery = types.join(",");
const response = await fetch(
`https://www.coryd.dev/api/search.php?q=${query}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}`,
`https://www.coryd.dev/api/search.php?q=${encodeURIComponent(
query,
)}&type=${typeQuery}&page=${page}&pageSize=${PAGE_SIZE}`,
);
const data = await response.json();
total = data.total || 0;
const formattedResults = (data.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 [];
} finally {
isLoading = false;
$loadMoreButton.disabled = false;
$loadMoreButton.textContent = "Load More";
}
};
const getSelectedTypes = () =>
Array.from($typeCheckboxes)
.filter((cb) => cb.checked)
.map((cb) => cb.value);
const updateSearchResults = (results) => {
if (currentPage === 1) {
renderSearchResults(results);
@ -189,58 +210,45 @@ description: Search through posts and other content on my site.
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
? ` <mark>${total_plays} plays</mark>`
: ""
}
</h3>
<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;
}
$results.innerHTML = '<li class="search__results--loading">Searching...</li>';
$results.style.display = "block";
$loadMoreButton.style.display = "none";
const results = await loadSearchIndex(query, getSelectedTypes(), 1);
currentResults = results;
currentPage = 1;
updateSearchResults(results);
};
$input.addEventListener("input", () => {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(handleSearch, 150);
debounceTimeout = setTimeout(handleSearch, 300);
});
$typeCheckboxes.forEach((cb) =>
cb.addEventListener("change", handleSearch),
);
$typeCheckboxes.forEach((cb) => cb.addEventListener("change", handleSearch));
$loadMoreButton.addEventListener("click", async () => {
if (isLoading) return;
currentPage++;
const nextResults = await loadSearchIndex(
$input.value.trim(),
getSelectedTypes(),
currentPage,
);
const nextResults = await loadSearchIndex($input.value.trim(), getSelectedTypes(), currentPage);
currentResults = [...currentResults, ...nextResults];
updateSearchResults(nextResults);
});
})();