Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
42 changes: 15 additions & 27 deletions packages/media-editor/src/image-editor/core/containment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,25 +86,28 @@ function getMinZoomForCover(
}

/**
* Compute the crop handle bounds in normalized visual space by finding the
* Compute the crop handle bounds in normalized visual space — the
* axis-aligned bounding box (AABB) of the actual image footprint at the
* current pan/zoom/rotation, then intersecting with the container viewport.
* current pan/zoom/rotation.
*
* Returns the full image AABB without intersecting with the container
* viewport. The viewport pan mechanism in the Cropper component allows
* the canvas to scroll so handles can reach the image edge even when it
* lies outside the visible canvas area.
*
* Unlike a static centerline-based calculation, this accounts for the
* current pan position — if the user pans right, the left bound tightens
* because the image's left edge has moved right.
*
* @param state The current cropper state (crop, zoom, rotation, flip).
* @param elementSize The fitted (unrotated) image element dimensions in pixels.
* @param visualSize The visual (rotated) image bounding box in pixels.
* @param containerSize The container dimensions in pixels.
* @param state The current cropper state (crop, zoom, rotation, flip).
* @param elementSize The fitted (unrotated) image element dimensions in pixels.
* @param visualSize The visual (rotated) image bounding box in pixels.
* @return The min/max x and y that a crop rect edge can reach in normalized space.
*/
export function getCropBounds(
state: CropperState,
elementSize: Size,
visualSize: Size,
containerSize: Size
visualSize: Size
): { minX: number; minY: number; maxX: number; maxY: number } {
if (
elementSize.width === 0 ||
Expand Down Expand Up @@ -140,13 +143,6 @@ export function getCropBounds(
[ -hw, hh ],
];

// Transform corners through CSS matrix → screen offsets from element center.
// Screen position = element_center + transformed_offset.
// Element center is at (containerW/2, containerH/2) after CSS centering.
// But we want normalized coords, so work relative to the visual image origin.
const offsetX = ( containerSize.width - visualSize.width ) / 2;
const offsetY = ( containerSize.height - visualSize.height ) / 2;

let imgMinX = Infinity;
let imgMaxX = -Infinity;
let imgMinY = Infinity;
Expand All @@ -167,19 +163,11 @@ export function getCropBounds(
imgMaxY = Math.max( imgMaxY, ny );
}

// Container bounds in normalized space.
const containerMinX = -offsetX / visualSize.width;
const containerMaxX = ( containerSize.width - offsetX ) / visualSize.width;
const containerMinY = -offsetY / visualSize.height;
const containerMaxY =
( containerSize.height - offsetY ) / visualSize.height;

// Crop bounds = intersection of image AABB and container bounds.
return {
minX: Math.max( imgMinX, containerMinX ),
minY: Math.max( imgMinY, containerMinY ),
maxX: Math.min( imgMaxX, containerMaxX ),
maxY: Math.min( imgMaxY, containerMaxY ),
minX: imgMinX,
minY: imgMinY,
maxX: imgMaxX,
maxY: imgMaxY,
Comment thread
andrewserong marked this conversation as resolved.
Resolved
};
}

Expand Down
37 changes: 13 additions & 24 deletions packages/media-editor/src/image-editor/core/test/camera.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,17 +548,15 @@ describe( 'getSourceRegionPercent', () => {
} );

describe( 'getCropBounds', () => {
it( 'allows crop handle to reach container edge when 4:3 image is zoomed in 3:2 container', () => {
// MtBlanc1.jpg is 500×375 (4:3) in a 600×400 container (3:2).
// At zoom=1, the image is 533×400 — 33px padding on each side.
// At zoom=1.75, the image fills the container. The crop handle
// should be able to reach the container left edge (pixel 0),
// which is at normalized x = -0.0625.
it( 'returns the image AABB — handles can reach the image edge regardless of container size', () => {
// 500×375 (4:3) in a 600×400 container (3:2).
// At zoom=1.75 the image overflows the container. Bounds should reflect
// the image footprint, not the container edge, so one drag can reach the
// image edge (viewport pan reveals content outside the canvas boundary).
const nat: Size = { width: 500, height: 375 };
const container: Size = { width: 600, height: 400 };
const { elementSize, visualSize } = getImageFit( container, nat, 0 );

// Verify the image doesn't fill the container at zoom=1.
expect( visualSize.width ).toBeLessThan( container.width );

const state = makeState( {
Expand All @@ -571,23 +569,14 @@ describe( 'getCropBounds', () => {
rotation: 0,
} );

const bounds = getCropBounds(
state,
elementSize,
visualSize,
container
);
const bounds = getCropBounds( state, elementSize, visualSize );

// boundsMinX should be negative (crop can extend left of visual image origin).
expect( bounds.minX ).toBeLessThan( 0 );
// The pixel position of boundsMinX should be the container left edge (pixel 0).
const offsetX = ( container.width - visualSize.width ) / 2;
const pixelLeft = offsetX + bounds.minX * visualSize.width;
expect( pixelLeft ).toBeCloseTo( 0, 0 );

// boundsMaxX should be > 1 (crop can extend right of visual image).
expect( bounds.maxX ).toBeGreaterThan( 1 );
const pixelRight = offsetX + bounds.maxX * visualSize.width;
expect( pixelRight ).toBeCloseTo( container.width, 0 );
// At zoom=1.75 the image extends well beyond the container on all sides.
// Bounds should be the image AABB corners (≈ ±0.375), not the container
// edges (which would be ≈ ±0.0625).
expect( bounds.minX ).toBeLessThan( -0.3 );
expect( bounds.maxX ).toBeGreaterThan( 1.3 );
expect( bounds.minY ).toBeLessThan( -0.3 );
expect( bounds.maxY ).toBeGreaterThan( 1.3 );
} );
} );
16 changes: 16 additions & 0 deletions packages/media-editor/src/image-editor/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,22 @@ export type CropperAction =
/** Resets to DEFAULT_STATE, optionally merging a partial override. */
| { type: 'RESET'; payload?: Partial< CropperState > };

/**
* Viewport camera state — display-only, does not affect export or undo.
*
* Applied as a CSS transform on the canvas div so the user can scroll the
* view independently of the crop. zoom > 1 magnifies; pan shifts in CSS px.
Comment thread
andrewserong marked this conversation as resolved.
Resolved
*/
export interface ViewportState {
zoom: number;
pan: { x: number; y: number };
}

export type ViewportAction =
| { type: 'SET_VIEWPORT_ZOOM'; payload: number }
| { type: 'SET_VIEWPORT_PAN'; payload: { x: number; y: number } }
| { type: 'RESET_VIEWPORT' };

/**
* The contract for a pluggable stencil component.
* Stencils render the crop area overlay and handle resize interactions.
Expand Down
26 changes: 26 additions & 0 deletions packages/media-editor/src/image-editor/core/viewport-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Internal dependencies
*/
import type { ViewportState, ViewportAction } from './types';

export const DEFAULT_VIEWPORT_STATE: ViewportState = {
zoom: 1,
pan: { x: 0, y: 0 },
};

export function viewportReducer(
state: ViewportState,
action: ViewportAction
): ViewportState {
switch ( action.type ) {
case 'SET_VIEWPORT_ZOOM':
return {
...state,
zoom: Math.min( 4, Math.max( 0.1, action.payload ) ),
};
case 'SET_VIEWPORT_PAN':
return { ...state, pan: action.payload };
case 'RESET_VIEWPORT':
return DEFAULT_VIEWPORT_STATE;
}
Comment thread
andrewserong marked this conversation as resolved.
Resolved
}
81 changes: 71 additions & 10 deletions packages/media-editor/src/image-editor/react/components/cropper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { useAriaAnnouncer } from '../hooks/use-aria-announcer';
import { RectangleStencil } from './stencils/rectangle-stencil';
import { DimmingOverlay } from './overlays/dimming-overlay';
import { GridOverlay } from './overlays/grid-overlay';
import { ViewportProvider, useViewport } from './viewport-provider';
import './cropper.scss';

/** Threshold for comparing normalized crop rect values. */
Expand Down Expand Up @@ -169,6 +170,11 @@ function CropperInner(
ref: React.ForwardedRef< HTMLDivElement >
) {
const { state, setImage, setCropRect, settleCrop } = controller;
const {
viewport: viewportState,
setViewportPan,
resetViewport,
} = useViewport();
// Canvas measurement via ResizeObserver. The canvas is the inner
// positioning context for image/stencil/handles — inset from the root
// by the handle gutter, so crop math operates on the reduced box.
Expand Down Expand Up @@ -274,8 +280,8 @@ function CropperInner(
if ( ! state.image || elementSize.width === 0 ) {
return undefined;
}
return getCropBounds( state, elementSize, visualSize, canvasSize );
}, [ state, elementSize, visualSize, canvasSize ] );
return getCropBounds( state, elementSize, visualSize );
}, [ state, elementSize, visualSize ] );
const [ isResizing, setIsResizing ] = useState( false );
const isResizingRef = useRef( false );

Expand Down Expand Up @@ -342,14 +348,41 @@ function CropperInner(
[ src, setImage, onImageLoaded ]
);

/**
* Handle crop rect changes from the stencil (during drag).
*/
const handleCropChange = useCallback(
( rect: NormalizedRect ) => {
setCropRect( rect );
// During a resize drag, pan the viewport so the handle stays
// visible even when the crop extends beyond the canvas edge.
if ( isResizingRef.current && visualSize.width > 0 ) {
Comment thread
andrewserong marked this conversation as resolved.
Resolved
Comment thread
andrewserong marked this conversation as resolved.
Resolved
Comment thread
andrewserong marked this conversation as resolved.
Resolved
const offsetX = ( canvasSize.width - visualSize.width ) / 2;
const offsetY = ( canvasSize.height - visualSize.height ) / 2;
const rightOverflow = Math.max(
0,
offsetX +
( rect.x + rect.width ) * visualSize.width -
canvasSize.width
);
const leftOverflow = Math.max(
0,
-( offsetX + rect.x * visualSize.width )
);
const bottomOverflow = Math.max(
0,
offsetY +
( rect.y + rect.height ) * visualSize.height -
canvasSize.height
);
const topOverflow = Math.max(
0,
-( offsetY + rect.y * visualSize.height )
);
setViewportPan( {
x: -rightOverflow + leftOverflow,
y: -bottomOverflow + topOverflow,
} );
Comment on lines +387 to +390

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It also wanted an equality check here for smoother interaction/performance.

				const nextViewportPan = {
					x: -rightOverflow + leftOverflow,
					y: -bottomOverflow + topOverflow,
				};
				if ( ! arePointsEqual( viewportPanRef.current, nextViewportPan ) ) {
					viewportPanRef.current = nextViewportPan;
					setViewportPan( nextViewportPan );
				}

The handleCropChange check avoids dispatching at all on the drag hot path. That means no reducer call, no context provider update attempt, and no React scheduling for viewport state when the computed pan is unchanged.

The reducer check is a correctness/backstop guard. It catches any other caller of setViewportPan() and keeps the reducer referentially stable if someone dispatches the same pan later. It also makes the reducer more robust as the viewport API grows.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cheers. For this one, I think we've already fixed it with the feedback on updating the reducer to bail if values match, so the consumer (this callback) doesn't need to worry about performing the check and avoiding calling setViewportPan. Rather, the code here can happily call with an update and the reducer is smart enough to do a no-op if it doesn't need to change anything.

}
},
[ setCropRect ]
[ setCropRect, setViewportPan, canvasSize, visualSize ]
Comment thread
andrewserong marked this conversation as resolved.
Resolved
);

// Settling animation: brief linear transition after resize end.
Expand Down Expand Up @@ -380,23 +413,28 @@ function CropperInner(
const handleResizeStart = useCallback( () => {
isResizingRef.current = true;
setIsResizing( true );
resetViewport();
onGestureStart?.();
Comment thread
andrewserong marked this conversation as resolved.
Resolved
}, [ onGestureStart ] );
}, [ onGestureStart, resetViewport ] );

/**
* Handle resize end — settle the crop rect (re-center, fill height).
* Handle resize end — settle the crop rect (re-center, fill height)
* and reset the viewport pan back to neutral.
*/
const handleResizeEnd = useCallback( () => {
isResizingRef.current = false;
setIsResizing( false );
setSettling( true );
// Reset viewport pan first so it transitions back to zero in sync
// with the settle animation on the image.
resetViewport();
settleCrop();
onGestureEnd?.();
clearTimeout( settleTimerRef.current );
settleTimerRef.current = setTimeout( () => {
setSettling( false );
}, 200 );
}, [ settleCrop, onGestureEnd ] );
}, [ settleCrop, onGestureEnd, resetViewport ] );

const imageTransition =
settling || isZooming ? 'transform 150ms linear' : undefined;
Expand All @@ -423,6 +461,20 @@ function CropperInner(
};
}, [ canvasSize, elementSize, transformString, imageTransition ] );

// Viewport pan CSS transform for the canvas div. Applied during resize
// drags to keep handles visible when the crop extends past the canvas edge.
// Transitions back to zero during the settle animation.
const settleTransition = settling ? 'transform 200ms ease-out' : undefined;
let canvasStyle: React.CSSProperties | undefined;
if ( viewportState.pan.x !== 0 || viewportState.pan.y !== 0 ) {
canvasStyle = {
transform: `translate(${ viewportState.pan.x }px, ${ viewportState.pan.y }px)`,
Comment thread
andrewserong marked this conversation as resolved.
Resolved
transition: settleTransition,
Comment thread
andrewserong marked this conversation as resolved.
Resolved
};
} else if ( settling ) {
canvasStyle = { transition: settleTransition };
Comment thread
andrewserong marked this conversation as resolved.
Resolved
}

// Forward the root element to the consumer's ref.
const setContainerRef = useCallback(
( element: HTMLDivElement | null ) => {
Expand Down Expand Up @@ -467,6 +519,7 @@ function CropperInner(
showInteractiveGrid &&
'wp-media-editor-image-editor__canvas--show-grid'
) }
style={ canvasStyle }
tabIndex={ 0 }
role="group"
aria-label={ __( 'Image editor' ) }
Expand Down Expand Up @@ -539,6 +592,14 @@ function CropperInner(
);
}

export const Cropper = forwardRef< HTMLDivElement, CropperProps >(
const CropperInnerWithRef = forwardRef< HTMLDivElement, CropperProps >(
CropperInner
);

export const Cropper = forwardRef< HTMLDivElement, CropperProps >(
( props, ref ) => (
<ViewportProvider>
<CropperInnerWithRef { ...props } ref={ ref } />
</ViewportProvider>
)
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* WordPress dependencies
*/
import { createContext, useContext } from '@wordpress/element';

/**
* Internal dependencies
*/
import {
useViewportState,
type UseViewportStateReturn,
} from '../hooks/use-viewport-state';

type ViewportContextValue = UseViewportStateReturn;

const ViewportContext = createContext< ViewportContextValue | null >( null );

export function ViewportProvider( {
children,
}: {
children: React.ReactNode;
} ) {
const viewportState = useViewportState();
return (
<ViewportContext.Provider value={ viewportState }>
{ children }
</ViewportContext.Provider>
);
}

export function useViewport(): UseViewportStateReturn {
const context = useContext( ViewportContext );
if ( ! context ) {
throw new Error(
'useViewport must be used within a ViewportProvider.'
);
}
return context;
}
Loading
Loading