Files
WebApp/src/app/features/indicadores/indicadores-page.ts
T

534 lines
29 KiB
TypeScript

import { DOCUMENT } from '@angular/common';
import { afterEveryRender, afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal, viewChild, viewChildren } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
import { Dominio, isDominio, Indicador, Tema } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { esSocioConteos } from './indicadores-conteos-pareados';
import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
import { TeaResumenPeriodo } from './tea-resumen-periodo';
import { IndicadorKpiPanel } from './indicador-kpi-panel';
import { IndicadorScreeningRoute } from './indicador-screening-route';
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
import { identityElementId, indicatorIdentity } from './indicadores-identities';
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
import { httpMessage } from './indicadores-http';
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
import { IndicadoresDefinitions } from './indicadores-definitions';
import { IndicadoresTracking } from './indicadores-tracking';
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { historicoDeDominio } from './indicadores-historico-config';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
{ id: 'seguimiento', label: 'Análisis de riesgos' },
{ id: 'datos', label: 'Datos y definiciones' },
];
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
// between its history and its follow-up list.
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
export const CAMA_ANALYSIS_ENABLED = false;
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; }
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
private readonly analisis = viewChild(IndicadoresAnalisis);
// The patients of a curve or a heatmap cell, opened in Seguimiento; the id makes a repeated click apply again.
// It belongs to the domain it was made in and stays while the user moves between the tabs.
readonly seleccionSeguimiento = signal<SeleccionSeguimiento | undefined>(undefined);
verPacientes(seleccion: SeleccionPacientes) {
this.seleccionSeguimiento.set({ ...seleccion, id: (this.seleccionSeguimiento()?.id ?? 0) + 1 });
this.changeSection('seguimiento');
}
// Back to the analysis: the part, the scroll and the focus where the user left them.
volverAlAnalisis() {
this.changeSection('analisis');
afterNextRender(() => this.analisis()?.restaurar(), { injector: this.injector });
}
setFichaPacienteAbierta(open: boolean) {
this.fichaPacienteAbierta.set(open);
}
changeSection(section: DashboardSection) {
if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return;
this.activeSection.set(section);
// Retain views, filters and Plotly hosts; only visible regions authorize loading.
if (section !== 'resumen') for (const card of this.graphicCards()) card.setVisible(false);
this.visibilityChanged();
}
sectionKeydown(event: KeyboardEvent) {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
const tabs = Array.from(this.element.nativeElement.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
const index = tabs.indexOf(event.target as HTMLButtonElement);
if (index < 0) return;
event.preventDefault();
const next = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1
: (index + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
// Manual activation: arrows move focus; Enter/Space activate the native button.
tabs[next].focus();
}
private readonly document = inject(DOCUMENT);
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly injector = inject(Injector);
private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
readonly kpiPanels = viewChildren(IndicadorKpiPanel);
// The opportunity cards share the period their own query already resolved.
get periodoCompartido(): string {
const deConsulta = this.kpiPanels().map(panel => panel.temporalReference.trim())
.find(text => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(text));
if (deConsulta) return deConsulta;
const applied = this.filters?.applied;
return applied?.selection.mode === 'explicit' && applied.selection.periodos.length === 1 ? applied.selection.periodos[0] : '';
}
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
private renderedCards: readonly IndicadorCatalogCard[] = [];
private visibilityObserver?: IntersectionObserver;
private sizeObserver?: ResizeObserver;
private readonly sizeTargets = new Set<Element>();
private frame?: number;
private stickyHeight = -1;
private visibilityDestroyed = false;
private readonly viewportChanged = () => this.visibilityChanged();
visibilityChanged() {
this.queueVisibility();
}
private queueVisibility() {
const browser = this.document.defaultView;
if (this.visibilityDestroyed || !this.visibilityObserver || !browser || this.frame !== undefined) return;
this.frame = browser.requestAnimationFrame(() => {
this.frame = undefined;
this.evaluateVisibility();
});
}
private clearVisibility() {
this.visibilityObserver?.disconnect();
this.visibilityObserver = undefined;
this.observedRegions.clear();
this.renderedCards = [];
if (this.frame !== undefined) this.document.defaultView?.cancelAnimationFrame(this.frame);
this.frame = undefined;
}
private syncVisibility() {
if (this.visibilityDestroyed || !this.document.defaultView) return;
const cards = this.graphicCards();
if (this.activeSection() !== 'resumen') {
for (const card of cards) card.setVisible(false);
return;
}
if (typeof IntersectionObserver === 'undefined') {
for (const card of cards) card.setVisible(true);
return;
}
const orderChanged = cards.length !== this.renderedCards.length || cards.some((card, i) => card !== this.renderedCards[i]);
this.renderedCards = [...cards];
this.refreshVisibilityObserver();
let changed = orderChanged;
for (const [region, card] of this.observedRegions) {
if (!cards.includes(card) || card.visibilityRegion?.nativeElement !== region) {
this.visibilityObserver?.unobserve(region);
this.observedRegions.delete(region);
changed = true;
}
}
for (const card of cards) {
const region = card.visibilityRegion?.nativeElement;
if (region && !this.observedRegions.has(region)) {
this.observedRegions.set(region, card);
this.visibilityObserver?.observe(region);
changed = true;
}
}
if (typeof ResizeObserver !== 'undefined') {
this.sizeObserver ??= new ResizeObserver(this.viewportChanged);
const targets = [this.document.querySelector('.institutional-header'), this.element.nativeElement.querySelector('.catalog-grid')]
.filter((target): target is Element => target !== null);
for (const target of this.sizeTargets) {
if (!targets.includes(target)) { this.sizeObserver.unobserve(target); this.sizeTargets.delete(target); }
}
for (const target of targets) {
if (!this.sizeTargets.has(target)) { this.sizeTargets.add(target); this.sizeObserver.observe(target); }
}
}
if (changed) this.visibilityChanged();
}
private refreshVisibilityObserver() {
const height = Math.max(0, this.document.querySelector('.institutional-header')?.getBoundingClientRect().bottom ?? 0);
if (this.visibilityObserver && Math.abs(height - this.stickyHeight) < 1) return;
this.stickyHeight = height;
this.visibilityObserver?.disconnect();
const observer = new IntersectionObserver(entries => {
// Callbacks from a replaced observer or retired target cannot authorize activation.
if (this.visibilityDestroyed || this.visibilityObserver !== observer) return;
if (entries.some(entry => this.observedRegions.has(entry.target))) this.queueVisibility();
}, { root: null, rootMargin: `-${height}px 0px 200px 0px`, threshold: 0 });
this.visibilityObserver = observer;
for (const region of this.observedRegions.keys()) observer.observe(region);
}
// Report: every selected chart has to be drawn, narrow enough for a page, before opening the print dialog.
readonly preparandoReporte = signal(false);
async descargarReporte() {
const browser = this.document.defaultView;
if (!browser || this.preparandoReporte()) return;
this.preparandoReporte.set(true);
for (const card of this.graphicCards()) card.setVisible(true);
this.changeDetector.markForCheck();
const espera = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const pendiente = () => this.element.nativeElement.querySelector('#panel-resumen mat-progress-bar, #panel-resumen .figure-skeleton');
await espera(100);
for (let i = 0; pendiente() && i < 150; i++) await espera(100);
// Charts resize to the page width on their next frames.
await espera(500);
const terminar = () => { this.preparandoReporte.set(false); this.changeDetector.markForCheck(); this.visibilityChanged(); };
browser.addEventListener('afterprint', terminar, { once: true });
browser.print();
}
private evaluateVisibility() {
if (this.preparandoReporte()) return;
const browser = this.document.defaultView;
if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return;
if (this.activeSection() !== 'resumen') return;
this.refreshVisibilityObserver();
const width = browser.innerWidth, height = browser.innerHeight;
// Reread connected graphic regions after scroll/reorder; old observer rectangles
// cannot activate a card that has since moved outside the current viewport.
for (const card of this.renderedCards) {
const region = card.visibilityRegion?.nativeElement;
if (!region || card.dominio !== this.dominio || !region.isConnected) continue;
const rect = region.getBoundingClientRect();
card.setVisible(rect.width > 0 && rect.height > 0 && rect.right > 0
&& rect.left < width && rect.bottom > this.stickyHeight && rect.top < height + 200);
}
this.changeDetector.markForCheck();
}
changeIndicatorSelection(ids: string[]) {
this.preserveCardFocus();
// Every indicator checked is the same as no filter, so later catalog additions also show.
this.indicatorSelection.set(ids.length === this.catalogOrder().length ? null : ids);
}
showAllIndicators() { this.changeIndicatorSelection(this.catalogOrder().map(item => item.id)); }
isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); }
togglePinned(item: Indicador) {
this.preserveCardFocus();
this.memory.togglePinned(this.dominio, item.id);
}
private preserveCardFocus() {
const focused = this.document.activeElement;
if (focused instanceof HTMLElement && this.element.nativeElement.contains(focused)
&& focused.closest('app-indicador-catalog-card')) {
// Moving a retained view can blur its control. Restore only that connected control,
// without overriding focus deliberately assigned elsewhere during the update.
afterNextRender(() => {
if (focused.isConnected && this.document.activeElement === this.document.body) {
focused.focus({ preventScroll: true });
}
}, { injector: this.injector });
}
}
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly service = inject(IndicadoresService);
private readonly periodService = inject(IndicadoresPeriodos);
private readonly initialPeriod = inject(IndicadoresInitialPeriod);
private readonly cancelInitialPeriod = new Subject<void>();
readonly initialPeriodState = signal<'ready' | 'loading' | 'error' | 'empty' | 'manual' | 'unavailable'>('ready');
readonly initialPeriodError = signal('');
get initialPeriodBlocked() { return this.initialPeriodState() !== 'ready'; }
get initialPeriodAnchorTitle() { return this.availableKpis[0]?.title ?? ''; }
retryInitialPeriod() { this.initializePeriod(); }
private initializePeriod() {
this.cancelInitialPeriod.next();
this.initialPeriodState.set('ready');
this.initialPeriodError.set('');
const domain = this.dominio, state = this.filters, anchor = this.kpisByDomain[domain][0];
if (!state || !anchor || !this.availableKpis.length || !this.memory.initialKpiPresentation(domain)) return;
if (!this.kpiIndicator(anchor.id)) { this.initialPeriodState.set('unavailable'); return; }
// A saved manual draft must survive navigation and a catalog retry.
if (pending(state)) { this.initialPeriodState.set('manual'); return; }
this.initialPeriodState.set('loading');
this.initialPeriod.find(domain, anchor, state.tipo, this.kpiIndicator(anchor.id)?.version).pipe(
map(period => ({ period, error: '' })),
catchError(error => of({ period: undefined, error: httpMessage(error) })),
takeUntil(this.cancelInitialPeriod), takeUntilDestroyed(this.destroyRef),
).subscribe(({ period, error }) => {
if (error) {
this.initialPeriodError.set(error);
this.initialPeriodState.set('error');
return;
}
if (!period) { this.initialPeriodState.set('empty'); return; }
state.tipo = period.tipo;
state.editors[period.tipo] = { added: state.editors[period.tipo]?.added ?? [],
draft: { mode: 'explicit', periodos: [period.periodo] } };
applyGlobal(state, this.filterTypes());
this.memory.finishInitialKpiPresentation(domain);
this.filtersEdited();
this.initialPeriodState.set('ready');
});
}
private readonly availabilityRequests = new Subject<void>();
readonly availability = signal(emptyAvailability());
private readonly memory = inject(IndicadoresMemory);
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute, { optional: true });
dominio: Dominio = 'tea';
readonly domainLabels: Record<Dominio, string> = {
tea: 'trastorno del espectro autista', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama',
};
readonly domainTitles: Record<Dominio, string> = {
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
};
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
kpiIndicator(id: string) {
const published = this.catalog().find(item => item.id === id);
if (published) return published;
// The lab partner is deliberately hidden from some catalogs, as in the paired figure.
// Reuse its established periodicity, without assigning the diagnosis version to lab data.
if (this.dominio === 'cacu' && id === CACU_RESULTADO_KPI.id) {
const diagnosis = this.catalog().find(item => item.id === 'cacu_dias_toma_diagnostico');
if (diagnosis) return { id, titulo: CACU_RESULTADO_KPI.title, contrato: diagnosis.contrato,
figuras: [], tipos_periodo: diagnosis.tipos_periodo };
}
return undefined;
}
// CaMa's summary: without the indicators it does not draw, and with the patients' counts on the exams' card.
private cardsDeCama(catalog: Indicador[]) {
const ids = catalog.map(item => item.id);
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
// The histopathology card keeps its place, first, whether pending or published.
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
}
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
get histopatologiaPendiente() {
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
}
// CaCu's screening route chart, once the catalog publishes every measure it reads.
get screeningRouteAvailable() {
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
}
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
get teaResumenPeriodo(): string | undefined {
const selection = this.filters?.applied.selection;
return this.dominio === 'tea' && selection?.mode === 'explicit' && selection.periodos.length === 1 ? selection.periodos[0] : undefined;
}
get opportunityKpis() {
const definitions = this.availableKpis;
if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions;
// Keep the established KPI definitions and initial-period anchor intact.
const diagnosis = definitions.findIndex(item => item.id === 'cacu_dias_toma_diagnostico');
return [...definitions.slice(0, diagnosis < 0 ? definitions.length : diagnosis), CACU_RESULTADO_KPI,
...definitions.slice(diagnosis < 0 ? definitions.length : diagnosis)];
}
// What the KPI grid draws. CaMa adds explicit pending cards for opportunity indicators the catalog does not publish.
get kpiCards(): KpiCardSlot[] {
if (this.dominio === 'cama') return camaKpiCards(id => this.catalog().some(item => item.id === id));
return this.opportunityKpis.map(definition => ({ definition, pending: false }));
}
private readonly catalogRequests = new Subject<void>();
readonly catalog = signal<Indicador[]>([]);
// Ids of the indicators to render; null shows the whole catalog.
readonly indicatorSelection = signal<string[] | null>(null);
// The summary follows CaMa's mockup: no search box and no pins in any domain.
readonly searchVisible = computed(() => false);
// Stable presentation order. Pins no longer reorder the summary.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
// The route chart draws its own measures: they get no card of their own once it is there.
const route = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : [];
return this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))]
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
});
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
readonly selectionSummary = computed(() => {
const selected = this.selectedIndicators();
if (this.indicatorSelection() === null) return 'Todos los indicadores';
if (selected.length === 1) return this.catalog().find(item => item.id === selected[0])?.titulo ?? selected[0];
return selected.length + ' indicadores';
});
readonly searchResults = computed(() => {
const selected = new Set(this.selectedIndicators());
return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
});
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
tema: Tema = 'claro';
filters?: GlobalFilterState;
readonly filterTypes = computed(() => domainTypes(this.catalog()));
retryAvailability() { this.availabilityRequests.next(); }
filtersEdited() { if (this.filters) this.memory.saveGlobal(this.dominio, this.filters); }
editFilters() {
if (this.memory.initialKpiPresentation(this.dominio)) {
this.cancelInitialPeriod.next();
this.initialPeriodState.set('manual');
}
this.filtersEdited();
}
applyFilters() {
this.evaluateVisibility();
if (!this.filters) return;
const draft = this.filters.editors[this.filters.tipo]?.draft;
if (!draft || !validDraft(draft, this.filters.tipo, this.filterTypes())) return;
const initial = this.memory.initialKpiPresentation(this.dominio);
this.cancelInitialPeriod.next();
this.initialPeriodState.set('ready');
this.memory.finishInitialKpiPresentation(this.dominio);
if (!applyGlobal(this.filters, this.filterTypes()) && !initial) return;
this.filtersEdited();
this.changeDetector.markForCheck();
}
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); }
// «Ir» in the indicator selector: show the indicator if it was filtered out, then scroll to its card.
goToIndicator(id: string, event?: Event) {
// The link sits inside a mat-option: it must not toggle the option's selection.
event?.preventDefault(); event?.stopPropagation();
if (!this.catalog().some(item => item.id === id)) return;
const selection = this.indicatorSelection();
if (selection && !selection.includes(id)) this.indicatorSelection.set([...selection, id]);
const key = indicatorIdentity(this.dominio, id), select = this.indicatorSelect();
const scroll = () => afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector });
// Closing the panel returns focus to the selector, which would cancel a scroll started before it ends.
if (select?.panelOpen) { select.openedChange.pipe(first(open => !open)).subscribe(scroll); select.close(); }
else scroll();
}
private scrollToIndicator(key: string) {
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()) return;
const target = this.document.getElementById(identityElementId(key));
const grid = this.element.nativeElement.querySelector('.catalog-grid');
if (!target || !grid?.contains(target)) return;
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
target.querySelector('h2')?.focus({ preventScroll: true });
this.keepAligned(target, grid);
}
// Figures above the card load as the scroll passes them and grow taller than their placeholders,
// pushing the card down. For a short while, put it back in place whenever the grid resizes;
// any scrolling by the user ends this.
private stopAligning?: () => void;
private keepAligned(target: HTMLElement, grid: Element) {
this.stopAligning?.();
const browser = this.document.defaultView;
if (!browser || typeof ResizeObserver === 'undefined') return;
const host = this.element.nativeElement;
const userInput = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const;
const observer = new ResizeObserver(() => {
const offset = target.getBoundingClientRect().top - host.getBoundingClientRect().top - parseFloat(browser.getComputedStyle(target).scrollMarginTop || '0');
if (Math.abs(offset) > 2) target.scrollIntoView({ behavior: 'instant', block: 'start' });
});
const timer = setTimeout(() => this.stopAligning?.(), 2500);
const stop = () => {
observer.disconnect(); clearTimeout(timer);
for (const type of userInput) host.removeEventListener(type, stop);
if (this.stopAligning === stop) this.stopAligning = undefined;
};
this.stopAligning = stop;
observer.observe(grid);
for (const type of userInput) host.addEventListener(type, stop, { passive: true });
}
constructor() {
afterEveryRender(() => {
this.syncVisibility();
});
const browser = this.document.defaultView;
if (typeof IntersectionObserver !== 'undefined') {
browser?.addEventListener('scroll', this.viewportChanged, { passive: true });
browser?.addEventListener('resize', this.viewportChanged);
}
this.destroyRef.onDestroy(() => {
this.stopAligning?.();
this.filtersEdited();
this.visibilityDestroyed = true;
this.clearVisibility();
this.sizeObserver?.disconnect();
this.sizeTargets.clear();
browser?.removeEventListener('scroll', this.viewportChanged);
browser?.removeEventListener('resize', this.viewportChanged);
});
const initialDomain: unknown = this.route?.snapshot.data['dominio'];
if (isDominio(initialDomain)) this.dominio = initialDomain;
this.tema = this.memory.theme(this.dominio);
this.availabilityRequests.pipe(switchMap(() => {
this.availability.set(emptyAvailability());
return this.periodService.dominio(this.dominio, this.catalog());
}), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state));
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
this.cancelInitialPeriod.next();
this.initialPeriodState.set('ready');
this.clearVisibility();
this.catalogLoading.set(true);
this.catalogError.set('');
this.catalog.set([]);
this.availabilityRequests.next();
return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })),
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
this.catalogLoading.set(false);
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
this.catalog.set(this.dominio === 'cama' ? items.map(item => item.id === 'cama_birads_456_mastografia'
? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item) : items);
this.filtersEdited();
this.catalogError.set(error);
this.availabilityRequests.next();
this.initializePeriod();
});
}
changeDominio(dominio: Dominio) {
if (!isDominio(dominio) || dominio === this.dominio) return;
this.activeSection.set('resumen');
this.indicatorSelection.set(null);
this.seleccionSeguimiento.set(undefined);
this.filtersEdited();
this.filters = undefined;
this.dominio = dominio;
this.tema = this.memory.theme(dominio);
this.catalogRequests.next();
}
retryCatalog() { this.catalogRequests.next(); }
changeTema(tema: Tema) {
if ((tema !== 'claro' && tema !== 'oscuro') || tema === this.tema) return;
this.evaluateVisibility();
this.tema = tema;
this.memory.rememberTheme(this.dominio, tema);
this.changeDetector.markForCheck();
}
}