0914b8db23
Confirmation, screening-to-diagnosis and exam-to-result cards leave the summary (they stay in Histórico and Datos y definiciones). The histopathological result by BI-RADS keeps its place and structure as a pending card, with no figure or number, until the catalog publishes its indicator. The patients KPI uses the reference's wording.
555 lines
29 KiB
TypeScript
555 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 { MatSelectModule } from '@angular/material/select';
|
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
|
import { ConnectedPosition, Overlay, OverlayModule } from '@angular/cdk/overlay';
|
|
import { catchError, 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, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
|
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
|
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 { IndicadoresHistorico } from './indicadores-historico';
|
|
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
|
import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel';
|
|
|
|
type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos';
|
|
|
|
const SECCIONES: readonly { id: DashboardSection; label: string }[] = [
|
|
{ id: 'resumen', label: 'Resumen' },
|
|
{ id: 'seguimiento', label: 'Seguimiento' },
|
|
{ id: 'datos', label: 'Datos y definiciones' },
|
|
];
|
|
const SECCIONES_CON_HISTORICO: readonly { id: DashboardSection; label: string }[] = [SECCIONES[0], { id: 'historico', label: 'Histórico' }, SECCIONES[1], SECCIONES[2]];
|
|
|
|
@Component({
|
|
selector: 'app-indicadores-page',
|
|
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico],
|
|
templateUrl: './indicadores-page.html',
|
|
styleUrl: './indicadores-page.scss',
|
|
})
|
|
export class IndicadoresPage {
|
|
// The history tab is CaMa's; the other domains keep their three sections.
|
|
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; }
|
|
get conHistorico() { return this.dominio === 'cama'; }
|
|
readonly activeSection = signal<DashboardSection>('resumen');
|
|
readonly fichaPacienteAbierta = signal(false);
|
|
setFichaPacienteAbierta(open: boolean) {
|
|
this.fichaPacienteAbierta.set(open);
|
|
if (open) this.closeGraphicNavigation(false, false);
|
|
}
|
|
changeSection(section: DashboardSection) {
|
|
if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return;
|
|
if (section !== 'resumen') this.closeGraphicNavigation(false, false);
|
|
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 searchInput = viewChild<ElementRef<HTMLInputElement>>('searchInput');
|
|
private readonly overlay = inject(Overlay);
|
|
readonly navigationScrollStrategy = this.overlay.scrollStrategies.reposition();
|
|
readonly navigationPositions: ConnectedPosition[] = [
|
|
{ originX: 'start', originY: 'center', overlayX: 'start', overlayY: 'center' },
|
|
{ originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top' },
|
|
{ originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'bottom' },
|
|
{ originX: 'end', originY: 'center', overlayX: 'end', overlayY: 'center' },
|
|
];
|
|
readonly navigationOpen = signal(false);
|
|
readonly navigationClosing = signal(false);
|
|
readonly navigationAttached = computed(() => this.navigationOpen() || this.navigationClosing());
|
|
readonly navigationKeyboard = signal(false);
|
|
private readonly navigationPanel = viewChild(IndicadoresNavegacionPanel);
|
|
private navigationHoverTimer?: ReturnType<typeof setTimeout>;
|
|
private navigationAnimationTimer?: ReturnType<typeof setTimeout>;
|
|
private navigationPointerInside = false;
|
|
// Removing the overlay can generate pointerenter on the button under a stationary cursor.
|
|
private navigationHoverDismissed = false;
|
|
readonly navigationItems = computed<readonly IndicadorNavegacionItem[]>(() =>
|
|
this.searchResults().items.map(item => ({ key: indicatorIdentity(this.dominio, item.id), titulo: item.titulo })));
|
|
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
|
|
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);
|
|
}
|
|
private evaluateVisibility() {
|
|
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();
|
|
}
|
|
clearSearch() {
|
|
this.changeSearchQuery('');
|
|
this.searchInput()?.nativeElement.focus({ preventScroll: true });
|
|
}
|
|
changeSearchQuery(query: string) {
|
|
this.preserveCardFocus();
|
|
this.searchQuery.set(query);
|
|
}
|
|
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: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
|
|
// At the start of the header line.
|
|
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
|
|
readonly kpisByDomain = KPI_BY_DOMAIN;
|
|
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);
|
|
return catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
|
|
}
|
|
// 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);
|
|
}
|
|
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
|
|
get shownIndicators() { return this.dominio === 'cama' ? this.searchResults().items.length : this.catalog().length; }
|
|
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
|
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[]>([]);
|
|
readonly searchQuery = signal('');
|
|
// CaMa follows the mockup: no search box and no pins; its cards are the ones the summary draws.
|
|
// The catalog is read first: `dominio` is not a signal, so a short-circuit before the read would leave this
|
|
// computed without dependencies, and it would never change after a visit to CaMa.
|
|
readonly searchVisible = computed(() => { const total = this.catalog().length; return this.dominio !== 'cama' && total >= 5; });
|
|
readonly searchResults = computed(() => {
|
|
const catalog = this.catalog();
|
|
// Stable presentation priority; search matches and pins still take precedence.
|
|
const items = this.dominio === 'cacu'
|
|
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
|
|
: this.dominio === 'cama' ? this.cardsDeCama(catalog) : catalog;
|
|
if (this.dominio === 'cama') return { items, active: false, count: 0 };
|
|
const query = this.normalizeSearch(this.searchQuery());
|
|
const prioritize = (group: Indicador[]) => [
|
|
...group.filter(item => this.isPinned(item)),
|
|
...group.filter(item => !this.isPinned(item)),
|
|
];
|
|
if (!query) return { items: prioritize(items), active: false, count: 0 };
|
|
const matches: Indicador[] = [];
|
|
const remaining: Indicador[] = [];
|
|
for (const item of items) {
|
|
const matchesQuery = [item.titulo, item.id].some(value => this.normalizeSearch(value).includes(query));
|
|
(matchesQuery ? matches : remaining).push(item);
|
|
}
|
|
return { items: [...prioritize(matches), ...prioritize(remaining)], active: true, count: matches.length };
|
|
});
|
|
private normalizeSearch(value: string) {
|
|
return value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim();
|
|
}
|
|
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)); }
|
|
get showGraphicNavigation() {
|
|
return this.dominio !== 'cama' && this.activeSection() === 'resumen' && !this.fichaPacienteAbierta() && !this.catalogLoading()
|
|
&& !this.catalogError() && !this.initialPeriodBlocked && this.navigationItems().length > 0;
|
|
}
|
|
toggleGraphicNavigation(event?: MouseEvent) {
|
|
if (!this.showGraphicNavigation) return;
|
|
if (this.navigationOpen()) this.closeGraphicNavigation(false);
|
|
else this.openGraphicNavigation(event?.detail === 0);
|
|
}
|
|
private openGraphicNavigation(keyboard = false) {
|
|
if (!this.showGraphicNavigation) return;
|
|
this.clearNavigationTimers();
|
|
this.navigationHoverDismissed = false;
|
|
this.navigationKeyboard.set(keyboard);
|
|
this.navigationClosing.set(false);
|
|
this.navigationOpen.set(true);
|
|
if (keyboard) afterNextRender(() => {
|
|
if (this.navigationOpen() && this.navigationKeyboard()) this.navigationPanel()?.focusFirstOption();
|
|
}, { injector: this.injector });
|
|
}
|
|
navigationTriggerKeydown(event: KeyboardEvent) {
|
|
if (event.key !== 'Enter' && event.key !== ' ') return;
|
|
event.preventDefault();
|
|
this.openGraphicNavigation(true);
|
|
}
|
|
navigationPointerEnter(event: PointerEvent) {
|
|
if (this.navigationHoverDismissed || !this.navigationCanHover(event)) return;
|
|
this.navigationPointerInside = true;
|
|
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
|
this.navigationHoverTimer = undefined;
|
|
if (!this.navigationOpen()) this.openGraphicNavigation();
|
|
}
|
|
navigationPointerMove(event: PointerEvent) {
|
|
if (!this.navigationHoverDismissed || !this.navigationCanHover(event)) return;
|
|
this.navigationHoverDismissed = false;
|
|
this.navigationPointerEnter(event);
|
|
}
|
|
private navigationCanHover(event: PointerEvent) {
|
|
return event.pointerType === 'mouse' && this.document.defaultView?.matchMedia?.('(hover: hover) and (pointer: fine)').matches;
|
|
}
|
|
navigationPointerLeave(event: PointerEvent) {
|
|
if (!this.navigationCanHover(event)) return;
|
|
this.navigationPointerInside = false;
|
|
this.scheduleNavigationClose();
|
|
}
|
|
navigationFocusOut() { this.scheduleNavigationClose(); }
|
|
private scheduleNavigationClose() {
|
|
if (!this.navigationOpen()) return;
|
|
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
|
this.navigationHoverTimer = setTimeout(() => {
|
|
this.navigationHoverTimer = undefined;
|
|
if (!this.navigationPointerInside && !this.navigationPanel()?.containsFocus()) this.closeGraphicNavigation(false);
|
|
}, 230);
|
|
}
|
|
navigationOverlayKeydown(event: KeyboardEvent) {
|
|
if (event.key !== 'Escape') return;
|
|
event.preventDefault();
|
|
this.closeGraphicNavigation();
|
|
}
|
|
private clearNavigationTimers() {
|
|
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
|
if (this.navigationAnimationTimer !== undefined) clearTimeout(this.navigationAnimationTimer);
|
|
this.navigationHoverTimer = this.navigationAnimationTimer = undefined;
|
|
}
|
|
closeGraphicNavigation(restoreFocus = true, animate = true) {
|
|
const wasOpen = this.navigationOpen();
|
|
this.clearNavigationTimers();
|
|
this.navigationHoverDismissed ||= wasOpen;
|
|
this.navigationPointerInside = false;
|
|
this.navigationKeyboard.set(false);
|
|
this.navigationOpen.set(false);
|
|
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
|
this.navigationClosing.set(animate && wasOpen && !reducedMotion);
|
|
if (this.navigationClosing()) this.navigationAnimationTimer = setTimeout(() => {
|
|
this.navigationAnimationTimer = undefined;
|
|
this.navigationClosing.set(false);
|
|
}, 180);
|
|
if (wasOpen && restoreFocus && this.showGraphicNavigation) {
|
|
this.element.nativeElement.querySelector<HTMLButtonElement>('.graphic-navigation-trigger')?.focus({ preventScroll: true });
|
|
}
|
|
}
|
|
closeGraphicNavigationFromOutside(event: MouseEvent) {
|
|
const target = event.target;
|
|
const trigger = this.element.nativeElement.querySelector<HTMLButtonElement>('.graphic-navigation-trigger');
|
|
if (target instanceof Node && trigger?.contains(target)) return;
|
|
this.closeGraphicNavigation(false);
|
|
}
|
|
selectGraphicNavigation(key: string) {
|
|
if (!this.navigationItems().some(item => item.key === key)) {
|
|
this.closeGraphicNavigation(false);
|
|
return;
|
|
}
|
|
this.closeGraphicNavigation(false, false);
|
|
afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector });
|
|
}
|
|
private scrollToIndicator(key: string) {
|
|
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()
|
|
|| !this.navigationItems().some(item => item.key === key)) 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 });
|
|
}
|
|
constructor() {
|
|
afterEveryRender(() => {
|
|
this.syncVisibility();
|
|
if (!this.showGraphicNavigation && (this.navigationAttached() || this.navigationHoverTimer !== undefined)) this.closeGraphicNavigation(false, false);
|
|
});
|
|
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.filtersEdited();
|
|
this.visibilityDestroyed = true;
|
|
this.closeGraphicNavigation(false, false);
|
|
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.closeGraphicNavigation(false, false);
|
|
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(items);
|
|
this.filtersEdited();
|
|
this.catalogError.set(error);
|
|
this.availabilityRequests.next();
|
|
this.initializePeriod();
|
|
});
|
|
}
|
|
changeDominio(dominio: Dominio) {
|
|
if (!isDominio(dominio) || dominio === this.dominio) return;
|
|
this.closeGraphicNavigation(false, false);
|
|
this.activeSection.set('resumen');
|
|
this.searchQuery.set('');
|
|
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();
|
|
}
|
|
}
|