Files
WebApp/src/app/features/indicadores/indicador-figure-panel.ts
T

521 lines
36 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal, output } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
import { DimensionEstrato, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, Tema } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { figurePresentation } from './indicadores.presentation';
import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile';
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory';
import { httpMessage } from './indicadores-http';
import { figureIdentity, identityElementId } from './indicadores-identities';
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones';
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified';
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
import { c2GeneralSelection } from './indicadores-c2-general-selection';
import { MatTooltipModule } from '@angular/material/tooltip';
@Component({
selector: 'app-indicador-figure-panel',
imports: [IndicadorFigureCard, MatTooltipModule],
template: `
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
@if (sidebar) {
<aside class="strata-sidebar" aria-label="Estratificación">
<fieldset class="sidebar-group">
<legend>Estratificar por</legend>
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
(click)="changeDimension('')">Sin estratificar</button>
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
@if (dimension && estratos.length > 1) {
<fieldset class="sidebar-group">
<legend>Mostrar</legend>
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
@for (e of estratos; track e.valor) {
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
}
</div>
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
</fieldset>
}
@if (dimension) {
<fieldset class="sidebar-group">
<legend>Medida</legend>
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
</fieldset>
}
</aside>
}
<header class="panel-controls">
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
<span class="selection-status" [class.selection-active]="!!generalSelectionContext" tabindex="0" role="status"
[attr.aria-label]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'"
[matTooltip]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'">
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
</span>
}
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
<legend>Distribución</legend>
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
(click)="changeDimension('')">Distribución general</button>
<button type="button" role="radio" [attr.aria-checked]="dimension !== ''" [class.active]="dimension !== ''"
[disabled]="!singlePeriod" (click)="chooseStratified()">Distribución estratificada</button>
</div>
@if (dimension && capabilities.length > 1) {
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
}
@if (dimension) {
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
}
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
}
@if (result().status === 'ready' && donutPages.length > 1) {
<nav class="donut-periods" aria-label="Periodos de la dona">
<button type="button" aria-label="Periodo anterior de la dona" [disabled]="donutPeriodIndex <= 0" (click)="changeDonutPeriod(-1)">‹</button>
<span role="status" aria-live="polite">{{ activeDonutPeriod }}, {{ donutPeriodIndex + 1 }} de {{ donutPages.length }}</span>
<button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
</nav>
}
</header>
<app-indicador-figure-card [state]="result()" [selected]="indicador"
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
<div class="stratified-detail">
@if (dimension && result().status === 'ready') {
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
<details><summary>Valores publicados</summary>
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
</tbody></table></div>
</details>
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
}
</div>
</section>
`,
styles: `
:host { display: grid; min-width: 0; }
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
.selection-active { color: var(--issste-text); font-weight: 600; }
.selection-status:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
.stratified-detail { min-width: 0; overflow-wrap: anywhere; }
@supports (grid-template-rows: subgrid) {
:host, .figure-panel { grid-template-rows: subgrid; }
.figure-panel { grid-row: span 8; }
.panel-controls { grid-row: 1; }
app-indicador-figure-card { grid-row: 2 / span 6; }
.stratified-detail { grid-row: 8; }
}
:host:has(app-indicador-figure-card.methodology-expanded),
.figure-panel:has(app-indicador-figure-card.methodology-expanded) { grid-template-rows: auto auto auto; }
.figure-panel:has(app-indicador-figure-card.methodology-expanded) { grid-row: auto; }
.distribution-control { margin: var(--issste-space-3) 0; padding: 0; border: 0; min-width: 0; }
.distribution-control legend { padding: 0; font-weight: 600; }
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
.distribution-dimensions { margin-top: .75rem; }
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text);
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
.distribution-toggle button:focus-visible, .distribution-dimensions button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.distribution-note { margin: .5rem 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
.cells { overflow: auto; max-height: 24rem; } th, td { text-align: start; padding: .5rem; }
.donut-periods { display: flex; align-items: center; justify-content: center; gap: .75rem; min-height: 48px; }
.donut-periods span { text-align: center; overflow-wrap: anywhere; }
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
.donut-periods button:disabled { opacity: .45; }
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
shared with the neighbouring panel, so the bars line up with the donut. */
:host { container-type: inline-size; }
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; }
.sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; }
.sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; }
.sidebar-list { display: grid; gap: .25rem; }
.sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start;
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface);
color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; }
.sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
.sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; }
.sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; }
.sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.sidebar-reset { margin-top: .5rem; }
.sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
@container (max-width: 559px) {
.figure-panel.with-sidebar { display: flex; flex-direction: column; }
.strata-sidebar { position: static; }
.sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); }
}
.visually-hidden {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
}
`,
})
export class IndicadorFigurePanel implements OnChanges {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) indicador!: Indicador;
@Input() metadata?: IndicadorMetadatos;
@Input({ required: true }) figuraId!: string;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() independentPeriods = false;
@Input() visible = true;
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
@Input() localSelection: DonutSelection = {};
readonly hierarchySelected = output<DonutSelection>();
readonly metadataRequested = output<void>();
donutPages: { period: string; state: FigureState }[] = [];
activeDonutPeriod?: string;
private donutIdentity = '';
get donutPeriodIndex() { return this.donutPages.findIndex(p => p.period === this.activeDonutPeriod); }
changeDonutPeriod(step: number) {
if (this.result().status !== 'ready' || ![-1, 1].includes(step)) return;
const page = this.donutPages[this.donutPeriodIndex + step];
if (!page) return;
this.activeDonutPeriod = page.period;
// Selection belongs to one page. Reset dependent category/stratum state
// even when the same labels exist in the following period.
this.hierarchySelected.emit({});
this.result.set(this.refreshDonutPage(page.state));
}
selectHierarchy(selection: DonutSelection) {
this.hierarchySelected.emit(selection.parent || selection.category
? { ...selection, period: this.activeDonutPeriod ?? this.readySelection?.periodos?.[0] } : {});
}
private refreshDonutPage(state: FigureState): FigureState {
const presentation = this.present(state.figure!, this.readySelection!, state.hierarchy);
return { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
}
private activateDonutPages(pages: { period: string; state: FigureState }[]): FigureState {
const plotHeight = pages.some(p => p.state.hierarchy) ? 440 : undefined;
this.donutPages = pages.map(p => ({ ...p, state: { ...p.state, plotHeight } }));
this.activeDonutPeriod = pages.some(p => p.period === this.activeDonutPeriod) ? this.activeDonutPeriod : pages[0]?.period;
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
}
dimension: DimensionEstrato | '' = '';
readonly etiquetaDimension = etiquetaDimension;
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
private medidaElegida?: MedidaEstrato;
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
changeMedida(medida: MedidaEstrato) {
if (medida === this.medida) return;
this.medidaElegida = medida;
this.representStratified();
}
cells: StratifiedCell[] = [];
/** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */
get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; }
estratos: StratumOption[] = [];
ocultos = new Set<string>();
toggleEstrato(valor: string) {
const ocultos = new Set(this.ocultos);
if (ocultos.has(valor)) ocultos.delete(valor);
else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor);
else return;
this.ocultos = ocultos;
this.representStratified();
}
mostrarTodos() {
if (!this.ocultos.size) return;
this.ocultos = new Set();
this.representStratified();
}
private representStratified() {
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
try { this.result.set(this.presentStratified(this.stratifiedData)); }
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
}
}
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
private stratifiedData?: IndicadorDatos;
private generalData?: IndicadorDatos;
private generalState?: FigureState;
generalSelectionContext?: string;
get capabilities() { return stratifiedCapabilities(this.indicador); }
get singlePeriod() { return this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1; }
changeDimension(value: DimensionEstrato | '') {
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
if (this.dimension === value) return;
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set();
this.requestFigure();
}
chooseStratified() {
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
}
private presentStratified(data: IndicadorDatos): FigureState {
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
this.estratos = stratumOptions(data);
const publicados = new Set(this.estratos.map(e => e.valor));
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos);
this.cells = adapted.cells;
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
source: 'datos', footnotes: data.notas,
emptyMessage: this.cells.length ? 'No hay magnitudes disponibles. Consulta las celdas suprimidas y sin información en la tabla de valores.' : 'No hay categorías publicadas para esta selección.' };
}
private presentGeneral(state: FigureState, selection: FigureSelection): FigureState {
const selected = this.generalData && state.figure
? c2GeneralSelection(state.figure, this.generalData, selection, this.localSelection) : undefined;
this.generalSelectionContext = selected?.context;
const presentation = this.present(selected?.figure ?? state.figure!, selection);
// Keep the complete original figure in state. Width/profile changes and
// restoration always derive afresh, including published percentage arrays.
return { ...state, ...presentation, figure: state.figure,
footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
}
private readySelection?: FigureSelection;
private plotWidth?: number;
private readonly service = inject(IndicadoresService);
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly destroyRef = inject(DestroyRef);
private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>();
private generation = 0;
private currentKey = '';
titleId = '';
distributionAvailabilityId = '';
readonly result = signal<FigureState>({ status: 'idle' });
get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin selección aplicada'; }
constructor() {
this.figureRequests.pipe(switchMap(request => request
? defer(() => this.loadFigure(request.selection)).pipe(
catchError(error => of({
status: 'error',
message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404
&& (request.selection.periodos?.length ?? 0) > 1
? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''),
} as FigureState)),
startWith({ status: 'loading' } as FigureState),
map(state => ({ state, selection: request.selection, revision: request.revision, generation: request.generation })))
: of({ state: { status: 'idle' } as FigureState, selection: undefined, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef))
.subscribe(({ state, selection, revision, generation }) => {
if (generation === this.generation && revision === this.applied?.revision) {
if (state.status === 'ready') {
this.readySelection = selection;
if (!this.dimension && this.indicador.contrato === 'C2'
&& selection?.figura === 'fig_c2_barras' && this.indicador.figuras.includes('fig_c2_donas')) {
this.generalState = state;
state = this.presentGeneral(state, selection);
}
if (!this.donutPages.length) this.activeDonutPeriod = selection?.periodos?.length === 1
? selection.periodos[0] : state.figure && donutPeriod(state.figure);
}
this.result.set(state);
}
});
}
private loadFigure(selection: FigureSelection) {
if (this.dimension && selection.periodos?.length === 1 && this.capabilities.includes(this.dimension)) {
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo!, selection.periodos, this.indicador.version, { estrato: this.dimension }).pipe(map(data => {
if (data.periodos.length !== 1 || data.periodos[0] !== selection.periodos![0]) throw new Error('Periodo estratificado inválido');
const state = this.presentStratified(data); this.stratifiedData = data; return state;
}));
}
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
const adapted = c1DonutFigure(data, selection);
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
}));
}
if (c1AlterationCapability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(map(data => {
const adapted = c1AlterationFigure(data, selection);
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
highlight: adapted.highlight, ownLayout: true, plotHeight: 400,
emptyMessage: adapted.total === 0 ? 'Ningún niño tiene su primer EEG de buena calidad en la selección; no hay un porcentaje que representar.' : undefined };
}));
}
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
// Both panels, KPI and numeric table share the exact same transport key.
// Do not catch /datos errors here: a backend failure is a real error state.
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(
switchMap(data => {
if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.');
if (selection.figura === 'fig_c2_barras') this.generalData = data;
const periods = selection.periodos ?? data.periodos;
if (selection.figura === 'fig_c2_donas' && periods.length > 1) {
const pages = periods.map(period => ({ period, adapted: c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }) }));
if (pages.every(p => p.adapted.status === 'supported')) {
return of(this.activateDonutPages(pages.map(({ period, adapted }) => {
if (adapted.status !== 'supported') throw new Error('Periodo no soportado');
return { period, state: { ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage } };
})));
}
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
}
const adapted = c2Figure(data, selection);
if (adapted.status === 'supported' && selection.dominio === 'tea') {
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
if (selection.figura === 'fig_c2_donas') {
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
}
return adapted.status === 'supported'
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
: this.publishedFigure(selection, adapted.reason, data);
}));
}
return this.publishedFigure(selection);
}
private publishedFigure(selection: FigureSelection, fallbackReason?: string, data?: IndicadorDatos) {
return defer(() => this.service.figura(selection)).pipe(
switchMap(figure => {
const pages = donutPeriodFigures(figure, selection, data?.periodos);
if (pages) return of(this.activateDonutPages(pages.map(({ period, figure: page }) => ({ period,
state: { ...this.present(page, selection, data && donutHierarchy(page, periodDatos(data, period))),
source: 'figuras' as const, fallbackReason,
emptyMessage: !page.data.length ? 'No hay valores representables publicados para el periodo ' + period + '. Consulta las notas de la figura.' : undefined } }))));
const period = this.indicador.contrato === 'C2'
? donutPeriod(figure) : undefined;
const present = (hierarchy?: DonutHierarchy) => ({ ...this.present(figure, selection, hierarchy), source: 'figuras' as const, fallbackReason });
// A fallback has already read /datos; don't request a different subset.
return !fallbackReason && period && selection.tipoPeriodo
? this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, [period], this.indicador.version).pipe(
map(data => present(donutHierarchy(figure, data))),
// The optional hierarchy must never prevent the published figure.
catchError(() => of(present())))
: of(present());
}));
}
private present(figure: NonNullable<FigureState['figure']>, selection: FigureSelection, hierarchy?: DonutHierarchy): FigureState {
const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth);
return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes,
categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth, hierarchy,
donutLegend: selection.figura === 'fig_c2_donas' && !hierarchy ? donutLegend(presentation.figure) : undefined,
plotWidth: selection.figura === 'fig_c2_donas' && this.indicador.contrato === 'C2' && this.plotWidth !== undefined
? (this.plotWidth < 480 ? 320 : 480) : undefined };
}
updatePlotWidth(width: number) {
if (!Number.isFinite(width) || width <= 0 || Math.floor(width) === this.plotWidth) return;
this.plotWidth = Math.floor(width);
if (this.dimension) return;
const state = this.result();
const responsiveC2Donut = this.indicador.contrato === 'C2' && this.figuraId === 'fig_c2_donas';
if ((this.visualProfile.axisLabels?.enabled || responsiveC2Donut)
&& state.status === 'ready' && state.figure && this.readySelection) {
const presentation = this.generalState ? this.presentGeneral(this.generalState, this.readySelection)
: this.present(state.figure, this.readySelection, state.hierarchy);
const next = { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
// A width change within the same label budget must not hide/repaint an
// equivalent graph (for example when only the scrollbar gutter changes).
if (JSON.stringify([next.presentationFigure, next.categoryLabels, next.minimumPlotWidth, next.plotWidth])
!== JSON.stringify([state.presentationFigure, state.categoryLabels, state.minimumPlotWidth, state.plotWidth])) this.result.set(next);
}
}
ngOnChanges(changes: SimpleChanges) {
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) {
this.dimension = ''; this.estratos = []; this.ocultos = new Set();
}
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
this.titleId = identityElementId(identity) + '-title';
this.distributionAvailabilityId = this.titleId + '-distribution-availability';
const key = this.requestKey();
if (key === this.currentKey) {
if (changes['localSelection'] && this.dimension && this.stratifiedData && this.result().status === 'ready') {
try { this.result.set(this.presentStratified(this.stratifiedData)); }
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
} else if (changes['localSelection'] && this.generalState && this.readySelection && this.result().status === 'ready') {
this.result.set(this.presentGeneral(this.generalState, this.readySelection));
}
const state = this.result();
if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) {
const next = this.generalState ? this.presentGeneral(this.generalState, this.readySelection)
: this.present(state.figure, this.readySelection, state.hierarchy);
this.result.set({ ...state, ...next, footnotes: state.source === 'datos' ? state.footnotes : next.footnotes });
}
return;
}
if (this.visible) this.requestFigure();
else {
// Cancel stale work immediately but retain the panel and its Plotly host.
const message = this.generation === 0
? 'Figura pendiente: se cargará al acercarse a esta región.'
: 'Actualización pendiente: se consultará al volver a esta región.';
this.generation++;
this.figureRequests.next(null);
this.currentKey = '';
this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined;
this.result.set({ status: 'deferred', message });
}
}
private requestKey() {
return JSON.stringify([figureIdentity(this.dominio, this.indicador.id, this.figuraId),
this.indicador.version, this.tema, this.applied?.revision, this.applied && selectionKey(this.applied),
this.indicador.tipos_periodo, this.indicador.figuras.includes(this.figuraId), this.dimension]);
}
requestFigure() {
if (!this.visible) return;
this.currentKey = this.requestKey();
this.stratifiedData = undefined; this.cells = [];
this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined;
this.donutPages = [];
const applied = this.applied;
const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo);
this.generation++;
if (!this.indicador.figuras.includes(this.figuraId) || !compatibility.compatible) {
this.figureRequests.next(null);
this.result.set({ status: 'incompatible', message: !compatibility.compatible
? compatibility.reason : 'Esta figura ya no está publicada en el catálogo.' });
return;
}
this.figureRequests.next({ revision: applied.revision, generation: this.generation, selection: {
dominio: this.dominio, indicador: this.indicador.id, figura: this.figuraId,
tipoPeriodo: applied.tipo, tema: this.tema,
periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined,
} });
}
}