From 07a83b2e3db40f4a380092d6566500799b340dcd Mon Sep 17 00:00:00 2001 From: Martin Kagamino Lehoux Date: Fri, 21 Aug 2026 16:13:12 +0200 Subject: feat: fuzzy autocomplete for add-item input Replace the native with a custom fuzzysort-driven component (FuzzyAutocomplete) with keyboard nav and highlighted matches, preserving exact-match auto-add. Extract a unit-tested fuzzy-search helper, and gitignore .juggler/. Fix the dev DB boot failure caused by a sibling project's ambient DATABASE_URL leaking in by overriding it (file:./data.db) in mise.toml. --- src/lib/components/FuzzyAutocomplete.svelte | 159 ++++++++++++++++++++++++++++ src/lib/components/fuzzy-search.test.ts | 53 ++++++++++ src/lib/components/fuzzy-search.ts | 25 +++++ src/routes/+page.svelte | 51 ++------- 4 files changed, 243 insertions(+), 45 deletions(-) create mode 100644 src/lib/components/FuzzyAutocomplete.svelte create mode 100644 src/lib/components/fuzzy-search.test.ts create mode 100644 src/lib/components/fuzzy-search.ts (limited to 'src') diff --git a/src/lib/components/FuzzyAutocomplete.svelte b/src/lib/components/FuzzyAutocomplete.svelte new file mode 100644 index 0000000..f5bef94 --- /dev/null +++ b/src/lib/components/FuzzyAutocomplete.svelte @@ -0,0 +1,159 @@ + + +
+ { + open = true; + }} + onkeydown={onKeydown} + onfocus={() => { + open = true; + }} + onblur={() => { + // hide after a tick so click on an option still registers + setTimeout(() => { + open = false; + }, 150); + }} + /> + {#if open && results.length > 0} + + {/if} +
+ + diff --git a/src/lib/components/fuzzy-search.test.ts b/src/lib/components/fuzzy-search.test.ts new file mode 100644 index 0000000..57d0d1d --- /dev/null +++ b/src/lib/components/fuzzy-search.test.ts @@ -0,0 +1,53 @@ +import { describe, it, expect } from 'vitest'; +import { matchItems, FUZZ_LIMIT } from './fuzzy-search'; +import type { FuzzyItem } from './fuzzy-search'; + +const catalog: FuzzyItem[] = [ + { id: 1, name: 'Citron' }, + { id: 2, name: 'Citrons' }, + { id: 3, name: 'Concombre' }, + { id: 4, name: 'Tomate' }, + { id: 5, name: 'Carotte' }, + { id: 6, name: 'Lait' }, +]; + +describe('matchItems', () => { + it('returns nothing for an empty or whitespace query', () => { + expect(matchItems(catalog, '')).toHaveLength(0); + expect(matchItems(catalog, ' ')).toHaveLength(0); + }); + + it('matches a fuzzy query, ranking the best match first', () => { + const res = matchItems(catalog, 'citrn'); + expect(res.length).toBeGreaterThanOrEqual(1); + // exact-ish run should beat the pluralised variant + expect(res[0].obj.name).toBe('Citron'); + }); + + it('is case-insensitive', () => { + const res = matchItems(catalog, 'TOMA'); + expect(res[0].obj.name).toBe('Tomate'); + }); + + it('keeps matched-across-junk subsequence results', () => { + const res = matchItems(catalog, 'cb'); // C-o-n-**c**ombre → c arguments + const names = res.map((r) => r.obj.name); + expect(names).toContain('Concombre'); + }); + + it('respects the limit', () => { + const many = Array.from({ length: 40 }, (_, i) => ({ + id: i, + name: `Article ${i}`, + })); + const res = matchItems(many, 'article'); + expect(res.length).toBeLessThanOrEqual(FUZZ_LIMIT); + }); + + it('sorts best matches first by descending score', () => { + const res = matchItems(catalog, 'tomate'); + for (let i = 1; i < res.length; i++) { + expect(res[i - 1].score).toBeGreaterThanOrEqual(res[i].score); + } + }); +}); diff --git a/src/lib/components/fuzzy-search.ts b/src/lib/components/fuzzy-search.ts new file mode 100644 index 0000000..31597b0 --- /dev/null +++ b/src/lib/components/fuzzy-search.ts @@ -0,0 +1,25 @@ +import fuzzysort, { type KeyResult } from 'fuzzysort'; + +export type FuzzyItem = { id: number; name: string }; + +export const FUZZ_LIMIT = 8; +export const FUZZ_THRESHOLD = 0.2; + +export type FuzzyMatch = KeyResult; + +/** Fuzzy-match `items` against `query`, ranked best-first. Empty/whitespace + * query returns no matches. Results carry `.score`, `.target`, `.highlight()` + * and `.obj` (the matched item). */ +export function matchItems( + items: FuzzyItem[], + query: string, + { + limit = FUZZ_LIMIT, + threshold = FUZZ_THRESHOLD, + }: { limit?: number; threshold?: number } = {}, +): FuzzyMatch[] { + const q = query.trim(); + if (q === '') return []; + const snap = fuzzysort.snapshot(items, { key: 'name' }); + return Array.from(fuzzysort.go(q, snap, { limit, threshold })); +} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 9900bb3..66380a4 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -2,10 +2,10 @@ import { deserialize } from '$app/forms'; import { goto } from '$app/navigation'; import { enhance } from '$app/forms'; + import FuzzyAutocomplete from '$lib/components/FuzzyAutocomplete.svelte'; let { data, form } = $props(); let name = $state(''); - let inputRef: HTMLInputElement; // eslint-disable-next-line svelte/prefer-writable-derived let localItems = $state([]); let addError = $state(''); @@ -41,7 +41,6 @@ const action = redirectToEdit ? '?/addAndEdit' : '?/add'; name = ''; - inputRef.focus(); try { const response = await fetch(action, { @@ -79,48 +78,15 @@
- { - if (e.key === 'Enter') { - e.preventDefault(); - handleAdd(false); - } - }} - oninput={(e) => { - if ((e as InputEvent).inputType === 'insertReplacementText') { - const val = e.currentTarget.value.trim().toLowerCase(); - const match = data.catalog.find( - (item) => item.name.toLowerCase() === val, - ); - if (match) { - name = match.name; - handleAdd(false); - } - } - }} - onchange={(e) => { - const val = e.currentTarget.value.trim().toLowerCase(); - const match = data.catalog.find( - (item) => item.name.toLowerCase() === val, - ); - if (match) { - name = match.name; - handleAdd(false); - } + onselect={(item) => { + name = item.name; + handleAdd(false); }} /> - - {#each data.catalog as item (item.id)} - - {/each} - @@ -187,11 +153,6 @@ z-index: 10; } - .add-bar input { - flex: 1; - background: var(--surface); - } - .add-bar button { width: 3rem; height: 3rem; -- cgit v1.3