87 lines
2.6 KiB
TypeScript
87 lines
2.6 KiB
TypeScript
import { Injectable, OnDestroy, inject } from '@angular/core';
|
|
import { CategoryService } from '../../core/service/category.service';
|
|
import { BehaviorSubject, Observable, Subscription, map } from 'rxjs';
|
|
import { Category } from '../../core/rest-services/category/model/category';
|
|
|
|
export interface DisplayableCategory {
|
|
id: string;
|
|
name: string;
|
|
subCategories: DisplayableSubCategory[];
|
|
isOpenned: boolean;
|
|
}
|
|
|
|
export interface DisplayableSubCategory {
|
|
id: string;
|
|
name: string;
|
|
}
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class SideMenuService implements OnDestroy {
|
|
private categoryService = inject(CategoryService);
|
|
private categoriesSubject = new BehaviorSubject<DisplayableCategory[]>([]);
|
|
private categoriesSubscription: Subscription | undefined;
|
|
|
|
constructor() {
|
|
this.categoriesSubscription = this.categoryService.categories$
|
|
.pipe(
|
|
map(categories =>
|
|
categories
|
|
.filter(category => category.subCategories?.length)
|
|
.map(category =>
|
|
this.mapToDisplayableCategory(category)
|
|
)
|
|
)
|
|
)
|
|
.subscribe(categories => this.categoriesSubject.next(categories));
|
|
}
|
|
|
|
ngOnDestroy(): void {
|
|
this.categoriesSubscription?.unsubscribe();
|
|
}
|
|
|
|
private mapToDisplayableCategory(category: Category): DisplayableCategory {
|
|
return {
|
|
id: category.id,
|
|
name: category.name,
|
|
subCategories: category.subCategories.map(subCategory => this.mapToDisplayableSubCategory(subCategory)),
|
|
isOpenned: false
|
|
};
|
|
}
|
|
|
|
private mapToDisplayableSubCategory(subCategory: Category): DisplayableSubCategory {
|
|
return {
|
|
id: subCategory.id,
|
|
name: subCategory.name
|
|
}
|
|
}
|
|
|
|
get categories$(): Observable<DisplayableCategory[]> {
|
|
return this.categoriesSubject.asObservable();
|
|
}
|
|
|
|
private get categories(): DisplayableCategory[] {
|
|
return this.categoriesSubject.value;
|
|
}
|
|
|
|
private save(categories: DisplayableCategory[]): void {
|
|
this.categoriesSubject.next(categories);
|
|
}
|
|
|
|
setOpenned(category: DisplayableCategory): void {
|
|
const categories = this.categories;
|
|
const matchingCategory = categories.find(categoryTemp => categoryTemp.id === category.id);
|
|
if (matchingCategory) {
|
|
const actualOpennedCategory = categories.find(category => category.isOpenned);
|
|
if (actualOpennedCategory && actualOpennedCategory.id === matchingCategory.id) {
|
|
matchingCategory.isOpenned = false;
|
|
} else {
|
|
categories.forEach(categoryTemp => categoryTemp.isOpenned = false);
|
|
matchingCategory.isOpenned = true;
|
|
}
|
|
this.save(categories);
|
|
}
|
|
}
|
|
}
|