Refactor Sidebar.tsx

This commit is contained in:
Eric NGUYEN 2022-09-16 16:35:22 +02:00
parent 0476a294d6
commit 1cd38f24cf

View file

@ -15,12 +15,18 @@ function HandleDragStart(event: React.DragEvent<HTMLButtonElement>): void {
event.dataTransfer.setData('type', (event.target as HTMLButtonElement).id);
}
interface CategoryWrapper {
category: ICategory
children: JSX.Element[]
}
export function Sidebar(props: ISidebarProps): JSX.Element {
const rootElements: Array<JSX.Element | undefined> = [];
const categories = new Map<string, ICategory>();
const categoriesElements = new Map<string, JSX.Element[]>(props.categories.map(category => {
categories.set(category.Type, category);
return [category.Type, []];
const categories = new Map<string, CategoryWrapper>(props.categories.map(category => {
return [category.Type, {
category,
children: []
}];
}));
// build the components
@ -46,30 +52,22 @@ export function Sidebar(props: ISidebarProps): JSX.Element {
return;
}
const category = categoriesElements.get(componentOption.Category);
const category = categories.get(componentOption.Category);
if (category === undefined) {
console.error(`[Category] Category does not exists in configuration.Categories: ${componentOption.Category}`);
return;
}
category.push(componentButton);
category.children.push(componentButton);
});
// build the categories
categoriesElements.forEach((options, categoryName) => {
const category = categories.get(categoryName);
if (category === undefined) {
// should never go here
console.error(`[Category] Category does not exists in configuration.Categories: ${categoryName}`);
return;
}
categories.forEach((categoryWrapper, categoryName) => {
rootElements.unshift(
<Category
key={categoryName}
category={category}
category={categoryWrapper.category}
>
{ options }
{ categoryWrapper.children }
</Category>);
});