From b9d682040545b513983f5532239c6bd4a1e21384 Mon Sep 17 00:00:00 2001 From: enes Date: Wed, 11 Dec 2024 14:36:07 +0100 Subject: [PATCH] feat(category): check if user defined already exists, remove duplicates --- .../Filters/CategoryFilterPopup.tsx | 77 +++++++++++++------ src/utils/category.ts | 12 +-- 2 files changed, 55 insertions(+), 34 deletions(-) diff --git a/src/components/Filters/CategoryFilterPopup.tsx b/src/components/Filters/CategoryFilterPopup.tsx index 252f73d..d7c3840 100644 --- a/src/components/Filters/CategoryFilterPopup.tsx +++ b/src/components/Filters/CategoryFilterPopup.tsx @@ -1,10 +1,11 @@ -import React, { useEffect, useState } from 'react' +import React, { useEffect, useMemo, useState } from 'react' import { createPortal } from 'react-dom' import { Category } from 'types' import { addToUserCategories, capitalizeEachWord, - deleteFromUserCategories + deleteFromUserCategories, + flattenCategories } from 'utils' import { useLocalStorage } from 'hooks' import styles from './CategoryFilterPopup.module.scss' @@ -35,6 +36,21 @@ export const CategoryFilterPopup = ({ setHierarchies(filterHierarchies) } const [inputValue, setInputValue] = useState('') + const userHierarchiesMatching = useMemo( + () => + flattenCategories(userHierarchies, []).some((h) => + h.hierarchy.includes(inputValue.toLowerCase()) + ), + [inputValue, userHierarchies] + ) + const hierarchiesMatching = useMemo( + () => + flattenCategories(categoriesData, []).some((h) => + h.hierarchy.includes(inputValue.toLowerCase()) + ), + [inputValue] + ) + const handleInputChange = (e: React.ChangeEvent) => { setInputValue(e.target.value) } @@ -75,13 +91,14 @@ export const CategoryFilterPopup = ({ const path = values.join(':') // Add new hierarchy to current selection and active selection + // Convert through set to remove duplicates setFilterHierarchies((prev) => { prev.push(path) - return [...prev] + return Array.from(new Set([...prev])) }) setHierarchies((prev) => { prev.push(path) - return [...prev] + return Array.from(new Set([...prev])) }) setInputValue('') } @@ -149,6 +166,7 @@ export const CategoryFilterPopup = ({ overflow: 'auto' }} > + {!userHierarchiesMatching &&
No results.
} {userHierarchies .filter((c) => typeof c !== 'string') .map((c, i) => ( @@ -187,6 +205,15 @@ export const CategoryFilterPopup = ({ )}
+
+ +

Maybe

+
No results.

-
- Add and search for "{inputValue}" category -
+ ) : ( +
- - - - -
+ + + + +
+ )}
{(categoriesData as Category[]).map((category, i) => ( { @@ -26,16 +26,6 @@ export const getCategories = () => { return flattenCategories(categoriesData) } -export const buildCategories = (input: string[]) => { - const categories: (string | Category)[] = [] - - input.forEach((cat) => { - addToUserCategories(categories, cat) - }) - - return categories -} - export const addToUserCategories = ( categories: (string | Category)[], input: string