From b9091cd51b4fd67e7c131031c982a2957a400b2f Mon Sep 17 00:00:00 2001 From: Kobu Date: Sun, 4 Aug 2024 22:54:52 +0200 Subject: [PATCH] feat: use fuzzy find for categoy picker --- .../ui-providers/CategoryPickerUiProvider.tsx | 35 ++++++++----------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/next-frontend/components/ui-providers/CategoryPickerUiProvider.tsx b/next-frontend/components/ui-providers/CategoryPickerUiProvider.tsx index 4589c62..690e3aa 100644 --- a/next-frontend/components/ui-providers/CategoryPickerUiProvider.tsx +++ b/next-frontend/components/ui-providers/CategoryPickerUiProvider.tsx @@ -4,8 +4,6 @@ import { Result } from "@badrap/result"; import { CategoryRequest } from "@kobu-labs/nowaster-js-typing"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { Check, ChevronsUpDown } from "lucide-react"; - -import { prefixBasedMatch } from "@/lib/searching"; import { cn } from "@/lib/utils"; import { queryKeys } from "@/components/hooks/queryHooks/queryKeys"; import { Badge } from "@/components/shadcn/badge"; @@ -22,6 +20,7 @@ import { PopoverTrigger, } from "@/components/shadcn/popover"; import { ScrollArea } from "@/components/shadcn/scroll-area"; +import FuzzySearch from "fuzzy-search"; export type MultipleCategoryPickerUiProviderProps = { availableCategories: string[]; @@ -35,6 +34,12 @@ export type MultipleCategoryPickerUiProviderProps = { modal?: boolean; }; +const fuzzyFindStrategy = (category: string, searchTerm: string): boolean => { + const searcher = new FuzzySearch([category], []); + const result = searcher.search(searchTerm); + return result.length !== 0 +} + export const MultipleCategoryPickerUiProvider: FC< MultipleCategoryPickerUiProviderProps > = (props) => { @@ -68,15 +73,10 @@ export const MultipleCategoryPickerUiProvider: FC< ); } - if (props.categoryMatchStrategy) { - categoriesInDisplayOrder = categoriesInDisplayOrder.filter((category) => - props.categoryMatchStrategy!(category, searchTerm) - ); - } else { - categoriesInDisplayOrder = categoriesInDisplayOrder.filter((category) => - prefixBasedMatch(category, searchTerm, { caseInsensitive: true }) - ); - } + const matchStrategy = props.categoryMatchStrategy ?? fuzzyFindStrategy; + categoriesInDisplayOrder = categoriesInDisplayOrder.filter((category) => + matchStrategy(category, searchTerm) + ); return ( - props.categoryMatchStrategy!(category, searchTerm) - ); - } else { - categoriesInDisplayOrder = categoriesInDisplayOrder.filter((category) => - prefixBasedMatch(category, searchTerm, { caseInsensitive: true }) - ); - } + const matchStrategy = props.categoryMatchStrategy ?? fuzzyFindStrategy; + categoriesInDisplayOrder = categoriesInDisplayOrder.filter((category) => + matchStrategy(category, searchTerm) + ); return (