feat: search the items on a shopping list (#8275)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
PulfordJandClaude Opus 5 authored and GitHub committed 2026-09-25 17:17:11 +00:00
1 parent 8399b0f2b5
commit 552ad0b3e9
4 files changed
+435 -51

No files matched your search

@@ -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> = {}): 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);
});
});
@@ -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<ShoppingListItemOut[]> | ComputedRef<ShoppingListItemOut[]>,
) {
/**
* 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<ISearchableItem[]>(() =>
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,
};
}
@@ -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,
+112 -51
View File
@@ -84,9 +84,18 @@
{{ shoppingList.name }}
</h2>
<v-spacer />
<!-- The search toggle stays while the field is open, so a list that shrinks to the
threshold mid-search can still close it. "Check all" would also check items the
search is hiding, so it is disabled while searching. -->
<BaseButtonGroup
class="d-flex"
:buttons="[
...(canSearch || isSearchOpen ? [{
icon: $globals.icons.search,
text: $t('search.search'),
event: 'search',
color: isSearchOpen ? 'primary' : undefined,
}] : []),
{
icon: $globals.icons.contentCopy,
text: '',
@@ -108,6 +117,7 @@
icon: $globals.icons.checkboxMultipleMarkedOutline,
text: $t('shopping-list.check-all-items'),
event: 'check',
disabled: isSearching,
},
{
icon: $globals.icons.dotsVertical,
@@ -127,6 +137,7 @@
],
},
]"
@search="toggleSearch"
@edit="edit = true"
@three-dot="threeDot = true"
@check="openCheckAll"
@@ -153,6 +164,23 @@
v-if="!edit"
class="py-2 d-flex flex-column ga-1 shopping-list-view"
>
<!-- Search, toggled from the page title -->
<v-text-field
v-if="isSearchOpen"
:model-value="search"
:label="$t('search.search')"
:prepend-inner-icon="$globals.icons.search"
autofocus
clearable
hide-details
density="compact"
variant="solo"
flat
single-line
@update:model-value="value => search = value ?? ''"
@click:clear="clearSearch"
/>
<!-- Create Item -->
<ShoppingListAddItemForm
v-if="$vuetify.display.smAndDown"
@@ -189,75 +217,82 @@
</div>
<TransitionGroup name="scroll-x-transition">
<BaseExpansionPanels v-for="(value, key) in itemsByLabel" :key="key" :v-model="0" start-open>
<v-expansion-panel class="shopping-list-section">
<!-- the label colour fills the header bar; an uncoloured (or unlabelled) header is muted instead -->
<v-expansion-panel-title
:color="getLabelColor(key)"
class="body-1 section-title"
:class="getLabelColor(key) ? '' : 'text-medium-emphasis'"
>
{{ key }}
</v-expansion-panel-title>
<v-expansion-panel-text eager>
<VueDraggable
:model-value="value"
handle=".handle"
:delay="250"
:delay-on-touch-only="true"
@start="loadingCounter += 1"
@end="loadingCounter -= 1"
@update:model-value="updateIndexUncheckedByLabel(key.toString(), $event)"
<template v-for="(value, key) in itemsByLabel" :key="key">
<BaseExpansionPanels v-if="hasMatches(value)" :v-model="0" start-open>
<v-expansion-panel class="shopping-list-section">
<!-- the label colour fills the header bar; an uncoloured (or unlabelled) header is muted instead -->
<v-expansion-panel-title
:color="getLabelColor(key)"
class="body-1 section-title"
:class="getLabelColor(key) ? '' : 'text-medium-emphasis'"
>
<TransitionGroup name="scroll-x-transition">
<ShoppingListItem
v-for="(item, index) in value"
:key="item.id"
v-model="value[index]"
class="my-2 w-auto shopping-list-item-row"
:edit="editingItem === item.id"
:labels="allLabels || []"
:units="allUnits || []"
:foods="allFoods || []"
:recipes="recipeMap"
@checked="(item) => {
saveListItem(item);
itemCheckedToast(item);
}"
@save="(item) => {
editingItem = undefined;
saveListItem(item);
}"
@delete="deleteListItem(item)"
@view="editingItem = undefined"
@edit="editingItem = item.id"
/>
</TransitionGroup>
</VueDraggable>
</v-expansion-panel-text>
</v-expansion-panel>
</BaseExpansionPanels>
{{ key }}
</v-expansion-panel-title>
<v-expansion-panel-text eager>
<VueDraggable
:model-value="value"
handle=".handle"
:delay="250"
:delay-on-touch-only="true"
:disabled="isSearching"
@start="loadingCounter += 1"
@end="loadingCounter -= 1"
@update:model-value="updateIndexUncheckedByLabel(key.toString(), $event)"
>
<TransitionGroup name="scroll-x-transition">
<template v-for="(item, index) in value" :key="item.id">
<ShoppingListItem
v-if="matchesSearch(item)"
v-model="value[index]"
class="my-2 w-auto shopping-list-item-row"
:edit="editingItem === item.id"
:labels="allLabels || []"
:units="allUnits || []"
:foods="allFoods || []"
:recipes="recipeMap"
@checked="(item) => {
saveListItem(item);
itemCheckedToast(item);
}"
@save="(item) => {
editingItem = undefined;
saveListItem(item);
}"
@delete="deleteListItem(item)"
@view="editingItem = undefined"
@edit="editingItem = item.id"
/>
</template>
</TransitionGroup>
</VueDraggable>
</v-expansion-panel-text>
</v-expansion-panel>
</BaseExpansionPanels>
</template>
</TransitionGroup>
<!-- Checked Items -->
<v-expansion-panels flat rounded>
<v-expansion-panel v-if="listItems.checked && listItems.checked.length > 0">
<v-expansion-panels v-model="checkedPanel" flat rounded>
<v-expansion-panel v-if="listItems.checked && hasMatches(listItems.checked)">
<v-expansion-panel-title class="border-solid border-thin py-1">
<div class="d-flex align-center flex-0-1-100">
<div class="flex-1-0">
{{ $t('shopping-list.items-checked-count', listItems.checked ? listItems.checked.length : 0) }}
{{ $t('shopping-list.items-checked-count', visibleCheckedCount) }}
</div>
<div class="justify-end">
<!-- both act on every checked item, including any the search is hiding -->
<BaseButtonGroup
:buttons="[
{
icon: $globals.icons.checkboxMultipleBlankOutline,
text: $t('shopping-list.uncheck-all-items'),
event: 'uncheck',
disabled: isSearching,
},
{
icon: $globals.icons.delete,
text: $t('shopping-list.delete-checked'),
event: 'delete',
disabled: isSearching,
},
]"
@uncheck="openUncheckAll"
@@ -268,7 +303,7 @@
</v-expansion-panel-title>
<v-expansion-panel-text eager>
<TransitionGroup name="scroll-x-transition">
<div v-for="(item, idx) in listItems.checked" :key="item.id">
<div v-for="(item, idx) in listItems.checked" v-show="matchesSearch(item)" :key="item.id">
<ShoppingListItem
v-model="listItems.checked[idx]"
class="strike-through-note shopping-list-item-row"
@@ -284,6 +319,15 @@
</v-expansion-panel-text>
</v-expansion-panel>
</v-expansion-panels>
<v-alert
v-if="!hasSearchResults"
type="info"
variant="tonal"
density="compact"
>
{{ $t('search.no-results') }}
</v-alert>
</section>
<!-- Recipe References -->
@@ -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<number | undefined>(undefined);
watch(isSearching, (searching) => {
checkedPanel.value = searching ? 0 : undefined;
});
</script>
<style>