import { Component, ElementRef, Input, OnChanges, output, signal, SimpleChanges, viewChild } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatTooltipModule } from '@angular/material/tooltip'; import { Dominio, hasNoVisibleValues, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { figureTitle } from './indicadores.presentation'; import { figureDisplayName } from './indicadores-figure-labels'; import { CategoryLabel } from './indicadores-axis-labels'; import { figureIdentity, identityElementId } from './indicadores-identities'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadorAyuda } from './indicador-ayuda'; import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology'; import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown'; import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight'; import { recolorFigure } from './indicadores-c2-palette'; // The panel owns requests; the card receives the original and its presentation copy. export interface FigureState { status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; footnotes?: readonly string[]; categoryLabels?: readonly CategoryLabel[]; minimumPlotWidth?: number; donutLegend?: readonly DonutLegendEntry[]; // The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is. ownLayout?: boolean; // Legend buttons that highlight one part of the figure (CaCu style). highlight?: FigureHighlight; plotWidth?: number; plotHeight?: number; message?: string; hierarchy?: DonutHierarchy; source?: 'datos' | 'figuras'; fallbackReason?: string; emptyMessage?: string; } @Component({ selector: 'app-indicador-figure-card', standalone: true, host: { '[class.methodology-expanded]': 'methodologyExpanded()' }, imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, IndicadorAyuda], templateUrl: './indicador-figure-card.html', styleUrl: './indicador-figure-card.scss', }) export class IndicadorFigureCard implements OnChanges { private readonly donutNavigation = viewChild>('donutNavigation'); private readonly donutKeyboard = viewChild>('donutKeyboard'); private currentState!: FigureState; // Keep the mounted host's last presentation only. The template hides it whenever // it is not the current result; this is neither applied state nor a results cache. chartFigure?: PlotlyFigure; chartMinimumWidth?: number; activeParent?: string; activeCategory?: string; readonly hierarchySelected = output(); selectCategory(category: string) { if (!this.state.hierarchy?.children.some(c => c.parent === this.activeParent && c.label === category)) return; this.activeCategory = this.activeCategory === category ? undefined : category; this.hierarchySelected.emit({ parent: this.activeParent, category: this.activeCategory }); } get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; } legendColor(label: string, parent: boolean): string { const painted = this.chartFigure ? recolorFigure(this.chartFigure) : undefined; const trace = painted?.data[parent && this.activeParent ? 1 : 0]; const labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined; const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : undefined; return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor'; } @Input({ required: true }) set state(value: FigureState) { if (value.status !== 'ready' || value.figure !== this.currentState?.figure || JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; } this.currentState = value; if (value.status === 'ready') { this.updateDonut(); this.chartMinimumWidth = value.minimumPlotWidth; } } get state() { return this.currentState; } ngOnChanges(changes: SimpleChanges) { if (changes['dominio'] || changes['figuraId'] || (changes['selected'] && changes['selected'].previousValue?.id !== this.selected?.id)) { this.activeParent = undefined; if (this.state.status === 'ready') this.updateDonut(); } } private updateDonut() { const { presentationFigure, hierarchy } = this.state; // Empty pages retain the series' plot height as well. This is a derived // layout copy; the original figure and its annotations remain available. const source = presentationFigure && this.state.plotHeight ? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure; this.chartFigure = source && hierarchy ? donutView(source, hierarchy, this.activeParent, this.state.plotWidth) : source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection) : source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source; } expandParent(parent: string) { if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent) || !this.state.hierarchy.children.some(c => c.parent === parent && c.value > 0)) return; this.activeParent = parent; this.activeCategory = undefined; this.updateDonut(); this.hierarchySelected.emit({ parent }); } returnToParents(event?: MouseEvent) { if (!this.activeParent) return; this.activeParent = undefined; this.activeCategory = undefined; this.updateDonut(); this.hierarchySelected.emit({}); // The restore button disappears. Transfer keyboard focus to the first // persistent alternative; pointer users return to the graphic region. if (event) { const target = event.detail === 0 ? this.donutKeyboard()?.nativeElement.querySelector('button') : this.donutNavigation()?.nativeElement; target?.focus(); } } highlightSelection: HighlightSelection = {}; readonly highlightRows = highlightRows; get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; } highlight(kind: 'group' | 'item', id: string) { if (!this.state.highlight) return; this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id); this.updateDonut(); } highlightBack() { const sel = this.highlightSelection; this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {}; this.updateDonut(); } plotClicked(event: unknown) { if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return; const point = event.points[0]; if (this.state.highlight) { const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number' ? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined; if (hit) this.highlight(hit.kind, hit.id); return; } if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label); else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label); } // A round "?" button with the reading guide instead of the «Cómo leer» box. @Input() ayudaRedonda = false; @Input() selected?: Indicador; @Input() metadata?: IndicadorMetadatos; @Input({ required: true }) figuraId!: string; @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) tema!: Tema; readonly retry = output(); readonly plotWidthChanged = output(); reportPlotWidth(width: unknown) { if (typeof width === 'number') this.plotWidthChanged.emit(width); } readonly methodologyExpanded = signal(false); readonly metadataRequested = output(); toggleMethodology() { const open = !this.methodologyExpanded(); this.methodologyExpanded.set(open); if (open && !this.metadata) this.metadataRequested.emit(); } get methodologyId(): string { return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology'; } // Editorial classification of complete local sentences by known family. // Keep mixed C3r/Wilson sentences and all backend content visible. private get contract(): string | undefined { return this.figuraId.startsWith('fig_c1') ? 'C1' : this.figuraId.startsWith('fig_c2') ? 'C2' : this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato; } readonly hasNoVisibleValues = hasNoVisibleValues; readonly figureTitle = figureTitle; readonly figureDisplayName = figureDisplayName; readonly periodInterpretation = PERIOD_INTERPRETATION; get interpretation(): readonly string[] { return figureInterpretation(this.metadata, this.figuraId, this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie')); } // The figure's notes live in "Cómo leer"; the cut-off date stays under the plot // because it is the only temporal reference of the data on the card. get cutoffDate(): string | undefined { if (this.state.status !== 'ready') return undefined; for (const note of this.state.footnotes ?? []) { const match = /Fecha de corte: (\d{4}-\d{2}-\d{2})/.exec(note); if (match) return match[1]; } return undefined; } }