import { AfterContentInit, Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { SkeletonDisplayConfig } from '@yourcause/common'; import { distinctUntilChanged, map, Subscription } from 'rxjs'; import { DashboardsService } from '../dashboards.service'; import { Dashboards, GCDashboards } from '../dashboards.typing'; @Component({ selector: 'gc-home-dashboard-widget', templateUrl: './home-dashboard-widget.component.html', styleUrls: ['./home-dashboard-widget.component.scss'] }) export class HomeDashboardWidgetComponent implements OnInit, OnDestroy, AfterContentInit { @Input() dashboardId: number; @Input() widgetFromAPI: GCDashboards.WidgetConfigFromApi; @Input() editing: boolean; @Input() isPreview: boolean; @Output() onEdit = new EventEmitter(); @Output() onRemove = new EventEmitter(); @Output() onDrilldown = new EventEmitter<{ clickEvent: Dashboards.ChartClickEvent; widget: GCDashboards.Widget; }>(); skeletonConfig: SkeletonDisplayConfig; widgetPromise: Promise; widgetConfig: GCDashboards.WidgetConfig; gridConfig: GCDashboards.Widget['grid']; sub: Subscription; constructor ( private dashboardService: DashboardsService ) { } ngOnInit () { this.widgetConfig = this.dashboardService.parseWidgetConfig(this.widgetFromAPI); this.gridConfig = this.dashboardService.convertChartToGridConfig(this.widgetConfig, this.widgetFromAPI.id); } ngAfterContentInit () { this.setSkeletonConfig(); this.setWidgetPromise(); this.sub = this.dashboardService.changesTo$('widgetDisplayMap') .pipe(map(widgetDisplayMap => widgetDisplayMap[this.widgetFromAPI.id])) .pipe(distinctUntilChanged()) .subscribe(() => { this.setWidgetPromise(); }); } private setSkeletonConfig () { this.skeletonConfig = this.dashboardService.getSkeletonConfigByType(this.widgetConfig) as SkeletonDisplayConfig; } setWidgetPromise () { this.widgetPromise = (async () => { const widgetOnState = this.dashboardService.widgetDisplayMap[this.widgetFromAPI.id]; if (!widgetOnState) { const isRefresh = widgetOnState === null; // assume that if the widget on the state was set to null, we already had it at some point and are trying to refresh the data await this.dashboardService.fetchWidgetDetailForDashboard( this.widgetFromAPI, this.dashboardId, this.isPreview, isRefresh ); } return this.dashboardService.widgetDisplayMap[this.widgetFromAPI.id];; })(); } handleEditClick (widget: GCDashboards.Widget) { this.onEdit.emit(widget); } handleRemoveClick () { this.onRemove.emit(); } handleDrilldownClick ( clickEvent: Dashboards.ChartClickEvent, widget: GCDashboards.Widget ) { this.onDrilldown.emit({ clickEvent, widget }); } refreshWidget () { this.setWidgetPromise(); } ngOnDestroy () { this.sub.unsubscribe(); } }