42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
import type { FileCategory } from '../api'
|
|
|
|
export interface CategoryOption {
|
|
value: string
|
|
label: string
|
|
}
|
|
|
|
export function findCategory(categories: FileCategory[], id: string): FileCategory | undefined {
|
|
for (const category of categories) {
|
|
if (category.id === id) return category
|
|
const nested = findCategory(category.children, id)
|
|
if (nested) return nested
|
|
}
|
|
return undefined
|
|
}
|
|
|
|
export function categoryContains(category: FileCategory, id: string): boolean {
|
|
return category.id === id || category.children.some((child) => categoryContains(child, id))
|
|
}
|
|
|
|
export function getCategoryPath(categories: FileCategory[], id: string): string[] {
|
|
for (const category of categories) {
|
|
if (category.id === id) return [category.name]
|
|
const nestedPath = getCategoryPath(category.children, id)
|
|
if (nestedPath.length > 0) return [category.name, ...nestedPath]
|
|
}
|
|
return []
|
|
}
|
|
|
|
export function flattenCategoryOptions(
|
|
categories: FileCategory[],
|
|
depth = 0,
|
|
): CategoryOption[] {
|
|
return categories.flatMap((category) => [
|
|
{
|
|
value: category.id,
|
|
label: `${' '.repeat(depth)}${depth > 0 ? '└ ' : ''}${category.name}`,
|
|
},
|
|
...flattenCategoryOptions(category.children, depth + 1),
|
|
])
|
|
}
|