import { describe, expect, it } from 'vitest'; import { CENTRE, TALL, WIDE, cropFor, normalizeFocus, roundHalfUp } from './focusMath'; // The same vectors as src/SlpModularCms.Core.Tests/Media/MediaPureFunctionTests.cs (FocusMathTests.KnownVectors). const vectors: [number, number, 'wide' | 'tall', number, number, number, [number, number, number, number]][] = [ [1600, 1067, 'wide', 0.5, 0.5, 1.0, [0, 0, 1600, 1067]], [1600, 1067, 'tall', 0.5, 0.5, 1.0, [374, 1, 853, 1066]], [1600, 1067, 'tall', 0.0, 0.5, 1.0, [0, 1, 853, 1066]], [1600, 1067, 'tall', 1.0, 0.5, 1.0, [747, 1, 853, 1066]], [1600, 1067, 'wide', 0.45, 0.35, 2.0, [320, 107, 800, 533]], [2560, 1702, 'tall', 0.55, 0.6, 1.0, [728, 1, 1361, 1701]], [1000, 2000, 'wide', 0.5, 0.5, 1.0, [0, 667, 1000, 667]], ]; describe('cropFor', () => { it.each(vectors)('%i x %i %s at (%d, %d) zoom %d', (w, h, ratio, x, y, zoom, [cx, cy, cw, ch]) => { expect(cropFor(w, h, ratio === 'tall' ? TALL : WIDE, { x, y, zoom })).toEqual({ x: cx, y: cy, width: cw, height: ch }); }); it('always stays inside the image and keeps the focus point inside the crop', () => { for (let i = 0; i < 2000; i++) { const w = 1 + Math.floor(Math.random() * 6000); const h = 1 + Math.floor(Math.random() * 6000); const focus = { x: Math.random(), y: Math.random(), zoom: 1 + Math.random() * 3 }; for (const ratio of [WIDE, TALL]) { const c = cropFor(w, h, ratio, focus); expect(c.x).toBeGreaterThanOrEqual(0); expect(c.y).toBeGreaterThanOrEqual(0); expect(c.x + c.width).toBeLessThanOrEqual(w); expect(c.y + c.height).toBeLessThanOrEqual(h); expect(focus.x * w).toBeGreaterThanOrEqual(c.x - 1); expect(focus.x * w).toBeLessThanOrEqual(c.x + c.width + 1); expect(focus.y * h).toBeGreaterThanOrEqual(c.y - 1); expect(focus.y * h).toBeLessThanOrEqual(c.y + c.height + 1); } } }); it('survives values that are out of range or not numbers', () => { const c = cropFor(1600, 1067, TALL, { x: Number.NaN, y: Infinity, zoom: -Infinity }); expect(c.x).toBeGreaterThanOrEqual(0); expect(c.x + c.width).toBeLessThanOrEqual(1600); }); it('rejects an image without a size', () => { expect(() => cropFor(0, 100, WIDE, CENTRE)).toThrow(RangeError); }); }); describe('normalizeFocus and roundHalfUp', () => { it('clamps and defaults', () => { expect(normalizeFocus({ x: -1, y: 2, zoom: 9 })).toEqual({ x: 0, y: 1, zoom: 4 }); expect(normalizeFocus({ x: Number.NaN, y: Number.NaN, zoom: Number.NaN })).toEqual({ x: 0.5, y: 0.5, zoom: 1 }); }); it('rounds .5 up like the host', () => { expect(roundHalfUp(373.5)).toBe(374); expect(roundHalfUp(0.5)).toBe(1); expect(roundHalfUp(2.4)).toBe(2); }); });