feat(indicadores): un solo periodo y selector de indicadores gráficos

- El filtro general admite un único periodo (Elegir periodo); agregar otro lo reemplaza.
- Buscar indicadores pasa a ser una lista desplegable con casillas; solo los
  indicadores marcados se muestran en Indicadores gráficos, con Mostrar todos.
This commit is contained in:
2026-10-29 03:38:20 +00:00
parent 2cbb994667
commit 123232592f
16 changed files with 149 additions and 287 deletions
@@ -228,7 +228,7 @@ describe('IndicadorFigurePanel', () => {
expect(state?.applied?.selection.mode).toBe('todos');
apply();
const manual = figure();
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
expect(manual.request.params.get('periodos')).toBe('2025-S2');
control.select([]);
expect(manual.cancelled).toBe(false);
expect(control.canApply).toBe(false);
@@ -308,7 +308,7 @@ describe('IndicadorFigurePanel', () => {
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
http.expectNone(r => r.url.includes('/figuras/'));
});
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
const control = filters(); control.changeMode('manual'); control.year = '2025';
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
@@ -320,7 +320,6 @@ describe('IndicadorFigurePanel', () => {
expect(page.result().figure).toBeUndefined();
expect(page.result().message).toContain('esta selección');
expect(page.result().message).not.toContain('2025');
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
expect(control.selectedPeriods).toEqual(periodos);
control.select([]);
page.requestFigure();
@@ -344,7 +343,7 @@ describe('IndicadorFigurePanel', () => {
page.requestFigure();
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
retry.flush({ data: [], layout: {} });
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
expect(control.selectedPeriods).toEqual(['2025-S2']);
});
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
load(); figure().flush({ data: [], layout: {} });
@@ -354,7 +353,7 @@ describe('IndicadorFigurePanel', () => {
expect(old.cancelled).toBe(false);
apply(); const current = figure();
expect(old.cancelled).toBe(true);
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
expect(current.request.params.get('periodos')).toBe('2025-S2');
current.flush({ data: [{ y: [12] }], layout: {} });
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
expect(page.result().figure?.data[0]['y']).toEqual([12]);
@@ -12,16 +12,16 @@
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodo' }}</span></mat-select-trigger>
<mat-option value="todos">Todos con reporte</mat-option>
<mat-option value="manual">Elegir periodos</mat-option>
<mat-option value="manual">Elegir periodo</mat-option>
</mat-select>
</mat-form-field>
}
@if (entry.draft.mode !== 'todos') {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodos seleccionados</mat-label>
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
@if (availability) {
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
@@ -58,7 +58,7 @@
}
@if (error) { <p class="error" role="alert">{{ error }}</p> }
<p class="draft-summary">Selección en edición: {{ summary }}</p>
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
@@ -18,18 +18,22 @@ describe('UX-04 control asistido', () => {
control = fixture.componentInstance;
});
afterEach(() => fixture.destroy());
function periodSelect() {
return fixture.debugElement.queryAll(By.css('mat-form-field'))
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
}
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
await fixture.whenStable(); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
fixture.componentRef.setInput('state', {
...control.state, editors: { ...control.state.editors, semestre: {
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
} },
});
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2');
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
expect(values.map(e => e.textContent)).toContain('2025-S2');
expect(values.map(e => e.textContent)).toContain('Elegir periodo');
fixture.componentRef.setInput('state', {
...control.state, editors: { ...control.state.editors, semestre: {
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
@@ -46,7 +50,8 @@ describe('UX-04 control asistido', () => {
control.changeMode('manual');
fixture.detectChanges();
await Promise.resolve();
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
const select = periodSelect();
expect(select.componentInstance.multiple).toBe(false);
const model = select.injector.get(NgModel);
const writes = vi.spyOn(model.control, 'setValue');
const edits = vi.spyOn(control.edited, 'emit');
@@ -54,16 +59,16 @@ describe('UX-04 control asistido', () => {
fixture.detectChanges();
await Promise.resolve();
}
expect(model.control.value).toEqual([]);
expect(model.control.value).toBeNull();
expect(writes).not.toHaveBeenCalled();
expect(edits).not.toHaveBeenCalled();
expect(control.state.applied?.selection.mode).toBe('todos');
});
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => {
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
control.changeTipo('mes');
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
fixture.detectChanges(); await fixture.whenStable();
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
const select = periodSelect();
const model = select.injector.get(NgModel);
const writes = vi.spyOn(model.control, 'setValue');
for (let i = 0; i < 3; i++) {
@@ -100,15 +105,16 @@ describe('UX-04 control asistido', () => {
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
});
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
control.unit = 'S2'; control.add();
control.select(['2025-S2']);
expect(control.selectedPeriods).toEqual(['2025-S2']);
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
fixture.detectChanges();
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
expect(select).toBeTruthy();
const select = periodSelect();
expect(select.componentInstance.multiple).toBe(false);
expect(select.nativeElement.querySelector('button')).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
fixture.nativeElement.querySelector('.remove button').click();
@@ -29,7 +29,7 @@ export class IndicadorPeriodFilters implements OnChanges {
ngOnChanges() { this.year = this.unit = this.error = ''; }
get entry() { return this.state.editors[this.state.tipo]!; }
// NgModel schedules a microtask and markForCheck when its input reference changes.
// Keep the empty multiple-select value stable so an unchanged draft can settle.
// Keep the empty selection stable so an unchanged draft can settle.
private readonly emptyPeriods: string[] = [];
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
@@ -55,8 +55,10 @@ export class IndicadorPeriodFilters implements OnChanges {
this.error = '';
this.edited.emit();
}
// Only one period can be chosen: cards and figures never combine periods.
select(values: string[]) {
const unique = [...new Set(values)];
if (unique.length > 1) return;
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
this.edited.emit();
@@ -70,9 +72,8 @@ export class IndicadorPeriodFilters implements OnChanges {
return;
}
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
const selected = this.selectedPeriods;
this.entry.added.push(period);
this.select([...selected, period]);
this.select([period]);
}
remove(period: string) {
this.entry.added = this.entry.added.filter(p => p !== period);
@@ -96,17 +96,17 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
expect(card('cacu_eu13')).toBeDefined();
http.expectNone(() => true);
});
it('EU7 primero sin alterar catálogo; búsqueda y fijación prevalecen y conservan identidades y memoria', () => {
it('EU7 primero sin alterar catálogo; selección y fijación prevalecen y conservan identidades y memoria', () => {
const original = page.catalog(), before = cards();
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
expect(before[0].indicador.id).toBe('cacu_eu7');
page.togglePinned(original[0]); fixture.detectChanges();
expect(cards()[0]).toBe(card('cacu_eu13'));
page.changeSearchQuery('anómala'); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('ind1');
page.changeSearchQuery(''); fixture.detectChanges();
page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
page.showAllIndicators(); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('cacu_eu13');
for (const c of before) expect(card(c.indicador.id)).toBe(c);
expect(page.catalog()).toBe(original);
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
http.expectNone(() => true);
@@ -82,9 +82,9 @@ describe('D.2 integración de autoridad global y consumidores', () => {
http.expectNone(() => true);
});
it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => {
load(); open(); respond(); draft('semestre', ['2025-S1', '2025-S2']); apply(); respond();
load(); open(); respond(); draft('semestre', ['2025-S2']); apply(); respond();
const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied;
editor().select(['2025-S2', '2025-S1']); apply();
editor().select(['2025-S2']); apply();
expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result);
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
});
@@ -145,7 +145,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges();
expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos');
draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load();
expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
expect(editor().selectedPeriods).toEqual(['2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
expect(cards()[0].visible).toBe(false);
http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' }));
http.expectNone(() => true);
@@ -139,19 +139,18 @@ describe('UX-10 navegación lateral del catálogo gráfico', () => {
}
});
it('sigue el orden priorizado por búsqueda y fijación mientras el panel está abierto', async () => {
it('sigue la selección y la fijación mientras el panel está abierto', async () => {
await load([item('one', 'Alfa'), item('two', 'Beta'), item('three', 'Gamma')]);
page.togglePinned(page.catalog()[2]);
fixture.detectChanges();
await openPanel();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
page.changeSearchQuery('beta');
page.changeIndicatorSelection(['two']);
fixture.detectChanges();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Beta', 'Gamma', 'Alfa']);
page.changeSearchQuery('sin coincidencias');
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Beta']);
page.changeIndicatorSelection(['one', 'two', 'three']);
fixture.detectChanges();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
page.searchQuery.set('');
page.catalog.set([item('updated', 'Versión actualizada'), item('two', 'Beta')]);
fixture.detectChanges();
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Versión actualizada', 'Beta']);
@@ -62,7 +62,7 @@ describe('UX-04 navegación Angular', () => {
const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
const req = load('tea', harness);
expect(req.request.params.get('periodos')).toBe('2025-S1');
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] });
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] });
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
});
it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => {
@@ -114,23 +114,20 @@
<div class="catalog-search">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Buscar indicadores</mat-label>
<input #searchInput matInput type="search" [ngModel]="searchQuery()" (ngModelChange)="changeSearchQuery($event)"
placeholder="Título o identificador" aria-describedby="catalog-search-help catalog-search-result" />
<button mat-icon-button matIconSuffix type="button" (click)="clearSearch()" [disabled]="!searchQuery()"
aria-label="Limpiar búsqueda"><mat-icon aria-hidden="true">close</mat-icon></button>
<mat-hint id="catalog-search-help">Las coincidencias aparecen primero; todos los indicadores siguen visibles.</mat-hint>
<mat-select multiple [ngModel]="selectedIndicators()" (ngModelChange)="changeIndicatorSelection($event)" aria-describedby="catalog-search-result">
<mat-select-trigger><span class="select-value">{{ selectionSummary() }}</span></mat-select-trigger>
@for (item of catalogOrder(); track item.id) { <mat-option [value]="item.id">{{ item.titulo }}</mat-option> }
</mat-select>
</mat-form-field>
<button mat-stroked-button type="button" (click)="showAllIndicators()" [disabled]="indicatorSelection() === null">Mostrar todos</button>
</div>
<p id="catalog-search-result" class="search-result">
@if (searchResults().active) {
@if (searchResults().count) {
{{ searchResults().count }} coincidencias de {{ catalog().length }} indicadores. Todos permanecen disponibles.
} @else {
No se encontraron coincidencias. El catálogo completo permanece disponible; los indicadores fijados aparecen primero.
}
}
<p id="catalog-search-result" class="search-result" role="status">
Mostrando {{ searchResults().items.length }} de {{ catalog().length }} indicadores.
</p>
}
@if (!searchResults().items.length) {
<p class="state" role="status">No hay indicadores seleccionados. Elige al menos uno en «Buscar indicadores».</p>
}
<div class="catalog-grid">
@for (item of searchResults().items; track cardIdentity(item)) {
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
@@ -46,12 +46,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; }
.catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
.catalog-search { display: flex; justify-content: flex-end; margin-top: var(--issste-space-4); }
.catalog-search { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-4); }
.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
.catalog-search button { width: 48px; height: 48px; }
.catalog-search button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -3px; }
// Keep search semantics; Material supplies the single accessible clear control.
.catalog-search input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; }
.catalog-search button { min-height: 48px; }
.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right;
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
@@ -213,7 +213,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
page.changeTema('oscuro'); fixture.detectChanges();
const themedA = request('f1');
expect(themedA.request.params.get('periodos')).toBe('2025-S1');
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S2']);
themedA.flush({ data: [], layout: {} });
});
it('UX-06D expandir metodología carga metadatos una vez y conserva panel, figura y borrador', () => {
@@ -241,7 +241,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add();
cards()[0].setVisible(false); fixture.detectChanges(); toggle();
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']);
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S2']);
http.expectNone(() => true);
});
it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => {
@@ -72,7 +72,6 @@ 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 overlay = inject(Overlay);
readonly navigationScrollStrategy = this.overlay.scrollStrategies.reposition();
readonly navigationPositions: ConnectedPosition[] = [
@@ -197,14 +196,12 @@ export class IndicadoresPage {
}
this.changeDetector.markForCheck();
}
clearSearch() {
this.changeSearchQuery('');
this.searchInput()?.nativeElement.focus({ preventScroll: true });
}
changeSearchQuery(query: string) {
changeIndicatorSelection(ids: string[]) {
this.preserveCardFocus();
this.searchQuery.set(query);
// Every indicator checked is the same as no filter, so later catalog additions also show.
this.indicatorSelection.set(ids.length === this.catalog().length ? null : ids);
}
showAllIndicators() { this.changeIndicatorSelection(this.catalog().map(item => item.id)); }
isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); }
togglePinned(item: Indicador) {
this.preserveCardFocus();
@@ -307,31 +304,28 @@ export class IndicadoresPage {
}
private readonly catalogRequests = new Subject<void>();
readonly catalog = signal<Indicador[]>([]);
readonly searchQuery = signal('');
readonly searchVisible = computed(() => this.catalog().length >= 5);
readonly searchResults = computed(() => {
// Ids of the indicators to render; null shows the whole catalog.
readonly indicatorSelection = signal<string[] | null>(null);
readonly searchVisible = computed(() => this.catalog().length >= 2);
// Stable presentation priority; pins still take precedence in the grid.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
// Stable presentation priority; search matches and pins still take precedence.
const items = this.dominio === 'cacu'
return this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
: 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 selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
readonly selectionSummary = computed(() => {
const selected = this.selectedIndicators();
if (this.indicatorSelection() === null) return 'Todos los indicadores';
if (selected.length === 1) return this.catalog().find(item => item.id === selected[0])?.titulo ?? selected[0];
return selected.length + ' indicadores';
});
readonly searchResults = computed(() => {
const selected = new Set(this.selectedIndicators());
const items = this.catalogOrder().filter(item => selected.has(item.id));
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
});
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
tema: Tema = 'claro';
@@ -518,7 +512,7 @@ export class IndicadoresPage {
if (!isDominio(dominio) || dominio === this.dominio) return;
this.closeGraphicNavigation(false, false);
this.activeSection.set('resumen');
this.searchQuery.set('');
this.indicatorSelection.set(null);
this.filtersEdited();
this.filters = undefined;
this.dominio = dominio;
@@ -92,7 +92,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles');
expect(panels()[0].result().value).toBeUndefined();
});
it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => {
it('selección mensual edita sin HTTP; un periodo consulta y no se pueden elegir varios', async () => {
load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu');
const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges();
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
@@ -103,10 +103,9 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
expect(control.selectedPeriods).toEqual(['2025-10']);
fixture.componentInstance.applyFilters(); fixture.detectChanges();
expect(panels().every(p => p.result().state === 'Selección no consolidable' && p.result().value === undefined)).toBe(true);
http.expectNone(() => true);
control.select(['2025-02', '2025-10']); fixture.componentInstance.applyFilters(); fixture.detectChanges();
expect(panels().every(p => p.result().state !== 'Selección no consolidable')).toBe(true);
http.expectNone(() => true);
await fixture.whenStable();
});
@@ -63,25 +63,22 @@ describe('UX-06E.D.3.B fijación temporal', () => {
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
});
it('coincidencias preceden a los fijados no coincidentes y la fijación resuelve cada grupo', async () => {
it('la selección de indicadores conserva la prioridad de los fijados', async () => {
await pin('i3'); await pin('i4');
page.changeSearchQuery(' EVALUACION '); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i4', 'i1', 'i3', 'i0', 'i2']);
expect(page.searchResults().count).toBe(2); expect(page.searchResults().active).toBe(true);
await pin('i1'); expect(ids()).toEqual(['i1', 'i4', 'i3', 'i0', 'i2']);
expect(cards()).toHaveLength(items.length); http.expectNone(() => true);
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i3', 'i4', 'i1']);
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
expect(cards()).toHaveLength(3); http.expectNone(() => true);
});
it('limpiar mediante el buscador restaura fijados primero y mantiene foco', async () => {
await pin('i3'); page.changeSearchQuery('Edad'); fixture.detectChanges(); await settle();
expect(ids()[0]).toBe('i0');
it('Mostrar todos restaura el catálogo con los fijados primero', async () => {
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i0']);
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
expect(page.searchQuery()).toBe(''); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.catalog-search input')); http.expectNone(() => true);
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true);
});
it('búsqueda sin coincidencias conserva todo el catálogo con prioridad de fijados', async () => {
await pin('i2'); page.changeSearchQuery('inexistente'); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i2', 'i0', 'i1', 'i3', 'i4']); expect(page.searchResults().count).toBe(0);
expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); http.expectNone(() => true);
it('un fijado sin seleccionar no se muestra', async () => {
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i0', 'i1']); http.expectNone(() => true);
});
it('memoria independiente por dominio y persistente al recrear la página', async () => {
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
@@ -4,15 +4,11 @@ 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 { NgModel } from '@angular/forms';
import { MatSelect } from '@angular/material/select';
import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-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';
const items: Indicador[] = [
@@ -23,16 +19,15 @@ const items: Indicador[] = [
{ id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
];
describe('UX-05C búsqueda local y partición estable', () => {
describe('Selección de indicadores gráficos', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let page: IndicadoresPage;
let http: HttpTestingController;
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
const disconnect = vi.fn();
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined);
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; });
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
@@ -43,184 +38,61 @@ describe('UX-05C búsqueda local y partición estable', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
}
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).filter(p => p.result().status !== 'deferred'); }
function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); }
function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); }
function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); }
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
async function search(value: string) {
input().value = value; input().dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges(); await settle();
}
function respond() {
http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges();
}
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
function ids() { return cards().map(c => c.indicador.id); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
function select() { return fixture.debugElement.query(By.css('.catalog-search mat-select'))?.componentInstance as MatSelect | undefined; }
function showAll(): HTMLButtonElement { return fixture.nativeElement.querySelector('.catalog-search button'); }
function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => {
it.each([0, 1, 2, 5])('muestra el selector desde dos indicadores: 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.visible)).toBe(true);
http.expectNone(() => true);
if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
});
it.each([
['sexo', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['M02', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['tribuci', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['SEXO', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
['evaluacion', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2],
[' EVALUACIÓN ', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2],
['imposible', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
['', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
[' ', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
])('consulta %s preserva todos los objetos y el catálogo original', async (query, ids, count) => {
load(); const original = page.catalog(), snapshot = JSON.stringify(original), before = cards();
await search(query as string);
expect(cards().map(c => c.indicador.id)).toEqual(ids);
expect(page.searchResults().count).toBe(count); expect(page.searchResults().active).toBe(!!(query as string).trim());
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot);
for (const card of cards()) {
expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id));
expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.visible).toBe(false);
}
if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible');
if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe('');
expect(!!select()).toBe(count >= 2); expect(cards()).toHaveLength(count);
http.expectNone(() => true);
});
it('D.1 mantiene KPI fuera de la búsqueda y del recuento y utiliza un único suffix Material', async () => {
load(); await settle();
const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'));
const field = fixture.nativeElement.querySelector('.catalog-search mat-form-field') as HTMLElement;
const clear = field.querySelector('button')!;
expect(clear.hasAttribute('matIconSuffix')).toBe(true);
expect(clear.closest('.mat-mdc-form-field-icon-suffix')).toBeTruthy();
expect(fixture.nativeElement.querySelectorAll('.catalog-search button')).toHaveLength(1);
expect(input().type).toBe('search');
for (const query of ['sexo', 'Indicador destacado', '']) {
await search(query);
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis);
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
expect(cards()).toHaveLength(5);
}
it('lista todo el catálogo, con todos seleccionados al inicio', () => {
load();
expect(select()!.multiple).toBe(true);
expect(select()!.options.map(o => o.viewValue)).toEqual(items.map(i => i.titulo));
expect(page.selectedIndicators()).toEqual(items.map(i => i.id));
expect(page.selectionSummary()).toBe('Todos los indicadores');
expect(result()).toBe('Mostrando 5 de 5 indicadores.');
expect(showAll().disabled).toBe(true);
http.expectNone(() => true);
});
it('escritura y limpieza mantienen foco, cursor, etiqueta y ayudas sin HTTP', async () => {
load(); await settle(); const field = input(); field.focus(); await search('sexo');
expect(document.activeElement).toBe(field); expect(field.value).toBe('sexo');
field.setSelectionRange(2, 2); fixture.detectChanges(); await settle(); expect(field.selectionStart).toBe(2); expect(field.selectionEnd).toBe(2);
expect(field.labels?.[0].textContent).toContain('Buscar indicadores');
for (const id of field.getAttribute('aria-describedby')!.split(' ')) expect(document.getElementById(id)).toBeTruthy();
expect(fixture.nativeElement.querySelector('#catalog-search-result').getAttribute('aria-live')).toBeNull();
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement;
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); clear.focus(); expect(document.activeElement).toBe(clear); clear.click(); fixture.detectChanges(); await settle();
expect(page.searchQuery()).toBe(''); expect(field.value).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
expect(clear.disabled).toBe(true); expect(input()).toBe(field); expect(document.activeElement).toBe(field);
await search('edad'); field.setSelectionRange(2, 2); expect(document.activeElement).toBe(field); expect(field.selectionStart).toBe(2);
it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
load(); const before = cards(), original = page.catalog();
choose(['B02', 'E05']);
expect(ids()).toEqual(['B02', 'E05']);
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
expect(page.selectionSummary()).toBe('2 indicadores');
expect(result()).toBe('Mostrando 2 de 5 indicadores.');
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
expect(page.catalog()).toBe(original);
http.expectNone(() => true);
});
it('botón nativo iconográfico conserva nombre, semántica, tamaño y estado sin HTTP', async () => {
load(); await settle();
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement;
expect(clear.type).toBe('button'); expect(clear.disabled).toBe(true);
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda');
const icon = clear.querySelector('mat-icon')!;
expect(icon.textContent).toBe('close'); expect(icon.getAttribute('aria-hidden')).toBe('true');
expect(clear.textContent).not.toContain('Limpiar');
expect(getComputedStyle(clear).width).toBe('48px'); expect(getComputedStyle(clear).height).toBe('48px');
await search('sexo'); expect(clear.disabled).toBe(false); expect(clear.tabIndex).toBe(0);
// jsdom does not synthesize native keyboard activation. Verify that keys remain
// available to the browser; Enter/Space activation is a Chrome acceptance check.
for (const key of ['Enter', ' ']) {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
clear.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
}
clear.focus(); clear.click(); fixture.detectChanges(); await settle();
expect(document.activeElement).toBe(input()); expect(clear.disabled).toBe(true);
it('sin selección no muestra tarjetas y Mostrar todos restaura el catálogo', () => {
load(); choose([]);
expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados');
expect(showAll().disabled).toBe(false);
showAll().click(); fixture.detectChanges();
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(showAll().disabled).toBe(true);
http.expectNone(() => true);
});
it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => {
load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); respond(); await settle();
const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts();
const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add();
page.applyFilters(); fixture.detectChanges(); respond(); await settle();
c.year = '2025'; c.unit = 'S2'; c.add(); c.year = '2026';
fixture.detectChanges(); await settle();
const states = beforePanels.map(p => p.applied), results = beforePanels.map(p => p.result());
const titleIds = beforePanels.map(p => p.titleId);
expect(new Set(titleIds).size).toBe(beforePanels.length);
const snapshots = states.map(s => JSON.stringify(s)), hosts = beforeCharts.map(c => c.host.nativeElement);
const selects = fixture.debugElement.queryAll(By.directive(MatSelect)).filter(e => e.componentInstance.multiple);
const writes = selects.map(e => vi.spyOn(e.injector.get(NgModel).control, 'setValue'));
const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'saveGlobal'), restores = vi.spyOn(memory, 'restoreGlobal');
const reacts = runtime.react.mock.calls.length;
const helps = [...fixture.nativeElement.querySelectorAll('.methodology-toggle')] as HTMLButtonElement[];
expect(helps).toHaveLength(5);
const helpIds = helps.map(button => button.getAttribute('aria-controls')!);
expect(new Set(helpIds).size).toBe(5);
for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true);
helps[0].click(); fixture.detectChanges();
http.expectOne(r => r.url.endsWith('/metadatos')).flush({});
fixture.detectChanges(); await settle();
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]);
for (const query of ['sexo', 'evaluacion', '']) {
if (query) await search(query);
else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); }
for (const card of beforeCards) expect(cards().find(c => c.indicador.id === card.indicador.id)).toBe(card);
for (const panel of beforePanels) expect(panels().find(p => p.indicador.id === panel.indicador.id)).toBe(panel);
beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c));
beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c));
}
expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.visible)).toBe(true);
for (const button of helps) expect(button.isConnected).toBe(true);
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
helps[0].click(); fixture.detectChanges(); await settle();
expect(document.getElementById(helpIds[0])?.hidden).toBe(true);
expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts);
expect(beforePanels.map(p => p.titleId)).toEqual(titleIds);
for (const id of titleIds) {
const heading = document.getElementById(id)!;
expect(heading.tagName).toBe('H3'); expect(heading.parentElement!.getAttribute('aria-labelledby')).toBe(id);
}
beforePanels.forEach((p, i) => { expect(p.applied).toBe(states[i]); expect(JSON.stringify(p.applied)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); });
beforeCharts.forEach((c, i) => expect(c.host.nativeElement).toBe(hosts[i]));
expect(c.year).toBe('2026'); expect(c.unit).toBe('S2'); expect(c.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
for (const write of writes) expect(write).not.toHaveBeenCalled();
expect(saves).not.toHaveBeenCalled(); expect(restores).not.toHaveBeenCalled();
expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
http.expectNone(() => true);
it('marcar todos equivale a no filtrar', () => {
load(); choose(['A01']); choose(items.map(i => i.id));
expect(page.indicatorSelection()).toBeNull(); expect(page.selectionSummary()).toBe('Todos los indicadores');
});
it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => {
load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges();
const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo');
b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle();
await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error');
expect(panels()).toEqual([before[2], before[0], before[1]]); http.expectNone(() => true);
a.flush({ data: [{ y: [1] }], layout: {} }); await settle(); expect(before[0].result().figure?.data[0]['y']).toEqual([1]);
const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} });
expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true);
it('los indicadores destacados no dependen de la selección', () => {
load(); const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'));
choose(['A01']);
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
});
it('reordenar el catálogo conserva foco en el selector global existente', async () => {
load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle();
filters()[0].changeMode('manual'); fixture.detectChanges(); await settle();
const field = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf<HTMLElement>).at(-1)!;
field.focus(); expect(document.activeElement).toBe(field);
page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle();
expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true);
page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field);
http.expectNone(() => true);
});
it('cambiar de dominio limpia búsqueda y volver conserva figura y borrador mediante memoria existente', async () => {
load(); cards()[2].setVisible(true); 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].visible).toBe(false);
page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe('');
expect(cards().map(c => c.visible)).toEqual([false, false, false, false, false]);
http.expectNone(() => true); cards()[2].setVisible(true); 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; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); load(); respond();
expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
it('cambiar de dominio restablece la selección', () => {
load(); choose(['A01']);
page.changeDominio('cacu'); fixture.detectChanges(); expect(page.indicatorSelection()).toBeNull();
load(items, 'cacu'); expect(ids()).toEqual(items.map(i => i.id));
});
});
@@ -160,7 +160,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true);
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
const request = http.expectOne(r => r.url.includes('/i0/figuras/'));
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
expect(request.request.params.get('periodos')).toBe('2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true);
});
it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => {
@@ -181,15 +181,16 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
cards()[0].selectFigure('g'); await render(); http.expectNone(() => true); expect(panels()[0].result().status).toBe('deferred');
positions([[200, 0]]); notify(); await confirm(); http.expectOne(r => r.url.endsWith('/figuras/g')).flush({ data: [], layout: {} });
});
it('fijación y búsqueda conservan componentes y descartan callbacks con geometría antigua', async () => {
it('fijación y selección conservan componentes y descartan callbacks con geometría antigua', async () => {
await load(); const before = cards(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]);
const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render();
page.changeSearchQuery('Indicador 3'); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
page.changeIndicatorSelection([items[3].id, items[4].id]); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
observer().emit(target); await idle(); http.expectNone(() => true);
expect(cards()[0]).toBe(before[3]); expect(cards()[1]).toBe(before[4]); expect(cards().every(c => before.includes(c))).toBe(true);
positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
// The pinned indicator leads; the other selected one keeps its component.
expect(cards()).toEqual([before[4], before[3]]);
positions(cards().map((_, i) => [i === 1 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
expect(cards()[0].selectedFigure).toBe('f');
expect(cards()[1].selectedFigure).toBe('f');
});
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
await load([items[0]]); positions([[200, 0]]); notify(); await confirm();