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