import type { FocusDto } from '../services/types'; /** A named aspect ratio (width:height). The same two as the host cuts. */ export interface Ratio { name: 'wide' | 'tall'; numerator: number; denominator: number; } export const WIDE: Ratio = { name: 'wide', numerator: 3, denominator: 2 }; export const TALL: Ratio = { name: 'tall', numerator: 4, denominator: 5 }; export const MAX_ZOOM = 4; export const CENTRE: FocusDto = { x: 0.5, y: 0.5, zoom: 1 }; export interface CropRect { x: number; y: number; width: number; height: number; } /** Rounds .5 up, like the host (C# FocusMath.RoundHalfUp), so the preview is the same crop as the stored file. */ export const roundHalfUp = (value: number): number => Math.floor(value + 0.5); const clamp = (value: number, min: number, max: number): number => Math.min(Math.max(value, min), max); /** Clamps every value into its valid range; anything that is not a number becomes the default. */ export function normalizeFocus(focus: FocusDto): FocusDto { const finite = (v: number, fallback: number) => (Number.isNaN(v) ? fallback : v); return { x: clamp(finite(focus.x, 0.5), 0, 1), y: clamp(finite(focus.y, 0.5), 0, 1), zoom: clamp(finite(focus.zoom, 1), 1, MAX_ZOOM), }; } /** * The crop for a ratio around a focus point: the largest rectangle of the ratio that fits the image, shrunk by the * zoom, centred on the point and moved the smallest amount needed to stay inside. Twin of the host's C# `FocusMath`; * `focusMath.test.ts` and the C# tests share their vectors. */ export function cropFor(imageWidth: number, imageHeight: number, ratio: Ratio, focus: FocusDto): CropRect { if (imageWidth <= 0 || imageHeight <= 0) { throw new RangeError('The image must have a size.'); } const f = normalizeFocus(focus); // The largest crop of the ratio inside the image: as wide as the image, or as high as the image. const cw0 = imageWidth * ratio.denominator > imageHeight * ratio.numerator ? (imageHeight * ratio.numerator) / ratio.denominator : imageWidth; let cw = clamp(Math.floor(cw0 / f.zoom), 1, imageWidth); let ch = Math.max(1, roundHalfUp((cw * ratio.denominator) / ratio.numerator)); if (ch > imageHeight) { ch = imageHeight; cw = clamp(Math.floor((ch * ratio.numerator) / ratio.denominator), 1, imageWidth); } const x = clamp(roundHalfUp(f.x * imageWidth - cw / 2), 0, imageWidth - cw); const y = clamp(roundHalfUp(f.y * imageHeight - ch / 2), 0, imageHeight - ch); return { x, y, width: cw, height: ch }; }