Skip to content

Commit

Permalink
feat: use fuzzy find for categoy picker
Browse files Browse the repository at this point in the history
  • Loading branch information
Kobu committed Oct 5, 2024
1 parent 513f944 commit b9091cd
Showing 1 changed file with 15 additions and 20 deletions.
35 changes: 15 additions & 20 deletions next-frontend/components/ui-providers/CategoryPickerUiProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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[];
Expand All @@ -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) => {
Expand Down Expand Up @@ -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 (
<Popover
Expand Down Expand Up @@ -213,15 +213,10 @@ export const SingleCategoryPickerUiProvider: 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 (
<Popover
Expand Down

0 comments on commit b9091cd

Please sign in to comment.