275 lines
13 KiB
TypeScript
275 lines
13 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, RouterLink } 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 { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
|
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
|
|
import { IndicadoresService } from './indicadores.service';
|
|
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, validDraft } from './indicadores-memory';
|
|
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
|
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
|
import { indicatorIdentity } from './indicadores-identities';
|
|
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
|
import { httpMessage } from './indicadores-http';
|
|
|
|
@Component({
|
|
selector: 'app-indicadores-page',
|
|
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters],
|
|
templateUrl: './indicadores-page.html',
|
|
styleUrl: './indicadores-page.scss',
|
|
})
|
|
export class IndicadoresPage {
|
|
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 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 (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;
|
|
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 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 });
|
|
readonly dominios = DOMINIOS;
|
|
dominio: Dominio = 'tea';
|
|
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
|
readonly kpisByDomain = KPI_BY_DOMAIN;
|
|
kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); }
|
|
get availableKpis() { return this.kpisByDomain[this.dominio]; }
|
|
get initialKpiPresentation() { return !!this.availableKpis.length && this.memory.initialKpiPresentation(this.dominio); }
|
|
private readonly catalogRequests = new Subject<void>();
|
|
readonly catalog = signal<Indicador[]>([]);
|
|
readonly searchQuery = signal('');
|
|
readonly searchVisible = computed(() => this.catalog().length >= 5);
|
|
readonly searchResults = computed(() => {
|
|
const items = this.catalog();
|
|
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); }
|
|
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.initialKpiPresentation;
|
|
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); }
|
|
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.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.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();
|
|
});
|
|
}
|
|
changeDominio(dominio: Dominio) {
|
|
if (!isDominio(dominio) || dominio === this.dominio) return;
|
|
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();
|
|
}
|
|
}
|