diff --git a/docs/i18n-inventory.md b/docs/i18n-inventory.md index 62c33ea..2b63c92 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/` = `950e87aed191c15e2ea061efd6ff0e41e12a54a2` and `src-tauri/src/` = `4e040c3e38251119abf3e7d0de46376d82d9c885`. +Generated by `node scripts/i18n-inventory.mjs` from the source trees `src/` = `eb4547b4f645376c9d2e56581547abd336534584` and `src-tauri/src/` = `4e040c3e38251119abf3e7d0de46376d82d9c885`. 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`. diff --git a/odd/tasks/229-detail-panel-width.md b/odd/tasks/229-detail-panel-width.md new file mode 100644 index 0000000..5282c87 --- /dev/null +++ b/odd/tasks/229-detail-panel-width.md @@ -0,0 +1,40 @@ +# #229 — Fit detail panel width to the work area +Branch: `fix/229-detail-panel-width`; base: `0852eba386c340dece3a03cfadbf6e1deb3a021c`; delivery: ask-on-risk, local work only. +Checks: focused Vitest, `npm test`, `npm run typecheck`; forecast: 250–400 authored diff lines, one coherent work-unit commit. + +## Specs +S1 — Issue requirement: «Que el panel nunca se salga del área de trabajo en ancho, igual que ya ocurre en altura.» Source: https://github.com/egdev6/quorb/issues/229 +S2 — Owner-approved geometry: «**Factor:** el mínimo entre el de altura y el de ancho, con escalado uniforme. El límite horizontal es `area.w` en los bordes superior e inferior, y el espacio libre junto a la tira, descontando la separación, en los laterales. `DetailPlacement` ya incluye `strip` y `edge`, así que no hace falta cambiar el payload.» +S3 — Owner-approved height: «**Altura devuelta:** `maxHeight` solo cuando la altura es el límite activo; si no, `ceil(natural × factor)`.» +S4 — Owner-approved degenerate case: «**Sin espacio útil:** igual que `panelHeightLimit`, el límite de ancho se acota a un mínimo de 1, sin usar `placement-failed`, que queda para fallos de colocación nativa.» +S5 — Owner-approved physical containment: «**Píxeles físicos:** verificar que los bordes derecho e inferior no superen el área tras el redondeo de `physicalPanelBounds`, resolviéndolo en el detalle sin tocar el conversor compartido con la tira.» +S6 — Scope exclusions: «**Fuera de alcance:** escala mínima legible, scroll y redistribución del contenido.» «#265 y #314 quedan fuera.» Keep payload, shared converter, strip geometry and #250 placement/retry contracts unchanged. +S7 — Owner-requested tests: «En los tests, además de lo que indicas, conviene ampliar la prueba de contención de los cuatro bordes con escala de texto 2,25 y áreas estrechas (la actual usa ancho 300 sin escala) y actualizar la aserción de `DetailPanel.test.tsx` si cambia la llamada a `fitPanel`.» Check no fit, width-only, height-only, both with each dominant axis and ties, negative monitor origins, fractional DPI, actual DOM/native size coherence, and existing placement behavior. Manual Windows visual validation must be reported unavailable if no Windows runtime exists. +Approval source for S2–S7: https://github.com/egdev6/quorb/issues/229#issuecomment-7157846474 +S8 — Publication request: «pues subimos la rama a github.com/egdev6/quorb y genramos pr en la pr en español comentar que me gustaría que alguien con windows nativo nos confirmara que es correcto lo que se ha implementado. tiene sentido pedirlo?» Publish branch and Spanish PR to the explicitly authorized upstream; retain pending Windows proof without claiming it passed. + +## Tasks +T1 — S1–S7; route: bounded worker (context backstop), parent owns physical strategy; done (automated implementation checks); fitting and detail-local physical containment implemented with comments; commit: 3b7332d; RED exit1 20 failed/87 passed, final GREEN exit0 107 passed, typecheck exit0. +T2 — S1–S7; route: parent spot-check and assessment; done (automated local work); full suite exit0 (1287 Vitest + 329 Node), parent spot-check exit0 107/107, typecheck exit0; source commit 3b7332d; committed ASSESS medium, reviewDue=false/under_budget, no independent verifier required, no native review started. Peer base-study received, not a verification of the implementation; Windows proof remains T3. +T3 — S7; route: human Windows runtime; blocked (no Windows runtime available); visual check of text scale, clipping, corners and interaction; commit: N/A. +T4 — S8; route: parent; done; scoped format ddad8b8, inventory/preflight a0c25c7; branch published to egdev6/quorb and Spanish PR https://github.com/egdev6/quorb/pull/315 opened against main, assigned to ludevdot; native Windows validation requested explicitly; CI pending. + +## Log +L1 — User implementation request verbatim: «sabiendo esto empezamos con el desarrollo apoyandonos de la sesion 01a21247-9d8d-7760-bdf0-ce334663beda para lo que necesites, tanto en investigacion , como en desarrollo, tu decides» +L2 — Preimplementation: branch verified clean; GitHub assignee ludevdot verified against `gh api user`; owner approval and latest acknowledgement read. RDD on. Peer 01a21247-9d8d-7760-bdf0-ce334663beda asked for read-only physical containment strategy. No source edits yet. +L3 — Research: fitPanel only caps height; width is already rendered basal monitor width (CSS layout divides by base). Shared physicalPanelBounds rounds origin and ceils size; changing it would affect strip behavior. #250 does not validate work-area containment. Explorer supplied focused runner `npx vitest run --dir src lib/detail-panel.test.ts lib/dock.test.ts DetailPanel.placement.test.tsx`; `npm test` includes Vitest and Node scripts, `npm run typecheck` is available. No tests run yet. Existing comments are the proportionate fitting documentation; no CLI/API/help behavior changes planned. +L4 — Risk forecast: detail-only behavior, no data/security/concurrency/delivery changes intended. Reassess item 3 if shared unrequested behavior changes; do not alter shared converter or strip. Physical strategy implemented in fitDetailPanel: recover integer physical work-area origin/size separately, derive inward strip bounds with ceil/floor, uniformly refit DOM if native rounded dimensions exceed budget, then clamp physical origin. No truncation beneath larger content; shared converter unchanged. + +L5 — Writer T1 evidence: RED exit1 (20 failed/87 passed), first GREEN exit1 (4 failed/103 passed, DOM operation-order ulp mismatch), corrected and final GREEN exit0 (107/107), typecheck exit0. Logs: /var/folders/9f/dwn9fytx6zx61dklp7tcs_nr0000gn/T/gpWrafwp/gaQgcva7/quorb-229-writer.g9WfmN/. Parent spot check exit0 107/107; git diff --check exit0. Full npm test job-1 exit0. +L6 — Initial uncommitted ASSESS unavailable because untracked task document lacked declaration; no review lineage created. Will assess the committed work-unit selector after local commit. Windows visual validation unavailable; T3 remains blocked. Risk: none (detail-only fitting logic and callsite; shared converter, payload, strip geometry, and native placement contracts unchanged). + +L7 — Work-unit commit 3b7332d, 310 authored changed lines. ASSESS over base 0852eba386c340dece3a03cfadbf6e1deb3a021c with committedOnly=true: medium, reviewDue=false, reviewDueReason=under_budget, independentVerifier=false. No receipt/approval claimed. Full npm test exit0: 1287 Vitest + 329 Node tests, zero failures. Peer contrast was pending at this point (resolved in L8); T3 awaits Windows runtime. No push/PR. + +L8 — Peer base-study received: agrees width/height factor, real strip bounds, min1/no failure gate and local physical fix. Its context predates 3b7332d, so this is research support, NOT an independent review of current code. No new proven defect. Proposed ceil logical width and size-only shrink were not adopted: implementation preserves proportional fit and uniformly refits DOM before any surface resize. Suggested risks (shared panelRect/concurrent queue) do not apply to the diff: neither implementation nor contracts changed there. Automated T2 complete; T3 remains blocked. Rollback boundary: five source/test files changed by 3b7332d, no unrelated edits. + +L9 — User publication request verbatim: «pues subimos la rama a github.com/egdev6/quorb y genramos pr en la pr en español comentar que me gustaría que alguien con windows nativo nos confirmara que es correcto lo que se ha implementado. tiene sentido pedirlo?» Origin is ludevdot/quorb (fork), authorized target is egdev6/quorb, viewerPermission WRITE verified. Will push explicit upstream URL without changing remotes. +L10 — Publication preflight found one Biome formatting error in src/lib/detail-panel.test.ts; corrected with scoped formatter (only array wrapping). Biome now exit0, 225 warnings/31 infos retained, focused tests exit0 107/107. Inventory was refreshed in 2cc9320; formatting source-tree change requires another generated hash refresh. Source review baseline remains 0852eba. + +L11 — Final publication preflight: npm test and npm run build exit0 (1287 Vitest + 329 Node); build emits nonblocking >500kB chunk warning. cargo fmt --check, inventory --check and diff --check exit0. Scoped formatting commit ddad8b8; generated inventory refreshed again against its source tree. Windows manual proof remains pending and will be requested in Spanish PR. + +L12 — Publication verified: https://github.com/egdev6/quorb/pull/315 OPEN, base main, head fix/229-detail-panel-width, assignee ludevdot. Spanish body includes exact approved scope, actual check results, explicit native Windows/WebView2 validation request and no claim of manual proof. Five CI checks initially IN_PROGRESS (Windows, Linux, macOS ARM64, static code safety, secrets scan). Push passed normal Biome/cargo-fmt hooks. Foreground delivery used after pre-delivery guard refused background execution without running it; no bypass. Final slice ASSESS: medium, reviewDue=false/under_budget. No merge/release authorized or performed. diff --git a/src/DetailPanel.placement.test.tsx b/src/DetailPanel.placement.test.tsx index 9a41abd..7d33219 100644 --- a/src/DetailPanel.placement.test.tsx +++ b/src/DetailPanel.placement.test.tsx @@ -11,12 +11,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { DetailPanel } from './DetailPanel'; import type { DetailPlacementReport } from './detail-placement'; -import { DETAIL_EVENTS, type DetailState, type PhysicalBounds } from './lib/detail-panel'; +import { DETAIL_EVENTS, panelScaleFromTransform, type DetailState, type PhysicalBounds } from './lib/detail-panel'; +import { panelHeightLimit, stripRect, type Edge } from './lib/dock'; const harness = vi.hoisted(() => ({ states: [] as unknown[], stateIndex: 0, stateWrite: vi.fn(), + textScale: 1, refs: [] as { current: unknown }[], refIndex: 0, effects: [] as { run: () => void | (() => void) }[], @@ -73,7 +75,7 @@ vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: () => ({ hide: nati vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async () => () => {}), emitTo: native.emitTo })); vi.mock('@tauri-apps/plugin-opener', () => ({ openUrl: vi.fn(async () => {}) })); vi.mock('./i18n/use-locale', () => ({ useLocale: () => 'es' })); -vi.mock('./lib/useTextScale', () => ({ useTextScale: () => 1 })); +vi.mock('./lib/useTextScale', () => ({ useTextScale: () => harness.textScale })); const granted: PhysicalBounds = { x: 815, y: 88, w: 330, h: 400 }; @@ -162,14 +164,14 @@ const failureNotices = () => * Monta el panel con estado y ejecuta su efecto de placement real con la * secuencia de informes nativa indicada. */ -const runPlacement = async (reports: DetailPlacementReport[], place?: () => Promise) => { +const runPlacement = async (reports: DetailPlacementReport[], place?: () => Promise, state = detailState) => { harness.states = []; harness.stateIndex = 0; harness.refs = []; harness.refIndex = 0; harness.effects = []; harness.layoutEffects = []; - harness.states[0] = detailState; // `data`: hay algo que colocar. + harness.states[0] = state; // `data`: hay algo que colocar. let index = 0; native.setDetailBounds.mockImplementation(place ?? (async () => reports[Math.min(index++, reports.length - 1)])); native.setSurfaceClip.mockResolvedValue(undefined); @@ -177,7 +179,7 @@ const runPlacement = async (reports: DetailPlacementReport[], place?: () => Prom // El componente registra sus efectos al llamarse. DetailPanel(); harness.refs[0].current = panelElement; // `panelRef` - harness.refs[1].current = detailState; // `dataRef`: la sesión de detalle vigente + harness.refs[1].current = state; // `dataRef`: la sesión de detalle vigente expect(harness.layoutEffects).toHaveLength(1); const cleanup = harness.layoutEffects[0].run(); await flush(); @@ -198,6 +200,8 @@ describe('the detail placement effect (#250/S17)', () => { devicePixelRatio: 1, }); panelHeight = 400; + panelElement.style.transform = 'scale(1)'; + harness.textScale = 1; resize = null; vi.stubGlobal( 'ResizeObserver', @@ -225,6 +229,58 @@ describe('the detail placement effect (#250/S17)', () => { vi.resetAllMocks(); }); + it.each(['top', 'bottom', 'left', 'right'] as Edge[])('keeps the rendered transform and native size coherent on narrow %s placements', async (edge) => { + harness.textScale = 2.25; + const sf = 1.25; + const area = { x: -1973 / sf, y: -237 / sf, w: 397 / sf, h: 611 / sf }; + const vertical = edge === 'left' || edge === 'right'; + const strip = stripRect(area, edge, 1, vertical ? 90 : 270, vertical ? 270 : 90); + const state = { + ...detailState, + area, + strip, + edge, + anchor: vertical ? strip.y + strip.h : strip.x + strip.w, + scaleFactor: sf, + maxHeight: panelHeightLimit(area, edge, strip), + }; + const cleanup = await runPlacement([applied()], undefined, state); + // Re-render the real component with its committed fit and inspect its JSX style. + harness.stateIndex = 0; + harness.refIndex = 0; + const tree = DetailPanel(); + if (!tree) throw new Error('Expected the detail panel to render'); + const style = tree.props.children.props.style; + const zoom = panelScaleFromTransform(style.transform); + const physical = native.setDetailBounds.mock.calls[0][0] as PhysicalBounds; + expect(zoom).toBeLessThan(1); + expect(style.width).toBe(state.width); + expect(style.visibility).toBe('visible'); + expect(physical.w).toBeGreaterThanOrEqual(style.width * zoom * harness.textScale * sf); + expect(physical.h).toBeGreaterThanOrEqual(panelHeight * zoom * harness.textScale * sf); + expect(physical.x).toBeGreaterThanOrEqual(-1973); + expect(physical.y).toBeGreaterThanOrEqual(-237); + expect(physical.x + physical.w).toBeLessThanOrEqual(-1576); + expect(physical.y + physical.h).toBeLessThanOrEqual(374); + const clip = native.setSurfaceClip.mock.calls[0][0]; + expect(clip.width).toBe(physical.w); + expect(clip.height).toBe(physical.h); + expect(clip.radii[0]).toBeCloseTo(Math.min(physical.w / 2, physical.h / 2, 14 * zoom * harness.textScale * sf), 10); + expect(native.showDetail).toHaveBeenCalledTimes(1); + expect(native.hide).not.toHaveBeenCalled(); + expect(failureNotices()).toEqual([]); + if (typeof cleanup === 'function') cleanup(); + }); + + it('still requests native placement for a degenerate area rather than declaring placement failure', async () => { + const state = { ...detailState, area: { x: 0, y: 0, w: 0, h: 0 }, maxHeight: 1 }; + const cleanup = await runPlacement([applied()], undefined, state); + expect(native.setDetailBounds).toHaveBeenCalledTimes(1); + expect(native.showDetail).toHaveBeenCalledTimes(1); + expect(failureNotices()).toEqual([]); + if (typeof cleanup === 'function') cleanup(); + }); + it('never places nor shows the panel when the native placement failed', async () => { const cleanup = await runPlacement([readFailed()]); // La colocación se vuelve a pedir: la inicial más el presupuesto acotado @@ -247,6 +303,7 @@ describe('the detail placement effect (#250/S17)', () => { it('shows the panel as before when the placement is confirmed', async () => { const cleanup = await runPlacement([applied()]); expect(native.setDetailBounds).toHaveBeenCalledTimes(1); + expect(native.setDetailBounds).toHaveBeenCalledWith(granted); expect(native.showDetail).toHaveBeenCalledTimes(1); expect(positioned()).toBe(true); // Sólo la geometría confirmada (read-back) queda cacheada. diff --git a/src/DetailPanel.test.tsx b/src/DetailPanel.test.tsx index 41c7b03..44daf9b 100644 --- a/src/DetailPanel.test.tsx +++ b/src/DetailPanel.test.tsx @@ -23,9 +23,8 @@ describe('DetailPanel (SSR)', () => { // clips and re-lays out with it; physical bounds keep the monitor scale alone. it('fits and clips with the text scale of its own window', () => { expect(source).toContain('const textScale = useTextScale();'); - expect(source).toContain('fitPanel(data, layoutHeightOf(panel, entry), base, textScale)'); + expect(source).toContain('fitDetailPanel(data, layoutHeightOf(panel, entry), base, textScale, data.scaleFactor)'); expect(source).toContain('measureSurfaceClip(panel, physical, next.zoom * textScale * data.scaleFactor)'); - expect(source).toContain('physicalPanelBounds(detailBounds(data, next), data.scaleFactor)'); expect(source).toContain('}, [data, enqueue, textScale]);'); }); }); diff --git a/src/DetailPanel.tsx b/src/DetailPanel.tsx index 70b179b..7c982a3 100644 --- a/src/DetailPanel.tsx +++ b/src/DetailPanel.tsx @@ -13,10 +13,8 @@ import { clipSurfaceSafely, measureSurfaceClip } from './lib/surface-clip'; import { createLatestQueue, basePanelZoom, - detailBounds, - fitPanel, + fitDetailPanel, panelScaleFromTransform, - physicalPanelBounds, sameFit, DETAIL_EVENTS, type DetailInteraction, @@ -149,11 +147,12 @@ export function DetailPanel() { const layout = (entry?: ResizeObserverEntry) => { const panel = panelRef.current; if (disposed || !panel) return; - const next = fitPanel(data, layoutHeightOf(panel, entry), base, textScale); + // Fit the DOM and native surface together, including physical rounding at + // the work-area edges; never clip the surface under a larger transform. + const { fit: next, physical } = fitDetailPanel(data, layoutHeightOf(panel, entry), base, textScale, data.scaleFactor); setFit((old) => (old && sameFit(old, next) ? old : next)); // Compare native (physical) bounds, not logical ones: a DPI change with identical // logical geometry must still resize the window. - const physical = physicalPanelBounds(detailBounds(data, next), data.scaleFactor); // #215: the cache only ever holds // read-back-confirmed geometry, so the ±1 px rounding tolerance of X11 applies // by the same rule as the widget; on a platform without read-back the cache diff --git a/src/lib/detail-panel.test.ts b/src/lib/detail-panel.test.ts index eb6a6e9..04581ce 100644 --- a/src/lib/detail-panel.test.ts +++ b/src/lib/detail-panel.test.ts @@ -4,6 +4,7 @@ import { createLatestQueue, detailBounds, fitPanel, + fitDetailPanel, isCurrentDetailInteraction, panelScaleFromTransform, panelWidthFor, @@ -226,22 +227,126 @@ describe('panel fit with text scale', () => { }); }); +describe('width-limited panel fit', () => { + it.each([ + // width, maxHeight, expected factor: no shrink, width only, height only, + // both overflowing with width/height dominance, and an exact tie. + [1000, 1000, 1], + [300, 1000, 0.5], + [1000, 225, 0.5], + [240, 225, 0.4], + [300, 180, 0.4], + [300, 225, 0.5], + ])('uniformly fits width %s and height %s with factor %s', (width, maxHeight, factor) => { + const p = placement({ area: { ...area, w: width }, width: 400, maxHeight }); + const fit = fitPanel(p, 400, 0.75, 1.5); + expect(fit.zoom).toBeCloseTo(0.75 * factor, 12); + // placement.width already includes basal zoom: never apply base twice. + expect(fit.width).toBeCloseTo(600 * factor, 12); + expect(fit.height).toBe(450 * factor); + expect(fit.scaled).toBe(factor < 1); + }); + + it.each(['top', 'bottom', 'left', 'right'] as Edge[])('uses real strip coordinates and gap 8 on %s', (edge) => { + const p = placement({ + area: { x: -500, y: -100, w: 500, h: 900 }, + edge, + strip: { x: -440, y: -60, w: 100, h: 80 }, + width: 600, + maxHeight: 900, + }); + const limit = edge === 'left' ? 332 : edge === 'right' ? 52 : 500; + const fit = fitPanel(p, 300, 1); + expect(fit.width).toBeCloseTo(limit, 12); + expect(fit.zoom).toBeCloseTo(limit / 600, 12); + expect(fit.height).toBe(Math.ceil(300 * (limit / 600))); + expect(fit.scaled).toBe(true); + }); + + it('ceils the scaled natural height, not maxHeight, when width alone is active', () => { + const fit = fitPanel(placement({ area: { ...area, w: 250 }, width: 400, maxHeight: 803.9216 }), 301, 1, 2); + expect(fit).toEqual({ zoom: 0.3125, width: 250, height: 189, scaled: true }); + }); + + it.each(['top', 'bottom', 'left', 'right'] as Edge[])('clamps unusable width to one on %s without changing placement', (edge) => { + const p = placement({ area: { x: 0, y: 0, w: 0, h: 900 }, edge, strip: { x: 0, y: 0, w: 80, h: 80 }, width: 300, maxHeight: 900 }); + const original = structuredClone(p); + const fit = fitPanel(p, 300, 1); + expect(fit.width).toBe(1); + expect(fit.height).toBe(1); + expect(fit.zoom).toBe(1 / 300); + expect(fit.scaled).toBe(true); + expect(p).toEqual(original); + }); +}); + +// Work areas originate as integer physical position/size divided by sf (Widget.geoOf). +// Full containment requires at least one logical pixel of usable space on each axis; +// impossible/degenerate areas still fit without declaring a native placement failure. +describe('detail-local physical fit', () => { + it.each(['top', 'bottom', 'left', 'right'] as Edge[])('contains text scale 2.25 on narrow fractional-DPI monitors on %s', (edge) => { + const vertical = edge === 'left' || edge === 'right'; + for (const sf of [1, 1.02, 1.25, 1.5, 1.75, 2]) { + for (const origin of [ + [0, 0], + [-1973, -237], + ]) { + const monitor = { x: origin[0] / sf, y: origin[1] / sf, w: 397 / sf, h: 611 / sf }; + for (const offset of [0, 0.5, 1]) { + const strip = stripRect(monitor, edge, offset, vertical ? 40 * 2.25 : 120 * 2.25, vertical ? 120 * 2.25 : 40 * 2.25); + const p: DetailPlacement = { + area: monitor, + edge, + strip, + anchor: vertical ? strip.y + strip.h : strip.x + strip.w, + width: 333, + maxHeight: panelHeightLimit(monitor, edge, strip), + }; + const original = structuredClone(p); + for (const layoutHeight of [120, 320, 5000]) { + const { fit, physical } = fitDetailPanel(p, layoutHeight, 0.75, 2.25, sf); + expect(physical.x).toBeGreaterThanOrEqual(origin[0]); + expect(physical.y).toBeGreaterThanOrEqual(origin[1]); + expect(physical.x + physical.w).toBeLessThanOrEqual(origin[0] + 397); + expect(physical.y + physical.h).toBeLessThanOrEqual(origin[1] + 611); + // Native size covers both dimensions painted by the same uniform DOM zoom. + expect(physical.w).toBeGreaterThanOrEqual((p.width / 0.75) * fit.zoom * 2.25 * sf); + expect(physical.h).toBeGreaterThanOrEqual(layoutHeight * fit.zoom * 2.25 * sf); + if (edge === 'left') expect(physical.x).toBeGreaterThanOrEqual(Math.ceil((strip.x + strip.w + 8) * sf)); + if (edge === 'right') expect(physical.x + physical.w).toBeLessThanOrEqual(Math.floor((strip.x - 8) * sf)); + if (edge === 'top') expect(physical.y).toBeGreaterThanOrEqual(Math.ceil((strip.y + strip.h + 8) * sf)); + if (edge === 'bottom') expect(physical.y + physical.h).toBeLessThanOrEqual(Math.floor((strip.y - 8) * sf)); + } + expect(p).toEqual(original); + } + } + } + }); + + it('preserves the previous fit and native geometry when no rounding adjustment is needed', () => { + const p = placement({ area: { x: 0, y: 0, w: 1920, h: 1080 }, strip: { x: 760, y: 0, w: 400, h: 80 }, anchor: 980 }); + const fit = fitPanel(p, 400, 1); + expect(fitDetailPanel(p, 400, 1, 1, 1)).toEqual({ fit, physical: physicalPanelBounds(detailBounds(p, fit), 1) }); + }); +}); + describe('independent detail window', () => { it.each(['top', 'bottom', 'left', 'right'] as Edge[])('fits the natural and scaled panel inside the monitor on %s without changing the strip', (edge) => { const vertical = edge === 'left' || edge === 'right'; + const monitor = { ...area, w: 397 }; for (const offset of [0, 0.5, 1]) { - const strip = stripRect(area, edge, offset, vertical ? 80 : 400, vertical ? 400 : 80); + const strip = stripRect(monitor, edge, offset, vertical ? 90 : 270, vertical ? 270 : 90); const original = { ...strip }; const anchor = vertical ? strip.y + 40 : strip.x + 40; for (const layoutHeight of [120, 320, 5000]) { - const p: DetailPlacement = { area, strip, edge, anchor, width: 300, maxHeight: panelHeightLimit(area, edge, strip) }; - const fit = fitPanel(p, layoutHeight, 1); + const p: DetailPlacement = { area: monitor, strip, edge, anchor, width: 300, maxHeight: panelHeightLimit(monitor, edge, strip) }; + const fit = fitPanel(p, layoutHeight, 1, 2.25); const rect = detailBounds(p, fit); - expect(contains(area, rect.x, rect.y)).toBe(true); - expect(rect.x + rect.w).toBeLessThanOrEqual(area.x + area.w + 1e-9); - expect(rect.y + rect.h).toBeLessThanOrEqual(area.y + area.h + 1e-9); - // Scaling never widens the panel beyond its baseline width. - expect(rect.w).toBeLessThanOrEqual(p.width + 1e-9); + expect(contains(monitor, rect.x, rect.y)).toBe(true); + expect(rect.x + rect.w).toBeLessThanOrEqual(monitor.x + monitor.w + 1e-9); + expect(rect.y + rect.h).toBeLessThanOrEqual(monitor.y + monitor.h + 1e-9); + // Scaling never widens the panel beyond its text-scaled baseline width. + expect(rect.w).toBeLessThanOrEqual(p.width * 2.25 + 1e-9); expect(fit.height).toBeLessThanOrEqual(p.maxHeight); expect(strip).toEqual(original); } diff --git a/src/lib/detail-panel.ts b/src/lib/detail-panel.ts index 2f70a5e..f119c28 100644 --- a/src/lib/detail-panel.ts +++ b/src/lib/detail-panel.ts @@ -75,7 +75,7 @@ export interface PanelFit { zoom: number; /** Rendered logical width after proportional scaling. */ width: number; - /** Rendered logical height; never above `maxHeight`. */ + /** Rendered logical height, ceiled except at an active height limit. */ height: number; /** Whether the content had to be scaled down to fit the work area. */ scaled: boolean; @@ -87,23 +87,93 @@ export interface PanelFit { * `layoutHeight` is the panel's unscaled CSS height (transforms do not reflow, so * this is stable regardless of the scale currently applied). The natural height, * in monitor units, is that value at basal zoom times `scale`, the text scale of - * the detail window (#228). When it exceeds `maxHeight` the whole panel is scaled - * down proportionally; otherwise it keeps its basal zoom and natural height. The - * zoom is a CSS transform, so it never carries the text scale; width and height - * are monitor units. Returning `maxHeight` verbatim when scaling avoids the ceil() - * phantom pixel that a 600.000061 rendered box would otherwise produce. + * the detail window (#228). Width already includes basal zoom. The smaller of + * the width and height factors uniformly shrinks the content, never enlarging it. + * Zoom is a CSS transform and never carries the text scale; sizes are monitor + * units. Return maxHeight verbatim only when height is active (including ties), + * avoiding a ceil() phantom pixel; otherwise ceil the scaled natural height. */ export function fitPanel(placement: DetailPlacement, layoutHeight: number, base: number, scale = 1): PanelFit { + return fitWithin(placement, layoutHeight, base, scale, panelWidthLimit(placement), placement.maxHeight); +} + +/** Space inward of the actual strip, not an assumed flush strip of the same size. */ +function panelWidthLimit({ area, strip, edge }: DetailPlacement): number { + const available = edge === 'left' ? area.x + area.w - strip.x - strip.w - 8 : edge === 'right' ? strip.x - 8 - area.x : area.w; + return Math.max(1, available); +} + +function fitWithin(placement: DetailPlacement, layoutHeight: number, base: number, scale: number, maxWidth: number, maxHeight: number): PanelFit { const natural = Math.max(1, layoutHeight) * base * scale; - const factor = natural > placement.maxHeight ? placement.maxHeight / natural : 1; + const heightLimit = Math.max(1, maxHeight); + const heightFactor = heightLimit / natural; + const factor = Math.min(1, heightFactor, Math.max(1, maxWidth) / (placement.width * scale)); return { zoom: base * factor, width: placement.width * scale * factor, - height: factor < 1 ? Math.max(1, placement.maxHeight) : Math.max(1, Math.ceil(natural)), + height: heightFactor === factor ? heightLimit : Math.max(1, Math.ceil(natural * factor)), scaled: factor < 1, }; } +/** + * Fit and place only the detail in the integer physical space inward of its strip. + * Widget.geoOf divides integer work-area position/size by sf; round those values + * back separately (do not ceil the logical area's size like a rendered surface). + * Inward strip boundaries round into the free space, retaining at least gap 8. + * + * Usually only the rounded origin needs clamping. If ceil(size × sf) will not fit, + * refit the content uniformly before converting again, never truncate the native + * surface under a larger DOM transform. A tiny physical inset absorbs float error + * at integer size boundaries. If logical ceil(height) still exceeds the physical + * budget, use its whole-logical-pixel height limit and refit by the same rules. + * Full containment requires usable width/height >= ceil(sf), since detailBounds + * pads each dimension to at least one logical pixel. Impossible areas retain that + * minimum and still use the normal native placement/retry path, not a new failure. + */ +export function fitDetailPanel( + placement: DetailPlacement, + layoutHeight: number, + base: number, + scale: number, + sf: number, +): { fit: PanelFit; physical: PhysicalBounds } { + const { area, strip, edge } = placement; + let left = Math.round(area.x * sf); + let top = Math.round(area.y * sf); + let right = left + Math.round(area.w * sf); + let bottom = top + Math.round(area.h * sf); + if (edge === 'left') left = Math.max(left, Math.ceil((strip.x + strip.w + 8) * sf)); + if (edge === 'right') right = Math.min(right, Math.floor((strip.x - 8) * sf)); + if (edge === 'top') top = Math.max(top, Math.ceil((strip.y + strip.h + 8) * sf)); + if (edge === 'bottom') bottom = Math.min(bottom, Math.floor((strip.y - 8) * sf)); + const width = Math.max(1, right - left); + const height = Math.max(1, bottom - top); + let fit = fitPanel(placement, layoutHeight, base, scale); + const physicalOf = (value: PanelFit) => { + const bounds = detailBounds(placement, value); + // Use the DOM's operation order too: algebraically equal products can differ + // by an ulp, and ceil must cover the painted size rather than clip that ulp. + bounds.w = Math.max(bounds.w, (placement.width / base) * value.zoom * scale); + bounds.h = Math.max(bounds.h, Math.max(1, layoutHeight) * value.zoom * scale); + return physicalPanelBounds(bounds, sf); + }; + let physical = physicalOf(fit); + if (physical.w > width || physical.h > height) { + const maxWidth = Math.min(panelWidthLimit(placement), (width - 1e-9) / sf); + const maxHeight = Math.min(placement.maxHeight, (height - 1e-9) / sf); + fit = fitWithin(placement, layoutHeight, base, scale, maxWidth, maxHeight); + physical = physicalOf(fit); + if (physical.h > height) { + fit = fitWithin(placement, layoutHeight, base, scale, maxWidth, Math.floor(maxHeight)); + physical = physicalOf(fit); + } + } + physical.x = Math.max(left, Math.min(physical.x, right - physical.w)); + physical.y = Math.max(top, Math.min(physical.y, bottom - physical.h)); + return { fit, physical }; +} + /** Logical bounds of the fitted panel next to its strip. */ export function detailBounds(placement: DetailPlacement, fit: PanelFit): Rect { return panelRect(placement.area, placement.edge, placement.strip, placement.anchor, Math.max(1, fit.width), Math.max(1, fit.height));