diff --git a/docs/i18n-inventory.md b/docs/i18n-inventory.md index a1f4ac0..bc45dc8 100644 --- a/docs/i18n-inventory.md +++ b/docs/i18n-inventory.md @@ -1,6 +1,6 @@ # i18n inventory (egdev6/quorb#66) -Generated by `node scripts/i18n-inventory.mjs` from the source trees `src/` = `022e58a407ccc53d4d5e7f09d191bf6b1a0e5770` and `src-tauri/src/` = `d90774adefab1cd050cb8654be3b747d775eeaf8`. +Generated by `node scripts/i18n-inventory.mjs` from the source trees `src/` = `3f7ebef152a2d8ca83a7dfe23fe07158a2652108` and `src-tauri/src/` = `d90774adefab1cd050cb8654be3b747d775eeaf8`. Any commit whose `git rev-parse :src` and `:src-tauri/src` match has these exact texts. Do not edit by hand: regenerate, or verify with `node scripts/i18n-inventory.mjs --check`. @@ -18,9 +18,9 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a | Area | Distinct texts | Sites | |---|---:|---:| -| React (`src/`) | 1125 | 1227 | +| React (`src/`) | 1126 | 1228 | | Rust (`src-tauri/src/`) | 610 | 763 | -| Total | 1696 | 1990 | +| Total | 1697 | 1991 | ## src-tauri/src/channel.rs @@ -2044,6 +2044,10 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - id="${…}$1" - url(#${…}$1) +## src/lib/test-slots.ts + +- Nombre de slot duplicado: '${…}'. Revisa src/lib/test-slots.ts. + ## src/lib/updater-policy.ts - La actualización automática no está disponible en este modo. diff --git a/src/lib/auto-hide.test.ts b/src/lib/auto-hide.test.ts index aaaa6af..c3c4db1 100644 --- a/src/lib/auto-hide.test.ts +++ b/src/lib/auto-hide.test.ts @@ -11,6 +11,7 @@ import { DETAIL_EVENTS, physicalPanelBounds } from './detail-panel'; import { POINTER_SURFACE_EVENT } from './hover-presence'; import { NO_PANEL, type PanelState } from './anchor-panel'; import type { UsageReport } from './types'; +import { SLOT, SKIP, WIDGET_REFS, WIDGET_STATE_COUNT, WIDGET_REF_COUNT, WIDGET_STATES } from './test-slots'; type GripHandlers = { onPointerDown(event: ReactPointerEvent): void; @@ -120,6 +121,15 @@ function findDock(node: ReactNode): DockHandlers | undefined { // own refs, so the drag/detail refs below start at 1 (#271, revisión). const widgetEffects = vi.hoisted(() => ({ states: [] as unknown[], stateIndex: 0, + // Iniciales que Widget pasa a cada useState/useRef, en orden de render. + // El test de coherencia (#286) los compara contra la tabla de slots. + stateInitials: [] as unknown[], refInitials: [] as unknown[], + // Recuentos esperados de la tabla de slots (#286): el mock no puede importar + // el módulo (hoisting), así que el test los inyecta aquí ANTES de renderizar + // (`widgetEffects.expectedStateCount = WIDGET_STATE_COUNT`). Si un render + // crea más hooks de los declarados, el guard estalla en el punto exacto. + expectedStateCount: null as number | null, + expectedRefCount: null as number | null, refs: [] as { current: unknown }[], refIndex: 0, getConfig: vi.fn(), openSettings: vi.fn(), effects: [] as { run: () => void | (() => void); deps?: readonly unknown[]; name?: string }[], @@ -137,6 +147,14 @@ vi.mock('react', async (importOriginal) => { ...react, useState: ((initial?: unknown) => { const index = widgetEffects.stateIndex++; + widgetEffects.stateInitials.push(initial); + // Disparidad temprana con la tabla de slots (#286): si el render crea + // más useState de los declarados, falla aquí, en el punto exacto. + // Los recuentos se inyectan desde el test (el factory no puede importar). + const expected = widgetEffects.expectedStateCount; + if (expected != null && index >= expected) { + throw new Error(`El Widget crea más useState (${index + 1}) de los que declara la tabla de slots (#286). Actualiza src/lib/test-slots.ts.`); + } const value = index in widgetEffects.states ? widgetEffects.states[index] : typeof initial === 'function' ? initial() : initial; // Commit state explicitly in tests, but preserve the actual updater result. @@ -148,6 +166,11 @@ vi.mock('react', async (importOriginal) => { }) as typeof react.useState, useRef: ((initial: unknown) => { const index = widgetEffects.refIndex++; + widgetEffects.refInitials.push(initial); + const expected = widgetEffects.expectedRefCount; + if (expected != null && index >= expected) { + throw new Error(`El Widget crea más useRef (${index + 1}) de los que declara la tabla de slots (#286). Actualiza src/lib/test-slots.ts.`); + } return widgetEffects.refs[index] ??= { current: initial }; }) as typeof react.useRef, useEffect: ((run, deps) => { @@ -194,6 +217,15 @@ vi.mock('@tauri-apps/api/event', () => ({ emitTo: vi.fn(), })); +// Recuentos esperados de la tabla de slots (#286): el mock no puede importar +// `test-slots` (hoisting de `vi.mock`), así que el test los inyecta en el +// objeto hoisted. El guard NO se activa globalmente: los componentes de los +// orbs (ProviderLogo tiene un `useState` para el fallback de imagen rota) +// añaden hooks suyos cuando hay informes visibles, así que un Widget CON datos +// consume más hooks que el Widget vacío de la tabla. El test de coherencia +// activa el guard sobre un render sin orbs, donde la secuencia es exactamente +// la declarada en `test-slots.ts`. + describe('auto-hide geometry and phases', () => { it.each(['top', 'bottom', 'left', 'right'] as Edge[])('keeps only a centered semicircle inside the strip on %s', (edge) => { const vertical = edge === 'left' || edge === 'right'; @@ -417,31 +449,31 @@ describe('Widget effect mutation ordering', () => { } renderToStaticMarkup(createElement(CaptureWidget)); // Refs de Widget: [0]=generation (hook), [1]=stripRef, [2]=peekRef (#271). - widgetEffects.refs[1].current = { dataset: {} }; - widgetEffects.refs[2].current = { dataset: {} }; + widgetEffects.refs[SLOT.stripRef].current = { dataset: {} }; + widgetEffects.refs[SLOT.peekRef].current = { dataset: {} }; return { - placement: widgetEffects.effects.find(e => e.deps?.[0] === widgetEffects.states[7])!, - drag: widgetEffects.effects.find(e => e.deps?.[0] === widgetEffects.states[11] - && e.deps?.[1] === widgetEffects.states[7])!, + placement: widgetEffects.effects.find(e => e.deps?.[0] === widgetEffects.states[SLOT.geo])!, + drag: widgetEffects.effects.find(e => e.deps?.[0] === widgetEffects.states[SLOT.dragging] + && e.deps?.[1] === widgetEffects.states[SLOT.geo])!, grip: grip!, }; }; const renderWidget = (dragging: boolean, autoHide = false, sf = geo.sf) => { // Hook slots belong to Widget (useDockReveal/useUpdaterMode are isolated above). - widgetEffects.states[0] = autoHide ? { autoHide, accounts: [], nineRouter: { baseUrl: '' } } : null; - widgetEffects.states[7] = sf === geo.sf ? geo : { ...geo, sf }; - widgetEffects.states[8] = { w: 400, h: 80 }; - widgetEffects.states[11] = dragging; + widgetEffects.states[SLOT.config] = autoHide ? { autoHide, accounts: [], nineRouter: { baseUrl: '' } } : null; + widgetEffects.states[SLOT.geo] = sf === geo.sf ? geo : { ...geo, sf }; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.dragging] = dragging; return commitWidget(); }; // Text scale (#228): the strip is measured in CSS px and placed in monitor units. const renderScaled = (scale: number, sf: number, phase: RevealPhase = 'open') => { widgetEffects.textScale = scale; widgetEffects.phase = phase; - widgetEffects.states[0] = null; - widgetEffects.states[7] = { ...geo, sf }; - widgetEffects.states[8] = { w: 400, h: 80 }; - widgetEffects.states[11] = false; + widgetEffects.states[SLOT.config] = null; + widgetEffects.states[SLOT.geo] = { ...geo, sf }; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.dragging] = false; return commitWidget(); }; const placeScaled = async (scale: number, sf: number, phase: RevealPhase = 'open') => { @@ -455,7 +487,7 @@ describe('Widget effect mutation ordering', () => { strip, win, bounds: widgetEffects.bounds.mock.calls[0]?.[0], clip: widgetEffects.clip.mock.calls[0]?.[0], - pos: widgetEffects.states[12], + pos: widgetEffects.states[SLOT.pos], }; }; const configureNative = () => { @@ -518,9 +550,9 @@ describe('Widget effect mutation ordering', () => { id: 'a', name: 'A', kind: 'subscription', status: 'ok', plan: null, meters: [], spend: null, message: null, action: null, fetchedAt: '2026-11-01T00:00:00Z', } as unknown as UsageReport; - widgetEffects.states[3] = [report]; - widgetEffects.states[9] = { providerId: 'a', anchored: true }; - widgetEffects.states[10] = 30; // Orb centre in CSS px from the strip start. + widgetEffects.states[SLOT.reports] = [report]; + widgetEffects.states[SLOT.panel] = { providerId: 'a', anchored: true }; + widgetEffects.states[SLOT.anchorRel] = 30; // Orb centre in CSS px from the strip start. renderScaled(scale, sf); const detail = widgetEffects.effects.find((e) => e.deps?.[0] === report)!; detail.run(); @@ -675,7 +707,7 @@ describe('Widget effect mutation ordering', () => { const commitSnapIfReady = async () => { // Model React's post-pointerup commit once config and dragging state change. // Use Widget's actual placement effect to apply the resulting native bounds. - if (!snapCommitted && widgetEffects.states[11] === false && widgetEffects.patch.mock.calls.length > 0) { + if (!snapCommitted && widgetEffects.states[SLOT.dragging] === false && widgetEffects.patch.mock.calls.length > 0) { const cleanup = commitWidget().placement.run(); if (typeof cleanup === 'function') cleanupSnap = cleanup; snapCommitted = true; @@ -688,7 +720,7 @@ describe('Widget effect mutation ordering', () => { await up; await flush(); await commitSnapIfReady(); - const canonical = widgetEffects.states[0] as { dockEdge: Edge; dockOffset: number }; + const canonical = widgetEffects.states[SLOT.config] as { dockEdge: Edge; dockOffset: number }; expect({ earlyReads, earlySnaps, edge: canonical.dockEdge, offset: canonical.dockOffset, nativePosition }) .toEqual({ earlyReads: delayBeforeDispatch ? 0 : 1, @@ -778,7 +810,7 @@ describe('Widget effect mutation ordering', () => { const snap = nearestEdge(geo.area, 760 + 408 * expected, 40 * expected); expect(widgetEffects.patch).toHaveBeenCalledTimes(1); expect(widgetEffects.patch.mock.calls[0][0]).toMatchObject({ dockEdge: snap.edge, dockOffset: snap.offset }); - expect(widgetEffects.states[11]).toBe(false); + expect(widgetEffects.states[SLOT.dragging]).toBe(false); }); it.each([ @@ -823,8 +855,8 @@ describe('Widget effect mutation ordering', () => { expect(earlyReads).toBe(0); expect(dispatched.size).toBe(2); expect(widgetEffects.setPosition.mock.calls.map(call => call[0].y)).toEqual([960, 860]); - expect(widgetEffects.states[11]).toBe(false); - expect(widgetEffects.states[0]).toMatchObject({ dockEdge: 'bottom', dockOffset: 0.4 }); + expect(widgetEffects.states[SLOT.dragging]).toBe(false); + expect(widgetEffects.states[SLOT.config]).toMatchObject({ dockEdge: 'bottom', dockOffset: 0.4 }); const cleanup = commitWidget().placement.run(); await flush(); expect(f.position()).toEqual({ x: 568, y: 1000 }); @@ -849,7 +881,7 @@ describe('Widget effect mutation ordering', () => { await flush(); expect(widgetEffects.setPosition).toHaveBeenCalledTimes(1); expect(widgetEffects.patch).not.toHaveBeenCalled(); - if (cancel === 'new gesture') expect(widgetEffects.states[11]).toBe(true); + if (cancel === 'new gesture') expect(widgetEffects.states[SLOT.dragging]).toBe(true); }); it('does not let an old pointerup snap or clear a newer gesture', async () => { @@ -864,7 +896,7 @@ describe('Widget effect mutation ordering', () => { releaseRead({ x: 760, y: 0 }); await oldUp; await flush(); - expect({ patches: widgetEffects.patch.mock.calls.length, dragging: widgetEffects.states[11] }) + expect({ patches: widgetEffects.patch.mock.calls.length, dragging: widgetEffects.states[SLOT.dragging] }) .toEqual({ patches: 0, dragging: true }); f.acceptFrame(1000, 8); await flush(); @@ -897,19 +929,19 @@ describe('Widget effect mutation ordering', () => { f.grip.onPointerDown(f.pointer(40)); await flush(); if (failure === 'origin') { - expect(widgetEffects.states[11]).toBe(false); + expect(widgetEffects.states[SLOT.dragging]).toBe(false); } else { f.acceptFrame(1000); await flush(); await f.grip.onPointerUp(f.pointer(1000)); - expect(widgetEffects.states[11]).toBe(false); + expect(widgetEffects.states[SLOT.dragging]).toBe(false); } f.grip.onPointerDown(f.pointer(40, 8)); await flush(); f.acceptFrame(1000, 8); await flush(); await f.grip.onPointerUp(f.pointer(1000, 8)); - expect(widgetEffects.states[11]).toBe(false); + expect(widgetEffects.states[SLOT.dragging]).toBe(false); expect(widgetEffects.patch.mock.calls.at(-1)?.[0]).toMatchObject({ dockEdge: 'bottom' }); }); @@ -926,7 +958,7 @@ describe('Widget effect mutation ordering', () => { expect(widgetEffects.setPosition).toHaveBeenCalledTimes(1); expect(widgetEffects.setPosition.mock.calls[0][0]).toMatchObject({ x: 760, y: 960 }); expect(widgetEffects.patch.mock.calls[0][0]).toMatchObject({ dockEdge: 'bottom' }); - expect(widgetEffects.states[11]).toBe(false); + expect(widgetEffects.states[SLOT.dragging]).toBe(false); }); it('cancels an unaccepted RAF at pointerup and ignores another pointer', async () => { @@ -934,7 +966,7 @@ describe('Widget effect mutation ordering', () => { f.grip.onPointerDown(f.pointer(40)); await flush(); await f.grip.onPointerUp(f.pointer(1000, 8)); - expect(widgetEffects.states[11]).toBe(true); + expect(widgetEffects.states[SLOT.dragging]).toBe(true); expect(widgetEffects.patch).not.toHaveBeenCalled(); f.grip.onPointerMove(f.pointer(1000)); expect(f.frames.size).toBe(1); @@ -942,7 +974,7 @@ describe('Widget effect mutation ordering', () => { expect(f.frames.size).toBe(0); expect(widgetEffects.setPosition).not.toHaveBeenCalled(); expect(widgetEffects.patch.mock.calls[0][0]).toMatchObject({ dockEdge: 'top' }); - expect(widgetEffects.states[11]).toBe(false); + expect(widgetEffects.states[SLOT.dragging]).toBe(false); }); it.each(['new gesture', 'unmount'])('ignores a snap response arriving after %s', async (cancel) => { @@ -961,13 +993,13 @@ describe('Widget effect mutation ordering', () => { await oldUp; await flush(); expect(widgetEffects.stateWrite).toHaveBeenCalledTimes(writes); - expect(widgetEffects.states[0]).toBeNull(); + expect(widgetEffects.states[SLOT.config]).toBeNull(); if (cancel === 'new gesture') { - expect(widgetEffects.states[11]).toBe(true); + expect(widgetEffects.states[SLOT.dragging]).toBe(true); f.acceptFrame(1000, 8); await flush(); await f.grip.onPointerUp(f.pointer(1000, 8)); - expect(widgetEffects.states[0]).toMatchObject({ dockEdge: 'bottom' }); + expect(widgetEffects.states[SLOT.config]).toMatchObject({ dockEdge: 'bottom' }); } }); @@ -1060,15 +1092,15 @@ describe('Widget effect mutation ordering', () => { widgetEffects.stateIndex = 0; widgetEffects.refIndex = 0; widgetEffects.effects = []; - widgetEffects.states[0] = { autoHide, accounts: [], nineRouter: { baseUrl: '' }, alerts: { threshold: 90 } }; - widgetEffects.states[7] = geo; - widgetEffects.states[8] = { w: 400, h: 80 }; - widgetEffects.states[11] = false; + widgetEffects.states[SLOT.config] = { autoHide, accounts: [], nineRouter: { baseUrl: '' }, alerts: { threshold: 90 } }; + widgetEffects.states[SLOT.geo] = geo; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.dragging] = false; let tree: ReactNode = null; function CaptureStrip() { tree = Widget(); return tree; } renderToStaticMarkup(createElement(CaptureStrip)); // La sesión de detalle vigente: revisión 5, proveedor 'a'. - widgetEffects.refs[8].current = { revision: 5, report: { id: 'a' } }; + widgetEffects.refs[SLOT.detailStateRef].current = { revision: 5, report: { id: 'a' } }; // Cada prueba usa sus propios listeners. widgetEffects.listeners.delete('detail-interaction'); widgetEffects.listeners.delete('detail-dismiss'); @@ -1082,8 +1114,8 @@ describe('Widget effect mutation ordering', () => { it('closes the panel and frees the strip when the detail declares a placement failure (#250/S22)', async () => { const setTimeoutSpy = vi.fn(); vi.stubGlobal('window', { clearTimeout: vi.fn(), setTimeout: setTimeoutSpy }); - widgetEffects.states[9] = { providerId: 'a', anchored: true }; // Panel abierto y anclado. - widgetEffects.states[14] = true; // `collapsed`: la tira está replegada. + widgetEffects.states[SLOT.panel] = { providerId: 'a', anchored: true }; // Panel abierto y anclado. + widgetEffects.states[SLOT.collapsed] = true; // `collapsed`: la tira está replegada. const { listener, autoHideEffect } = renderStrip(true); // El cleanup del efecto llama a `emitTo(...).catch(...)` y el doble del // arnés devuelve `undefined`: el efecto se deja vivo a propósito. @@ -1097,12 +1129,12 @@ describe('Widget effect mutation ordering', () => { // Con el panel abierto, la tira está ocupada: el auto-ocultar la mantiene // visible y no programa el repliegue. autoHideEffect.run(); - expect(widgetEffects.states[14]).toBe(false); + expect(widgetEffects.states[SLOT.collapsed]).toBe(false); expect(setTimeoutSpy).not.toHaveBeenCalled(); // El detalle declara que no pudo colocarse... for (const handler of handlers) handler({ payload: { revision: 5, provider: 'a', kind: 'placement-failed' } }); // ...la tira cierra el panel... - expect(widgetEffects.states[9]).toEqual({ providerId: null, anchored: false }); +expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: null, anchored: false }); // ...y la tira queda libre: el auto-ocultar puede replegarla (abajo). // Con el panel cerrado, la tira ya no está ocupada: el auto-ocultar vuelve // a replegarla (la tira se repinta con el panel ya cerrado). @@ -1113,7 +1145,7 @@ describe('Widget effect mutation ordering', () => { it('ignores a placement failure notice from a stale detail session (#250/S22)', async () => { vi.stubGlobal('window', { clearTimeout: vi.fn(), setTimeout: vi.fn() }); - widgetEffects.states[9] = { providerId: 'a', anchored: true }; + widgetEffects.states[SLOT.panel] = { providerId: 'a', anchored: true }; const { listener } = renderStrip(false); listener.run(); await flush(); @@ -1124,15 +1156,15 @@ describe('Widget effect mutation ordering', () => { for (const handler of handlers) handler({ payload: { revision: 5, provider: 'a', kind: 'enter' } }); // Otra revisión: el aviso es viejo. for (const handler of handlers) handler({ payload: { revision: 4, provider: 'a', kind: 'placement-failed' } }); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: true }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: true }); // Otro proveedor: la sesión ya no es la vigente. for (const handler of handlers) handler({ payload: { revision: 5, provider: 'other', kind: 'placement-failed' } }); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: true }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: true }); }); it('still closes the panel when the backend dismisses the detail (#250/S22)', async () => { vi.stubGlobal('window', { clearTimeout: vi.fn(), setTimeout: vi.fn() }); - widgetEffects.states[9] = { providerId: 'a', anchored: true }; + widgetEffects.states[SLOT.panel] = { providerId: 'a', anchored: true }; const { listener } = renderStrip(false); listener.run(); await flush(); @@ -1143,7 +1175,7 @@ describe('Widget effect mutation ordering', () => { const dismiss = widgetEffects.listeners.get('detail-dismiss') ?? []; expect(dismiss.length).toBeGreaterThan(0); for (const handler of dismiss) handler(); - expect(widgetEffects.states[9]).toEqual({ providerId: null, anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: null, anchored: false }); }); // El cierre pedido por el detalle es idéntico al cierre normal: también @@ -1156,12 +1188,12 @@ describe('Widget effect mutation ordering', () => { addEventListener: () => {}, removeEventListener: () => {}, }); // Un orbe visible: el puntero puede pasar por encima y agendar la apertura. - widgetEffects.states[3] = [{ + widgetEffects.states[SLOT.reports] = [{ id: 'a', name: 'A', kind: 'subscription', status: 'ok', plan: null, meters: [], spend: null, message: null, action: null, fetchedAt: '2026-11-01T00:00:00Z', } as unknown as UsageReport]; // El panel está cerrado: la apertura del orbe queda pendiente. - widgetEffects.states[9] = { providerId: null, anchored: false }; + widgetEffects.states[SLOT.panel] = { providerId: null, anchored: false }; const { listener, tree } = renderStrip(false); const hover = findOrbHover(tree); expect(hover).toBeDefined(); @@ -1171,12 +1203,12 @@ describe('Widget effect mutation ordering', () => { expect(handlers.length).toBeGreaterThan(0); // El puntero pasa por encima del orbe: la apertura queda agendada... hover!({ getBoundingClientRect: () => ({ left: 0, top: 0, width: 56, height: 56 }) } as HTMLElement); - expect(widgetEffects.states[9]).toEqual({ providerId: null, anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: null, anchored: false }); // ...y el detalle declara que no pudo colocarse. for (const handler of handlers) handler({ payload: { revision: 5, provider: 'a', kind: 'placement-failed' } }); // La apertura pendiente se cancela: el panel no se abre. await vi.advanceTimersByTimeAsync(2000); - expect(widgetEffects.states[9]).toEqual({ providerId: null, anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: null, anchored: false }); }); }); @@ -1193,11 +1225,11 @@ describe('the localized placement reason', () => { widgetEffects.stateIndex = 0; widgetEffects.refIndex = 0; widgetEffects.effects = []; - widgetEffects.states[0] = { autoHide: true, locale, accounts: [], nineRouter: { baseUrl: '' } }; - widgetEffects.states[7] = geo; - widgetEffects.states[8] = { w: 400, h: 80 }; - widgetEffects.states[18] = failed; - widgetEffects.states[19] = failed ? 'size_refused' : null; + widgetEffects.states[SLOT.config] = { autoHide: true, locale, accounts: [], nineRouter: { baseUrl: '' } }; + widgetEffects.states[SLOT.geo] = geo; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.placementFailed] = failed; + widgetEffects.states[SLOT.placementReason] = failed ? 'size_refused' : null; return renderToStaticMarkup(createElement(Widget)); }; @@ -1246,9 +1278,9 @@ describe('the localized placement reason', () => { widgetEffects.refIndex = 0; widgetEffects.effects = []; widgetEffects.phase = 'hidden'; - widgetEffects.states[0] = null; // config pendiente - widgetEffects.states[7] = { ...geo, sf: 1 }; - widgetEffects.states[8] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.config] = null; // config pendiente + widgetEffects.states[SLOT.geo] = { ...geo, sf: 1 }; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; const html = renderToStaticMarkup(createElement(Widget)); expect(html).not.toContain('class="peek"'); widgetEffects.phase = undefined; @@ -1259,10 +1291,10 @@ describe('the localized placement reason', () => { widgetEffects.refIndex = 0; widgetEffects.effects = []; widgetEffects.phase = 'hidden'; - widgetEffects.states[0] = null; // config sigue null - widgetEffects.states[1] = true; // configFailed - widgetEffects.states[7] = { ...geo, sf: 1 }; - widgetEffects.states[8] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.config] = null; // config sigue null + widgetEffects.states[SLOT.configFailed] = true; // configFailed + widgetEffects.states[SLOT.geo] = { ...geo, sf: 1 }; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; const html = renderToStaticMarkup(createElement(Widget)); expect(html).toContain('class="peek"'); expect(html).toContain('aria-label="Mostrar Quorb"'); @@ -1312,21 +1344,21 @@ describe('Widget startup wiring (#271, revisión)', () => { // El efecto de colocación mide el surface montado; los refs se llenan en // el render de SSR, aquí los simulamos para que `measureSurfaceClip` pueda // leer los radios. - widgetEffects.refs[1] ??= { current: null }; // stripRef - widgetEffects.refs[1].current = { dataset: {} }; - widgetEffects.refs[2] ??= { current: null }; // peekRef - widgetEffects.refs[2].current = { dataset: {} }; + widgetEffects.refs[SLOT.stripRef] ??= { current: null }; // stripRef + widgetEffects.refs[SLOT.stripRef].current = { dataset: {} }; + widgetEffects.refs[SLOT.peekRef] ??= { current: null }; // peekRef + widgetEffects.refs[SLOT.peekRef].current = { dataset: {} }; setDragMode('native'); }; /** Config pendiente: estado base para todos los casos. */ const pendingStates = () => { - widgetEffects.states[0] = null; // config pendiente - widgetEffects.states[7] = geo; - widgetEffects.states[8] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.config] = null; // config pendiente + widgetEffects.states[SLOT.geo] = geo; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; // `Widget` inicialmente marca la red de seguridad como ya pasada; lo que // queremos probar es el efecto de colocación mostrando antes del timer. - widgetEffects.refs[24] ??= { current: false }; // shown (refs[0] = generation del hook) - widgetEffects.refs[24].current = false; + widgetEffects.refs[SLOT.shown] ??= { current: false }; // shown (refs[0] = generation del hook) + widgetEffects.refs[SLOT.shown].current = false; }; afterEach(() => { @@ -1381,7 +1413,7 @@ describe('Widget startup wiring (#271, revisión)', () => { // Cinco reintentos con backoff: avanzamos suficiente para agotarlos. await vi.advanceTimersByTimeAsync(60_000); await flush(); - expect(widgetEffects.states[1]).toBe(true); // configFailed + expect(widgetEffects.states[SLOT.configFailed]).toBe(true); // configFailed const html = renderHtml(); expect(html).toContain('Reintentar'); expect(html).toContain('title="sin backend"'); @@ -1391,7 +1423,7 @@ describe('Widget startup wiring (#271, revisión)', () => { it('an unrelated usage error while pending does not break the neutral state', () => { pendingStates(); - widgetEffects.states[6] = 'boom'; // error genérico (refresco/arrastre) + widgetEffects.states[SLOT.error] = 'boom'; // error genérico (refresco/arrastre) const html = renderHtml(); expect(html).toContain('strip__pending'); expect(html).not.toContain('Cargando'); @@ -1404,10 +1436,10 @@ describe('Widget startup wiring (#271, revisión)', () => { useFakeWindowTimers(); widgetEffects.getConfig.mockReturnValue(new Promise(() => {})); // pendiente pendingStates(); - widgetEffects.states[11] = false; // dragging + widgetEffects.states[SLOT.dragging] = false; // dragging renderHtml(); // La colocación normal muestra la ventana (efecto real, no solo el timer). - const placement = widgetEffects.effects.find((e) => e.deps?.[0] === widgetEffects.states[7])!; + const placement = widgetEffects.effects.find((e) => e.deps?.[0] === widgetEffects.states[SLOT.geo])!; const cleanup = placement.run(); await flush(); expect(widgetEffects.show).toHaveBeenCalledTimes(1); @@ -1424,6 +1456,40 @@ describe('Widget startup wiring (#271, revisión)', () => { if (typeof cleanup === 'function') cleanup(); if (typeof cleanupTimer === 'function') cleanupTimer(); }); + + // Coherencia de la tabla de slots (#286): el render de Widget SIN orbs (sin + // datos → sin ProviderLogo) consume EXACTAMENTE los useState/useRef + // declarados, en orden de ejecución y con los iniciales esperados. Añadir o + // reordenar un hook en Widget.tsx (o en useWidgetStartup) rompe este test y + // obliga a tocar solo test-slots.ts. Los componentes de los orbs quedan + // fuera a propósito: añaden hooks propios, así que la tabla declara el + // mínimo del propio Widget. + it('Widget consumes exactly the declared slots, in order, with matching initials (#286)', () => { + widgetEffects.expectedStateCount = WIDGET_STATE_COUNT; + widgetEffects.expectedRefCount = WIDGET_REF_COUNT; + widgetEffects.stateIndex = 0; + widgetEffects.refIndex = 0; + widgetEffects.stateInitials = []; + widgetEffects.refInitials = []; + widgetEffects.states = []; + widgetEffects.refs = []; + try { + renderToStaticMarkup(createElement(Widget)); + } finally { + widgetEffects.expectedStateCount = null; + widgetEffects.expectedRefCount = null; + } + expect(widgetEffects.stateIndex).toBe(WIDGET_STATE_COUNT); + expect(widgetEffects.refIndex).toBe(WIDGET_REF_COUNT); + WIDGET_STATES.forEach((spec, i) => { + if (spec.initial === SKIP) return; + expect(widgetEffects.stateInitials[i], `initial de estado ${spec.name}`).toEqual(spec.initial); + }); + WIDGET_REFS.forEach((spec, i) => { + if (spec.initial === SKIP) return; + expect(widgetEffects.refInitials[i], `initial de ref ${spec.name}`).toEqual(spec.initial); + }); + }); }); // #250 (S16): the close decision follows the pointer presence model, never a @@ -1458,12 +1524,12 @@ describe('hover presence wiring', () => { widgetEffects.stateIndex = 0; widgetEffects.refIndex = 0; widgetEffects.effects = []; - widgetEffects.states[0] = null; - widgetEffects.states[3] = [report, reportB]; - widgetEffects.states[7] = geo; - widgetEffects.states[8] = { w: 400, h: 80 }; - widgetEffects.states[9] = panel; - widgetEffects.states[11] = false; + widgetEffects.states[SLOT.config] = null; + widgetEffects.states[SLOT.reports] = [report, reportB]; + widgetEffects.states[SLOT.geo] = geo; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.panel] = panel; + widgetEffects.states[SLOT.dragging] = false; let dock: DockHandlers | undefined; let hover: ((el: HTMLElement) => void) | undefined; let leave: (() => void) | undefined; @@ -1553,9 +1619,9 @@ describe('hover presence wiring', () => { detail('enter'); // The detail window reports the pointer inside it. // The strip's `mouseleave` never arrives: Wayland native drops it. detail('leave'); // The detail window reports the pointer left it. - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); it('closes the detail when the strip reports leave and the pointer is outside both surfaces', async () => { @@ -1563,7 +1629,7 @@ describe('hover presence wiring', () => { dock.onMouseEnter(); dock.onMouseLeave(); await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); it('keeps the detail open while the pointer is inside it', async () => { @@ -1572,7 +1638,7 @@ describe('hover presence wiring', () => { dock.onMouseLeave(); // Arms the close. detail('enter'); // The detail cancels it. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); }); it('keeps the detail open when the pointer returns to the strip', async () => { @@ -1581,17 +1647,17 @@ describe('hover presence wiring', () => { detail('leave'); // Arms the close. dock.onMouseEnter(); // The strip cancels it. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); }); it('releases the strip presence when the detail reports enter', async () => { const { dock, detail } = await wire(); dock.onMouseEnter(); - expect(widgetEffects.states[13]).toBe(true); // The strip knows the pointer is on it. + expect(widgetEffects.states[SLOT.inside]).toBe(true); // The strip knows the pointer is on it. detail('enter'); // The pointer cannot be in the two windows at once: the strip's presence // is invalid, so its auto-hide is not frozen any more. - expect(widgetEffects.states[13]).toBe(false); + expect(widgetEffects.states[SLOT.inside]).toBe(false); }); // #264/S13: la salida de la tira que llega mucho después de la evidencia @@ -1607,7 +1673,7 @@ describe('hover presence wiring', () => { await vi.advanceTimersByTimeAsync(3000); dock.onMouseLeave(); await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S14: la misma salida pegada al gesto (pocos ms) es el resto de ese @@ -1618,7 +1684,7 @@ describe('hover presence wiring', () => { detail('enter'); dock.onMouseLeave(); // Pega al `enter` del detalle: mismo gesto. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); }); // #264/S16: GTK entrega el `leave` de la ventana del detalle aunque @@ -1629,9 +1695,9 @@ describe('hover presence wiring', () => { dock.onMouseEnter(); detail('enter'); // El DOM sí entrega la entrada al detalle. native('detail', 'leave'); // La salida llega sólo por el relé nativo. - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S16: la entrada nativa es la misma evidencia que la del DOM: si el @@ -1643,10 +1709,10 @@ describe('hover presence wiring', () => { detail('enter'); detail('leave'); // Arma el cierre. await vi.advanceTimersByTimeAsync(100); - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); native('detail', 'enter'); // El puntero vuelve: el cierre se cancela. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); }); // #264/S16: la salida nativa de la tira también cierra: es la misma @@ -1656,7 +1722,7 @@ describe('hover presence wiring', () => { dock.onMouseEnter(); native('widget', 'leave'); // La salida de la tira llega por el relé nativo. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264: el nativo manda cuando existe. En cuanto llega el primer cruce @@ -1669,7 +1735,7 @@ describe('hover presence wiring', () => { await vi.advanceTimersByTimeAsync(100); dock.onMouseLeave(); // El DOM también avisa, más tarde: ya no manda. await vi.advanceTimersByTimeAsync(180); // 280 ms desde la salida nativa. - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264 (R2): en Wayland puede llegar `enter nativo → leave nativo → enter @@ -1681,7 +1747,7 @@ describe('hover presence wiring', () => { native('detail', 'leave'); // Y sale (nativo): el cierre se arma. detail('enter'); // El DOM avisa la entrada tarde: ya no manda. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264: sin ningún cruce nativo el DOM sigue decidiendo la presencia, que @@ -1692,7 +1758,7 @@ describe('hover presence wiring', () => { detail('enter'); detail('leave'); // Sólo el DOM: el cierre se arma y el panel se cierra. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S20: la precedencia nativa es POR SUPERFICIE. Con un solo booleano, @@ -1707,7 +1773,7 @@ describe('hover presence wiring', () => { detail('enter'); await vi.advanceTimersByTimeAsync(280); // Con el puntero sobre el detalle el panel no se cierra. - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); }); // #264/S20: el detalle sin relé conserva su salida por el DOM: si el relé @@ -1719,7 +1785,7 @@ describe('hover presence wiring', () => { detail('enter'); // El detalle, sin relé, avisa su entrada por el DOM. detail('leave'); // Y su salida por el DOM: el cierre se arma. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S20: el espejo del anterior. El relé cubre el detalle y no la tira: @@ -1731,7 +1797,7 @@ describe('hover presence wiring', () => { dock.onMouseEnter(); // El puntero vuelve a la tira, que no tiene relé: por el DOM. await vi.advanceTimersByTimeAsync(280); // Con el puntero sobre la tira el panel no se cierra. - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); }); // #170/#223: que un panel anclado siga abierto es intencional. El modelo @@ -1746,7 +1812,7 @@ describe('hover presence wiring', () => { // Más que el retardo de cierre: si el guard del anclaje desapareciera, el // timer se armaría y el panel se cerraría solo. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: true }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: true }); }); // #264/S21: un `leave` que se repite con la presencia ya en `outside` no @@ -1759,7 +1825,7 @@ describe('hover presence wiring', () => { await vi.advanceTimersByTimeAsync(200); dock.onMouseLeave(); // La salida que se repite no lo rearma. await vi.advanceTimersByTimeAsync(100); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S21: da igual cuántas salidas lleguen: el cierre sigue siendo el de @@ -1772,7 +1838,7 @@ describe('hover presence wiring', () => { await vi.advanceTimersByTimeAsync(50); } await vi.advanceTimersByTimeAsync(50); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S21: entrar a una superficie cancela el cierre, así que la salida @@ -1787,9 +1853,9 @@ describe('hover presence wiring', () => { await vi.advanceTimersByTimeAsync(100); detail('leave'); // t0+200: el puntero sale: el cierre se arma de nuevo. await vi.advanceTimersByTimeAsync(279); - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); await vi.advanceTimersByTimeAsync(1); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S21: si no hay ningún cierre pendiente, la salida lo arma. Es el @@ -1804,10 +1870,10 @@ describe('hover presence wiring', () => { await vi.advanceTimersByTimeAsync(50); hover(orbElement as unknown as HTMLElement); // El hover del orbe cancela los timers. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toMatchObject({ providerId: 'a' }); + expect(widgetEffects.states[SLOT.panel]).toMatchObject({ providerId: 'a' }); dock.onMouseLeave(); // Ya no hay cierre pendiente: esta salida lo arma. await vi.advanceTimersByTimeAsync(280); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S21: lo mismo por el relé nativo (#264/S16): la salida que se @@ -1819,7 +1885,7 @@ describe('hover presence wiring', () => { await vi.advanceTimersByTimeAsync(200); native('widget', 'leave'); // La salida que se repite no lo rearma. await vi.advanceTimersByTimeAsync(100); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S19: el bloqueo del hover tras reordenar (#222/#240) lo libera el @@ -1863,7 +1929,7 @@ describe('hover presence wiring', () => { reorder(orbs); // El reordenamiento bloquea el hover (#222). native('widget', 'leave'); // La salida llega sólo por el relé nativo. await hoverAfterTheGuard(hover); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: false }); }); // El puntero pasa de la tira al detalle: ya no está en la tira, así que @@ -1874,7 +1940,7 @@ describe('hover presence wiring', () => { reorder(orbs); detail('enter'); // El puntero entra al detalle. await hoverAfterTheGuard(hover); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: false }); }); // #222: el detalle se cierra con el puntero encima del orbe (justo al @@ -1889,7 +1955,7 @@ describe('hover presence wiring', () => { await hoverAfterTheGuard(hover); // La apertura retardada del hover, si el bloqueo no estuviera puesto. await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // Sin cruce nativo (Windows y macOS) la salida del DOM sigue siendo la @@ -1900,7 +1966,7 @@ describe('hover presence wiring', () => { reorder(orbs); dock.onMouseLeave(); // La salida del DOM: Windows y macOS. await hoverAfterTheGuard(hover); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: false }); }); // #264/S23: el bloqueo tras reordenar cubre un solo orbe, el que quedó @@ -1914,7 +1980,7 @@ describe('hover presence wiring', () => { reorder(orbs); await vi.advanceTimersByTimeAsync(500); enterB?.(orbElement as unknown as HTMLElement); // El hover del otro orbe. - expect(widgetEffects.states[9]).toEqual({ providerId: 'b', anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'b', anchored: false }); }); // #264/S28: el soltar quita la vista previa y aplica el orden nuevo, y eso @@ -1928,7 +1994,7 @@ describe('hover presence wiring', () => { leave?.(); // El salto de layout del soltar. await hoverAfterTheGuard(hover); await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // #264/S30: soltar fuera de la tira no deja bloqueo. En Linux la salida @@ -1942,7 +2008,7 @@ describe('hover presence wiring', () => { await hoverAfterTheGuard(hover); // La apertura retardada del hover: sin bloqueo, el detalle abre. await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: false }); }); // #264/S31: soltar en un hueco de la tira tampoco deja bloqueo: no hay @@ -1955,7 +2021,7 @@ describe('hover presence wiring', () => { await hoverAfterTheGuard(hover); // La apertura retardada del hover: sin bloqueo, el detalle abre. await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: false }); }); // #264/S23: el bloqueo se acaba cuando el puntero sale del orbe bloqueado @@ -1966,12 +2032,12 @@ describe('hover presence wiring', () => { reorder(orbs); hover(orbElement as unknown as HTMLElement); // El enter del orbe bloqueado: no abre y lo confirma. await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); leave?.(); // El puntero sale de ese orbe. await vi.advanceTimersByTimeAsync(500); hover(orbElement as unknown as HTMLElement); // Vuelve a entrar: ahora sí abre. await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: false }); }); // #279: una cancelación no deja el bloqueo del reordenamiento puesto: no @@ -1988,7 +2054,7 @@ describe('hover presence wiring', () => { await hoverAfterTheGuard(hover); // El hover con el panel cerrado espera el `OPEN_DELAY` antes de abrir. await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: false }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: false }); }); }); }); @@ -2027,15 +2093,15 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { widgetEffects.stateIndex = 0; widgetEffects.refIndex = 0; widgetEffects.effects = []; - widgetEffects.states[0] = { + widgetEffects.states[SLOT.config] = { providerOrder: ['a', 'b', 'c'], hiddenProviders: [], accounts: [], nineRouter: { baseUrl: '' }, alerts: { threshold: 90 }, }; - widgetEffects.states[3] = [report('a'), report('b'), report('c')]; - widgetEffects.states[7] = geo; - widgetEffects.states[8] = { w: 400, h: 80 }; - widgetEffects.states[11] = false; - if (reorder !== undefined) widgetEffects.states[21] = reorder; + widgetEffects.states[SLOT.reports] = [report('a'), report('b'), report('c')]; + widgetEffects.states[SLOT.geo] = geo; + widgetEffects.states[SLOT.stripSize] = { w: 400, h: 80 }; + widgetEffects.states[SLOT.dragging] = false; + if (reorder !== undefined) widgetEffects.states[SLOT.reorder] = reorder; let tree: ReactNode = null; function CaptureWidget() { tree = Widget(); return tree; } const markup = renderToStaticMarkup(createElement(CaptureWidget)); @@ -2100,7 +2166,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { const dragged = findOrbPointers(tree).find((o) => o.id === 'a')!; // El DOM sigue el orden guardado (a, b, c) con las posiciones de la vista // previa: a en la ranura 0, c en la 1 y b en la 2. - widgetEffects.refs[7].current = { + widgetEffects.refs[SLOT.orbsRef].current = { querySelectorAll: () => [ { dataset: { id: 'a' }, getBoundingClientRect: () => ({ left: 0, top: 0, width: 60, height: 60 }) }, { dataset: { id: 'b' }, getBoundingClientRect: () => ({ left: 200, top: 0, width: 60, height: 60 }) }, @@ -2171,7 +2237,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { /** La tira de tres orbes con las posiciones que decide la vista previa. */ const strip = () => { - widgetEffects.refs[7].current = { + widgetEffects.refs[SLOT.orbsRef].current = { querySelectorAll: () => [ { dataset: { id: 'a' }, getBoundingClientRect: () => ({ left: 0, top: 0, width: 60, height: 60 }) }, { dataset: { id: 'b' }, getBoundingClientRect: () => ({ left: 200, top: 0, width: 60, height: 60 }) }, @@ -2210,9 +2276,9 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { it('does not anchor the panel when Escape is pressed with the button still down (#279/S16)', () => { const { tree } = render(null); const dragged = drag(tree); - expect(widgetEffects.states[21]).not.toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).not.toBeNull(); escapeKey(); - expect(widgetEffects.states[21]).toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).toBeNull(); // El usuario suelta. dragged.onPointerUp({ clientX: 150, clientY: 30, pointerId: 1, @@ -2220,7 +2286,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { }); // Y el navegador despacha el `click` de la cola sobre el mismo orbe. dragged.onClick?.(orb); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); expect(widgetEffects.patch).not.toHaveBeenCalled(); }); @@ -2238,7 +2304,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { currentTarget: { releasePointerCapture: () => {} }, }); plain.onClick?.(orb); - expect(widgetEffects.states[9]).toEqual({ providerId: 'a', anchored: true }); + expect(widgetEffects.states[SLOT.panel]).toEqual({ providerId: 'a', anchored: true }); }); // El `enter` diferido del navegador no abre el detalle: para eso está el @@ -2255,7 +2321,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { await vi.advanceTimersByTimeAsync(400); findOrbHover(tree)?.(orb); await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // La ventana entre el Escape y la suelta: el gesto sigue vivo (el botón @@ -2267,7 +2333,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { await vi.advanceTimersByTimeAsync(400); findOrbHover(tree)?.(orb); await vi.advanceTimersByTimeAsync(400); - expect(widgetEffects.states[9]).toEqual(NO_PANEL); + expect(widgetEffects.states[SLOT.panel]).toEqual(NO_PANEL); }); // Después del Escape el gesto cancelado no mueve más la vista previa: si @@ -2276,29 +2342,29 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { const { tree } = render(null); const dragged = drag(tree); escapeKey(); - expect(widgetEffects.states[21]).toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).toBeNull(); dragged.onPointerMove({ clientX: 200, clientY: 30 }); - expect(widgetEffects.states[21]).toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).toBeNull(); }); // Un `pointercancel` durante el arrastre deja el orden guardado sin cambios. it('does not save the order when the drag is cancelled (#279)', () => { const { tree } = render(null); const dragged = drag(tree); - expect(widgetEffects.states[21]).not.toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).not.toBeNull(); dragged.onPointerCancel?.({ pointerId: 1, currentTarget: { releasePointerCapture: () => {} }, }); expect(widgetEffects.patch).not.toHaveBeenCalled(); - expect(widgetEffects.states[21]).toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).toBeNull(); }); // Escape durante el arrastre restaura el orden original. it('does not save the order when Escape cancels the drag (#279)', () => { const { tree } = render(null); drag(tree); - expect(widgetEffects.states[21]).not.toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).not.toBeNull(); // El efecto se busca por nombre (#279/S19): el texto de su fuente se // rompe con cualquier refactor. Y el handler es el que registró la // tira, que el arnés intercepta (#279). @@ -2306,7 +2372,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { escape!.run(); keydown.forEach((h) => h({ key: 'Escape' } as KeyboardEvent)); expect(widgetEffects.patch).not.toHaveBeenCalled(); - expect(widgetEffects.states[21]).toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).toBeNull(); }); // Soltar normalmente sigue guardando el nuevo orden: la separación de la @@ -2314,7 +2380,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { it('still saves the order when the orb is dropped (#279)', () => { const { tree } = render(null); drag(tree); - const preview = widgetEffects.states[21] as { id: string; order: string[] }; + const preview = widgetEffects.states[SLOT.reorder] as { id: string; order: string[] }; // Los handlers son cierres del render que los creó: el que suelta tiene // que ser el del render nuevo, con la vista previa ya escrita. const { tree: after } = render(preview); @@ -2325,7 +2391,7 @@ describe('the reorder preview keeps the DOM still (#264/L18)', () => { }); expect(widgetEffects.patch).toHaveBeenCalledTimes(1); expect(widgetEffects.patch).toHaveBeenCalledWith({ providerOrder: preview.order }); - expect(widgetEffects.states[21]).toBeNull(); + expect(widgetEffects.states[SLOT.reorder]).toBeNull(); }); }); }); diff --git a/src/lib/test-slots.ts b/src/lib/test-slots.ts new file mode 100644 index 0000000..405b055 --- /dev/null +++ b/src/lib/test-slots.ts @@ -0,0 +1,131 @@ +// Tabla de slots del mock de react (#286). +// +// Los tests que montan el `Widget` completo (auto-hide.test.ts) referencian los +// estados/refs del mock por POSICIÓN, pero en runtime los hooks no tienen +// nombre: `vi.mock('react')` solo recibe `useRef(initial)` o +// `useState(initial)`. Este módulo es la ÚNICA fuente de verdad de esa +// correspondencia nombre → índice, en orden de ejecución del render: +// +// useWidgetStartup consume states[0..2] y refs[0] antes que Widget +// (`config`, `configFailed`, `configError` y `generation`), y después vienen +// los propios de Widget en orden de declaración. +// +// Regla de mantenimiento: al añadir/reordenar un `useState`/`useRef` en +// `Widget.tsx` o en el hook, SOLO se toca este fichero — los índices se +// derivan de la posición en el array. Un test de coherencia (#286) falla si la +// tabla se desalinea con lo que el render realmente consume, y el mock lanza +// en el punto exacto si un render sobrepasa los contadores declarados. +// +// `initial` es el valor esperado del hook en el primer render; sirve de +// oráculo para detectar reordenamientos (no como mecanismo de lookup, que +// sigue siendo el índice). Los iniciales no deterministas (objetos creados por +// factoría, `Date.now()`, funciones, promesas…) llevan `SKIP`. + +/** Marcador: el valor inicial no es determinista y no se verifica. */ +export const SKIP = Symbol('test-slots.skip-initial'); + +export interface SlotSpec { + name: string; + initial: unknown; +} + +/** Estados que `Widget` crea en un render, en orden de ejecución. */ +export const WIDGET_STATES = [ + { name: 'config', initial: null }, // useWidgetStartup + { name: 'configFailed', initial: false }, // useWidgetStartup + { name: 'configError', initial: null }, // useWidgetStartup + { name: 'reports', initial: [] }, + { name: 'loading', initial: false }, + { name: 'updatedAt', initial: null }, + { name: 'error', initial: null }, + { name: 'geo', initial: null }, + { name: 'stripSize', initial: null }, + { name: 'panel', initial: SKIP }, // NO_PANEL + { name: 'anchorRel', initial: 0 }, + { name: 'dragging', initial: false }, + { name: 'pos', initial: { strip: { x: 0, y: 0 } } }, + { name: 'inside', initial: false }, + { name: 'collapsed', initial: false }, + { name: 'focused', initial: false }, + { name: 'peekFocused', initial: false }, + { name: 'placementRetry', initial: 0 }, + { name: 'placementFailed', initial: false }, + { name: 'placementReason', initial: null }, + { name: 'revealUntil', initial: 0 }, + { name: 'reorder', initial: null }, + { name: 'update', initial: { phase: 'idle' } }, +] as const satisfies readonly SlotSpec[]; + +/** Refs que `Widget` crea en un render, en orden de ejecución. */ +export const WIDGET_REFS = [ + { name: 'generation', initial: 0 }, // useWidgetStartup + { name: 'stripRef', initial: null }, + { name: 'peekRef', initial: null }, + { name: 'widgetQueue', initial: SKIP }, // createLatestQueue() + { name: 'widgetBounds', initial: null }, + { name: 'widgetBoundsReadBack', initial: false }, + { name: 'placementInFlight', initial: false }, + { name: 'orbsRef', initial: null }, + { name: 'detailStateRef', initial: null }, + { name: 'detailReadyRef', initial: false }, + { name: 'detailRevision', initial: SKIP }, // Date.now() + // #264/S32 (merge de #275): el puntero del detalle ya no se lee por ref, + // lo comunica el propio detalle por eventos. Tres refs nuevas del Widget: + { name: 'hoverRef', initial: 'outside' }, + { name: 'hoverAtRef', initial: 0 }, + { name: 'nativeCrossingsRef', initial: SKIP }, // { widget: false, detail: false } + { name: 'configRef', initial: null }, + { name: 'appliedConfigRef', initial: null }, + { name: 'reportsRef', initial: [] }, + { name: 'geoRef', initial: null }, + { name: 'inFlight', initial: false }, + { name: 'refreshAbort', initial: null }, + { name: 'refreshSeq', initial: 0 }, + { name: 'refreshEnv', initial: '' }, + { name: 'closeTimer', initial: undefined }, + { name: 'openTimer', initial: undefined }, + { name: 'presenceRef', initial: SKIP }, // createDetailPresence(...) + { name: 'shown', initial: false }, + { name: 'hiddenByUser', initial: false }, + { name: 'drag', initial: null }, + { name: 'orbDrag', initial: null }, + { name: 'lastReorderAt', initial: 0 }, + { name: 'reorderHold', initial: SKIP }, // NO_HOLD (ReorderHold, #264/S23) + { name: 'openPeakRef', initial: SKIP }, // () => {} + { name: 'dragWork', initial: SKIP }, // Promise.resolve() + { name: 'dragMounted', initial: true }, +] as const satisfies readonly SlotSpec[]; + +/** Estados del probe de `useWidgetStartup` (use-widget-startup.test.ts). */ +export const STARTUP_STATES = [ + { name: 'config', initial: null }, + { name: 'configFailed', initial: false }, + { name: 'configError', initial: null }, +] as const satisfies readonly SlotSpec[]; + +/** Construye `nombre → índice` desde uno o más arrays ordenados (única fuente). */ +function buildSlotIndex(groups: readonly (readonly SlotSpec[])[]): Record { + const index: Record = {}; + for (const specs of groups) { + for (const [i, spec] of specs.entries()) { + // Un nombre repetido (dentro de una tabla o entre estados/refs al + // fusionarlos en `SLOT`) sobrescribiría el índice en silencio y los + // tests leerían el slot equivocado (#286). + if (spec.name in index) { + throw new Error(`Nombre de slot duplicado: '${spec.name}'. Revisa src/lib/test-slots.ts.`); + } + index[spec.name] = i; + } + } + return index; +} + +/** `SLOT.shown`, `SLOT.geo`, `SLOT.stripRef`… → índice posicional en el mock. */ +export const SLOT = buildSlotIndex([WIDGET_STATES, WIDGET_REFS]); + +/** Índices del probe del hook (separados: el hook no monta Widget). */ +export const STARTUP_SLOT = buildSlotIndex([STARTUP_STATES]); + +export const WIDGET_STATE_COUNT = WIDGET_STATES.length; +export const WIDGET_REF_COUNT = WIDGET_REFS.length; +export const STARTUP_STATE_COUNT = STARTUP_STATES.length; diff --git a/src/lib/use-widget-startup.test.ts b/src/lib/use-widget-startup.test.ts index 6c32947..ce08c1c 100644 --- a/src/lib/use-widget-startup.test.ts +++ b/src/lib/use-widget-startup.test.ts @@ -12,9 +12,13 @@ import { createElement } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { useWidgetStartup, STARTUP_SHOW_DELAY_MS } from './use-widget-startup'; +import { SKIP, STARTUP_SLOT, STARTUP_STATES, STARTUP_STATE_COUNT } from './test-slots'; const state = vi.hoisted(() => ({ states: [] as unknown[], stateIndex: 0, + // Iniciales que el hook pasa a cada useState, en orden de render (#286). + stateInitials: [] as unknown[], + expectedStateCount: null as number | null, effects: [] as { run: () => void | (() => void); deps?: readonly unknown[] }[], getConfig: vi.fn(), listeners: new Map void)[]>(), @@ -26,6 +30,13 @@ vi.mock('react', async (importOriginal) => { ...react, useState: ((initial?: unknown) => { const index = state.stateIndex++; + state.stateInitials.push(initial); + // Disparidad temprana con la tabla de slots (#286): el render del probe + // no debe crear más useState de los declarados para el hook. + const expected = state.expectedStateCount; + if (expected != null && index >= expected) { + throw new Error(`useWidgetStartup crea más useState (${index + 1}) de los que declara STARTUP_STATES (#286). Actualiza src/lib/test-slots.ts.`); + } const value = index in state.states ? state.states[index] : typeof initial === 'function' ? initial() : initial; // El valor inicial vive en el slot: el test lo lee con `state.states[i]` @@ -49,6 +60,10 @@ vi.mock('@tauri-apps/api/event', () => ({ }), })); +// Recuento esperado de la tabla de slots del hook (#286): inyectado aquí +// (el factory de `vi.mock` no puede importar `test-slots` por hoisting). +state.expectedStateCount = STARTUP_STATE_COUNT; + /** Promise controlable para `getConfig` (pendiente hasta que el test decida). */ function deferred() { let resolve!: (c: unknown) => void; @@ -68,11 +83,11 @@ function probe(options: Parameters[0] = {}) { return createElement('pre', null, 'probe'); } renderToStaticMarkup(createElement(Probe)); - // Los tres primeros slots de estado del hook: config, configFailed, configError. + // Slots del hook por nombre (#286): la tabla vive en `test-slots.ts`. const read = (): { config: unknown; configFailed: boolean; configError: string | null } => ({ - config: state.states[0] ?? null, - configFailed: state.states[1] as boolean, - configError: (state.states[2] ?? null) as string | null, + config: state.states[STARTUP_SLOT.config] ?? null, + configFailed: state.states[STARTUP_SLOT.configFailed] as boolean, + configError: (state.states[STARTUP_SLOT.configError] ?? null) as string | null, }); const load = state.effects.find((e) => e.run.toString().includes('getConfig'))!; const timer = state.effects.find((e) => e.run.toString().includes('setTimeout'))!; @@ -218,4 +233,22 @@ describe('useWidgetStartup wiring (#271)', () => { await vi.advanceTimersByTimeAsync(STARTUP_SHOW_DELAY_MS + 1); expect(onReadyToShow).toHaveBeenCalledTimes(1); }); + + // Coherencia de la tabla de slots (#286): el render del probe consume + // exactamente los useState que declara STARTUP_STATES, en orden y con los + // iniciales esperados. Un useState de más en el hook (o un reordenamiento) + // rompe este test pidiendo actualizar la tabla. + it('the probe consumes exactly the useState declared in STARTUP_STATES, with matching initials', () => { + state.stateIndex = 0; + state.stateInitials = []; + state.states = []; + probe(); + expect(state.stateIndex).toBe(STARTUP_STATE_COUNT); + STARTUP_STATES.forEach((spec, i) => { + // `STARTUP_STATES` no declara SKIP hoy; el cast mantiene el oráculo + // válido si la tabla lo usa en el futuro (#286). + if ((spec.initial as unknown) === SKIP) return; + expect(state.stateInitials[i], `initial de ${spec.name}`).toEqual(spec.initial); + }); + }); });