# Adding Bookmarks to My Blog Part 3: Search

*2026-11-19*

> Adding client-side search for Raindrop.io bookmarks on my blog


Once I'd got bookmarks [synchronising to a DynamoDB table]({{< relref "adding-bookmarks-to-my-blog-1" >}}) and the corresponding [Markdown pages being generated]({{< relref "adding-bookmarks-to-my-blog-2" >}}), I quickly realised that I had gathered a lot of bookmarks [over the years](/bookmarks/years). Bookmarks could be viewed by year or [by tag](/bookmarks/tags), but there was no way to find something by keyword.

Given the blog is not backed by a database and bookmark pages are generated as part of the build, the search had to run entirely client-side: ship a static index alongside the site and filter it in the browser.

# Contents

This blog post covers adding client-side search to the bookmarks section on this blog:  

* [**Emitting a JSON index**](#emitting-a-json-index) - updating the `generate_bookmarks.py` Python script to write a JSON index
* [**Adding a search page**](#adding-a-search-page) - adding a Markdown page that hosts the search UI
* [**Adding a search script**](#adding-a-search-page-script) - adding the client-side JavaScript that does the searching
* [**Enhancements**](#enhancements) - fuzzy search, pagination, shareable URLs and skeleton rows
* [**Troubleshooting**](#troubleshooting) - issues encountered during implementation and deployment

# Emitting a JSON index{#emitting-a-json-index}

First up was an index to search against, and JSON fits this naturally as a client-side searchable structure.

I added a writer function to `generate_bookmarks.py`, called from `main()` after `record_image` is populated so the bookmark covers resolve:

```python
import json

def write_search_index(records, record_image, args, tag_slugs):
    """
    Write a static JSON index for client-side search. Hugo copies static/
    to the site root verbatim, so this is served at /search/bookmarks.json.
    Output is deterministic (sorted entries, fixed separators) so unchanged
    data produces a byte-identical file and the CI diff guard stays quiet.
    """
    entries = []
    for record in records:
        rd = record.get("raindrop", {})
        entry = {
            "id": str(record.get("id", "")),
            "title": rd.get("title") or rd.get("domain") or "",
            "link": rd.get("link") or "",
            "domain": rd.get("domain") or "",
            "date": (rd.get("created") or "")[:10],
            "excerpt": (rd.get("excerpt") or "")[:160],
            "tags": [t for t in (rd.get("tags") or []) if t],
        }
        # Index-aligned with tags so the search UI links to the same
        # collision-free tag paths as the generated pages
        entry["tagSlugs"] = [tag_slugs.get(t) or slugify(t) for t in entry["tags"]]
        img = cover_url(record_image, record.get("id"))
        if img:
            entry["image"] = img
        entries.append(entry)

    dest = Path(args.static_dir) / "search" / "bookmarks.json"
    dest.parent.mkdir(parents=True, exist_ok=True)
    # Fixed separators + sort for byte-identical output when data hasn't changed
    entries.sort(key=lambda e: (e["date"], e["id"]), reverse=True)
    dest.write_text(
        json.dumps({"bookmarks": entries}, ensure_ascii=False, separators=(",", ":")),
        encoding="utf-8", newline="\n",
    )
    logger.info("Wrote search index: %s (%d entries)", dest, len(entries))
    return len(entries)
```

Two helpers keep it in step with the generated pages. `cover_url()` turns a record's entry in `record_image` into the cover's path on the main listing pages, and `tag_slugs` maps each tag to the same URL slug the tag pages use. A plain slug would merge tags like "C", "C#" and "C++" into one `c` page, so clashes get `-2`, `-3` and so on. The index carries the slugs in `tagSlugs`, in the same order as `tags`, so search results link to the right tag pages:

```python
def cover_url(record_image, record_id):
    """
    Absolute URL of a record's cover on the main listing pages, or None.
    record_image maps record id -> (page_no, filename).
    """
    entry = record_image.get(record_id)
    if not entry:
        return None
    page_no, filename = entry
    if page_no == 1:
        return f"/bookmarks/{IMAGE_DIR_NAME}/{filename}"
    return f"/bookmarks/page/{page_no}/{IMAGE_DIR_NAME}/{filename}"
```

I then added a new script flag using `parser.add_argument("--static-dir", default="static")` - writing the JSON index into `static/` means Hugo copies it to the site root verbatim at `/search/bookmarks.json`.

Size-wise, around ~1,400 entries x ~350 bytes is roughly 500 KB raw, but JSON with this shape compresses ~5-10x:

[![JSON bookmarks index](json-bookmarks-index.png)](json-bookmarks-index.png)

CloudFront serves this as compressed data, so it's tens of KB over the wire. It's also loaded lazily, so it costs nothing until someone actually searches - and once loaded, scanning 1,400 objects is effectively instantaneous.

The index only holds each cover's path, not the image. The covers themselves are resized to small WebP thumbnails when the pages are generated, so their paths end in `.webp`, and a page of search results downloads thumbnails rather than full-size originals.

# Adding a search page{#adding-a-search-page}

With Markdown pages supporting raw HTML, adding a search page at `/bookmarks/search` is straightforward - a search input, a status line, and a `div` for the results:

```markdown
---
title: Search bookmarks
layout: single
hideReadingTime: true
---

<input type="search" id="bookmark-search" class="form-control" placeholder="Search bookmarks..." autocomplete="off">
<p id="search-status" class="color-fg-muted f6 mt-2"></p>
<div id="search-results" class="Box mt-3"></div>

<script src="/js/bookmark-search.js"></script>
```

To begin with I added the client-side JavaScript as a `<script>` tag directly on the page, but later moved it into Hugo's asset pipeline, bundled with Fuse.js and loaded only on this page (see [JavaScript minification](#javascript-minification)).

# Adding a search script{#adding-a-search-page-script}

The script imports Fuse.js (see [Adding fuzzy search](#adding-fuzzy-search)), then runs as an [IIFE](https://en.wikipedia.org/wiki/Immediately_invoked_function_expression) on page load. It returns straight away if the search input, status line or results container is missing, so it does nothing on any other page. It consists of 16 functions and event bindings:

| Name                                  | Description                                                            |
|---------------------------------------|------------------------------------------------------------------------|
| `setStatus`                           | Sets the `search-status` text                                          |
| `urlFor`                              | Builds the canonical URL for a search state                            |
| `updateUrl`                           | Updates the browser's URL and history so back and forward buttons work |
| `window.addEventListener("popstate")` | Binds an event to handle browser history changes                       |
| `restoreFromUrl`                      | Restores the current search from a URL, allowing URLs to be shared     |
| `loadIndex`                           | Uses the Fetch API to load the JSON search index                       |
| `results.addEventListener("click")`   | Binds an event to handle click events on pager clicks                  |
| `totalPages`                          | Calculates the total number of pages for pagination                    |
| `runSearch`                           | Executes the search and updates the UI                                 |
| `renderPage`                          | Renders the search results page                                        |
| `renderPager`                         | Renders the pagination controls                                        |
| `renderSkeleton`                      | Renders a loading skeleton for the search results                      |
| `rankHits`                            | Ranks search results based on relevance                                |
| `renderRow`                           | Renders a single search result row                                     |
| `slugify`                             | Fallback tag slug, for index entries without `tagSlugs`                |
| `escapeHtml`                          | Used in various places to escape HTML entities                         |

The full script is shown below:

```javascript
// Bundled with Fuse by Hugo's js.Build (see layouts/baseof.html). The
// "/*!" comment below is a legal comment esbuild keeps in the minified
// bundle, since the vendored file's own licence header gets stripped.
/*! Includes Fuse.js v7.5.0 (https://fusejs.io) | (c) Kiro Risk | Apache License 2.0 */
import Fuse from "./vendor/fuse-7.5.0.min.mjs";

(function () {
    let fuse = null;               // lazy-built on first search
    const input = document.getElementById("bookmark-search");
    const results = document.getElementById("search-results");
    const status = document.getElementById("search-status");
    if (!input || !results || !status) return;   // not the search page
    const PLACEHOLDER = "/images/bookmark-placeholder.jpg";
    const RESULTS_PER_PAGE = 20;   // search result pages
    const SKELETON_ROWS = 5;
    const PAGER_WINDOW = 2;        // page links shown either side of current

    // Fuzzy-tolerance knobs - see notes on tuning below
    const FUSE_OPTIONS = {
        keys: [
            { name: "title", weight: 0.45 },
            { name: "tags", weight: 0.25 },
            { name: "domain", weight: 0.15 },
            { name: "excerpt", weight: 0.15 }
        ],
        threshold: 0.4,            // 0 = exact, 1 = matches anything; lower = stricter
        ignoreLocation: true,      // don't penalise matches late in long excerpts
        minMatchCharLength: 2,     // ignore 1-char noise
        includeScore: true         // required for the rankHits tie-break below
    };

    // Current search state
    let lastHits = null;
    let currentPage = 1;
    let currentQuery = "";

    // Status line, styled like the listing pages' date line
    function setStatus(text) {
        if (!text) { status.innerHTML = ""; return; }
        status.innerHTML =
            '<div class="d-flex flex-items-center color-fg-muted f5 mb-3"><span>' +
            escapeHtml(text) + "</span></div>";
    }

    // Canonical URL for a search state: ?q=term, plus &page=N above page 1
    function urlFor(q, page) {
        const params = new URLSearchParams();
        if (q) params.set("q", q);
        if (q && page > 1) params.set("page", page);
        const qs = params.toString();
        return window.location.pathname + (qs ? "?" + qs : "");
    }

    // Keep the address bar in sync so the URL is always shareable.
    // push=true inserts a history entry (pager clicks, so Back unwinds
    // through result pages); push=false rewrites the current entry
    // (typing, so intermediate keystrokes never pile up).
    function updateUrl(push) {
        const url = urlFor(currentQuery, lastHits ? currentPage : 1);
        if (push) history.pushState(null, "", url);
        else history.replaceState(null, "", url);
    }

    // Back/Forward: render whatever search state the URL describes
    window.addEventListener("popstate", () => {
        const params = new URLSearchParams(window.location.search);
        const q = (params.get("q") || "").trim();
        let page = parseInt(params.get("page") || "1", 10);
        if (!(page >= 1)) page = 1;

        if (!q) {
            // Back to the bare search page - clear and show the idle state
            currentQuery = "";
            lastHits = null;
            currentPage = 1;
            input.value = "";
            renderSkeleton();
            return;
        }

        input.value = q;
        currentQuery = q;

        if (lastHits) {
            // Same query already searched - just re-slice, no re-search
            currentPage = Math.min(page, totalPages());
            setStatus(lastHits.length + " match" + (lastHits.length === 1 ? "" : "es"));
            renderPage();
            input.scrollIntoView({ block: "start" });
        } else {
            currentPage = page;
            runSearch();
        }
    });

    // Restore a shared URL (?q=...&page=N) on load. Seeds the history
    // stack so Back from a deep page steps to page 1 of the results
    // before leaving the search page entirely.
    function restoreFromUrl() {
        const params = new URLSearchParams(window.location.search);
        const q = (params.get("q") || "").trim();

        if (!q) return false;        // nothing to restore - caller renders idle state

        let page = parseInt(params.get("page") || "1", 10);
        if (!(page >= 1)) page = 1;

        input.value = q;
        currentQuery = q;
        currentPage = page;

        if (page > 1) {
            history.replaceState(null, "", urlFor(q, 1));   // the "page 1" entry
            history.pushState(null, "", urlFor(q, page));   // where we actually are
        }

        runSearch();
        return true;
    }

    function loadIndex(done) {
        if (fuse) return done();
        setStatus("Loading search index...");
        fetch("/search/bookmarks.json")
            .then((r) => {
                if (!r.ok) throw new Error("HTTP " + r.status);
                return r.json();
            })
            .then((d) => {
                fuse = new Fuse(d.bookmarks, FUSE_OPTIONS);
                done();
            })
            .catch((err) => {
                setStatus("Search unavailable (" + err.message + ")");
            });
    }

    let timer;
    input.addEventListener("input", () => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            currentPage = 1;           // typing always restarts pagination
            runSearch();
        }, 150);                     // debounce
    });

    // Pager clicks - delegated once on the container, so re-rendered
    // pagers don't need rebinding. Each hop pushes a history entry.
    results.addEventListener("click", (e) => {
        const el = e.target.closest("[data-page]");
        if (!el) return;
        e.preventDefault();
        const p = parseInt(el.getAttribute("data-page"), 10);
        if (p >= 1 && p <= totalPages()) {
            currentPage = p;
            updateUrl(true);           // pushState - Back walks back through pages
            renderPage();
            // Back to the top of the results, as a listing-page reload would
            input.scrollIntoView({ block: "start" });
        }
    });

    function totalPages() {
        return Math.max(1, Math.ceil((lastHits ? lastHits.length : 0) / RESULTS_PER_PAGE));
    }

    // Shared by the input listener, URL restoration and popstate. Sets the
    // query from the input and renders; the URL is synced afterwards, which
    // for restored/popstate calls just re-states the URL the browser is
    // already showing.
    function runSearch() {
        const q = input.value.trim();
        currentQuery = q;

        if (q.length < 2) {
            lastHits = null;
            currentPage = 1;
            updateUrl(false);          // strip the query string (rewrite entry)
            renderSkeleton();
            return;
        }
        loadIndex(() => {
            // fuse.search returns [{ item, score }] ordered best-first
            const hits = fuse.search(q);

            // Re-rank: equal Fuse scores fall back to newest first by date.
            // Full ties (same score AND same date) keep Fuse's original order,
            // since Array.prototype.sort is stable in all modern browsers.
            hits.sort(rankHits);

            lastHits = hits;

            // Clamp restored page numbers to the real range
            if (currentPage > totalPages()) currentPage = totalPages();

            setStatus(hits.length + " match" + (hits.length === 1 ? "" : "es"));
            updateUrl(false);
            renderPage();
        });
    }

    // Draw the current page of results plus the pager. Re-slices the
    // in-memory hit list - no re-search, so paging is instant.
    function renderPage() {
        if (!lastHits) { renderSkeleton(); return; }

        const pages = totalPages();
        const start = (currentPage - 1) * RESULTS_PER_PAGE;
        const slice = lastHits.slice(start, start + RESULTS_PER_PAGE);

        results.innerHTML =
            slice.map((h) => renderRow(h.item)).join("") +
            renderPager(pages);
    }

    // Pager in the same idiom as the bookmark-pagination shortcode:
    // paginate-container > pagination, with previous/next, windowed page
    // links and &hellip; gaps. Links are anchored, but clicks are intercepted
    // above (data-page) so no navigation happens.
    function renderPager(pages) {
        if (pages < 2) return "";

        const items = [];

        items.push(currentPage > 1
            ? '<a class="previous_page" data-page="' + (currentPage - 1) + '" href="?q=' +
            encodeURIComponent(currentQuery) + '&page=' + (currentPage - 1) +
            '" rel="prev">Previous</a>'
            : '<span class="previous_page disabled">Previous</span>');

        // Windowed page numbers with gaps, like Hugo's pagination template
        const visible = [];
        const lo = Math.max(1, currentPage - PAGER_WINDOW);
        const hi = Math.min(pages, currentPage + PAGER_WINDOW);

        // Always include first and last page, with gaps between when needed
        const add = (p) => { if (visible.indexOf(p) === -1) visible.push(p); };
        add(1);
        for (let p = lo; p <= hi; p++) add(p);
        add(pages);
        visible.sort((a, b) => a - b);

        let prev = 0;
        for (const pp of visible) {
            if (pp - prev > 1) items.push('<span class="gap">&hellip;</span>');
            items.push(pp === currentPage
                ? '<em class="current">' + pp + "</em>"
                : '<a data-page="' + pp + '" href="?q=' + encodeURIComponent(currentQuery) +
                '&page=' + pp + '">' + pp + "</a>");
            prev = pp;
        }

        items.push(currentPage < pages
            ? '<a class="next_page" data-page="' + (currentPage + 1) + '" href="?q=' +
            encodeURIComponent(currentQuery) + '&page=' + (currentPage + 1) +
            '" rel="next">Next</a>'
            : '<span class="next_page disabled">Next</span>');

        return '<div class="paginate-container mt-3"><div class="pagination">' +
            items.join("") + "</div></div>";
    }

    // Idle-state content: hint line + static ghost cards previewing the
    // result shape. colour adapts to light/dark via the theme token.
    function renderSkeleton() {
        setStatus("Type at least two characters to search your bookmarks.");
        let rows = "";
        for (let i = 0; i < SKELETON_ROWS; i++) {
            rows +=
                '<div class="Box-row">' +
                '<article class="d-flex flex-column flex-md-row">' +
                '<div class="mr-md-3 mb-2 mb-md-0" style="flex-shrink: 0;">' +
                '<div class="rounded-2 color-bg-subtle" ' +
                'style="width: 140px; height: 74px;"></div>' +
                "</div>" +
                '<div class="flex-auto">' +
                // Title bar: intentionally shorter than the text widths
                '<div class="rounded-1 color-bg-subtle mb-2" style="height: 20px; width: 55%;"></div>' +
                // Meta line
                '<div class="rounded-1 color-bg-subtle mb-3" style="height: 12px; width: 25%;"></div>' +
                // Excerpt block
                '<div class="rounded-1 color-bg-subtle mb-2" style="height: 12px; width: 90%;"></div>' +
                '<div class="rounded-1 color-bg-subtle mb-3" style="height: 12px; width: 75%;"></div>' +
                // Tag pills
                '<div class="d-flex flex-wrap">' +
                '<div class="rounded-2 color-bg-subtle mr-1 mb-1" style="height: 22px; width: 46px;"></div>' +
                '<div class="rounded-2 color-bg-subtle mr-1 mb-1" style="height: 22px; width: 62px;"></div>' +
                '<div class="rounded-2 color-bg-subtle mr-1 mb-1" style="height: 22px; width: 52px;"></div>' +
                "</div>" +
                "</div>" +
                "</article>" +
                "</div>";
        }
        results.innerHTML = rows;
    }

    // Lower Fuse score = more relevant, so sort ascending; date strings are
    // ISO (YYYY-MM-DD) so lexicographic compare equals chronological compare.
    // Undated records ("") sort last within their score band.
    function rankHits(a, b) {
        if (a.score !== b.score) return a.score - b.score;
        const da = a.item.date || "";
        const db = b.item.date || "";
        if (da === db) return 0;
        return da < db ? 1 : -1;
    }

    // Renders exactly the markup emitted by bookmark-card.html
    function renderRow(b) {
        const img = b.image || PLACEHOLDER;

        let meta = "";
        if (b.date) {
            meta =
                '<a href="/bookmarks/years/' + escapeHtml(b.date.slice(0, 4)) + '/" class="color-fg-muted">' +
                "<time datetime=\"" + escapeHtml(b.date) + "\">Saved on " + escapeHtml(b.date) + "</time>" +
                "</a>" +
                '<span class="mx-2">&middot;</span>';
        }

        // tagSlugs (index-aligned) comes from the generator, which resolves
        // slug collisions; slugify() is the fallback for older indexes
        const tags = b.tags.map((t, i) =>
            '<a href="/bookmarks/tags/' +
            encodeURIComponent((b.tagSlugs && b.tagSlugs[i]) || slugify(t)) +
            '/" class="Label Label--secondary mr-1 mb-1">' + escapeHtml(t) + "</a>"
        ).join("");

        return (
            '<div class="Box-row">' +
            '<article class="d-flex flex-column flex-md-row">' +
            '<div class="mr-md-3 mb-2 mb-md-0" style="flex-shrink: 0;">' +
            '<a href="' + escapeHtml(b.link) + '" target="_blank" rel="noopener noreferrer">' +
            '<img src="' + escapeHtml(img) + '" alt="' + escapeHtml(b.title) +
            '" loading="lazy" class="rounded-2 post-list-image bookmark-card__image">' +
            "</a>" +
            "</div>" +
            '<div class="flex-auto">' +
            '<h2 class="f3 lh-condensed mb-1">' +
            '<a href="' + escapeHtml(b.link) + '" class="Link--primary" target="_blank" rel="noopener noreferrer">' +
            escapeHtml(b.title) +
            "</a>" +
            "</h2>" +
            '<div class="d-flex flex-items-center color-fg-muted f6 mb-2">' +
            meta +
            "<span>" + escapeHtml(b.domain) + "</span>" +
            "</div>" +
            (b.excerpt
                ? '<p class="color-fg-muted mb-2">' + escapeHtml(b.excerpt) + "</p>"
                : "") +
            (tags ? '<div class="d-flex flex-wrap">' + tags + "</div>" : "") +
            "</div>" +
            "</article>" +
            "</div>"
        );
    }

    // Must stay in lockstep with slugify() in generate_bookmarks.py
    function slugify(s) {
        return String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
    }

    function escapeHtml(s) {
        return String(s || "").replace(/[&<>"']/g, (c) =>
            ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c])
        );
    }

    // Restore from a shared URL if present, else render the idle state and
    // put the cursor in the search box so the page is ready to type in.
    // Desktop only: focusing an input on load pops the virtual keyboard on
    // touch devices, so we check for a fine (mouse/trackpad) pointer first.
    // Focus is deliberately skipped for restored loads so a shared link
    // doesn't tempt the visitor into overwriting the prefilled query.
    if (!restoreFromUrl()) {
        renderSkeleton();
        if (window.matchMedia("(pointer: fine)").matches) {
            input.focus();
        }
    }
})();
```

# Enhancements{#enhancements}

Beyond the basic substring matching I started with, the implementation gained fuzzy search, pagination, shareable URLs and skeleton rows. The notable behaviours are covered below.

## Adding fuzzy search

My first pass did a plain lowercase substring scan across title, domain, excerpt and tags:

```javascript
function search() {
    var q = input.value.trim().toLowerCase();
    if (q.length < 2) { results.innerHTML = ""; setStatus(""); return; }
    loadIndex(function () {
        var hits = index.filter(function (b) {
            var hay = (b.title + " " + b.domain + " " + b.excerpt + " " +
                b.tags.join(" ")).toLowerCase();
            return hay.indexOf(q) !== -1;
        });
        setStatus(hits.length + " match" + (hits.length === 1 ? "" : "es"));
        results.innerHTML = hits.slice(0, 50).map(renderRow).join("");
    });
}
```

That works, but it's brittle - one typo, and you get zero results. I replaced it with [Fuse.js](https://www.fusejs.io/) fuzzy matching, which tolerates typos and ranks matches. At first I loaded it from a CDN, using the UMD-style `fuse.min.js` build because the script expected the classic `Fuse` global:

```html
<script src="https://cdn.jsdelivr.net/npm/fuse.js/dist/fuse.min.js"></script>
```

That URL isn't pinned to a version, so the search could change or break whenever a new Fuse release came out, and every visit to the search page depended on a third-party host. I later moved to a pinned copy of Fuse's ES module build, committed as `assets/js/vendor/fuse-7.5.0.min.mjs`, and import it at the top of the search script:

```javascript
// Bundled with Fuse by Hugo's js.Build (see layouts/baseof.html). The
// "/*!" comment below is a legal comment esbuild keeps in the minified
// bundle, since the vendored file's own licence header gets stripped.
/*! Includes Fuse.js v7.5.0 (https://fusejs.io) | (c) Kiro Risk | Apache License 2.0 */
import Fuse from "./vendor/fuse-7.5.0.min.mjs";
```

Hugo bundles the two into a single file (see [JavaScript minification](#javascript-minification)), so the page loads one script from the blog itself. That also suits the site's Content-Security-Policy, which only allows scripts from the blog and its two analytics services - a CDN script tag would now be reported as a violation. Upgrading Fuse means replacing the vendored file and updating the import and licence comment.

The `FUSE_OPTIONS` in the full script above are what determines [how the search is performed](https://www.fusejs.io/fuzzy-search.html#controlling-fuzziness):

```javascript
    const FUSE_OPTIONS = {
        keys: [
            { name: "title", weight: 0.45 },
            { name: "tags", weight: 0.25 },
            { name: "domain", weight: 0.15 },
            { name: "excerpt", weight: 0.15 }
        ],
        threshold: 0.4,            // 0 = exact, 1 = matches anything; lower = stricter
        ignoreLocation: true,      // don't penalise matches late in long excerpts
        minMatchCharLength: 2,     // ignore 1-char noise
        includeScore: true         // required for the rankHits tie-break below
    };
```

* `threshold`: 0.4 is a reasonable starting point; if searches feel too loose (irrelevant results creeping in for short queries), drop it to 0.3. If legit typos aren't matching, nudge up to 0.45.
* `ignoreLocation`: matters specifically for this data - without it, Fuse penalises matches deep in long excerpts, and excerpts run to 160 chars.
* keys weights bias matches toward titles and tags over body text, which matches how people actually search bookmarks ("that AWS article", "kubernetes").

## Pagination

![Search pagination](search-pagination.png#center)

The old substring implementation capped results at 50 hits and silently dropped the rest. Pagination means all hits are reachable, which is how the listing pages behave:

* Ranked hits are cached in `lastHits`, so clicking through pages just re-slices and re-renders. Fuse never runs again.
* The pager mirrors the bookmark-pagination shortcode: `paginate-container > pagination`, with `previous_page/next_page`, `<em class="current">` for the active page, `&hellip;` gaps, and a windowed middle range with first and last always shown.
* One click listener on the container parses `data-page` attributes, so re-rendered pagers never need rebinding. The links carry real `href`s so they're keyboard-focusable and middle-clickable, but the handler intercepts left-clicks and prevents navigation.
* After a page change, the viewport jumps back to the input, mimicking what a real listing-page reload does, so the user isn't stranded below the fold.

## Shareable URLs

![Shareable URLs](shareable-urls.png#center)

I wanted some way for visitors to be able to share links to a search result with a specific page number - e.g. `?q=kubernetes&page=3` - that works when pasted into a chat or opened in a new tab.

The address bar stays in sync on every state change. Clearing the search strips the query string back to the bare page URL - no stale `?q=` lingering after an empty box - and since Fuse debounces at 150 ms and `replaceState` is cheap, the bar always reflects what's rendered. Page numbers are only appended above page 1, and invalid or out-of-range pages get clamped to the real hit range, so `?q=ai&page=99` lands on the last page rather than nothing.

History behaviour splits along one deliberate line: deliberate navigation enters history, transient typing doesn't.

* Typed searches use `replaceState`, so intermediate keystrokes never pile up as history entries.
* Pager clicks use `pushState`, so each hop from page 1 → 2 → 3 is its own entry, and Back walks down the pages one step at a time before leaving the search page entirely.
* Shared deep links seed the stack: `restoreFromUrl()` rewrites the current entry to the page-1 URL, then pushes the deep page on top - so Back from a deep link reaches page 1 of the results rather than exiting the site immediately.
* The `popstate` listener renders whatever the URL says: re-slicing cached hits if only the page changed, or clearing back to the skeleton if the query is gone.

## Skeleton rows

When the page first loads it's not obvious what the page is for, so skeleton rows illustrate dummy search results without listing any data. This is handled by `renderSkeleton()`, which concatenates a block of static HTML five times over before rendering it to the page - no animation, just ghost cards that adapt to light/dark via theme tokens:

![Skeleton rows](skeleton-rows.png#center)

The same handler also renders the skeleton whenever the input drops below two characters, so the page settles back to its idle state.

## Desktop-only autofocus

Programmatic focus on page load pops the virtual keyboard immediately on phones, which can be annoying. Therefore, focus is gated behind a pointer check so desktop gets autofocus and mobile waits for a tap:

```javascript
if (!restoreFromUrl()) {
  renderSkeleton();
  if (window.matchMedia("(pointer: fine)").matches) {
    input.focus();
  }
}
```

Focus is deliberately skipped for restored loads as well, so a shared link doesn't tempt the visitor into overwriting the prefilled query.

## JavaScript minification{#javascript-minification}

Rather than shipping the search script raw, it goes through Hugo's asset pipeline in `/layouts/baseof.html`. Hugo's built-in esbuild (`js.Build`) follows the `import`, bundles Fuse and the search script into one minified file, and `fingerprint` gives it a content-hashed filename and a Subresource Integrity hash. It's only included on the search page itself:

```html
{{- if eq .RelPermalink "/bookmarks/search/" }}
{{- $bookmarkSearchJs := resources.Get "js/bookmark-search.js" | js.Build (dict "minify" true "targetPath" "js/bookmark-search.min.js") | fingerprint -}}
<script src="{{ $bookmarkSearchJs.RelPermalink }}" integrity="{{ $bookmarkSearchJs.Data.Integrity }}"></script>
{{- end }}
```

The output is an ordinary script rather than a module, so the page doesn't need `type="module"`. Because the filename changes whenever the contents do, browsers can cache it for a year without ever running a stale copy.

# Troubleshooting{#troubleshooting}

The biggest gotcha wasn't the JavaScript - it was the generator - `main()` wipes `content/bookmarks/` on every run:

```python
if not args.keep_output and output_dir.exists():
    shutil.rmtree(output_dir)
```

So a hand-committed search page gets deleted by the next CI generation.

The fix was for the generator to own the search page itself, via a `write_search_page()` function gated behind the same `--no-search` flag as the JSON index:

```python
SEARCH_PAGE_MARKUP = """---
title: Search bookmarks
description: Search all bookmarks by keyword
layout: single
hideReadingTime: true
rssIgnore: true
---

<input type="search" id="bookmark-search" class="form-control" placeholder="Search bookmarks..." autocomplete="off">
<p id="search-status" class="color-fg-muted f6 mt-2"></p>
<div id="search-results" class="Box mt-3"></div>
"""
```

Note the page is a leaf bundle (`index.md`, not `_index.md`) so Hugo renders it at `/bookmarks/search/`:

```python
def write_search_page(output_dir):
    """
    Write the client-side search page at /bookmarks/search/.

    This must live IN the generated tree because main() wipes --output-dir
    every run — a hand-committed content/bookmarks/search/index.md would
    be deleted on the next generation. The markup is static, so output is
    deterministic.
    """
    search_dir = output_dir / "search"
    search_dir.mkdir(parents=True, exist_ok=True)
    path = search_dir / "index.md"       # leaf bundle — NOT _index.md
    path.write_text(SEARCH_PAGE_MARKUP, encoding="utf-8", newline="\n")
    logger.info("Wrote search page %s", path)
```

And the call in `def main()`:

```python
    # Client-side search page + JSON index (optional)
    search_entries = 0
    if not args.no_search:
        write_search_page(output_dir)
        search_entries = write_search_index(records, record_image, args, tag_slugs)
```

Wiping a directory on every run is risky in its own right: a mistyped `--output-dir content` would delete every hand-written post. So the generator also writes a `.generated-by-generate_bookmarks` marker file into the directory, and refuses to delete one that isn't empty and doesn't have the marker:

```python
def check_output_dir(output_dir: Path) -> None:
    """
    Refuse to use an output directory this script didn't create.

    main() deletes --output-dir before regenerating, so it must only ever
    point at generated content. Missing and empty directories are fine;
    otherwise the GENERATED_MARKER file must be present. Applies with
    --keep-output too, since that run writes the marker and would make
    the directory wipeable by the next normal run.
    """
    if not output_dir.exists():
        return
    if not output_dir.is_dir():
        raise SystemExit(f"Refusing to use --output-dir {output_dir}: not a directory")
    if (output_dir / GENERATED_MARKER).is_file() or not any(output_dir.iterdir()):
        return
    raise SystemExit(
        f"Refusing to use --output-dir {output_dir}: it isn't empty and wasn't "
        f"created by this script (no {GENERATED_MARKER} file), and it would be "
        f"deleted. Check the path; if it really is old generated output, "
        f"delete it yourself and re-run.")
```

`main()` calls it before doing anything else, including connecting to AWS, so a bad path fails straight away.

# Wrapping up{#wrapping-up}

With the JSON index, the search page and the script in place, the bookmarks section now supports [full-text search](/bookmarks/search) with fuzzy matching, instant pagination and shareable deep-linked results - all client-side, with no database and no runtime cost beyond one lazily-loaded, compressed JSON file.

Everything the feature needs lives in the generator: the index and the page are regenerated on every CI run, so search stays in step with the bookmarks themselves. The remaining tuning surface is small - Fuse's threshold and the key weights - and can be adjusted whenever search results feel too loose or too strict.

