import { ComponentRef, Injectable, ViewContainerRef } from '@angular/core'; import { ColorPickerService } from '@dilvant/utils'; import { Mapper } from '../classes/Mapper'; import { IApp } from '../interfaces/IApp'; import { ISection } from '../interfaces/ISection'; @Injectable({ providedIn: 'root', }) export class ComponentLoaderService { private viewContainerRef!: ViewContainerRef; constructor(private _colorPockerSrv: ColorPickerService) {} loadMany( vcr: ViewContainerRef, app: IApp, keyStorage: string ): Promise[]> { let sections: ISection[] = app.sections!; if ((app)?.theme) { this._colorPockerSrv.colors((app)?.theme.colors); } let appOnly = { ...app }; delete appOnly.sections; vcr.clear(); let promises = []; if (sections?.length) { promises = sections .filter((s) => s.active) .map((s) => { return this.build(vcr, s, appOnly, keyStorage); }); } else { promises = [this.build(vcr, sections, appOnly, keyStorage)]; } return Promise.allSettled(promises); } build( vcr: ViewContainerRef, section: ISection, app?: IApp, keyStorage?: string ): Promise<{ intance: any; key: string }> { return new Promise((resolve, reject) => { if (!this.viewContainerRef || (this.viewContainerRef && vcr)) { this.viewContainerRef = vcr; } else { vcr = this.viewContainerRef; } setTimeout(() => { let component = new Mapper().find(section.key!); if (!component) return reject('Section not found'); let dynComponent: ComponentRef = vcr.createComponent(component); if (section) dynComponent.instance.section = section; if (app) dynComponent.instance.app = app; if (keyStorage) dynComponent.instance.keyStorage = keyStorage; return resolve({ intance: dynComponent.instance, key: section.key!, }); }, 0); }); } }