import { AfterViewInit, Component, inject, ElementRef, Input, OnChanges, OnDestroy, output, signal, ViewChild } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; import { PlotlyController } from './plotly-controller'; import { PLOTLY_LOADER } from './plotly-runtime'; @Component({ selector: 'app-plotly-chart', imports: [MatButtonModule, MatProgressBarModule], template: ` @if (status() === 'loading') { } @if (status() === 'error') {

No se pudo representar la figura. Puedes reintentar.

} @if (status() === 'ready' && notes.length) {

Notas de la figura

@for (note of notes; track $index) {

}
} `, styles: `:host { display: block; min-width: 0; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { display: none; padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } @media (max-width: 850px) { .notes { display: block; } }`, }) export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @Input() label = 'Figura estadística'; @Input({ required: true }) figure!: PlotlyFigure; @ViewChild('host', { static: true }) host!: ElementRef; readonly renderError = output(); readonly status = signal<'loading' | 'ready' | 'error'>('loading'); get notes(): string[] { const annotations = this.figure?.layout['annotations']; if (!Array.isArray(annotations)) return []; return annotations.flatMap(annotation => annotation && typeof annotation.text === 'string' ? [annotation.text] : []); } private readonly loadPlotly = inject(PLOTLY_LOADER); private controller?: PlotlyController; private observer?: ResizeObserver; private readonly windowResize = () => this.controller?.resize(); ngAfterViewInit() { this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => { this.status.set(state); if (state === 'error') this.renderError.emit(); }); if (typeof ResizeObserver !== 'undefined') { this.observer = new ResizeObserver(this.windowResize); this.observer.observe(this.host.nativeElement); } else window.addEventListener('resize', this.windowResize); this.controller.setFigure(this.figure); } ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); } retry() { this.controller?.setFigure(this.figure); } ngOnDestroy() { this.observer?.disconnect(); window.removeEventListener('resize', this.windowResize); this.controller?.destroy(); } }