Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 51 additions & 26 deletions packages/media-editor/src/image-editor/core/camera.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import { mat2d, vec2 } from 'gl-matrix';
*/
import type { CropperState, NormalizedPoint, Size, Camera } from './types';
import { degreesToRadians } from './math/rotation';
import {
isSafeNumber,
isValidSize,
safeBoundedNumber,
sanitizeCropperState,
} from './math/sanitize';

// Pre-allocated scratch buffers for `screenToWorld`, which is called per
// pointermove. Module-level singletons — safe because usage is synchronous.
Expand All @@ -27,6 +33,19 @@ export function getRotatedBBox(
height: number,
rotation: number
): Size {
// Short-circuit on any unsafe input. `isSafeNumber` is stricter than
// `Number.isFinite`: very large but technically-finite rotations (e.g.
// `Number.MAX_VALUE`) overflow inside `degreesToRadians` and then
// `Math.cos`/`Math.sin` return `NaN`, so the magnitude bound matters.
if (
! isSafeNumber( width ) ||
! isSafeNumber( height ) ||
! isSafeNumber( rotation ) ||
width <= 0 ||
height <= 0
) {
return { width: 0, height: 0 };
}
const rad = degreesToRadians( rotation );
Comment thread
ramonjd marked this conversation as resolved.
Resolved
const cosR = Math.abs( Math.cos( rad ) );
const sinR = Math.abs( Math.sin( rad ) );
Expand Down Expand Up @@ -54,27 +73,31 @@ export function getImageFit(
imageSize: Size,
rotation: number
): { elementSize: Size; visualSize: Size } {
if (
containerSize.width === 0 ||
containerSize.height === 0 ||
imageSize.width === 0 ||
imageSize.height === 0
) {
if ( ! isValidSize( containerSize ) || ! isValidSize( imageSize ) ) {
return {
elementSize: { width: 0, height: 0 },
visualSize: { width: 0, height: 0 },
};
}
const safeRotation = safeBoundedNumber( rotation, 0 );
// Snap rotation to the nearest 90° multiple for layout sizing.
// This keeps the stencil a stable size through fine ±45° rotation
// (no inflation at 15°/30° etc.) while still swapping aspect at
// 90°/180°/270° so the snap rotate preserves the framed content.
const snapRotation = Math.round( rotation / 90 ) * 90;
const snapRotation = Math.round( safeRotation / 90 ) * 90;
const naturalBBox = getRotatedBBox(
imageSize.width,
imageSize.height,
snapRotation
);
// Defensive: getRotatedBBox returns zero dims for hostile inputs, which
// would make fitScale infinite. Mirror the zero-container short-circuit.
if ( naturalBBox.width === 0 || naturalBBox.height === 0 ) {
return {
elementSize: { width: 0, height: 0 },
visualSize: { width: 0, height: 0 },
};
}
const fitScale = Math.min(
containerSize.width / naturalBBox.width,
containerSize.height / naturalBBox.height
Expand Down Expand Up @@ -113,20 +136,17 @@ export function createCamera(
): Camera {
const m = mat2d.create();

if (
containerSize.width === 0 ||
containerSize.height === 0 ||
imageSize.width === 0 ||
imageSize.height === 0
) {
if ( ! isValidSize( containerSize ) || ! isValidSize( imageSize ) ) {
return m;
}

const safeState = sanitizeCropperState( state );

// Use the nearest 90° multiple for layout sizing so the stencil
// and visual bounds are stable through fine rotation. The actual
// `state.rotation` is still used for the rotation component of
// the matrix below.
const snapRotation = Math.round( state.rotation / 90 ) * 90;
const snapRotation = Math.round( safeState.rotation / 90 ) * 90;
Comment thread
ramonjd marked this conversation as resolved.
Resolved

// Rotated bounding box of the natural image (at snap angle).
const naturalBBox = getRotatedBBox(
Expand All @@ -135,6 +155,12 @@ export function createCamera(
snapRotation
);

// Defensive: getRotatedBBox returns zero dims for unsafe inputs. Mirror
// the zero-size short-circuit so `fitScale` doesn't become Infinity.
if ( naturalBBox.width === 0 || naturalBBox.height === 0 ) {
return m;
}

// "Contain" fit: scale rotated bounding box to fit within container.
const fitScale = Math.min(
containerSize.width / naturalBBox.width,
Expand Down Expand Up @@ -162,20 +188,23 @@ export function createCamera(
] );

// Pan offset in visual-space pixels.
mat2d.translate( m, m, [ state.pan.x * visualW, state.pan.y * visualH ] );
mat2d.translate( m, m, [
safeState.pan.x * visualW,
safeState.pan.y * visualH,
] );

// Flip (viewport-relative — composed outside rotation so horizontal
// flip always mirrors across the viewport's vertical axis).
mat2d.scale( m, m, [
state.flip.horizontal ? -1 : 1,
state.flip.vertical ? -1 : 1,
safeState.flip.horizontal ? -1 : 1,
safeState.flip.vertical ? -1 : 1,
] );

// Rotate.
mat2d.rotate( m, m, degreesToRadians( state.rotation ) );
mat2d.rotate( m, m, degreesToRadians( safeState.rotation ) );

// Zoom.
mat2d.scale( m, m, [ state.zoom, state.zoom ] );
mat2d.scale( m, m, [ safeState.zoom, safeState.zoom ] );

// Center origin (shift so 0.5,0.5 in rendered-pixel space = origin).
mat2d.translate( m, m, [ -renderedW / 2, -renderedH / 2 ] );
Expand Down Expand Up @@ -304,15 +333,11 @@ export function createExportCamera(
outputSize: Size
): Camera {
const m = mat2d.create();
const { rotation, flip, cropRect, zoom, pan } = state;
if (
imageSize.width === 0 ||
imageSize.height === 0 ||
outputSize.width === 0 ||
outputSize.height === 0
) {
if ( ! isValidSize( imageSize ) || ! isValidSize( outputSize ) ) {
return m;
}
const { rotation, flip, cropRect, zoom, pan } =
sanitizeCropperState( state );
// Reference frame for cropRect/pan is the snap-rotation bbox — that's
// what the stencil and CSS matrix use in the preview (see createCamera
// and getImageFit). Using the true rotation here would position the
Expand Down
104 changes: 62 additions & 42 deletions packages/media-editor/src/image-editor/core/containment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import { mat2d, vec2 } from 'gl-matrix';
*/
import type { CropperState, NormalizedRect, Size } from './types';
import { degreesToRadians } from './math/rotation';
import {
isValidSize,
safeBoundedNumber,
sanitizeCropperState,
sanitizeRect,
} from './math/sanitize';
import { createCamera, getRotatedBBox, getVisibleBounds } from './camera';

/** Floating-point epsilon for "close enough to equal" comparisons. */
Expand Down Expand Up @@ -109,25 +115,22 @@ export function getImageCropBounds(
elementSize: Size,
visualSize: Size
): { minX: number; minY: number; maxX: number; maxY: number } {
if (
elementSize.width === 0 ||
elementSize.height === 0 ||
visualSize.width === 0 ||
visualSize.height === 0
) {
if ( ! isValidSize( elementSize ) || ! isValidSize( visualSize ) ) {
return { minX: 0, minY: 0, maxX: 1, maxY: 1 };
}

const safeState = sanitizeCropperState( state );

// Build the same CSS matrix as use-transform-style: flip * rotate * zoom.
// Flip is outside rotation so it acts in viewport axes (see createCamera).
const tx = state.pan.x * visualSize.width;
const ty = state.pan.y * visualSize.height;
const rad = degreesToRadians( state.rotation );
const tx = safeState.pan.x * visualSize.width;
const ty = safeState.pan.y * visualSize.height;
const rad = degreesToRadians( safeState.rotation );
const cos = Math.cos( rad );
const sin = Math.sin( rad );
const sx = state.flip.horizontal ? -1 : 1;
const sy = state.flip.vertical ? -1 : 1;
const z = state.zoom;
const sx = safeState.flip.horizontal ? -1 : 1;
const sy = safeState.flip.vertical ? -1 : 1;
const z = safeState.zoom;
const ma = sx * cos * z;
const mb = sy * sin * z;
const mc = -sx * sin * z;
Expand Down Expand Up @@ -190,17 +193,25 @@ export function restrictCropRect(
rotation: number,
imageAspectRatio: number
): NormalizedRect {
const aspectRatio = Math.max( imageAspectRatio, Number.EPSILON );
// Guard against non-finite inputs. The reducer normalizes these, but
// programmatic callers or deserialized state could still send NaN/±Infinity
// through here, where it would silently propagate into the crop rect.
const safeRect = sanitizeRect( cropRect );
const zoomCandidate = safeBoundedNumber( zoom, 1 );
const safeZoom = zoomCandidate >= Number.EPSILON ? zoomCandidate : 1;
const safeRotation = safeBoundedNumber( rotation, 0 );
const safeAspect = safeBoundedNumber( imageAspectRatio, 1 );
const aspectRatio = Math.max( safeAspect, Number.EPSILON );
// Crop rect lives in the SNAP-rotation visual bbox (matching the stencil
// layout); projection into the image-local frame uses the TRUE rotation.
const snapRotation = Math.round( rotation / 90 ) * 90;
const snapRotation = Math.round( safeRotation / 90 ) * 90;
const { visualW, visualH } = getVisualDimensions(
snapRotation,
aspectRatio
);
const { absC, absS } = getVisualDimensions( rotation, aspectRatio );
const W = cropRect.width;
const H = cropRect.height;
const { absC, absS } = getVisualDimensions( safeRotation, aspectRatio );
const W = safeRect.width;
const H = safeRect.height;

// Crop full-extents in pixel-proportional space, projected to image-local frame.
const cropWPx = W * visualW;
Expand All @@ -209,8 +220,8 @@ export function restrictCropRect(
const spanBeta = cropWPx * absS + cropHPx * absC;

// Image full-extents at zoom z: (aspectRatio*z, z).
const limitAlpha = aspectRatio * zoom;
const limitBeta = zoom;
const limitAlpha = aspectRatio * safeZoom;
const limitBeta = safeZoom;

let t = 1;
if ( spanAlpha > 0 ) {
Expand All @@ -221,13 +232,14 @@ export function restrictCropRect(
}
if ( t >= 1 - EPSILON ) {
// Crop fits at the current zoom — no size change needed.
// Position is handled by restrictPanZoom, not here.
return cropRect;
// Return the sanitized rect (not the raw arg) so non-finite fields
// don't slip through this path. Position is handled by restrictPanZoom.
return safeRect;
}
const newW = W * t;
const newH = H * t;
const centerX = cropRect.x + W / 2;
const centerY = cropRect.y + H / 2;
const centerX = safeRect.x + W / 2;
const centerY = safeRect.y + H / 2;
let newX = centerX - newW / 2;
let newY = centerY - newH / 2;
newX = Math.max( 0, Math.min( newX, 1 - newW ) );
Expand Down Expand Up @@ -280,15 +292,23 @@ export function restrictPanZoom(
// 6. Convert the world-space correction to a pan-field correction by
// mapping it through the camera's linear part back to screen space,
// then dividing by the visual bounds.
const aspectRatio =
imageSize.width > 0 && imageSize.height > 0
? imageSize.width / imageSize.height
: 1;
const minZoom = getMinZoomForCover( state.rotation, aspectRatio, cropRect );
const zoom = Math.max( state.zoom, minZoom );
const safeState = sanitizeCropperState( state );
const safeCropRect = sanitizeRect( cropRect );
// Use `isValidSize` rather than a bare `> 0` check so Infinity dims
// don't drive `Infinity / Infinity = NaN` into `getMinZoomForCover`
// and leak as `zoom: NaN` through the no-correction early return.
const aspectRatio = isValidSize( imageSize )
? imageSize.width / imageSize.height
: 1;
const minZoom = getMinZoomForCover(
safeState.rotation,
aspectRatio,
safeCropRect
);
const zoom = Math.max( safeState.zoom, minZoom );

// Step 2: build camera with candidate pan and corrected zoom.
const candidateState = { ...state, zoom };
const candidateState = { ...safeState, zoom };
const camera = createCamera(
candidateState,
CANONICAL_CONTAINER,
Expand All @@ -300,7 +320,7 @@ export function restrictPanZoom(
// nearest 90° rotation (matching `getImageFit`), so it's stable
// through fine rotation. CSS zoom only affects the <img> element,
// not the stencil.
const snapRotation = Math.round( state.rotation / 90 ) * 90;
const snapRotation = Math.round( safeState.rotation / 90 ) * 90;
const baseCamera = createCamera(
{
...candidateState,
Expand All @@ -316,24 +336,24 @@ export function restrictPanZoom(
// Stencil corners in screen space (axis-aligned rect within visual bounds).
const stencilCorners: [ number, number ][] = [
[
visibleBounds.left + cropRect.x * visibleBounds.width,
visibleBounds.top + cropRect.y * visibleBounds.height,
visibleBounds.left + safeCropRect.x * visibleBounds.width,
visibleBounds.top + safeCropRect.y * visibleBounds.height,
],
[
visibleBounds.left +
( cropRect.x + cropRect.width ) * visibleBounds.width,
visibleBounds.top + cropRect.y * visibleBounds.height,
( safeCropRect.x + safeCropRect.width ) * visibleBounds.width,
visibleBounds.top + safeCropRect.y * visibleBounds.height,
],
[
visibleBounds.left +
( cropRect.x + cropRect.width ) * visibleBounds.width,
( safeCropRect.x + safeCropRect.width ) * visibleBounds.width,
visibleBounds.top +
( cropRect.y + cropRect.height ) * visibleBounds.height,
( safeCropRect.y + safeCropRect.height ) * visibleBounds.height,
],
[
visibleBounds.left + cropRect.x * visibleBounds.width,
visibleBounds.left + safeCropRect.x * visibleBounds.width,
visibleBounds.top +
( cropRect.y + cropRect.height ) * visibleBounds.height,
( safeCropRect.y + safeCropRect.height ) * visibleBounds.height,
],
];

Expand Down Expand Up @@ -371,7 +391,7 @@ export function restrictPanZoom(
minWy >= -EPSILON &&
maxWy <= 1 + EPSILON
) {
return { pan: state.pan, zoom };
return { pan: safeState.pan, zoom };
}

// Compute world-space correction needed.
Expand Down Expand Up @@ -410,10 +430,10 @@ export function restrictPanZoom(
// The correction is subtractive: a positive world shift (dw > 0) means
// the image needs to move opposite to pan direction, so pan decreases.
const newPanX =
state.pan.x -
safeState.pan.x -
( visibleBounds.width > 0 ? dsx / visibleBounds.width : 0 );
const newPanY =
state.pan.y -
safeState.pan.y -
( visibleBounds.height > 0 ? dsy / visibleBounds.height : 0 );

return {
Expand Down
Loading
Loading