From 552ad0b3e9bbc8f86fde57ef1f46cf4fd1e072e7 Mon Sep 17 00:00:00 2001 From: PulfordJ Date: Fri, 25 Sep 2026 17:17:11 +0000 Subject: [PATCH] feat: search the items on a shopping list (#8275) Co-authored-by: Claude Opus 5 --- .../use-shopping-list-search.test.ts | 184 ++++++++++++++++++ .../use-shopping-list-search.ts | 111 +++++++++++ .../use-shopping-list-page.ts | 28 +++ frontend/app/pages/shopping-lists/[id].vue | 163 +++++++++++----- 4 files changed, 435 insertions(+), 51 deletions(-) create mode 100644 frontend/app/composables/shopping-list-page/sub-composables/use-shopping-list-search.test.ts create mode 100644 frontend/app/composables/shopping-list-page/sub-composables/use-shopping-list-search.ts diff --git a/frontend/app/composables/shopping-list-page/sub-composables/use-shopping-list-search.test.ts b/frontend/app/composables/shopping-list-page/sub-composables/use-shopping-list-search.test.ts new file mode 100644 index 000000000..a7e22c838 --- /dev/null +++ b/frontend/app/composables/shopping-list-page/sub-composables/use-shopping-list-search.test.ts @@ -0,0 +1,184 @@ +import { ref } from "vue"; +import { describe, expect, test } from "vitest"; +import { SEARCH_MIN_LIST_SIZE, useShoppingListSearch } from "./use-shopping-list-search"; +import type { ShoppingListItemOut } from "~/lib/api/types/household"; + +function listItem(id: string, overrides: Partial = {}): ShoppingListItemOut { + return { + id, + shoppingListId: "list", + groupId: "group", + householdId: "household", + ...overrides, + } as ShoppingListItemOut; +} + +/** + * `matchesSearch` reads `debouncedSearch`, which is normally populated by a + * debounced watcher. Setting it directly keeps these tests synchronous, as in + * use-search.test.ts. + */ +function searchFor(items: ShoppingListItemOut[], query: string) { + const composable = useShoppingListSearch(ref(items)); + composable.debouncedSearch.value = query; + return composable; +} + +describe("useShoppingListSearch matching", () => { + test("an empty query matches every item and is not 'searching'", () => { + const items = [listItem("a", { note: "Kitchen roll" }), listItem("b", { note: "Bread" })]; + const { isSearching, matchesSearch, countMatches, hasMatches } = searchFor(items, ""); + + expect(isSearching.value).toBe(false); + expect(items.every(matchesSearch)).toBe(true); + expect(countMatches(items)).toBe(2); + expect(hasMatches(items)).toBe(true); + }); + + test("matches a note-only item by its note text", () => { + const items = [listItem("a", { note: "Kitchen roll" }), listItem("b", { note: "Bread" })]; + const { matchesSearch } = searchFor(items, "kitchen"); + + expect(items.filter(matchesSearch).map(i => i.id)).toEqual(["a"]); + }); + + test("matches a food-backed item by food name", () => { + const items = [ + listItem("a", { food: { id: "f1", name: "Avocado" } }), + listItem("b", { food: { id: "f2", name: "Bread" } }), + ]; + const { matchesSearch } = searchFor(items, "avocado"); + + expect(items.filter(matchesSearch).map(i => i.id)).toEqual(["a"]); + }); + + test("matches a food-backed item by its note as well as its food", () => { + const items = [ + listItem("a", { food: { id: "f1", name: "Avocado" }, note: "ripe ones" }), + listItem("b", { food: { id: "f2", name: "Bread" } }), + ]; + const { matchesSearch } = searchFor(items, "ripe"); + + expect(items.filter(matchesSearch).map(i => i.id)).toEqual(["a"]); + }); + + test("matches a food alias", () => { + const items = [ + listItem("a", { food: { id: "f1", name: "Aubergine", aliases: [{ name: "Eggplant" }] } }), + listItem("b", { food: { id: "f2", name: "Bread" } }), + ]; + const { matchesSearch } = searchFor(items, "eggplant"); + + expect(items.filter(matchesSearch).map(i => i.id)).toEqual(["a"]); + }); + + test("matches on label name, so searching an aisle narrows the list to it", () => { + const items = [ + listItem("a", { note: "Persil Non Bio", label: { name: "Laundry" } }), + listItem("b", { note: "Comfort Fresh", label: { name: "Laundry" } }), + listItem("c", { note: "Bread", label: { name: "Bakery" } }), + ]; + const { matchesSearch, countMatches } = searchFor(items, "laundry"); + + expect(items.filter(matchesSearch).map(i => i.id)).toEqual(["a", "b"]); + expect(countMatches(items)).toBe(2); + }); + + test("a query that matches nothing yields no matches", () => { + const items = [listItem("a", { note: "Kitchen roll" }), listItem("b", { note: "Bread" })]; + const { matchesSearch, countMatches, hasMatches } = searchFor(items, "zzzznope"); + + expect(items.some(matchesSearch)).toBe(false); + expect(countMatches(items)).toBe(0); + expect(hasMatches(items)).toBe(false); + }); + + test("clearSearch restores every item", () => { + const items = [listItem("a", { note: "Kitchen roll" }), listItem("b", { note: "Bread" })]; + const composable = searchFor(items, "bread"); + expect(composable.countMatches(items)).toBe(1); + + composable.clearSearch(); + expect(composable.isSearching.value).toBe(false); + expect(composable.countMatches(items)).toBe(2); + }); +}); + +describe("useShoppingListSearch fuzzy noise", () => { + test("does not match items that merely look similar to the query", () => { + // Grouping the list by label removes any notion of a weaker match sorting + // lower, so a fuzzy hit would read as a real one. These are the cases a + // fuzzy tier actually produced against a real list. + const items = [ + listItem("wash-liquid", { note: "Washing up liquid" }), + listItem("wash-gloves", { note: "Washing up gloves" }), + listItem("stash", { note: "Extra chocolate treat - secret surprise stash" }), + listItem("cash", { note: "Get cash out" }), + ]; + const { matchesSearch } = searchFor(items, "cash"); + + expect(items.filter(matchesSearch).map(i => i.id)).toEqual(["cash"]); + }); + + test("a query with no real match returns nothing rather than a near-miss", () => { + const items = [ + listItem("a", { note: "Twinings honey & camomile tea" }), + listItem("b", { note: "Toilet paper, family pack of 16" }), + ]; + const { matchesSearch, hasMatches } = searchFor(items, "milk"); + + expect(items.some(matchesSearch)).toBe(false); + expect(hasMatches(items)).toBe(false); + }); + + test("a multi-word query matches as a phrase, like every other search in the app", () => { + // useSearch matches the query as a single string rather than as independent + // terms, so word order matters. Kept as a test because it is the one + // behaviour that differs from a naive per-term matcher. + const items = [ + listItem("beans", { note: "Green beans, bags" }), + listItem("peppers", { note: "Green peppers" }), + ]; + + expect(items.filter(searchFor(items, "green bean").matchesSearch).map(i => i.id)) + .toEqual(["beans"]); + expect(items.filter(searchFor(items, "bean green").matchesSearch)) + .toEqual([]); + }); +}); + +describe("useShoppingListSearch toggle", () => { + const items = (count: number) => Array.from({ length: count }, (_, i) => listItem(`${i}`, { note: `Item ${i}` })); + + test(`is only offered once the list has more than ${SEARCH_MIN_LIST_SIZE} items`, () => { + const list = ref(items(SEARCH_MIN_LIST_SIZE)); + const { canSearch } = useShoppingListSearch(list); + expect(canSearch.value).toBe(false); + + list.value = items(SEARCH_MIN_LIST_SIZE + 1); + expect(canSearch.value).toBe(true); + }); + + test("starts closed and opens on toggle", () => { + const { isSearchOpen, toggleSearch } = useShoppingListSearch(ref(items(30))); + expect(isSearchOpen.value).toBe(false); + + toggleSearch(); + expect(isSearchOpen.value).toBe(true); + }); + + test("closing the field clears the query, so nothing stays hidden", () => { + const list = items(30); + const composable = useShoppingListSearch(ref(list)); + composable.toggleSearch(); + composable.search.value = "Item 1"; + composable.debouncedSearch.value = "Item 1"; + expect(composable.isSearching.value).toBe(true); + + composable.toggleSearch(); + expect(composable.isSearchOpen.value).toBe(false); + expect(composable.search.value).toBe(""); + expect(composable.isSearching.value).toBe(false); + expect(composable.countMatches(list)).toBe(30); + }); +}); diff --git a/frontend/app/composables/shopping-list-page/sub-composables/use-shopping-list-search.ts b/frontend/app/composables/shopping-list-page/sub-composables/use-shopping-list-search.ts new file mode 100644 index 000000000..14389f814 --- /dev/null +++ b/frontend/app/composables/shopping-list-page/sub-composables/use-shopping-list-search.ts @@ -0,0 +1,111 @@ +import type { ShoppingListItemOut } from "~/lib/api/types/household"; +import type { ISearchableItem } from "~/composables/use-search"; +import { useSearch } from "~/composables/use-search"; + +/** + * A list this size or smaller fits on a screen or two, where scrolling finds an + * item as quickly as searching would, so the search toggle is not offered. + */ +export const SEARCH_MIN_LIST_SIZE = 20; + +/** + * Composable for searching the items on a shopping list. + * + * Matching is delegated to `useSearch`, so the shopping list tolerates typos and + * ranks matches the same way every other search box in Mealie does. Only the + * *set* of matches is used and not its order: the list stays grouped by label in + * the user's aisle order, and non-matching items are hidden where they sit. + * + * This exposes a predicate rather than a filtered array because list items are + * rendered with `v-model` bound into their backing array, and `ShoppingListItem` + * replaces the whole item object when it is checked off. Rendering a filtered + * copy would write that update into a throwaway array and lose it. + */ +export function useShoppingListSearch( + listItems: Ref | ComputedRef, +) { + /** + * Adapt list items to `ISearchableItem`. An item is backed either by a food or + * by a free-text note, so both have to be searchable. Unit and label are + * matched on too -- searching a label is the quickest way to narrow a long + * list to a single aisle. + */ + const searchableItems = computed(() => + listItems.value.map(item => ({ + id: item.id, + name: item.food?.name ?? item.note ?? "", + pluralName: item.food?.pluralName ?? null, + abbreviation: item.unit?.abbreviation ?? null, + aliases: [ + ...(item.food?.aliases ?? []), + // A food-backed item can still carry a note ("ripe ones"), which the + // name above does not cover. + ...(item.food && item.note ? [{ name: item.note }] : []), + ...(item.unit?.name ? [{ name: item.unit.name }] : []), + ...(item.label?.name ? [{ name: item.label.name }] : []), + ], + })), + ); + + // `useSearch` ranks results and falls back to a fuzzy tier for typos, which is + // right for a dropdown where the best match sorts to the top and stray matches + // sit harmlessly at the bottom. This list is grouped by label and keeps the + // user's aisle order instead, so there is no "bottom" for a weak match to fall + // to: a fuzzy hit appears under its own aisle, indistinguishable from a real + // one. Measured against a 130-item list, the fuzzy tier turned "cash" into 11 + // matches (every "wash"/"washes"/"stash") and "milk" into 2 (camomile, family) + // while finding nothing the deterministic tiers missed. A zero threshold keeps + // Fuse from contributing those without touching the exact/prefix/word-prefix/ + // substring tiers, which do all the useful work here. + const { search, debouncedSearch, filtered, reset: clearSearch } = useSearch( + searchableItems, + { fuseOptions: { threshold: 0 } }, + ); + + const isSearching = computed(() => debouncedSearch.value.trim().length > 0); + + // The search field sits behind a toggle so it takes no room until it is + // wanted, and is only offered once the list is long enough to need it. + const isSearchOpen = ref(false); + const canSearch = computed(() => listItems.value.length > SEARCH_MIN_LIST_SIZE); + + // Closing the field also clears it, so a query nobody can see never leaves + // items hidden. + function toggleSearch() { + isSearchOpen.value = !isSearchOpen.value; + if (!isSearchOpen.value) { + clearSearch(); + } + } + + // `filtered` returns every item while the query is empty, so this holds the + // full set in that case and every item matches. + const matchedIds = computed(() => new Set(filtered.value.map(item => item.id))); + + function matchesSearch(item: ShoppingListItemOut): boolean { + return !isSearching.value || matchedIds.value.has(item.id); + } + + function countMatches(items: ShoppingListItemOut[]): number { + return isSearching.value ? items.filter(matchesSearch).length : items.length; + } + + function hasMatches(items: ShoppingListItemOut[]): boolean { + return isSearching.value ? items.some(matchesSearch) : items.length > 0; + } + + return { + search, + // Exposed for the same reason `useSearch` exposes it: it is what `filtered` + // actually reads, so tests can drive matching synchronously. + debouncedSearch, + isSearching, + isSearchOpen, + canSearch, + toggleSearch, + matchesSearch, + countMatches, + hasMatches, + clearSearch, + }; +} diff --git a/frontend/app/composables/shopping-list-page/use-shopping-list-page.ts b/frontend/app/composables/shopping-list-page/use-shopping-list-page.ts index bd1edc367..446dabb02 100644 --- a/frontend/app/composables/shopping-list-page/use-shopping-list-page.ts +++ b/frontend/app/composables/shopping-list-page/use-shopping-list-page.ts @@ -6,6 +6,7 @@ import { useShoppingListLabels } from "~/composables/shopping-list-page/sub-comp import { useShoppingListCopy } from "~/composables/shopping-list-page/sub-composables/use-shopping-list-copy"; import { useShoppingListCrud } from "~/composables/shopping-list-page/sub-composables/use-shopping-list-crud"; import { useShoppingListRecipes } from "~/composables/shopping-list-page/sub-composables/use-shopping-list-recipes"; +import { useShoppingListSearch } from "~/composables/shopping-list-page/sub-composables/use-shopping-list-search"; /** * Main composable that orchestrates all shopping list page functionality @@ -29,6 +30,28 @@ export function useShoppingListPage(listId: string) { // Track items organized by label const itemsByLabel = ref<{ [key: string]: ShoppingListItemOut[] }>({}); + // Initialize search over every item on the list, checked and unchecked alike, + // so a search can surface something that has already been checked off. + const searchManager = useShoppingListSearch( + computed(() => shoppingList.value?.listItems ?? []), + ); + const { isSearching, matchesSearch, countMatches } = searchManager; + + // Number of checked items currently visible, so the checked section can show + // how many of them the search matched rather than the total. + const visibleCheckedCount = computed(() => countMatches(listItems.checked)); + + // Whether the search matched anything at all, used to show an empty state. + const hasSearchResults = computed(() => { + if (!isSearching.value) { + return true; + } + return ( + Object.values(itemsByLabel.value).some(items => items.some(matchesSearch)) + || listItems.checked.some(matchesSearch) + ); + }); + function updateListItemOrder() { if (!shoppingList.value) return; @@ -166,6 +189,11 @@ export function useShoppingListPage(listId: string) { itemsByLabel, isOffline, + // Search + ...searchManager, + visibleCheckedCount, + hasSearchResults, + // Sub-composables ...state, ...labels, diff --git a/frontend/app/pages/shopping-lists/[id].vue b/frontend/app/pages/shopping-lists/[id].vue index 20caec75b..27e3b0c06 100644 --- a/frontend/app/pages/shopping-lists/[id].vue +++ b/frontend/app/pages/shopping-lists/[id].vue @@ -84,9 +84,18 @@ {{ shoppingList.name }} + + + + - - - - - {{ key }} - - - + + + + - - - - - - - + {{ key }} + + + + + + + + + + + - - + +
- {{ $t('shopping-list.items-checked-count', listItems.checked ? listItems.checked.length : 0) }} + {{ $t('shopping-list.items-checked-count', visibleCheckedCount) }}
+ -
+
+ + + {{ $t('search.no-results') }} + @@ -431,7 +475,24 @@ const { recipeList, removeRecipeReferenceToList, addRecipeReferenceToList, + search, + isSearching, + isSearchOpen, + canSearch, + toggleSearch, + matchesSearch, + hasMatches, + clearSearch, + visibleCheckedCount, + hasSearchResults, } = shoppingListPage; + +// Expand the checked section while searching, so an item that has already been +// checked off can be found and unchecked without expanding the section by hand. +const checkedPanel = ref(undefined); +watch(isSearching, (searching) => { + checkedPanel.value = searching ? 0 : undefined; +});