A command palette in forty lines

The post list already travels with every page, so filtering it in the browser needs no request and no library.

A search box that waits for the server spends a round trip on something the page already knows. Every page here carries the post list as one data attribute, so the palette filters in memory and opens instantly.

A dark placeholder card reading Palette

The data on the page

The server writes the list once, as JSON inside an attribute. The template escapes it, so quotes in a title cannot break the attribute or the page.

type palettePost struct {
	Title string `json:"title"`
	Desc  string `json:"desc,omitempty"`
	Slug  string `json:"slug"`
	Date  string `json:"date"`
}
<div id="search-palette" popover data-posts="{{postIndex}}">

Only the fields the list shows are included. The post body stays on the server, which keeps the page small as the archive grows.

A dark placeholder panel showing the palette open with two groups

The filter

Read the attribute once, lowercase the query, and match against the title and the description. Rows are built with createElement and textContent, never innerHTML, so a post title is text and cannot become markup.

function render(query) {
  var q = query.trim().toLowerCase();
  visible = [];
  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    if (q === '' || item.title.toLowerCase().indexOf(q) !== -1) {
      visible.push(item);
    }
  }
  drawRows(visible.slice(0, limit));
}

Matching is a substring test on purpose. Fuzzy matching sounds better and behaves worse on short lists, because it highlights letters the reader did not type.

Keyboard first

Key Action
Ctrl K / Cmd K Open or close the panel
Arrow Down / Arrow Up Move the highlight
Enter Open the highlighted row
Escape Close the panel

The highlight is one index, not a class on every row, so the code that moves it is short and the visual state cannot drift.

Without JavaScript

The panel is a form. Its input is named q, and its action is /blog, so pressing Enter with script off loads the server filtered list instead.

A feature that degrades to a working page is cheaper to trust than one that degrades to an apology.

What I would change

The palette shows twelve rows and stops. For an archive of hundreds of posts that is fine, because the reader is looking for something they already have in mind. If the site ever needed full text search, the shape would change: an index file, a fetch, and a real loading state, which is a bigger feature than this one.

Back to all posts