feat(indicadores): agregar busqueda priorizada UX-05C

This commit is contained in:
Angel Capetillo Zavala
2026-10-13 10:42:34 -06:00
parent 91832cc6ff
commit 9c012e9bb4
4 changed files with 226 additions and 3 deletions
@@ -27,7 +27,28 @@
</mat-select>
</mat-form-field>
<p role="status">{{ catalog().length }} indicadores publicados</p>
@for (item of catalog(); track cardIdentity(item)) {
@if (searchVisible()) {
<div class="catalog-search">
<mat-form-field subscriptSizing="dynamic">
<mat-label>Buscar indicadores</mat-label>
<input matInput type="search" [ngModel]="searchQuery()" (ngModelChange)="changeSearchQuery($event)"
placeholder="Título o identificador" aria-describedby="catalog-search-help catalog-search-result" />
<mat-hint id="catalog-search-help">Las coincidencias aparecen primero; todos los indicadores siguen visibles.</mat-hint>
</mat-form-field>
<button mat-stroked-button type="button" (click)="changeSearchQuery('')" [disabled]="!searchQuery()"
aria-label="Limpiar búsqueda de indicadores">Limpiar</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 en su orden original.
}
}
</p>
}
@for (item of searchResults().items; track cardIdentity(item)) {
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema"
[initialExpanded]="catalog().length === 1" />
}
@@ -7,3 +7,6 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.state { padding: 1.25rem; margin: 0; }
mat-form-field { width: 100%; max-width: 24rem; }
@media (max-width: 550px) { h1 { font: var(--mat-sys-headline-medium); } }
.catalog-search { display: flex; align-items: flex-start; gap: .75rem; flex-wrap: wrap; }
.catalog-search button { margin-top: .5rem; }
.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); }
@@ -1,10 +1,12 @@
import { ChangeDetectorRef, Component, DestroyRef, inject, signal } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
@@ -17,11 +19,28 @@ import { httpMessage } from './indicadores-http';
@Component({
selector: 'app-indicadores-page',
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard],
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
private readonly document = inject(DOCUMENT);
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly injector = inject(Injector);
changeSearchQuery(query: string) {
const focused = this.document.activeElement;
this.searchQuery.set(query);
if (focused instanceof HTMLElement && this.element.nativeElement.contains(focused)
&& focused.closest('app-indicador-catalog-card')) {
// Moving a retained view can blur its control. Restore only that connected control,
// without overriding focus deliberately assigned elsewhere during the update.
afterNextRender(() => {
if (focused.isConnected && this.document.activeElement === this.document.body) {
focused.focus({ preventScroll: true });
}
}, { injector: this.injector });
}
}
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly service = inject(IndicadoresService);
private readonly memory = inject(IndicadoresMemory);
@@ -32,6 +51,23 @@ export class IndicadoresPage {
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
private readonly catalogRequests = new Subject<void>();
readonly catalog = signal<Indicador[]>([]);
readonly searchQuery = signal('');
readonly searchVisible = computed(() => this.catalog().length >= 5);
readonly searchResults = computed(() => {
const items = this.catalog();
const query = this.normalizeSearch(this.searchQuery());
if (!query) return { 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: matches.length ? [...matches, ...remaining] : items, active: true, count: matches.length };
});
private normalizeSearch(value: string) {
return value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim();
}
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
tema: Tema = 'claro';
@@ -54,6 +90,7 @@ export class IndicadoresPage {
}
changeDominio(dominio: Dominio) {
if (!isDominio(dominio) || dominio === this.dominio) return;
this.searchQuery.set('');
this.dominio = dominio;
this.tema = this.memory.theme(dominio);
this.catalogRequests.next();
@@ -0,0 +1,162 @@
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 { 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[] = [
{ id: 'A01', titulo: 'Edad', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
{ id: 'B02', titulo: 'Evaluación inicial', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
{ id: 'M02_sexo', titulo: 'Distribución por sexo', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
{ id: 'D04', titulo: 'Seguimiento', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
{ id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
];
describe('UX-05C búsqueda local y partición estable', () => {
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.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined);
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); disconnect = disconnect; });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(),
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
function load(catalog = items, domain = 'tea') {
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); }
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')); }
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);
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.expanded).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('');
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')).toContain('Limpiar búsqueda'); 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));
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.toggle()); 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();
beforePanels[0].applyFilters(); request('A01').flush({ data: [{ y: [2, null] }], layout: {} });
c.unit = 'S2'; c.add(); c.year = '2026';
beforeFilters[1].changeMode('manual'); fixture.detectChanges(); await settle();
const states = beforePanels.map(p => p.filters), results = beforePanels.map(p => p.result());
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, 'save'), restores = vi.spyOn(memory, 'restore');
const reacts = runtime.react.mock.calls.length;
for (const query of ['sexo', 'evaluacion', '']) {
await search(query);
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.expanded)).toBe(true);
expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts);
beforePanels.forEach((p, i) => { expect(p.filters).toBe(states[i]); expect(JSON.stringify(p.filters)).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('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => {
load(); cards().slice(0, 3).forEach(c => c.toggle()); 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('mover una tarjeta abierta mantiene el foco en su control existente', async () => {
load(); cards()[2].toggle(); fixture.detectChanges(); respond(); await settle();
filters()[0].changeMode('manual'); fixture.detectChanges(); await settle();
const field = fixture.nativeElement.querySelector('app-indicador-period-filters input') as HTMLInputElement;
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 expansión y borrador mediante memoria existente', async () => {
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);
page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe('');
expect(cards().map(c => c.expanded)).toEqual([false, false, true, false, false]);
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();
expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
});
});