From 98d0614d80b995ec4ca55d34ff89a29ef62a258f Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 13 Oct 2026 16:34:28 -0600 Subject: [PATCH] feat(ui): habilitar apertura automatica UX-06E.D.1.1 --- .../indicadores/indicador-catalog-card.ts | 47 ++- .../indicadores/indicadores-memory.spec.ts | 20 +- .../indicadores/indicadores-memory.ts | 12 +- .../indicadores-navigation.spec.ts | 2 +- .../indicadores/indicadores-page.html | 2 +- .../indicadores/indicadores-page.spec.ts | 31 +- .../features/indicadores/indicadores-page.ts | 144 +++++++- .../indicadores-plotly-lifecycle.spec.ts | 2 + .../indicadores/indicadores-search.spec.ts | 7 +- .../indicadores-visibility.spec.ts | 310 ++++++++++++++++++ 10 files changed, 530 insertions(+), 47 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-visibility.spec.ts diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 993dfac..0b852bd 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -1,10 +1,10 @@ import { DOCUMENT } from '@angular/common'; -import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, ViewChild } from '@angular/core'; +import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, output, ViewChild } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { Dominio, Indicador, Tema } from './indicadores.models'; -import { IndicadoresMemory } from './indicadores-memory'; +import { CardActivation, IndicadoresMemory } from './indicadores-memory'; import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; import { IndicadorFigurePanel } from './indicador-figure-panel'; @@ -13,17 +13,19 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel], template: ` -
+

{{ indicador.titulo }}

{{ indicador.id }}

+ [attr.aria-controls]="contentId" [attr.aria-label]="(awaitingFigures ? 'Mostrar figuras de ' : expanded ? 'Contraer ' : 'Expandir ') + dominio + ' · ' + indicador.id + ' · ' + indicador.titulo" + (click)="toggle()">
- @if (expanded) { + @if (awaitingFigures) { + + } @else if (expanded && figuresActivated) { @for (figure of indicador.figuras; track panelIdentity(figure)) { @@ -52,14 +54,20 @@ export class IndicadorCatalogCard implements OnChanges { @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) indicador!: Indicador; @Input({ required: true }) tema!: Tema; - @Input({ required: true }) initialExpanded!: boolean; + @ViewChild('visibilityHeader', { static: true }) visibilityHeader!: ElementRef; + readonly host = inject>(ElementRef); + readonly activationChanged = output(); @ViewChild('toggleButton', { read: ElementRef }) toggleButton!: ElementRef; @ViewChild('content') content!: ElementRef; private readonly changeDetector = inject(ChangeDetectorRef); private readonly memory = inject(IndicadoresMemory); private readonly document = inject(DOCUMENT); private identity = ''; - expanded = false; + private state: CardActivation = 'pending'; + figuresActivated = false; + get expanded() { return this.state === 'auto-open' || this.state === 'manual-open'; } + get awaitingFigures() { return this.expanded && !this.figuresActivated; } + get awaitingVisibility() { return this.state === 'pending' || this.awaitingFigures; } titleId = ''; contentId = ''; panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); } @@ -70,14 +78,29 @@ export class IndicadorCatalogCard implements OnChanges { const id = identityElementId(identity); this.titleId = id + '-title'; this.contentId = id + '-content'; - this.expanded = this.memory.expanded(this.dominio, this.indicador.id) ?? this.initialExpanded; + this.state = this.memory.activation(this.dominio, this.indicador.id); + this.figuresActivated = false; + } + activateVisible() { + // Recheck the decision at commit time, including manual changes after observation. + if (!this.awaitingVisibility) return; + if (this.state === 'pending') { + this.state = 'auto-open'; + this.memory.rememberActivation(this.dominio, this.indicador.id, this.state); + } + this.figuresActivated = true; + this.changeDetector.markForCheck(); } toggle() { - if (this.expanded && this.content.nativeElement.contains(this.document.activeElement)) { + if (this.expanded && !this.awaitingFigures && this.content.nativeElement.contains(this.document.activeElement)) { this.toggleButton.nativeElement.focus(); } - this.expanded = !this.expanded; - this.memory.rememberExpansion(this.dominio, this.indicador.id, this.expanded); + // A restored open preference first shows its figures; the next click closes. + const opening = !this.expanded || this.awaitingFigures; + this.state = opening ? 'manual-open' : 'manual-closed'; + this.figuresActivated = opening; + this.memory.rememberActivation(this.dominio, this.indicador.id, this.state); + this.activationChanged.emit(); this.changeDetector.markForCheck(); } } diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts index f0913ac..05f1ad0 100644 --- a/src/app/features/indicadores/indicadores-memory.spec.ts +++ b/src/app/features/indicadores/indicadores-memory.spec.ts @@ -35,13 +35,15 @@ describe('UX-04 memoria temporal', () => { ['cacu', indicador, 'f'], ['tea', { ...indicador, id: 'otro' }, 'f'], ['tea', indicador, 'g'], ] as const) expect(memory.restore(domain, item, figure).editors.semestre?.draft.mode).toBe('todos'); }); - it('distingue ausencia de expansión, true y false y aísla dominios', () => { - expect(memory.expanded('tea', 'i')).toBeUndefined(); - memory.rememberExpansion('tea', 'i', false); - memory.rememberExpansion('cacu', 'i', true); - expect(memory.expanded('tea', 'i')).toBe(false); - expect(memory.expanded('cacu', 'i')).toBe(true); - expect(memory.expanded('tea', 'otro')).toBeUndefined(); + it('distingue activación pendiente, automática y manual y aísla dominios', () => { + expect(memory.activation('tea', 'i')).toBe('pending'); + memory.rememberActivation('tea', 'i', 'manual-closed'); + memory.rememberActivation('cacu', 'i', 'auto-open'); + expect(memory.activation('tea', 'i')).toBe('manual-closed'); + expect(memory.activation('cacu', 'i')).toBe('auto-open'); + expect(memory.activation('tea', 'otro')).toBe('pending'); + memory.rememberActivation('cama', 'i', 'manual-open'); + expect(memory.activation('cama', 'i')).toBe('manual-open'); memory.rememberTheme('cacu', 'oscuro'); expect(memory.theme('cacu')).toBe('oscuro'); expect(memory.theme('tea')).toBe('claro'); @@ -49,10 +51,10 @@ describe('UX-04 memoria temporal', () => { it('una instancia nueva reinicia las selecciones y no lee ni escribe almacenamiento', () => { const localRead = vi.spyOn(Storage.prototype, 'getItem'); const localWrite = vi.spyOn(Storage.prototype, 'setItem'); - memory.rememberTheme('tea', 'oscuro'); memory.rememberExpansion('tea', 'i', false); + memory.rememberTheme('tea', 'oscuro'); memory.rememberActivation('tea', 'i', 'manual-closed'); memory.save('tea', 'i', 'f', { tipo: 'mes', editors: { mes: { added: [], draft: { mode: 'empty' } } } }); const fresh = new IndicadoresMemory(); - expect(fresh.theme('tea')).toBe('claro'); expect(fresh.expanded('tea', 'i')).toBeUndefined(); + expect(fresh.theme('tea')).toBe('claro'); expect(fresh.activation('tea', 'i')).toBe('pending'); expect(fresh.restore('tea', indicador, 'f').tipo).toBe('semestre'); expect(localRead).not.toHaveBeenCalled(); expect(localWrite).not.toHaveBeenCalled(); localRead.mockRestore(); localWrite.mockRestore(); diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts index e6ca0ac..9978de8 100644 --- a/src/app/features/indicadores/indicadores-memory.ts +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -35,18 +35,20 @@ export function pending(state: FilterState): boolean { return draft.periodos.length !== periodos.length || draft.periodos.some(p => !periodos.includes(p)); } +export type CardActivation = 'pending' | 'auto-open' | 'manual-open' | 'manual-closed'; + @Injectable({ providedIn: 'root' }) export class IndicadoresMemory { private readonly themes = new Map(); - private readonly expansions = new Map(); + private readonly expansions = new Map(); private readonly filters = new Map(); theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; } rememberTheme(domain: Dominio, tema: Tema) { this.themes.set(domain, tema); } - expanded(domain: Dominio, indicador: string): boolean | undefined { - return this.expansions.get(JSON.stringify([domain, indicador])); + activation(domain: Dominio, indicador: string): CardActivation { + return this.expansions.get(JSON.stringify([domain, indicador])) ?? 'pending'; } - rememberExpansion(domain: Dominio, indicador: string, expanded: boolean) { - this.expansions.set(JSON.stringify([domain, indicador]), expanded); + rememberActivation(domain: Dominio, indicador: string, state: CardActivation) { + this.expansions.set(JSON.stringify([domain, indicador]), state); } private key(domain: Dominio, indicador: string, figura: string) { return JSON.stringify([domain, indicador, figura]); diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index 5ad5b40..2de4fd3 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -30,7 +30,7 @@ describe('UX-04 navegación Angular', () => { http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]); harness.detectChanges(); const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; - if (!card.expanded) { card.toggle(); harness.detectChanges(); } + if (!card.expanded || card.awaitingFigures) { card.toggle(); harness.detectChanges(); } const req = http.expectOne(r => r.url.includes('/figuras/')); req.flush({ data: [{ y: [0, null] }], layout: {} }); return req; diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index bfd61a0..954550c 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -61,7 +61,7 @@
@for (item of searchResults().items; track cardIdentity(item)) { + (activationChanged)="visibilityChanged()" /> }
} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 93d7f7b..d44b3d9 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -165,7 +165,7 @@ describe('UX-05B catálogo expandible', () => { expect(cards().every(card => !card.expanded)).toBe(true); http.expectNone(() => true); }); - it.each([0, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => { + it.each([0, 1, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => { const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i })); load(items); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); @@ -173,18 +173,18 @@ describe('UX-05B catálogo expandible', () => { expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/')); if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); }); - it('un indicador se abre y consulta exactamente una vez cada figura publicada', () => { - load([item]); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(2); + it('abrir manualmente un indicador consulta exactamente una vez cada figura publicada', () => { + load([item]); toggle(); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(2); request('f1').flush({ data: [], layout: {} }); request('f2').flush({ data: [], layout: {} }); fixture.detectChanges(); fixture.detectChanges(); http.expectNone(() => true); }); - it('la preferencia false prevalece sobre apertura automática al volver', () => { - load([item]); flushAll(); toggle(); + it('el cierre manual se conserva al volver sin consultar figuras', () => { + load([item]); toggle(); flushAll(); toggle(); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; load([item]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); }); it('indicador sin figuras informa y no consulta HTTP', () => { - load([{ ...item, figuras: [] }]); expect(cards()[0].expanded).toBe(true); + load([{ ...item, figuras: [] }]); toggle(); expect(cards()[0].expanded).toBe(true); expect(fixture.nativeElement.textContent).toContain('no tiene figuras disponibles'); expect(panels()).toHaveLength(0); http.expectNone(() => true); }); @@ -204,7 +204,7 @@ describe('UX-05B catálogo expandible', () => { expect(panels()[0].result().figure?.data[0]['y']).toEqual([3]); }); it('404 y reintento afectan solo una figura y 200 sin puntos sigue siendo resultado', () => { - load([item]); const a = request('f1'), b = request('f2'); + load([item]); toggle(); const a = request('f1'), b = request('f2'); a.flush('private', { status: 404, statusText: 'Not Found' }); b.flush({ data: [{ y: [null] }], layout: {} }); fixture.detectChanges(); expect(panels()[0].result().status).toBe('error'); expect(panels()[1].result().status).toBe('ready'); @@ -212,7 +212,7 @@ describe('UX-05B catálogo expandible', () => { panels()[0].requestFigure(); request('f1').flush({ data: [], layout: {} }); http.expectNone(() => true); }); it('edición y aplicación son independientes por figura y tema utiliza aplicación', () => { - load([item]); flushAll(); const a = control(), b = control(1); + load([item]); toggle(); flushAll(); const a = control(), b = control(1); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true); panels()[0].applyFilters(); const applied = request('f1'); expect(applied.request.params.get('periodos')).toBe('2025-S1'); applied.flush({ data: [], layout: {} }); a.unit = 'S2'; a.add(); @@ -226,7 +226,7 @@ describe('UX-05B catálogo expandible', () => { themedA.flush({ data: [], layout: {} }); themedB.flush({ data: [], layout: {} }); }); it('UX-06D expandir metodología conserva panel, figura y borrador sin generar HTTP', () => { - load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); flushAll(); + load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll(); const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; const filters = control(); filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); @@ -243,7 +243,7 @@ describe('UX-05B catálogo expandible', () => { } }); it('cerrar y reabrir restaura borrador y aplicado por figura sin confirmar borradores', () => { - load([item]); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); + load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); panels()[0].applyFilters(); request('f1').flush({ data: [], layout: {} }); a.unit = 'S2'; a.add(); control(1).changeTipo('mes'); control(1).year = '2026'; control(1).unit = '01'; control(1).add(); toggle(); toggle(); @@ -271,10 +271,11 @@ describe('UX-05B catálogo expandible', () => { it('restaura expansión y tema de dominio sin aplicar borrador pendiente', () => { load(); toggle(); flushAll(); control().changeMode('manual'); page.changeTema('oscuro'); fixture.detectChanges(); flushAll(); - page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); flushAll(); + page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll(); toggle(); page.changeDominio('tea'); fixture.detectChanges(); load(); expect(cards()[0].expanded).toBe(true); expect(cards()[1].expanded).toBe(false); - expect(page.tema).toBe('oscuro'); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false); + expect(page.tema).toBe('oscuro'); expect(cards()[0].awaitingFigures).toBe(true); http.expectNone(() => true); + toggle(); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false); expect(control().entry.draft.mode).toBe('empty'); a.flush({ data: [], layout: {} }); request('f2').flush({ data: [], layout: {} }); page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); expect(cards()[0].expanded).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true); @@ -285,7 +286,7 @@ describe('UX-05B catálogo expandible', () => { expect(cards()[1]).toBe(card); expect(panels()[0]).toBe(panel); http.expectNone(() => true); }); it('identidad eliminada no se monta aunque exista preferencia anterior', () => { - TestBed.inject(IndicadoresMemory).rememberExpansion('tea', 'removed', true); + TestBed.inject(IndicadoresMemory).rememberActivation('tea', 'removed', 'manual-open'); load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll(); }); it('botones semánticos anuncian expansión, IDs únicos y devuelven foco al contraer contenido', () => { @@ -303,7 +304,7 @@ describe('UX-05B catálogo expandible', () => { expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label')); }); it('copia de presentación y gráficos independientes conservan JSON binario, notas, ceros y nulos', () => { - load([item]); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } }; + load([item]); toggle(); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } }; const before = JSON.stringify(raw); request('f1').flush(raw); request('f2').flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges(); expect(JSON.stringify(raw)).toBe(before); expect(panels()[0].result().figure).toEqual(raw); const charts = fixture.debugElement.queryAll(By.directive(ChartStub)); expect(charts).toHaveLength(2); @@ -312,7 +313,7 @@ describe('UX-05B catálogo expandible', () => { expect(fixture.nativeElement.textContent).not.toContain('reportes no están disponibles'); }); it.each(['cacu', 'cama'] as const)('preserva advertencias y filtros mensuales de %s', domain => { - load([]); page.changeDominio(domain); load(syntheticCatalogs[domain], domain); flushAll(); + load([]); page.changeDominio(domain); load(syntheticCatalogs[domain], domain); toggle(); flushAll(); const c = control(); c.changeTipo('mes'); c.year = '2025'; c.unit = '01'; c.add(); http.expectNone(() => true); panels()[0].applyFilters(); const r = http.expectOne(r => r.url.includes('/figuras/')); expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 2705f16..17574e6 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -1,5 +1,5 @@ import { DOCUMENT } from '@angular/common'; -import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal, viewChild } from '@angular/core'; +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'; @@ -30,6 +30,132 @@ export class IndicadoresPage { private readonly element = inject>(ElementRef); private readonly injector = inject(Injector); private readonly searchInput = viewChild>('searchInput'); + private readonly graphicCards = viewChildren(IndicadorCatalogCard); + private readonly observedHeaders = new Map(); + private renderedCards: readonly IndicadorCatalogCard[] = []; + private visibilityObserver?: IntersectionObserver; + private sizeObserver?: ResizeObserver; + private readonly sizeTargets = new Set(); + private frame?: number; + private stickyHeight = -1; + private visibilityDestroyed = false; + private confirmation?: { cards: IndicadorCatalogCard[]; trigger: IndicadorCatalogCard; top: number; left: number; width: number; height: number; viewportWidth: number; viewportHeight: number }; + private readonly viewportChanged = () => this.visibilityChanged(); + + visibilityChanged() { + this.confirmation = undefined; + 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.observedHeaders.clear(); + this.renderedCards = []; + this.confirmation = undefined; + if (this.frame !== undefined) this.document.defaultView?.cancelAnimationFrame(this.frame); + this.frame = undefined; + } + private syncVisibility() { + if (this.visibilityDestroyed || typeof IntersectionObserver === 'undefined' || !this.document.defaultView) return; + const cards = this.graphicCards(); + 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 [header, card] of this.observedHeaders) { + if (!cards.includes(card) || !card.awaitingVisibility) { + this.visibilityObserver?.unobserve(header); + this.observedHeaders.delete(header); + changed = true; + } + } + for (const card of cards) { + const header = card.visibilityHeader.nativeElement; + if (card.awaitingVisibility && !this.observedHeaders.has(header)) { + this.observedHeaders.set(header, card); + this.visibilityObserver?.observe(header); + 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(); + this.confirmation = undefined; + 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.observedHeaders.has(entry.target))) this.queueVisibility(); + }, { root: null, rootMargin: `-${height}px 0px 0px 0px`, threshold: 0.25 }); + this.visibilityObserver = observer; + for (const header of this.observedHeaders.keys()) observer.observe(header); + } + private evaluateVisibility() { + const browser = this.document.defaultView; + if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return; + this.refreshVisibilityObserver(); + const width = browser.innerWidth, height = browser.innerHeight; + const rows: { top: number; cards: IndicadorCatalogCard[] }[] = []; + // Read the current DOM geometry; never retain index pairs or observer entry rectangles. + for (const card of this.renderedCards) { + if (card.dominio !== this.dominio || !card.host.nativeElement.isConnected) continue; + const top = card.host.nativeElement.getBoundingClientRect().top; + const row = rows.find(row => row.cards.length < 2 && Math.abs(row.top - top) <= 1); + if (row) row.cards.push(card); else rows.push({ top, cards: [card] }); + } + rows.sort((a, b) => a.top - b.top); + for (const row of rows) { + const trigger = row.cards.find(card => { + if (!card.awaitingVisibility || !this.observedHeaders.has(card.visibilityHeader.nativeElement)) return false; + const rect = card.visibilityHeader.nativeElement.getBoundingClientRect(); + const visibleWidth = Math.max(0, Math.min(rect.right, width) - Math.max(rect.left, 0)); + const visibleHeight = Math.max(0, Math.min(rect.bottom, height) - Math.max(rect.top, this.stickyHeight)); + return rect.width > 0 && rect.height > 0 && visibleWidth * visibleHeight / (rect.width * rect.height) >= 0.25; + }); + if (!trigger) continue; + const rect = trigger.visibilityHeader.nativeElement.getBoundingClientRect(); + const previous = this.confirmation; + const stable = previous && previous.trigger === trigger && previous.cards.length === row.cards.length + && row.cards.every((card, i) => card === previous.cards[i]) + && Math.abs(previous.top - rect.top) <= 1 && Math.abs(previous.left - rect.left) <= 1 + && Math.abs(previous.width - rect.width) <= 1 && Math.abs(previous.height - rect.height) <= 1 + && previous.viewportWidth === width && previous.viewportHeight === height; + if (!stable) { + this.confirmation = { cards: row.cards, trigger, top: rect.top, left: rect.left, width: rect.width, height: rect.height, viewportWidth: width, viewportHeight: height }; + this.queueVisibility(); + return; + } + this.confirmation = undefined; + for (const card of row.cards) card.activateVisible(); + this.changeDetector.markForCheck(); + // Wait for Angular's height change before considering any lower row. + afterNextRender(() => this.queueVisibility(), { injector: this.injector }); + return; + } + this.confirmation = undefined; + } clearSearch() { this.changeSearchQuery(''); this.searchInput()?.nativeElement.focus({ preventScroll: true }); @@ -37,6 +163,7 @@ export class IndicadoresPage { changeSearchQuery(query: string) { const focused = this.document.activeElement; this.searchQuery.set(query); + this.confirmation = undefined; 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, @@ -86,10 +213,25 @@ export class IndicadoresPage { tema: Tema = 'claro'; 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.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.catalogRequests.pipe(startWith(undefined), switchMap(() => { + this.clearVisibility(); this.catalogLoading.set(true); this.catalogError.set(''); this.catalog.set([]); diff --git a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts index de21b79..2caa97d 100644 --- a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts +++ b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts @@ -26,6 +26,8 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }]); fixture.detectChanges(); + (fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).toggle(); + fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } diff --git a/src/app/features/indicadores/indicadores-search.spec.ts b/src/app/features/indicadores/indicadores-search.spec.ts index a38446d..7407224 100644 --- a/src/app/features/indicadores/indicadores-search.spec.ts +++ b/src/app/features/indicadores/indicadores-search.spec.ts @@ -57,8 +57,8 @@ describe('UX-05C búsqueda local y partición estable', () => { it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => { load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count); - expect(cards().every(c => c.expanded === (count === 1))).toBe(true); - if (count === 1) respond(); else http.expectNone(() => true); + expect(cards().every(c => !c.expanded)).toBe(true); + http.expectNone(() => true); if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); }); it.each([ @@ -210,9 +210,10 @@ describe('UX-05C búsqueda local y partición estable', () => { load(); cards()[2].toggle(); fixture.detectChanges(); respond(); await settle(); filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add(); await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe(''); - load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].expanded).toBe(true); + load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].expanded).toBe(false); page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.expanded)).toEqual([false, false, true, false, false]); + http.expectNone(() => true); cards()[2].toggle(); fixture.detectChanges(); const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} }); expect(filters()[0].selectedPeriods).toEqual(['2025-S1']); await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; load(); respond(); diff --git a/src/app/features/indicadores/indicadores-visibility.spec.ts b/src/app/features/indicadores/indicadores-visibility.spec.ts new file mode 100644 index 0000000..3686fd3 --- /dev/null +++ b/src/app/features/indicadores/indicadores-visibility.spec.ts @@ -0,0 +1,310 @@ +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Indicador } from './indicadores.models'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' }) +class ChartStub {} +const items: Indicador[] = Array.from({ length: 5 }, (_, i) => ({ + id: 'i' + i, titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'], +})); + +// jsdom geometry and browser notifications are explicit, independent inputs. +class IntersectionControl { + static instances: IntersectionControl[] = []; + readonly targets = new Set(); + observe = vi.fn((target: Element) => this.targets.add(target)); + unobserve = vi.fn((target: Element) => this.targets.delete(target)); + disconnect = vi.fn(() => this.targets.clear()); + constructor(readonly callback: IntersectionObserverCallback, readonly options: IntersectionObserverInit) { + IntersectionControl.instances.push(this); + } + emit(target: Element, isIntersecting = true) { + this.callback([{ target, isIntersecting, intersectionRatio: isIntersecting ? 1 : 0 } as IntersectionObserverEntry], this as unknown as IntersectionObserver); + } +} +class ResizeControl { + static instances: ResizeControl[] = []; + readonly targets = new Set(); + observe = vi.fn((target: Element) => this.targets.add(target)); + unobserve = vi.fn((target: Element) => this.targets.delete(target)); + disconnect = vi.fn(() => this.targets.clear()); + constructor(readonly callback: ResizeObserverCallback) { ResizeControl.instances.push(this); } + emit() { this.callback([], this as unknown as ResizeObserver); } +} + +describe('UX-06E.D.1.1 visibilidad controlada', () => { + let fixture: ReturnType>; + let page: IndicadoresPage; + let http: HttpTestingController; + let memory: IndicadoresMemory; + let sticky: HTMLElement; + let geometry: WeakMap; + let frames: Map; + let sequence: number; + const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; + function rect(top: number, left = 0, width = 600, height = 80): DOMRect { + return { x: left, y: top, top, left, width, height, right: left + width, bottom: top + height, toJSON: () => ({}) } as DOMRect; + } + beforeEach(() => { + IntersectionControl.instances = []; ResizeControl.instances = []; + geometry = new WeakMap(); frames = new Map(); sequence = 0; + vi.stubGlobal('IntersectionObserver', IntersectionControl); vi.stubGlobal('ResizeObserver', ResizeControl); + vi.stubGlobal('innerWidth', 1440); vi.stubGlobal('innerHeight', 800); + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { frames.set(++sequence, callback); return sequence; }); + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => { frames.delete(id); }); + vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function(this: Element) { return geometry.get(this) ?? rect(0, 0, 0, 0); }); + sticky = document.createElement('header'); sticky.className = 'institutional-header'; document.body.append(sticky); + geometry.set(sticky, rect(0, 0, 1440, 100)); + runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + create(); + }); + function create() { + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + http = TestBed.inject(HttpTestingController); memory = TestBed.inject(IndicadoresMemory); + } + afterEach(() => { fixture.destroy(); sticky.remove(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } + async function render() { fixture.detectChanges(); await fixture.whenStable(); } + async function load(catalog = items, domain = 'tea') { + http.expectOne('/' + domain + '/indicadores').flush(catalog); await render(); + positions(cards().map((_, i) => [1000 + i * 200, 0])); + } + function positions(values: number[][]) { + cards().forEach((card, i) => { + geometry.set(card.host.nativeElement, rect(values[i][0], values[i][1])); + geometry.set(card.visibilityHeader.nativeElement, rect(values[i][0] + 16, values[i][1])); + }); + } + function observer() { return IntersectionControl.instances.at(-1)!; } + async function frame() { + const callbacks = [...frames.values()]; frames.clear(); callbacks.forEach(callback => callback(0)); await render(); + } + async function confirm() { await frame(); await frame(); } + function notify(index = 0, intersects = true) { observer().emit(cards()[index].visibilityHeader.nativeElement, intersects); } + function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); } + async function idle() { + for (let i = 0; i < 6 && frames.size; i++) await frame(); + expect(frames.size).toBe(0); + } + + it('observa sólo cabeceras gráficas con viewport, umbral y margen sticky medido', async () => { + await load(); + expect(observer().options).toEqual({ root: null, threshold: 0.25, rootMargin: '-100px 0px 0px 0px' }); + expect([...observer().targets]).toEqual(cards().map(card => card.visibilityHeader.nativeElement)); + expect([...observer().targets].every(target => target.tagName === 'HEADER')).toBe(true); + expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2); + await idle(); http.expectNone(() => true); + }); + it('exige dos frames y activa una sola vez sin autocierre ni nuevas consultas', async () => { + await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); + await frame(); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + await frame(); expect(memory.activation('tea', 'i0')).toBe('auto-open'); expect(panels()).toHaveLength(1); respond(); + const panel = panels()[0], result = panel.result(); + positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); + observer().emit(cards()[0].visibilityHeader.nativeElement, false); await idle(); + positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); + expect(cards()[0].expanded).toBe(true); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); http.expectNone(() => true); + }); + it('abre juntas dos tarjetas de la fila real sin abrir filas inferiores', async () => { + await load(); positions([[200, 0], [200.5, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); + expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); + expect(panels()).toHaveLength(2); respond(); await idle(); http.expectNone(() => true); + }); + it('en una columna no asocia dos indicadores por índice', async () => { + await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await confirm(); + expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); + }); + it('una intersección fugaz y una entrada antigua no abren una tarjeta ya fuera', async () => { + await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); + positions([[900, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); await frame(); + notify(); await idle(); expect(cards().every(card => !card.expanded)).toBe(true); http.expectNone(() => true); + }); + it('un desplazamiento rápido invalida la confirmación geométrica previa', async () => { + await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); + positions([[400, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); await frame(); + expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); await idle(); + }); + it('procesa primero la fila superior y descarta inferiores desplazadas por reflow', async () => { + await load(); positions([[200, 0], [200, 650], [400, 0], [400, 650], [1000, 0]]); notify(2); await confirm(); + expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); respond(); + positions([[200, 0], [200, 650], [1100, 0], [1100, 650], [1300, 0]]); await idle(); + expect(cards()[2].expanded).toBe(false); http.expectNone(() => true); + }); + it('las filas todavía visibles se activan en nuevas evaluaciones después de render', async () => { + await load(); positions([[200, 0], [200, 650], [450, 0], [450, 650], [1000, 0]]); notify(); await confirm(); respond(); + await confirm(); expect(cards().map(card => card.expanded)).toEqual([true, true, true, true, false]); respond(); await idle(); + }); + it('recalcula asociaciones responsive entre los dos frames', async () => { + await load(); positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await frame(); + positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); window.dispatchEvent(new Event('resize')); + await frame(); expect(cards().every(card => !card.expanded)).toBe(true); + await frame(); expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); + }); + it('excluye cabeceras detrás de sticky y mide sus cambios de altura', async () => { + await load(); positions([[0, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); http.expectNone(() => true); + const old = observer(); geometry.set(sticky, rect(0, 0, 1440, 50)); ResizeControl.instances.find(instance => instance.targets.has(sticky))!.emit(); + await frame(); expect(old.disconnect).toHaveBeenCalled(); expect(observer().options.rootMargin).toBe('-50px 0px 0px 0px'); + await frame(); expect(cards()[0].expanded).toBe(true); respond(); await idle(); + }); + it('una cabecera parcialmente visible por debajo del umbral no se activa', async () => { + await load(); positions([[770, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); + expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + }); + it('cierre manual prevalece sobre una confirmación pendiente y permite reapertura', async () => { + await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); + cards()[0].toggle(); await render(); const request = http.expectOne(r => r.url.includes('/figuras/')); + cards()[0].toggle(); await render(); expect(request.cancelled).toBe(true); + notify(); await idle(); expect(memory.activation('tea', 'i0')).toBe('manual-closed'); http.expectNone(() => true); + cards()[0].toggle(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-open'); respond(); + }); + it('una compañera cerrada manualmente permanece cerrada', async () => { + memory.rememberActivation('tea', 'i1', 'manual-closed'); await load(); + positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); + expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); + }); + it.each(['tea', 'cacu', 'cama'] as const)('singleton %s espera visibilidad antes de consultar', async domain => { + if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); } + await load([items[0]], domain); await idle(); http.expectNone(() => true); expect(cards()[0].expanded).toBe(false); + positions([[200, 0]]); notify(); await confirm(); expect(memory.activation(domain, 'i0')).toBe('auto-open'); respond(); await idle(); + }); + it('regresar conserva abierto sin montar fuera del viewport, y carga al entrar', async () => { + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); respond(); + page.changeDominio('cacu'); await load([items[0]], 'cacu'); await idle(); + expect(cards()[0].expanded).toBe(false); + page.changeDominio('tea'); await load([items[0]]); await idle(); + expect(cards()[0].expanded).toBe(true); expect(cards()[0].awaitingFigures).toBe(true); expect(panels()).toHaveLength(0); http.expectNone(() => true); + expect(fixture.nativeElement.textContent).toContain('Apertura recordada'); + positions([[200, 0]]); notify(); await confirm(); expect(panels()).toHaveLength(1); respond(); await idle(); + expect(memory.activation('tea', 'i0')).toBe('auto-open'); + }); + it('fallback manual permite mostrar figuras restauradas al primer clic y cerrar al siguiente', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); create(); memory.rememberActivation('tea', 'i0', 'auto-open'); + await load([items[0]]); expect(IntersectionControl.instances).toHaveLength(0); http.expectNone(() => true); + const button = fixture.nativeElement.querySelector('app-indicador-catalog-card header button') as HTMLButtonElement; + expect(button.getAttribute('aria-expanded')).toBe('true'); expect(button.getAttribute('aria-label')).toContain('Mostrar figuras'); + button.focus(); button.click(); await render(); expect(document.activeElement).toBe(button); expect(panels()).toHaveLength(1); respond(); + button.click(); await render(); expect(button.getAttribute('aria-expanded')).toBe('false'); expect(panels()).toHaveLength(0); http.expectNone(() => true); + button.click(); await render(); expect(panels()).toHaveLength(1); respond(); + }); + it('búsqueda activa indirectamente una pendiente visible y conserva cierre manual al limpiar', async () => { + memory.rememberActivation('tea', 'i0', 'manual-closed'); await load(); await idle(); + const original = cards(); page.changeSearchQuery('Indicador 4'); await render(); + expect(cards()[0]).toBe(original[4]); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); + http.expectNone(() => true); notify(); await confirm(); respond(); + page.changeSearchQuery(''); await render(); expect(cards()).toEqual(original); + positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); + expect(cards()[0].expanded).toBe(false); expect(cards()[4].expanded).toBe(true); http.expectNone(() => true); + }); + it('reordenar una pendiente fuera de vista no autoriza carga con callback antiguo', async () => { + await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); const target = cards()[0].visibilityHeader.nativeElement; + notify(); await frame(); page.changeSearchQuery('Indicador 4'); await render(); + positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); observer().emit(target); await idle(); + expect(cards().every(card => !card.expanded)).toBe(true); http.expectNone(() => true); + }); + it('retirar tarjetas desobserva sus cabeceras y descarta callbacks tardíos', async () => { + await load(); const retired = cards()[0].visibilityHeader.nativeElement, active = observer(); + page.catalog.set(items.slice(1)); await render(); + expect(active.unobserve).toHaveBeenCalledWith(retired); active.emit(retired); await idle(); http.expectNone(() => true); + }); + it('cambiar de dominio cancela HTTP e ignora el observer saliente', async () => { + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); + const request = http.expectOne(r => r.url.includes('/figuras/')), old = observer(), target = cards()[0].visibilityHeader.nativeElement; + page.changeDominio('cama'); await load([items[0]], 'cama'); expect(request.cancelled).toBe(true); + expect(old.disconnect).toHaveBeenCalled(); old.emit(target); await idle(); http.expectNone(() => true); + }); + it('destruir desconecta observers, cancela frames y hace inocuos callbacks tardíos', async () => { + await load(); const active = observer(), target = cards()[0].visibilityHeader.nativeElement; + positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); + const sizeObserver = ResizeControl.instances.find(instance => instance.targets.has(sticky))!; + const scheduled = new Set(frames.keys()); + const cancellations = vi.mocked(window.cancelAnimationFrame).mock.calls.length; + fixture.destroy(); expect(active.disconnect).toHaveBeenCalled(); expect(sizeObserver.disconnect).toHaveBeenCalled(); + const cancelled = vi.mocked(window.cancelAnimationFrame).mock.calls.slice(cancellations).map(([id]) => id); + expect(cancelled.some(id => scheduled.has(id))).toBe(true); + for (const id of cancelled) expect(frames.has(id)).toBe(false); + // Angular/Material can own another global frame; late page callbacks must add none. + const remaining = frames.size; + active.emit(target); sizeObserver.emit(); window.dispatchEvent(new Event('scroll')); + expect(frames.size).toBe(remaining); http.expectNone(() => true); + }); + it('varias figuras mantienen errores y resultados independientes y se cancelan al cerrar', async () => { + await load([{ ...items[0], figuras: ['f', 'g', 'h'] }]); positions([[200, 0]]); notify(); await confirm(); + const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(3); + requests[0].flush('private', { status: 500, statusText: 'Error' }); requests[1].flush({ data: [{ y: [2] }], layout: {} }); await render(); + expect(panels().map(panel => panel.result().status)).toEqual(['error', 'ready', 'loading']); + const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); + cards()[0].toggle(); await render(); expect(requests[2].cancelled).toBe(true); + notify(); await idle(); http.expectNone(() => true); cards()[0].toggle(); await render(); + expect(panels()[0].filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1'] }); + expect(panels()[0].filters?.applied?.selection.mode).toBe('todos'); respond(); + }); + it('fallback sin observers permite la apertura y cierre de una tarjeta pendiente', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); vi.stubGlobal('ResizeObserver', undefined); create(); + await load([items[0]]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + const button = fixture.nativeElement.querySelector('app-indicador-catalog-card header button') as HTMLButtonElement; + for (const key of ['Tab', 'Enter', ' ']) { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); + } + button.click(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-open'); respond(); + button.click(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-closed'); http.expectNone(() => true); + }); + it('la activación protegida nunca sobrescribe una decisión manual', async () => { + memory.rememberActivation('tea', 'i0', 'manual-closed'); memory.rememberActivation('tea', 'i1', 'manual-open'); await load(); + cards()[0].activateVisible(); cards()[1].activateVisible(); await render(); + expect(memory.activation('tea', 'i0')).toBe('manual-closed'); expect(cards()[0].expanded).toBe(false); + expect(memory.activation('tea', 'i1')).toBe('manual-open'); expect(cards()[1].figuresActivated).toBe(true); respond(); + cards()[1].activateVisible(); await render(); http.expectNone(() => true); + }); + it('scroll progresivo reactiva evaluación sin mantener un bucle cuando todo está fuera', async () => { + await load(); await idle(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); + window.dispatchEvent(new Event('scroll')); await confirm(); respond(); await idle(); + positions([[-1000, 0], [200, 0], [1200, 0], [1400, 0], [1600, 0]]); + window.dispatchEvent(new Event('scroll')); await confirm(); respond(); await idle(); + expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); http.expectNone(() => true); + }); + it('búsqueda reconstruye la fila visual usando las mismas instancias', async () => { + await load(); await idle(); const before = cards(); page.changeSearchQuery('Indicador 4'); await render(); + positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); respond(); await idle(); + expect(memory.activation('tea', 'i4')).toBe('auto-open'); expect(memory.activation('tea', 'i0')).toBe('auto-open'); + expect(memory.activation('tea', 'i1')).toBe('pending'); + expect(cards().every(card => before.includes(card))).toBe(true); http.expectNone(() => true); + }); + it('una cabecera fuera horizontalmente no se considera visible', async () => { + await load([items[0]]); positions([[200, 1500]]); notify(); await idle(); + expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + }); + it('visibilidad y búsqueda conservan hosts Plotly, resultados y foco sin react ni purge repetidos', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); TestBed.resetTestingModule(); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); + await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); + const input = fixture.nativeElement.querySelector('.catalog-search input') as HTMLInputElement; input.focus(); notify(); await confirm(); respond(); await render(); + for (let i = 0; i < 12; i++) await Promise.resolve(); await render(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + const host = chart.host.nativeElement, panel = panels()[0], result = panel.result(), reacts = runtime.react.mock.calls.length; + expect(reacts).toBe(1); expect(document.activeElement).toBe(input); + page.changeSearchQuery('Indicador 0'); await render(); notify(); await idle(); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.host.nativeElement).toBe(host); + expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); expect(document.activeElement).toBe(input); + expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); http.expectNone(() => true); + }); +});