Search

A filter form that swaps the results as the visitor types, and still works as a plain GET form.

Updated

A search box that updates a list while the visitor types. The form is a real GET form, so without JavaScript it submits to the page and the page renders the matching results. With HTMX it requests the :results fragment of the page instead and swaps only the results.

There is no live example here, since the results come from the page's own data. The code is what a page with a list of people would hold.

<form
	method="get"
	action="{$page->url()}"
	hx-get="{$page->url()}:results"
	hx-trigger="input delay:300ms, submit"
	hx-sync="this:replace"
	hx-indicator="#results"
	hx-swap="none"
>
	{ui input,
		type: 'search',
		name: 'q',
		value: $q,
		placeholder: 'Search people',
		attrs: ['aria-label' => 'Search people'],
	/}
</form>

{fragment 'results'}
	{ui list,
		items: $people,
		attrs: ['id' => 'results'],
	/}
{/fragment}

input delay:300ms waits until the visitor pauses typing, and submit covers Enter. hx-sync="this:replace" cancels a request that is still loading when a newer one starts, so a slow answer never lands on top of a newer one. hx-swap="none" leaves the placement to the fragment, which swaps the whole list (outerHTML), so its id is in attrs.

hx-indicator="#results" puts .htmx-request on the list while it loads, and the list, table and card dim while they carry it. The target must be one of those elements, not a plain wrapper around them.

Do not add changed to the trigger. On a form it compares the form's own value, which never changes, so the request would never fire. input only fires when the value is edited, so it is not needed.

use Phlat\App;
use Phlat\Page;
use Phlat\Toolkit\San;
use Phlat\Toolkit\Str;

return function (App $app, Page $page): array {
	$q = Str::trim(Str::replace(San::text($app->request->query('q') ?? ''), ',', ' '));

	return [
		'q' => $q,
		'people' => $q === '' ? $page->children() : $page->children("search={$q},partial=true"),
	];
};

The view's controller reads q and puts it into a search= condition. A search term is split into words and each is matched safely, but the query syntax separates conditions with commas and has no way to escape one, so a,limit=9999 would add a limit condition and a,b would throw. The controller turns commas into spaces before the term reaches the query. partial=true matches the start of a word, so ann finds Anna while the visitor is still typing.

The typed term lives in the fragment's request URL, not the page URL, so a reload starts empty. A sort header or a load more button that sits beside the search carries q in its own href, so the three stay in step.

To filter rows that are already on the page, with no request, use data-filter on the control instead. Server search is for sets too large to render at once.