Files
commafeed/commafeed-client/src/components/content/add/CategorySelect.tsx

52 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-08-15 13:26:45 +02:00
import { t } from "@lingui/macro"
2023-12-29 23:09:30 +01:00
import { Select, type SelectProps } from "@mantine/core"
import { type ComboboxItem } from "@mantine/core/lib/components/Combobox/Combobox.types"
import { Constants } from "app/constants"
import { useAppSelector } from "app/store"
2024-01-08 13:26:20 +01:00
import { type Category } from "app/types"
import { flattenCategoryTree } from "app/utils"
type CategorySelectProps = Partial<SelectProps> & {
withAll?: boolean
withoutCategoryIds?: string[]
}
2022-08-15 13:26:45 +02:00
export function CategorySelect(props: CategorySelectProps) {
const rootCategory = useAppSelector(state => state.tree.rootCategory)
const categories = rootCategory && flattenCategoryTree(rootCategory)
2024-01-08 13:26:20 +01:00
const categoriesById = categories?.reduce((map, c) => {
map.set(c.id, c)
return map
}, new Map<string, Category>())
const categoryLabel = (cat: Category) => {
let label = cat.name
while (cat.parentId) {
const parent = categoriesById?.get(cat.parentId)
if (!parent) {
break
}
label = `${parent.name}${label}`
cat = parent
}
return label
}
2023-12-29 23:09:30 +01:00
const selectData: ComboboxItem[] | undefined = categories
2022-08-19 10:34:04 +02:00
?.filter(c => c.id !== Constants.categories.all.id)
2023-12-29 23:09:30 +01:00
.filter(c => !props.withoutCategoryIds?.includes(c.id))
.map(c => ({
2024-01-08 13:26:20 +01:00
label: categoryLabel(c),
value: c.id,
}))
.sort((c1, c2) => c1.label.localeCompare(c2.label))
2022-08-15 13:26:45 +02:00
if (props.withAll) {
selectData?.unshift({
label: t`All`,
2022-08-19 10:34:04 +02:00
value: Constants.categories.all.id,
2022-08-15 13:26:45 +02:00
})
}
return <Select {...props} data={selectData ?? []} disabled={!selectData} />
}