diff --git a/packages/media-editor/src/components/media-editor-crop-panel/crop-advanced-panel.tsx b/packages/media-editor/src/components/media-editor-crop-panel/crop-advanced-panel.tsx new file mode 100644 index 00000000000000..1d2595555ce56b --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/crop-advanced-panel.tsx @@ -0,0 +1,142 @@ +import { + __experimentalInputControlSuffixWrapper as InputControlSuffixWrapper, + PanelBody, +} from '@wordpress/components'; +import { __ } from '@wordpress/i18n'; +import { Stack } from '@wordpress/ui'; +import { useCropGestureHandlers } from '../../hooks/use-crop-gesture-handlers'; +import CropInput from './crop-input'; +import { useAdvancedCropControls } from './use-advanced-crop-controls'; + +interface CropAdvancedPanelProps { + aspectRatio?: number; + freeformCrop: boolean; + onPlacementControlInteraction?: () => void; + disabled?: boolean; +} + +const DEGREE_SUFFIX = °; + +export default function CropAdvancedPanel( { + aspectRatio, + freeformCrop, + onPlacementControlInteraction, + disabled = false, +}: CropAdvancedPanelProps ) { + const controls = useAdvancedCropControls( { + aspectRatio, + freeformCrop, + onPlacementControlInteraction, + } ); + const gestureHandlers = useCropGestureHandlers( { commitOnKeyUp: false } ); + + if ( ! controls.isReady ) { + return null; + } + + const { + rect, + ranges, + fineRotation, + onPreview, + onEdit, + onEditEnd, + onSessionStart, + onSessionEnd, + canMoveCropRect, + } = controls; + + return ( + + + + + onPreview( 'left', value ) } + onCommit={ ( value ) => onEdit( 'left', value ) } + onCommitEnd={ onEditEnd } + /> + onPreview( 'top', value ) } + onCommit={ ( value ) => onEdit( 'top', value ) } + onCommitEnd={ onEditEnd } + /> + + + onPreview( 'width', value ) } + onCommit={ ( value ) => onEdit( 'width', value ) } + onCommitEnd={ onEditEnd } + /> + onPreview( 'height', value ) } + onCommit={ ( value ) => onEdit( 'height', value ) } + onCommitEnd={ onEditEnd } + /> + + + + ); +} diff --git a/packages/media-editor/src/components/media-editor-crop-panel/crop-input-utils.ts b/packages/media-editor/src/components/media-editor-crop-panel/crop-input-utils.ts new file mode 100644 index 00000000000000..e0be70e798cc8a --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/crop-input-utils.ts @@ -0,0 +1,110 @@ +export interface CropInputRange { + minValue: number; + maxValue: number; + isEditable: boolean; +} + +export interface CropInputBounds { + value: number; + min: number; + max: number; +} + +export const INPUT_VALUE_EPSILON = 1e-6; + +function getStepPrecision( step: number ): number { + const stepString = step.toString(); + const decimalIndex = stepString.indexOf( '.' ); + return decimalIndex === -1 ? 0 : stepString.length - decimalIndex - 1; +} + +export function snapInputValueToStep( value: number, step: number ): number { + const precision = getStepPrecision( step ); + const snapped = Math.round( value / step ) * step; + return Number( snapped.toFixed( precision ) ); +} + +function roundIfNearStep( value: number, step: number ): number { + const snapped = snapInputValueToStep( value, step ); + return Math.abs( value - snapped ) < INPUT_VALUE_EPSILON ? snapped : value; +} + +function ceilInputValueToStep( value: number, step: number ): number { + return snapInputValueToStep( + Math.ceil( roundIfNearStep( value, step ) / step ) * step, + step + ); +} + +function floorInputValueToStep( value: number, step: number ): number { + return snapInputValueToStep( + Math.floor( roundIfNearStep( value, step ) / step ) * step, + step + ); +} + +export function makeRange( + minValue: number, + maxValue: number, + isEditable = true +): CropInputRange { + const max = Math.max( minValue, maxValue ); + return { + minValue, + maxValue: max, + isEditable: isEditable && max > minValue, + }; +} + +export function getInputBounds( + value: number, + range: CropInputRange, + commitStep: number +): CropInputBounds { + const snapped = snapInputValueToStep( value, commitStep ); + const min = ceilInputValueToStep( range.minValue, commitStep ); + const max = floorInputValueToStep( range.maxValue, commitStep ); + + if ( max < min ) { + return { + value: snapped, + min: snapped, + max: snapped, + }; + } + + // Keep the displayed value separate from the commit range. A transient + // cropper state may already be outside bounds after rotation, but arrow, + // wheel, and typed commits should still be judged against the real range. + return { + value: snapped, + min, + max, + }; +} + +export function getInputCommitValue( + nextValue: string, + bounds: CropInputBounds, + commitStep: number, + clampToBounds = false +): number | null { + if ( nextValue.trim() === '' ) { + return null; + } + + const parsed = Number( nextValue ); + if ( ! Number.isFinite( parsed ) ) { + return null; + } + + const snapped = snapInputValueToStep( parsed, commitStep ); + if ( snapped < bounds.min || snapped > bounds.max ) { + if ( ! clampToBounds ) { + return null; + } + return Math.min( bounds.max, Math.max( bounds.min, snapped ) ); + } + + return snapped; +} diff --git a/packages/media-editor/src/components/media-editor-crop-panel/crop-input.tsx b/packages/media-editor/src/components/media-editor-crop-panel/crop-input.tsx new file mode 100644 index 00000000000000..f35ad6dd24a079 --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/crop-input.tsx @@ -0,0 +1,77 @@ +import { + __experimentalInputControlSuffixWrapper as InputControlSuffixWrapper, + __experimentalNumberControl as NumberControl, +} from '@wordpress/components'; +import type { CropInputRange } from './crop-input-utils'; +import { useDeferredCommit } from './use-deferred-commit'; + +export interface CropInputProps { + label: string; + 'aria-label'?: string; + value: number; + range: CropInputRange; + disabled?: boolean; + /** Display step used by the underlying NumberControl (arrow-key increment). */ + step?: number; + /** Snap granularity applied when a value is committed. Defaults to `step`. */ + commitStep?: number; + suffix?: React.ReactNode; + onCommit: ( value: number ) => void; + onCommitEnd?: () => void; + commitOnChange?: boolean; + onPreview?: ( value: number | null ) => void; + onSessionStart?: () => void; + onSessionEnd?: () => void; +} + +const PX_SUFFIX = px; + +/** + * Numeric crop control with live preview and deferred finalization. + * + * All of the focus / draft / Enter / Escape state lives in + * `useDeferredCommit`; this component just renders. + * + * @param props Component props. + * @return Rendered number control. + */ +export default function CropInput( props: CropInputProps ) { + const { + label, + 'aria-label': ariaLabel, + value, + range, + disabled = false, + step = 1, + commitStep = step, + suffix = PX_SUFFIX, + onCommit, + onCommitEnd, + commitOnChange, + onPreview, + onSessionStart, + onSessionEnd, + } = props; + const handlers = useDeferredCommit( { + value, + range, + commitStep, + onCommit, + onCommitEnd, + commitOnChange, + onPreview, + onSessionStart, + onSessionEnd, + } ); + + return ( + + ); +} diff --git a/packages/media-editor/src/components/media-editor-crop-panel/index.tsx b/packages/media-editor/src/components/media-editor-crop-panel/index.tsx index e11da890b669fc..ffd759f18d6e8f 100644 --- a/packages/media-editor/src/components/media-editor-crop-panel/index.tsx +++ b/packages/media-editor/src/components/media-editor-crop-panel/index.tsx @@ -1,9 +1,11 @@ import { SelectControl as WCSelectControl } from '@wordpress/components'; import { Stack, VisuallyHidden } from '@wordpress/ui'; import { __ } from '@wordpress/i18n'; +import { resolveAspectRatio, useMediaEditor } from '../../state'; import { CROP_CONTROL_ATTR } from '../../hooks/use-crop-gesture-handlers'; import MediaEditorImageControls from '../media-editor-image-controls'; import type { AspectRatioPreset } from '../../image-editor/core/constants'; +import CropAdvancedPanel from './crop-advanced-panel'; export interface MediaEditorCropPanelProps { /** @@ -14,6 +16,8 @@ export interface MediaEditorCropPanelProps { aspectRatioValue: string; /** Setter for the aspect-ratio preset value. */ onAspectRatioChange: ( value: string ) => void; + /** Signal that a placement-oriented control is being adjusted. */ + onPlacementControlInteraction?: () => void; /** Aspect-ratio presets to display in the selector. */ aspectRatioOptions: AspectRatioPreset[]; /** Disable every control in the panel while the edit is saving. */ @@ -27,15 +31,23 @@ export interface MediaEditorCropPanelProps { * @param props * @param props.aspectRatioValue * @param props.onAspectRatioChange + * @param props.onPlacementControlInteraction * @param props.aspectRatioOptions * @param props.disabled */ export default function MediaEditorCropPanel( { aspectRatioValue, onAspectRatioChange, + onPlacementControlInteraction, aspectRatioOptions, disabled = false, }: MediaEditorCropPanelProps ) { + const { state } = useMediaEditor().cropper; + const resolvedAspectRatio = resolveAspectRatio( + aspectRatioValue, + state.image + ); + return ( // Tag the whole panel as a crop-control region so the modal's // Cmd+Z handler doesn't mistake the SelectControl input for a @@ -59,6 +71,12 @@ export default function MediaEditorCropPanel( { value: preset.value.toString(), } ) ) } /> + ); } diff --git a/packages/media-editor/src/components/media-editor-crop-panel/test/crop-advanced-panel.jsdom.test.tsx b/packages/media-editor/src/components/media-editor-crop-panel/test/crop-advanced-panel.jsdom.test.tsx new file mode 100644 index 00000000000000..a5a058c15e768c --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/test/crop-advanced-panel.jsdom.test.tsx @@ -0,0 +1,342 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import CropAdvancedPanel from '../crop-advanced-panel'; + +const mockSetCropRect = vi.fn(); +const mockSetRotation = vi.fn(); +const mockSettleCrop = vi.fn(); +const mockBeginGesture = vi.fn(); +const mockEndGesture = vi.fn(); +const mockSetPreviewCropRect = vi.fn(); +const mockNormalizedRect = { x: 0, y: 0, width: 1, height: 1 }; +const mockDefaultCropperState = { + image: { + src: 'test.jpg', + naturalWidth: 1000, + naturalHeight: 500, + }, + rotation: 0, + flip: { + horizontal: false, + vertical: false, + }, + pan: { x: 0, y: 0 }, + zoom: 1, + cropRect: { x: 0.1, y: 0.1, width: 0.4, height: 0.4 }, +}; +const mockDefaultCropGeometry = { + isReady: true, + rect: { + left: 100, + top: 50, + width: 400, + height: 200, + right: 500, + bottom: 250, + }, + imageBounds: { + minLeft: 0, + minTop: 0, + maxRight: 1000, + maxBottom: 500, + minWidth: 50, + minHeight: 25, + maxWidth: 1000, + maxHeight: 500, + }, + sourceRegion: null, +}; +type MockCropGeometry = typeof mockDefaultCropGeometry; +type MockCropperState = typeof mockDefaultCropperState; +type MockCropGeometryOverrides = Partial< + Omit< MockCropGeometry, 'rect' | 'imageBounds' > +> & { + rect?: Partial< MockCropGeometry[ 'rect' ] >; + imageBounds?: Partial< MockCropGeometry[ 'imageBounds' ] >; +}; +type MockCropperStateOverrides = Partial< + Omit< MockCropperState, 'image' | 'flip' > +> & { + image?: Partial< MockCropperState[ 'image' ] >; + flip?: Partial< MockCropperState[ 'flip' ] >; +}; +let mockCropGeometry = mockDefaultCropGeometry; +let mockCropperState = mockDefaultCropperState; +const mockApplyCropEdit = vi.fn( ( rect, field, value ) => { + const next = { ...rect, [ field ]: value }; + return { + ...next, + right: next.left + next.width, + bottom: next.top + next.height, + }; +} ); +const mockCropPixelRectToNormalizedRect = vi.fn( () => mockNormalizedRect ); +const mockGetCropPixelRect = vi.fn( ( _state, imageSize ) => ( { + left: 0, + top: 0, + width: imageSize.width, + height: imageSize.height, + right: imageSize.width, + bottom: imageSize.height, +} ) ); + +function setMockCropGeometry( overrides: MockCropGeometryOverrides = {} ) { + mockCropGeometry = { + ...mockDefaultCropGeometry, + ...overrides, + rect: { + ...mockDefaultCropGeometry.rect, + ...overrides.rect, + }, + imageBounds: { + ...mockDefaultCropGeometry.imageBounds, + ...overrides.imageBounds, + }, + }; +} + +function setMockCropperState( overrides: MockCropperStateOverrides = {} ) { + mockCropperState = { + ...mockDefaultCropperState, + ...overrides, + image: { + ...mockDefaultCropperState.image, + ...overrides.image, + }, + flip: { + ...mockDefaultCropperState.flip, + ...overrides.flip, + }, + }; +} + +vi.mock( + import( '../../../state' ), + () => + ( { + useMediaEditor: () => ( { + cropper: { + state: mockCropperState, + setCropRect: mockSetCropRect, + setRotation: mockSetRotation, + settleCrop: mockSettleCrop, + }, + beginGesture: mockBeginGesture, + endGesture: mockEndGesture, + } ), + } ) as unknown as typeof import( '../../../state' ) +); + +vi.mock( + import( '../../../image-editor/core/crop-geometry' ), + () => + ( { + applyCropEdit: ( + ...args: Parameters< typeof mockApplyCropEdit > + ) => mockApplyCropEdit( ...args ), + cropPixelRectToNormalizedRect: ( + ...args: Parameters< typeof mockCropPixelRectToNormalizedRect > + ) => mockCropPixelRectToNormalizedRect( ...args ), + getCropPixelRect: ( + ...args: Parameters< typeof mockGetCropPixelRect > + ) => mockGetCropPixelRect( ...args ), + } ) as unknown as typeof import( '../../../image-editor/core/crop-geometry' ) +); + +vi.mock( + import( '../../../image-editor/react/hooks/use-crop-geometry' ), + () => + ( { + useCropGeometry: () => mockCropGeometry, + } ) as unknown as typeof import( '../../../image-editor/react/hooks/use-crop-geometry' ) +); + +vi.mock( + import( '../../../image-editor/react/components/cropper-provider' ), + () => + ( { + useSetCropperPreviewRect: () => mockSetPreviewCropRect, + } ) as unknown as typeof import( '../../../image-editor/react/components/cropper-provider' ) +); + +describe( 'CropAdvancedPanel', () => { + beforeEach( () => { + vi.clearAllMocks(); + vi.useRealTimers(); + setMockCropGeometry(); + setMockCropperState(); + } ); + + it( 'settles after applying a numeric crop edit', () => { + render( ); + + fireEvent.click( screen.getByRole( 'button', { name: 'Advanced' } ) ); + const widthInput = screen.getByLabelText( 'Width' ); + fireEvent.focus( widthInput ); + fireEvent.change( widthInput, { target: { value: '600' } } ); + fireEvent.blur( widthInput ); + + expect( mockApplyCropEdit ).toHaveBeenCalledWith( + expect.objectContaining( { + left: 100, + top: 50, + width: 400, + height: 200, + } ), + 'width', + 600, + expect.objectContaining( { + bounds: expect.objectContaining( { + maxRight: 1000, + maxBottom: 500, + } ), + } ) + ); + expect( mockSetCropRect ).toHaveBeenCalledWith( mockNormalizedRect ); + expect( mockSettleCrop ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'does not apply out-of-range numeric crop drafts before completion', () => { + render( ); + + fireEvent.click( screen.getByRole( 'button', { name: 'Advanced' } ) ); + const widthInput = screen.getByLabelText( 'Width' ); + fireEvent.focus( widthInput ); + fireEvent.change( widthInput, { target: { value: '1' } } ); + + expect( mockSetCropRect ).not.toHaveBeenCalled(); + expect( mockSettleCrop ).not.toHaveBeenCalled(); + } ); + + it( 'clamps completed crop edits to the nearest input bound', () => { + render( ); + + fireEvent.click( screen.getByRole( 'button', { name: 'Advanced' } ) ); + const widthInput = screen.getByLabelText( 'Width' ); + fireEvent.focus( widthInput ); + fireEvent.change( widthInput, { target: { value: '9999' } } ); + fireEvent.blur( widthInput ); + + expect( mockApplyCropEdit ).toHaveBeenCalledWith( + expect.any( Object ), + 'width', + 900, + expect.objectContaining( { + bounds: expect.objectContaining( { maxWidth: 1000 } ), + } ) + ); + expect( mockSetCropRect ).toHaveBeenCalledWith( mockNormalizedRect ); + expect( mockSettleCrop ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'does not settle while the user is still typing', () => { + render( ); + + fireEvent.click( screen.getByRole( 'button', { name: 'Advanced' } ) ); + const widthInput = screen.getByLabelText( 'Width' ); + fireEvent.focus( widthInput ); + fireEvent.change( widthInput, { target: { value: '600' } } ); + fireEvent.change( widthInput, { target: { value: '650' } } ); + + // Draft edits update only the preview overlay until completion. + expect( mockSetPreviewCropRect ).toHaveBeenCalled(); + expect( mockSetCropRect ).not.toHaveBeenCalled(); + expect( mockSettleCrop ).not.toHaveBeenCalled(); + + fireEvent.blur( widthInput ); + + expect( mockSettleCrop ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'leaves out-of-range crop drafts editable until blur', () => { + render( ); + + fireEvent.click( screen.getByRole( 'button', { name: 'Advanced' } ) ); + const widthInput = screen.getByLabelText( 'Width' ); + fireEvent.focus( widthInput ); + fireEvent.change( widthInput, { target: { value: '9999' } } ); + + // Draft stays exactly as typed; nothing fires until the user signals + // completion explicitly. + expect( widthInput ).toHaveValue( 9999 ); + expect( mockSetCropRect ).not.toHaveBeenCalled(); + expect( mockSettleCrop ).not.toHaveBeenCalled(); + + fireEvent.blur( widthInput ); + + expect( mockApplyCropEdit ).toHaveBeenCalledWith( + expect.any( Object ), + 'width', + 900, + expect.objectContaining( { + bounds: expect.objectContaining( { maxWidth: 1000 } ), + } ) + ); + expect( mockSettleCrop ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'previews image-bound manual position edits without moving the cropper', () => { + setMockCropGeometry( { + rect: { + top: -85, + bottom: 115, + }, + imageBounds: { + minTop: -100, + maxBottom: 500, + maxHeight: 600, + }, + } ); + render( ); + + fireEvent.click( screen.getByRole( 'button', { name: 'Advanced' } ) ); + const topInput = screen.getByLabelText( 'Crop vertical position' ); + fireEvent.focus( topInput ); + fireEvent.change( topInput, { target: { value: '-84' } } ); + + expect( topInput ).toHaveValue( -84 ); + expect( mockSetPreviewCropRect ).toHaveBeenCalled(); + expect( mockSetCropRect ).not.toHaveBeenCalled(); + + fireEvent.blur( topInput ); + + expect( mockApplyCropEdit ).toHaveBeenCalledWith( + expect.any( Object ), + 'top', + -84, + expect.objectContaining( { + bounds: expect.objectContaining( { minTop: -100 } ), + } ) + ); + expect( mockSetCropRect ).toHaveBeenCalledWith( mockNormalizedRect ); + expect( mockSettleCrop ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'wires the fine rotation field to the controls hook', () => { + render( ); + + fireEvent.click( screen.getByRole( 'button', { name: 'Advanced' } ) ); + const rotationInput = screen.getByLabelText( 'Fine rotation angle' ); + fireEvent.focus( rotationInput ); + fireEvent.change( rotationInput, { target: { value: '30' } } ); + fireEvent.blur( rotationInput ); + + expect( mockSetRotation ).toHaveBeenCalledWith( 30 ); + } ); + + it( 'disables every field while the edit is saving', () => { + render( ); + + fireEvent.click( screen.getByRole( 'button', { name: 'Advanced' } ) ); + + expect( screen.getByLabelText( 'Fine rotation angle' ) ).toBeDisabled(); + expect( + screen.getByLabelText( 'Crop horizontal position' ) + ).toBeDisabled(); + expect( + screen.getByLabelText( 'Crop vertical position' ) + ).toBeDisabled(); + expect( screen.getByLabelText( 'Width' ) ).toBeDisabled(); + expect( screen.getByLabelText( 'Height' ) ).toBeDisabled(); + } ); +} ); diff --git a/packages/media-editor/src/components/media-editor-crop-panel/test/crop-input-utils.ts b/packages/media-editor/src/components/media-editor-crop-panel/test/crop-input-utils.ts new file mode 100644 index 00000000000000..d49426dd8e8164 --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/test/crop-input-utils.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest'; +import { + getInputBounds, + getInputCommitValue, + makeRange, + snapInputValueToStep, +} from '../crop-input-utils'; + +describe( 'makeRange', () => { + it( 'flags a single-point range as not editable', () => { + const range = makeRange( 100, 100 ); + + expect( range.minValue ).toBe( 100 ); + expect( range.maxValue ).toBe( 100 ); + expect( range.isEditable ).toBe( false ); + } ); + + it( 'flags a real range as editable by default', () => { + const range = makeRange( 0, 500 ); + + expect( range.isEditable ).toBe( true ); + } ); + + it( 'respects an explicit `isEditable=false`', () => { + const range = makeRange( 0, 500, false ); + + expect( range.isEditable ).toBe( false ); + } ); + + it( 'guards against an inverted range', () => { + const range = makeRange( 500, 100 ); + + expect( range.minValue ).toBe( 500 ); + expect( range.maxValue ).toBe( 500 ); + expect( range.isEditable ).toBe( false ); + } ); +} ); + +describe( 'snapInputValueToStep', () => { + it( 'snaps to integer step', () => { + expect( snapInputValueToStep( 12.3, 1 ) ).toBe( 12 ); + expect( snapInputValueToStep( 12.7, 1 ) ).toBe( 13 ); + } ); + + it( 'snaps to half-degree step and preserves precision', () => { + expect( snapInputValueToStep( 12.3, 0.5 ) ).toBe( 12.5 ); + expect( snapInputValueToStep( 12.74, 0.5 ) ).toBe( 12.5 ); + expect( snapInputValueToStep( 12.76, 0.5 ) ).toBe( 13 ); + } ); +} ); + +describe( 'getInputBounds', () => { + it( 'tolerates sub-precision drift in min bound', () => { + const range = makeRange( 0.000000001, 500 ); + const bounds = getInputBounds( 100, range, 1 ); + + expect( bounds.value ).toBe( 100 ); + expect( bounds.min ).toBe( 0 ); + expect( bounds.max ).toBe( 500 ); + } ); + + it( 'tolerates sub-precision drift in max bound', () => { + const range = makeRange( 0, 2559.999999999 ); + const bounds = getInputBounds( 400, range, 1 ); + + // Drift below ~1e-6 rounds up to the nearest integer so users can + // commit the expected integer pixel value. + expect( bounds.max ).toBe( 2560 ); + } ); + + it( 'keeps bounds strict when current value is outside the snapped min', () => { + const range = makeRange( 5, 100 ); + const bounds = getInputBounds( 3, range, 1 ); + + // The input may display an out-of-range state, but commits still use + // the real range so arrow/wheel edits cannot keep pushing outward. + expect( bounds.value ).toBe( 3 ); + expect( bounds.min ).toBe( 5 ); + expect( bounds.max ).toBe( 100 ); + } ); +} ); + +describe( 'getInputCommitValue', () => { + const bounds = { value: 100, min: 0, max: 500 }; + + it( 'returns null for an empty draft', () => { + expect( getInputCommitValue( '', bounds, 1 ) ).toBeNull(); + expect( getInputCommitValue( ' ', bounds, 1 ) ).toBeNull(); + } ); + + it( 'returns null for non-finite drafts', () => { + expect( getInputCommitValue( 'abc', bounds, 1 ) ).toBeNull(); + } ); + + it( 'snaps in-range drafts to the commit step', () => { + expect( getInputCommitValue( '12.4', bounds, 1 ) ).toBe( 12 ); + expect( getInputCommitValue( '12.6', bounds, 1 ) ).toBe( 13 ); + } ); + + it( 'rejects out-of-range drafts when not clamping', () => { + expect( getInputCommitValue( '9999', bounds, 1 ) ).toBeNull(); + expect( getInputCommitValue( '-10', bounds, 1 ) ).toBeNull(); + } ); + + it( 'clamps out-of-range drafts when requested', () => { + expect( getInputCommitValue( '9999', bounds, 1, true ) ).toBe( 500 ); + expect( getInputCommitValue( '-10', bounds, 1, true ) ).toBe( 0 ); + } ); +} ); diff --git a/packages/media-editor/src/components/media-editor-crop-panel/test/index.jsdom.test.tsx b/packages/media-editor/src/components/media-editor-crop-panel/test/index.jsdom.test.tsx index 18664d127b484f..44f44018e9e39f 100644 --- a/packages/media-editor/src/components/media-editor-crop-panel/test/index.jsdom.test.tsx +++ b/packages/media-editor/src/components/media-editor-crop-panel/test/index.jsdom.test.tsx @@ -6,6 +6,10 @@ import { MediaEditorStateProvider } from '../../../state'; globalThis.wpVitest.mockMatchMedia(); +vi.mock( import( '../crop-advanced-panel' ), () => ( { + default: () =>
, +} ) ); + function setupCropPanel( overrides: Partial< MediaEditorCropPanelProps > = {} ) { diff --git a/packages/media-editor/src/components/media-editor-crop-panel/test/use-advanced-crop-controls.jsdom.test.tsx b/packages/media-editor/src/components/media-editor-crop-panel/test/use-advanced-crop-controls.jsdom.test.tsx new file mode 100644 index 00000000000000..3f1139159e134b --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/test/use-advanced-crop-controls.jsdom.test.tsx @@ -0,0 +1,247 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, renderHook } from '@testing-library/react'; +import { useAdvancedCropControls } from '../use-advanced-crop-controls'; + +const mockSetCropRect = vi.fn(); +const mockSetRotation = vi.fn(); +const mockSettleCrop = vi.fn(); +const mockBeginGesture = vi.fn(); +const mockEndGesture = vi.fn(); +const mockSetPreviewCropRect = vi.fn(); + +const defaultState = { + image: { src: 'test.jpg', naturalWidth: 1000, naturalHeight: 500 }, + rotation: 0, + flip: { horizontal: false, vertical: false }, + pan: { x: 0, y: 0 }, + zoom: 1, + cropRect: { x: 0.1, y: 0.1, width: 0.4, height: 0.4 }, +}; + +const defaultGeometry = { + isReady: true as const, + rect: { + left: 100, + top: 50, + width: 400, + height: 200, + right: 500, + bottom: 250, + }, + imageBounds: { + minLeft: 0, + minTop: 0, + maxRight: 1000, + maxBottom: 500, + minWidth: 50, + minHeight: 25, + maxWidth: 1000, + maxHeight: 500, + }, + sourceRegion: null, +}; + +let mockCropperState = defaultState; +let mockCropGeometry: typeof defaultGeometry | { isReady: false } = + defaultGeometry; + +vi.mock( + import( '../../../state' ), + () => + ( { + useMediaEditor: () => ( { + cropper: { + state: mockCropperState, + setCropRect: mockSetCropRect, + setRotation: mockSetRotation, + settleCrop: mockSettleCrop, + }, + beginGesture: mockBeginGesture, + endGesture: mockEndGesture, + } ), + } ) as unknown as typeof import( '../../../state' ) +); + +vi.mock( + import( '../../../image-editor/react/hooks/use-crop-geometry' ), + () => + ( { + useCropGeometry: () => mockCropGeometry, + } ) as unknown as typeof import( '../../../image-editor/react/hooks/use-crop-geometry' ) +); + +vi.mock( + import( '../../../image-editor/react/components/cropper-provider' ), + () => + ( { + useSetCropperPreviewRect: () => mockSetPreviewCropRect, + } ) as unknown as typeof import( '../../../image-editor/react/components/cropper-provider' ) +); + +describe( 'useAdvancedCropControls', () => { + beforeEach( () => { + vi.clearAllMocks(); + mockCropperState = defaultState; + mockCropGeometry = defaultGeometry; + } ); + + it( 'returns isReady=false when geometry is not ready', () => { + mockCropGeometry = { isReady: false }; + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true } ) + ); + + expect( result.current.isReady ).toBe( false ); + } ); + + it( 'computes left/top/width/height ranges from the image bounds', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true } ) + ); + + if ( ! result.current.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + expect( result.current.ranges.left.minValue ).toBe( 0 ); + expect( result.current.ranges.left.maxValue ).toBe( 600 ); + expect( result.current.ranges.width.minValue ).toBe( 50 ); + expect( result.current.ranges.width.maxValue ).toBe( 900 ); + } ); + + it( 'allows manual position ranges to reach the image bounds', () => { + mockCropGeometry = { + ...defaultGeometry, + imageBounds: { + ...defaultGeometry.imageBounds, + minTop: -100, + maxBottom: 600, + maxHeight: 700, + }, + }; + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true } ) + ); + + if ( ! result.current.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + expect( result.current.ranges.top.minValue ).toBe( -100 ); + expect( result.current.ranges.top.maxValue ).toBe( 400 ); + } ); + + it( 'flags width/height as not editable when freeform is off', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: false } ) + ); + + if ( ! result.current.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + expect( result.current.ranges.width.isEditable ).toBe( false ); + expect( result.current.ranges.height.isEditable ).toBe( false ); + } ); + + it( 'constrains width/height ranges to the aspect-ratio envelope', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true, aspectRatio: 2 } ) + ); + + if ( ! result.current.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + // Aspect ratio 2:1 caps width by 2 * maxHeight and height by maxWidth / 2. + expect( result.current.ranges.width.maxValue ).toBe( 900 ); + expect( result.current.ranges.height.maxValue ).toBe( 450 ); + } ); + + it( 'commits a width edit and couples height under an aspect ratio', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true, aspectRatio: 2 } ) + ); + + const controls = result.current; + if ( ! controls.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + act( () => controls.onEdit( 'width', 600 ) ); + + expect( mockSetCropRect ).toHaveBeenCalledTimes( 1 ); + expect( mockSettleCrop ).not.toHaveBeenCalled(); + } ); + + it( 'previews a width edit without committing cropper state', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true, aspectRatio: 2 } ) + ); + + const controls = result.current; + if ( ! controls.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + act( () => controls.onPreview( 'width', 600 ) ); + + expect( mockSetPreviewCropRect ).toHaveBeenCalledTimes( 1 ); + expect( mockSetCropRect ).not.toHaveBeenCalled(); + expect( mockSettleCrop ).not.toHaveBeenCalled(); + } ); + + it( 'settles after a discrete edit ends', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true } ) + ); + + const controls = result.current; + if ( ! controls.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + act( () => controls.onEditEnd() ); + + expect( mockSettleCrop ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'applies fine rotation', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true } ) + ); + + const controls = result.current; + if ( ! controls.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + act( () => controls.fineRotation.onEdit( 12.5 ) ); + act( () => controls.fineRotation.onEditEnd() ); + + expect( mockSetRotation ).toHaveBeenCalledWith( 12.5 ); + } ); + + it( 'clamps fine rotation to the policy range', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true } ) + ); + + const controls = result.current; + if ( ! controls.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + act( () => controls.fineRotation.onEdit( 60 ) ); + + expect( mockSetRotation ).toHaveBeenCalledWith( 44.99 ); + } ); + + it( 'exposes session start/end gesture boundaries', () => { + const { result } = renderHook( () => + useAdvancedCropControls( { freeformCrop: true } ) + ); + + const controls = result.current; + if ( ! controls.isReady ) { + throw new Error( 'expected controls to be ready' ); + } + act( () => controls.onSessionStart() ); + expect( mockBeginGesture ).toHaveBeenCalledTimes( 1 ); + expect( mockEndGesture ).not.toHaveBeenCalled(); + + act( () => controls.onSessionEnd() ); + expect( mockEndGesture ).toHaveBeenCalledTimes( 1 ); + } ); +} ); diff --git a/packages/media-editor/src/components/media-editor-crop-panel/test/use-deferred-commit.jsdom.test.tsx b/packages/media-editor/src/components/media-editor-crop-panel/test/use-deferred-commit.jsdom.test.tsx new file mode 100644 index 00000000000000..24c930726832ce --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/test/use-deferred-commit.jsdom.test.tsx @@ -0,0 +1,533 @@ +import { describe, expect, it, vi } from 'vitest'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import { useDeferredCommit } from '../use-deferred-commit'; +import { makeRange } from '../crop-input-utils'; + +const RANGE = makeRange( 0, 500 ); + +function fakeKeyboardEvent( + key: 'Enter' | 'Escape' +): React.KeyboardEvent< HTMLInputElement > { + const target = { blur: vi.fn() }; + return { + key, + preventDefault: vi.fn(), + currentTarget: target, + target, + } as unknown as React.KeyboardEvent< HTMLInputElement >; +} + +describe( 'useDeferredCommit', () => { + it( 'renders the formatted value when not focused', () => { + const onCommit = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 123, + range: RANGE, + commitStep: 1, + onCommit, + } ) + ); + + expect( result.current.value ).toBe( '123' ); + expect( result.current.min ).toBe( 0 ); + expect( result.current.max ).toBe( 500 ); + expect( onCommit ).not.toHaveBeenCalled(); + } ); + + it( 'commits valid in-range drafts immediately', () => { + const onCommit = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + + expect( onCommit ).toHaveBeenCalledWith( 250 ); + } ); + + it( 'keeps input bounds active while focused', () => { + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit: vi.fn(), + } ) + ); + + act( () => result.current.onFocus() ); + + expect( result.current.min ).toBe( 0 ); + expect( result.current.max ).toBe( 500 ); + } ); + + it( 'does not commit out-of-range drafts until completion', () => { + const onCommit = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '9999' ) ); + + expect( onCommit ).not.toHaveBeenCalled(); + } ); + + it( 'previews valid drafts without committing when live commits are disabled', () => { + const onCommit = vi.fn(); + const onPreview = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + commitOnChange: false, + onCommit, + onPreview, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + + expect( onPreview ).toHaveBeenCalledWith( 250 ); + expect( onCommit ).not.toHaveBeenCalled(); + } ); + + it( 'commits deferred preview drafts on blur', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const onPreview = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + commitOnChange: false, + onCommit, + onCommitEnd, + onPreview, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + act( () => result.current.onBlur() ); + + expect( onCommit ).toHaveBeenCalledWith( 250 ); + expect( onPreview ).toHaveBeenLastCalledWith( null ); + expect( onCommitEnd ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'clears deferred previews on Escape without committing', () => { + const onCommit = vi.fn(); + const onPreview = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + commitOnChange: false, + onCommit, + onPreview, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + act( () => result.current.onKeyDown( fakeKeyboardEvent( 'Escape' ) ) ); + + expect( onPreview ).toHaveBeenLastCalledWith( null ); + expect( onCommit ).not.toHaveBeenCalled(); + } ); + + it( 'clears deferred previews once when Enter triggers blur', () => { + const onCommit = vi.fn(); + const onPreview = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + commitOnChange: false, + onCommit, + onPreview, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + act( () => result.current.onKeyDown( fakeKeyboardEvent( 'Enter' ) ) ); + act( () => result.current.onBlur() ); + + expect( onPreview ).toHaveBeenCalledWith( 250 ); + expect( onPreview ).toHaveBeenCalledWith( null ); + expect( onPreview ).toHaveBeenCalledTimes( 2 ); + } ); + + it( 'cancels deferred previews when value changes externally during focus', async () => { + const onCommit = vi.fn(); + const onPreview = vi.fn(); + const { result, rerender } = renderHook( + ( { value }: { value: number } ) => + useDeferredCommit( { + value, + range: RANGE, + commitStep: 1, + commitOnChange: false, + onCommit, + onPreview, + } ), + { initialProps: { value: 100 } } + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + rerender( { value: 300 } ); + + await waitFor( () => expect( result.current.value ).toBe( '300' ) ); + expect( onPreview ).toHaveBeenLastCalledWith( null ); + expect( onCommit ).not.toHaveBeenCalled(); + } ); + + it( 'does not commit outward edits from an already out-of-range value', () => { + const onCommit = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: -10, + range: RANGE, + commitStep: 1, + onCommit, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '-9' ) ); + + expect( result.current.value ).toBe( '-9' ); + expect( result.current.min ).toBe( 0 ); + expect( result.current.max ).toBe( 500 ); + expect( onCommit ).not.toHaveBeenCalled(); + } ); + + it( 'clamps and finalises on blur', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit, + onCommitEnd, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '9999' ) ); + act( () => result.current.onBlur() ); + + expect( onCommit ).toHaveBeenCalledWith( 500 ); + expect( onCommitEnd ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'does not fire onCommitEnd until the user blurs or presses Enter', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit, + onCommitEnd, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + act( () => result.current.onChange( '300' ) ); + act( () => result.current.onChange( '350' ) ); + + // Live commits fire as the user types, but the completion signal + // waits for an explicit boundary (blur or Enter) so session cleanup + // and final history flushing still happen once. + expect( onCommit ).toHaveBeenCalledTimes( 3 ); + expect( onCommitEnd ).not.toHaveBeenCalled(); + } ); + + it( 'leaves out-of-range drafts editable until blur', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit, + onCommitEnd, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '9999' ) ); + + // Draft stays exactly as typed; nothing fires until the user signals + // completion explicitly. + expect( result.current.value ).toBe( '9999' ); + expect( onCommit ).not.toHaveBeenCalled(); + expect( onCommitEnd ).not.toHaveBeenCalled(); + + act( () => result.current.onBlur() ); + + expect( onCommit ).toHaveBeenLastCalledWith( 500 ); + expect( onCommitEnd ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'commits + finalises on Enter', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit, + onCommitEnd, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + act( () => result.current.onKeyDown( fakeKeyboardEvent( 'Enter' ) ) ); + + expect( onCommit ).toHaveBeenLastCalledWith( 250 ); + expect( onCommitEnd ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'commits the latest draft when change and blur happen before a rerender', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit, + onCommitEnd, + } ) + ); + + act( () => result.current.onFocus() ); + const handlers = result.current; + + act( () => { + handlers.onChange( '250' ); + handlers.onBlur(); + } ); + + expect( onCommit ).toHaveBeenCalledTimes( 1 ); + expect( onCommit ).toHaveBeenLastCalledWith( 250 ); + expect( onCommitEnd ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'rolls back to the focus-time value on Escape', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit, + onCommitEnd, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + expect( onCommit ).toHaveBeenLastCalledWith( 250 ); + + act( () => result.current.onKeyDown( fakeKeyboardEvent( 'Escape' ) ) ); + + expect( onCommit ).toHaveBeenLastCalledWith( 100 ); + expect( onCommitEnd ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'keeps the typed draft when external state changes during focus', () => { + const onCommit = vi.fn(); + const { result, rerender } = renderHook( + ( { value }: { value: number } ) => + useDeferredCommit( { + value, + range: RANGE, + commitStep: 1, + onCommit, + } ), + { initialProps: { value: 100 } } + ); + + act( () => result.current.onFocus() ); + // External change (undo, settle, sibling commit, anything) reaches the + // hook as a new `value` prop. While focused, the input stays sovereign. + rerender( { value: 200 } ); + + expect( result.current.value ).toBe( '100' ); + } ); + + it( 'keeps an in-progress draft when external state changes during focus', () => { + const onCommit = vi.fn(); + const { result, rerender } = renderHook( + ( { value }: { value: number } ) => + useDeferredCommit( { + value, + range: RANGE, + commitStep: 1, + onCommit, + } ), + { initialProps: { value: 100 } } + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + rerender( { value: 300 } ); + + expect( result.current.value ).toBe( '250' ); + } ); + + it( 'displays the latest external value once the user blurs', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const { result, rerender } = renderHook( + ( { value }: { value: number } ) => + useDeferredCommit( { + value, + range: RANGE, + commitStep: 1, + onCommit, + onCommitEnd, + } ), + { initialProps: { value: 100 } } + ); + + act( () => result.current.onFocus() ); + rerender( { value: 200 } ); + expect( result.current.value ).toBe( '100' ); + + act( () => result.current.onBlur() ); + + expect( result.current.value ).toBe( '200' ); + expect( onCommit ).not.toHaveBeenCalled(); + expect( onCommitEnd ).not.toHaveBeenCalled(); + } ); + + it( 'does not commit the focus-time value on Enter when only external state changed', () => { + const onCommit = vi.fn(); + const onCommitEnd = vi.fn(); + const { result, rerender } = renderHook( + ( { value }: { value: number } ) => + useDeferredCommit( { + value, + range: RANGE, + commitStep: 1, + onCommit, + onCommitEnd, + } ), + { initialProps: { value: 100 } } + ); + + act( () => result.current.onFocus() ); + rerender( { value: 200 } ); + act( () => result.current.onKeyDown( fakeKeyboardEvent( 'Enter' ) ) ); + + expect( result.current.value ).toBe( '200' ); + expect( onCommit ).not.toHaveBeenCalled(); + expect( onCommitEnd ).not.toHaveBeenCalled(); + } ); + + it( 'fires onSessionStart on focus and onSessionEnd on blur', () => { + const onSessionStart = vi.fn(); + const onSessionEnd = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit: vi.fn(), + onSessionStart, + onSessionEnd, + } ) + ); + + act( () => result.current.onFocus() ); + expect( onSessionStart ).toHaveBeenCalledTimes( 1 ); + expect( onSessionEnd ).not.toHaveBeenCalled(); + + act( () => result.current.onChange( '250' ) ); + expect( onSessionStart ).toHaveBeenCalledTimes( 1 ); + expect( onSessionEnd ).not.toHaveBeenCalled(); + + act( () => result.current.onBlur() ); + expect( onSessionEnd ).toHaveBeenCalledTimes( 1 ); + } ); + + it.each( [ 'Enter', 'Escape' ] as const )( + 'fires onSessionEnd exactly once on %s (not again from the resulting blur)', + ( key ) => { + const onSessionEnd = vi.fn(); + const { result } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit: vi.fn(), + onSessionEnd, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + act( () => result.current.onKeyDown( fakeKeyboardEvent( key ) ) ); + act( () => result.current.onBlur() ); + + expect( onSessionEnd ).toHaveBeenCalledTimes( 1 ); + } + ); + + it( 'ends an active session before flushing a pending live commit on unmount', () => { + const onCommitEnd = vi.fn(); + const onSessionEnd = vi.fn(); + const { result, unmount } = renderHook( () => + useDeferredCommit( { + value: 100, + range: RANGE, + commitStep: 1, + onCommit: vi.fn(), + onCommitEnd, + onSessionEnd, + } ) + ); + + act( () => result.current.onFocus() ); + act( () => result.current.onChange( '250' ) ); + unmount(); + + expect( onCommitEnd ).toHaveBeenCalledTimes( 1 ); + expect( onSessionEnd ).toHaveBeenCalledTimes( 1 ); + expect( onSessionEnd.mock.invocationCallOrder[ 0 ] ).toBeLessThan( + onCommitEnd.mock.invocationCallOrder[ 0 ] + ); + } ); +} ); diff --git a/packages/media-editor/src/components/media-editor-crop-panel/use-advanced-crop-controls.ts b/packages/media-editor/src/components/media-editor-crop-panel/use-advanced-crop-controls.ts new file mode 100644 index 00000000000000..05d324a14d98de --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/use-advanced-crop-controls.ts @@ -0,0 +1,284 @@ +import { useCallback, useMemo } from '@wordpress/element'; +import { useMediaEditor } from '../../state'; +import { + applyCropEdit, + cropPixelRectToNormalizedRect, + type CropEditField, + type CropPixelRect, + type CropPixelRectBounds, +} from '../../image-editor/core/crop-geometry'; +import { fineRotation } from '../../image-editor/core/fine-rotation'; +import { useSetCropperPreviewRect } from '../../image-editor/react/components/cropper-provider'; +import { useCropGeometry } from '../../image-editor/react/hooks/use-crop-geometry'; +import { makeRange, type CropInputRange } from './crop-input-utils'; + +export interface AdvancedCropRanges { + left: CropInputRange; + top: CropInputRange; + width: CropInputRange; + height: CropInputRange; +} + +export interface AdvancedFineRotationConfig { + offset: number; + range: CropInputRange; + step: number; + onEdit: ( value: number ) => void; + onEditEnd: () => void; +} + +export type AdvancedCropControlsState = + | { isReady: false } + | { + isReady: true; + rect: CropPixelRect; + imageBounds: CropPixelRectBounds; + canMoveCropRect: boolean; + ranges: AdvancedCropRanges; + fineRotation: AdvancedFineRotationConfig; + onPreview: ( field: CropEditField, value: number | null ) => void; + onEdit: ( field: CropEditField, value: number ) => void; + onEditEnd: () => void; + /** + * Pass to live numeric controls' `onSessionStart` so the focused + * edit session opens one undo boundary. + */ + onSessionStart: () => void; + /** + * Pass to live numeric controls' `onSessionEnd` so the focused + * edit session closes one undo boundary. + */ + onSessionEnd: () => void; + }; + +export interface UseAdvancedCropControlsArgs { + aspectRatio?: number; + freeformCrop: boolean; + onPlacementControlInteraction?: () => void; +} + +// 1px — absorbs sub-pixel drift from rotation/zoom that would otherwise +// leave `rect.left` at, say, 0.0003 when the user clearly placed the crop +// against the image edge. Treat anything closer than 1px to the edge as +// anchored so the width/height ranges report a clean "from edge to edge". +const EDGE_SNAP_EPSILON = 1; + +/** + * Hook that wires the advanced crop panel to the cropper controller. + * + * Crop rectangle controls are draft-first: valid drafts paint a preview + * rectangle, then blur/Enter commits the rect once and settles the cropper. + * Fine rotation remains live because visual feedback is essential there. + * + * Returns `{ isReady: false }` until the cropper has measurements; the panel + * component should render nothing in that case. + * + * @param args Hook arguments. + * @param args.aspectRatio + * @param args.freeformCrop + * @param args.onPlacementControlInteraction + * @return Either an unready sentinel or the panel's full data + handlers. + */ +export function useAdvancedCropControls( { + aspectRatio, + freeformCrop, + onPlacementControlInteraction, +}: UseAdvancedCropControlsArgs ): AdvancedCropControlsState { + const { cropper, beginGesture, endGesture } = useMediaEditor(); + const { state, setCropRect, setRotation, settleCrop } = cropper; + const geometry = useCropGeometry(); + const setPreviewCropRect = useSetCropperPreviewRect(); + + const imageSize = useMemo( + () => + state.image + ? { + width: state.image.naturalWidth, + height: state.image.naturalHeight, + } + : { width: 0, height: 0 }, + [ state.image ] + ); + + const getEditedRect = useCallback( + ( field: CropEditField, value: number ): CropPixelRect | null => { + if ( ! geometry.isReady ) { + return null; + } + return applyCropEdit( geometry.rect, field, value, { + aspectRatio, + bounds: geometry.imageBounds, + } ); + }, + [ geometry, aspectRatio ] + ); + + const onPreview = useCallback( + ( field: CropEditField, value: number | null ) => { + if ( value === null ) { + setPreviewCropRect( null ); + return; + } + const next = getEditedRect( field, value ); + setPreviewCropRect( + next + ? cropPixelRectToNormalizedRect( next, state, imageSize ) + : null + ); + onPlacementControlInteraction?.(); + }, + [ + getEditedRect, + state, + imageSize, + setPreviewCropRect, + onPlacementControlInteraction, + ] + ); + + const onEdit = useCallback( + ( field: CropEditField, value: number ) => { + const next = getEditedRect( field, value ); + setPreviewCropRect( null ); + if ( ! next ) { + return; + } + setCropRect( + cropPixelRectToNormalizedRect( next, state, imageSize ) + ); + onPlacementControlInteraction?.(); + }, + [ + getEditedRect, + setCropRect, + state, + imageSize, + setPreviewCropRect, + onPlacementControlInteraction, + ] + ); + + const onEditEnd = useCallback( () => { + settleCrop(); + onPlacementControlInteraction?.(); + }, [ settleCrop, onPlacementControlInteraction ] ); + + const onFineRotationEdit = useCallback( + ( value: number ) => { + const clampedOffset = fineRotation.clamp( value ); + if ( + ! fineRotation.hasChanged( + clampedOffset, + fineRotation.offsetFromState( state.rotation, state.flip ) + ) + ) { + return; + } + setRotation( + fineRotation.absoluteFromOffset( + state.rotation, + state.flip, + clampedOffset + ) + ); + onPlacementControlInteraction?.(); + }, + [ + state.rotation, + state.flip, + setRotation, + onPlacementControlInteraction, + ] + ); + + const onSessionStart = useCallback( () => { + beginGesture(); + }, [ beginGesture ] ); + + const onSessionEnd = useCallback( () => { + endGesture(); + }, [ endGesture ] ); + + if ( ! geometry.isReady ) { + return { isReady: false }; + } + + const { rect, imageBounds } = geometry; + const ranges = buildRanges( rect, imageBounds, aspectRatio, freeformCrop ); + const fineRotationOffset = fineRotation.offsetFromState( + state.rotation, + state.flip + ); + + return { + isReady: true, + rect, + imageBounds, + canMoveCropRect: freeformCrop, + ranges, + onPreview, + onSessionStart, + onSessionEnd, + fineRotation: { + offset: fineRotationOffset, + range: makeRange( fineRotation.min, fineRotation.max ), + step: fineRotation.step, + onEdit: onFineRotationEdit, + onEditEnd: () => {}, + }, + onEdit, + onEditEnd, + }; +} + +function buildRanges( + rect: CropPixelRect, + bounds: CropPixelRectBounds, + aspectRatio: number | undefined, + freeformCrop: boolean +): AdvancedCropRanges { + const anchoredLeft = + Math.abs( rect.left - bounds.minLeft ) < EDGE_SNAP_EPSILON + ? bounds.minLeft + : rect.left; + const anchoredTop = + Math.abs( rect.top - bounds.minTop ) < EDGE_SNAP_EPSILON + ? bounds.minTop + : rect.top; + const maxWidthAtCurrentLeft = bounds.maxRight - anchoredLeft; + const maxHeightAtCurrentTop = bounds.maxBottom - anchoredTop; + const left = makeRange( bounds.minLeft, bounds.maxRight - rect.width ); + const top = makeRange( bounds.minTop, bounds.maxBottom - rect.height ); + + if ( ! freeformCrop ) { + return { + left, + top, + width: makeRange( rect.width, rect.width, false ), + height: makeRange( rect.height, rect.height, false ), + }; + } + + let minWidth = bounds.minWidth; + let maxWidth = maxWidthAtCurrentLeft; + let minHeight = bounds.minHeight; + let maxHeight = maxHeightAtCurrentTop; + + if ( aspectRatio && aspectRatio > 0 ) { + // Aspect-ratio coupling: lower bounds use the image's hard minimum + // (independent of current position), upper bounds use the + // position-anchored max so the coupled dimension can't push the + // crop past the bottom/right edge of the image. + minWidth = Math.max( minWidth, bounds.minHeight * aspectRatio ); + maxWidth = Math.min( maxWidth, maxHeightAtCurrentTop * aspectRatio ); + minHeight = Math.max( minHeight, bounds.minWidth / aspectRatio ); + maxHeight = Math.min( maxHeight, maxWidthAtCurrentLeft / aspectRatio ); + } + + return { + left, + top, + width: makeRange( minWidth, maxWidth ), + height: makeRange( minHeight, maxHeight ), + }; +} diff --git a/packages/media-editor/src/components/media-editor-crop-panel/use-deferred-commit.ts b/packages/media-editor/src/components/media-editor-crop-panel/use-deferred-commit.ts new file mode 100644 index 00000000000000..6269af9172ab70 --- /dev/null +++ b/packages/media-editor/src/components/media-editor-crop-panel/use-deferred-commit.ts @@ -0,0 +1,304 @@ +import { useEffect, useRef, useState } from '@wordpress/element'; +import { + getInputBounds, + getInputCommitValue, + type CropInputRange, +} from './crop-input-utils'; + +export interface UseDeferredCommitArgs { + value: number; + range: CropInputRange; + commitStep: number; + onCommit: ( value: number ) => void; + onCommitEnd?: () => void; + /** + * Whether valid drafts should be committed on every change. Disable for + * controls that show a draft preview and commit only on blur/Enter. + */ + commitOnChange?: boolean; + /** + * Called with the parsed draft value while `commitOnChange` is false. + * Receives `null` when the draft is not currently commit-valid. + */ + onPreview?: ( value: number | null ) => void; + /** + * Called on focus, before any draft handling. Use to suspend + * side-effects that should treat the whole focus → blur cycle as one + * session — e.g. pausing the cropper's auto-history debounce. + */ + onSessionStart?: () => void; + /** + * Called on blur, Enter, or Escape before `onCommitEnd`, even if the + * user did not change anything. Pair with `onSessionStart` to bound an + * edit session. + */ + onSessionEnd?: () => void; +} + +export interface UseDeferredCommitReturn { + value: string; + min: number | undefined; + max: number | undefined; + onFocus: () => void; + onBlur: () => void; + onChange: ( next: string | undefined ) => void; + onKeyDown: ( event: React.KeyboardEvent< HTMLInputElement > ) => void; +} + +/** + * Drive the numeric crop input's commit lifecycle from a single hook. + * + * Default mode is live commit: valid drafts fire `onCommit` on every change + * so the canvas tracks typing. When `commitOnChange` is false, valid drafts + * call `onPreview` instead and the real `onCommit` waits for blur/Enter — + * use this for controls that paint a draft preview rectangle on the canvas + * rather than mutating cropper state per keystroke. + * + * In both modes the displayed value is sovereign while focused: what the + * user types stays, and the input is never replaced by an external state + * change during a live-commit focus session. (Preview-mode focus sessions + * are resync'd by the effect below when the cropper changes underneath.) + * + * On blur or Enter, a user-edited numeric draft is clamped to the current + * bounds and committed, the session ends, and `onCommitEnd` (typically + * `settleCrop`) fires once. Escape restores the value captured on focus. + * + * @param args Hook arguments. + * @param args.value + * @param args.range + * @param args.commitStep + * @param args.onCommit + * @param args.onCommitEnd + * @param args.commitOnChange + * @param args.onPreview + * @param args.onSessionStart + * @param args.onSessionEnd + * @return Spreadable handlers + display value for a number input. + */ +export function useDeferredCommit( { + value, + range, + commitStep, + onCommit, + onCommitEnd, + commitOnChange = true, + onPreview, + onSessionStart, + onSessionEnd, +}: UseDeferredCommitArgs ): UseDeferredCommitReturn { + const [ focused, setFocused ] = useState( false ); + const [ draft, setDraft ] = useState( '' ); + const draftRef = useRef( '' ); + const skipBlurCommitRef = useRef( false ); + const initialValueRef = useRef( value ); + const lastCommittedDraftValueRef = useRef< number | null >( null ); + const hasPendingCommitEndRef = useRef( false ); + const hasUserEditedDraftRef = useRef( false ); + const onCommitEndRef = useRef( onCommitEnd ); + const onPreviewRef = useRef( onPreview ); + const onSessionEndRef = useRef( onSessionEnd ); + // Tracks whether `onSessionEnd` has already fired for the current focus + // session, so Enter/Escape and the subsequent blur do not double-fire. + const sessionEndedRef = useRef( true ); + const bounds = getInputBounds( value, range, commitStep ); + + useEffect( () => { + onCommitEndRef.current = onCommitEnd; + onPreviewRef.current = onPreview; + onSessionEndRef.current = onSessionEnd; + }, [ onCommitEnd, onPreview, onSessionEnd ] ); + + useEffect( () => { + return () => { + if ( sessionEndedRef.current ) { + return; + } + sessionEndedRef.current = true; + onPreviewRef.current?.( null ); + onSessionEndRef.current?.(); + if ( hasPendingCommitEndRef.current ) { + onCommitEndRef.current?.(); + hasPendingCommitEndRef.current = false; + } + }; + }, [] ); + + // Preview-mode resync: if the cropper changes underneath a focused + // preview (rotation, undo, sibling commit), the visible draft no longer + // corresponds to anything meaningful — the "baseline + edit" math + // against the old `value` produces a preview rectangle that misrepresents + // what would commit. Reset to the new baseline and clear the preview. + // Live-commit mode keeps the typed draft because there, the draft IS the + // commit and external state changes during focus are deliberately ignored. + useEffect( () => { + if ( + commitOnChange || + ! focused || + bounds.value === initialValueRef.current + ) { + return; + } + initialValueRef.current = bounds.value; + lastCommittedDraftValueRef.current = null; + hasPendingCommitEndRef.current = false; + hasUserEditedDraftRef.current = false; + draftRef.current = String( bounds.value ); + setDraft( String( bounds.value ) ); + onPreviewRef.current?.( null ); + }, [ bounds.value, commitOnChange, focused ] ); + + const endSession = () => { + if ( sessionEndedRef.current ) { + return; + } + sessionEndedRef.current = true; + onSessionEndRef.current?.(); + }; + + const runCommitEnd = () => { + if ( hasPendingCommitEndRef.current ) { + onCommitEndRef.current?.(); + hasPendingCommitEndRef.current = false; + } + }; + + const commitValue = ( + nextValue: string, + options: { clampToBounds?: boolean; updateDraft?: boolean } = {} + ): boolean => { + const commitValueCandidate = getInputCommitValue( + nextValue, + bounds, + commitStep, + options.clampToBounds + ); + if ( commitValueCandidate === null ) { + return false; + } + + if ( options.updateDraft ) { + draftRef.current = String( commitValueCandidate ); + setDraft( String( commitValueCandidate ) ); + } + if ( lastCommittedDraftValueRef.current !== commitValueCandidate ) { + onCommit( commitValueCandidate ); + hasPendingCommitEndRef.current = true; + } + lastCommittedDraftValueRef.current = commitValueCandidate; + return true; + }; + + // Lightweight twin of `commitValue` — runs the same parse + step snap + // but only notifies the consumer; the hook's commit bookkeeping + // (lastCommittedDraftValueRef, hasPendingCommitEndRef) stays untouched + // until blur/Enter. + const previewValue = ( nextValue: string ) => { + const previewValueCandidate = getInputCommitValue( + nextValue, + bounds, + commitStep + ); + onPreview?.( previewValueCandidate ); + }; + + // Finalise on blur or Enter. Silently no-ops when the user didn't touch + // the draft this session, so a focused-but-untouched input does not + // overwrite an external state change (e.g. undo while focused). + const completeDraft = () => { + if ( ! hasUserEditedDraftRef.current ) { + return; + } + + commitValue( draftRef.current, { + clampToBounds: true, + updateDraft: true, + } ); + }; + + const onFocus = () => { + initialValueRef.current = bounds.value; + lastCommittedDraftValueRef.current = null; + hasPendingCommitEndRef.current = false; + hasUserEditedDraftRef.current = false; + sessionEndedRef.current = false; + setFocused( true ); + draftRef.current = String( bounds.value ); + setDraft( String( bounds.value ) ); + onSessionStart?.(); + }; + + const onChange = ( nextValue: string | undefined ) => { + const nextDraft = nextValue ?? ''; + if ( nextDraft !== draftRef.current ) { + hasUserEditedDraftRef.current = true; + } + draftRef.current = nextDraft; + setDraft( nextDraft ); + if ( commitOnChange ) { + commitValue( nextDraft ); + } else { + previewValue( nextDraft ); + } + }; + + const onBlur = () => { + setFocused( false ); + const shouldSkipBlurCommit = skipBlurCommitRef.current; + if ( ! shouldSkipBlurCommit ) { + completeDraft(); + if ( ! commitOnChange ) { + onPreview?.( null ); + } + } + skipBlurCommitRef.current = false; + // Session end before commit end: `onCommitEnd` typically calls + // `settleCrop`, and the media editor's gesture boundary should be + // closed first so the session flushes as one undo entry. + endSession(); + runCommitEnd(); + }; + + const onKeyDown = ( event: React.KeyboardEvent< HTMLInputElement > ) => { + if ( event.key === 'Enter' ) { + event.preventDefault(); + skipBlurCommitRef.current = true; + setFocused( false ); + completeDraft(); + if ( ! commitOnChange ) { + onPreview?.( null ); + } + endSession(); + runCommitEnd(); + event.currentTarget.blur(); + } else if ( event.key === 'Escape' ) { + event.preventDefault(); + skipBlurCommitRef.current = true; + setFocused( false ); + if ( lastCommittedDraftValueRef.current !== null ) { + onCommit( initialValueRef.current ); + hasPendingCommitEndRef.current = true; + lastCommittedDraftValueRef.current = null; + } + if ( ! commitOnChange ) { + onPreview?.( null ); + } + endSession(); + runCommitEnd(); + event.currentTarget.blur(); + } + }; + + return { + value: focused ? draft : String( bounds.value ), + // Always expose bounds. `getInputBounds` reports the actual commit + // range even when the current value temporarily exceeds it (e.g. + // transient post-rotation state), so the NumberControl's spinner and + // keyboard arrows can't push the value out of range. + min: bounds.min, + max: bounds.max, + onFocus, + onBlur, + onChange, + onKeyDown, + }; +} diff --git a/packages/media-editor/src/components/media-editor-fine-rotation/index.tsx b/packages/media-editor/src/components/media-editor-fine-rotation/index.tsx index 13bb8017225cf1..0ba5fc01f64155 100644 --- a/packages/media-editor/src/components/media-editor-fine-rotation/index.tsx +++ b/packages/media-editor/src/components/media-editor-fine-rotation/index.tsx @@ -1,7 +1,7 @@ import { __ } from '@wordpress/i18n'; import { useMediaEditor } from '../../state'; import { useCropGestureHandlers } from '../../hooks/use-crop-gesture-handlers'; -import { MAX_ROTATION_OFFSET } from '../../image-editor/core/constants'; +import { fineRotation } from '../../image-editor/core/fine-rotation'; import RotationRuler from '../rotation-ruler'; export interface MediaEditorFineRotationProps { @@ -36,25 +36,16 @@ export default function MediaEditorFineRotation( { commitOnKeyUp: false, } ); - // `setRotation` is an absolute-angle setter. When a single flip is active - // the visual direction inverts, so slider input must flip sign to match - // what the user sees. `snapRotate90` already handles this internally. - const baseAngle = Math.round( state.rotation / 90 ) * 90; - const singleFlip = state.flip.horizontal !== state.flip.vertical; - const visualDir = singleFlip ? -1 : 1; - const fineOffset = ( state.rotation - baseAngle ) * visualDir; + const fineOffset = fineRotation.offsetFromState( + state.rotation, + state.flip + ); const handleRotationSlider = ( value: number ) => { - // Clamp strictly inside [-MAX, MAX). Exactly ±MAX lands state on a - // 90° midpoint and flips the derived baseAngle on the next render, - // causing subsequent events to spiral. - const EPS = 0.01; - const clamped = Math.max( - -MAX_ROTATION_OFFSET + EPS, - Math.min( MAX_ROTATION_OFFSET - EPS, value ) - ); onPlacementControlInteraction?.(); - setRotation( baseAngle + clamped * visualDir ); + setRotation( + fineRotation.absoluteFromOffset( state.rotation, state.flip, value ) + ); }; return ( @@ -65,8 +56,8 @@ export default function MediaEditorFineRotation( { > * { + flex: 1; + min-width: 0; +} + // `` renders `.components-snackbar-list` with // `position: absolute; width: 100%`. Portaled to `` it has no // positioned ancestor, so it collapses to a 0-size box at the document diff --git a/packages/media-editor/src/components/media-editor/index.tsx b/packages/media-editor/src/components/media-editor/index.tsx index e62047fb682ea4..69aeeabdd67a37 100644 --- a/packages/media-editor/src/components/media-editor/index.tsx +++ b/packages/media-editor/src/components/media-editor/index.tsx @@ -39,6 +39,7 @@ import MediaForm from '../media-form'; import { getMediaTypeFromMimeType } from '../../utils'; import { MediaEditorStateProvider, useMediaEditor } from '../../state'; import type { AspectRatioPreset } from '../../image-editor/core/constants'; +import { CropperProvider } from '../../image-editor'; import { CROP_CONTROL_ATTR } from '../../hooks/use-crop-gesture-handlers'; import MediaEditorKeyboardShortcutsModal from '../media-editor-keyboard-shortcuts-modal'; import { @@ -712,6 +713,9 @@ function MediaEditorContent( { @@ -872,11 +876,21 @@ function MediaEditorContent( { export function MediaEditor( props: MediaEditorProps ) { return ( - + ); } +function MediaEditorWithCropperProvider( props: MediaEditorProps ) { + const { cropper } = useMediaEditor(); + + return ( + + + + ); +} + // Attached to `MediaEditor` so frames import and arrange them, the way // `DataViewsPicker` exposes its own sub-components. They read what they need // from context, so a frame only chooses where they go and how they look. diff --git a/packages/media-editor/src/image-editor/core/crop-geometry.ts b/packages/media-editor/src/image-editor/core/crop-geometry.ts new file mode 100644 index 00000000000000..210b4c3da3c3dd --- /dev/null +++ b/packages/media-editor/src/image-editor/core/crop-geometry.ts @@ -0,0 +1,546 @@ +import type { CropperState, NormalizedRect, Size } from './types'; +import { getRotatedBBox } from './camera'; +import { getSourceRegion, type SourceRegion } from './source-region'; +import { DEFAULT_MIN_CROP_SIZE, type CropBounds } from './stencil-math'; + +const EPSILON = 1e-9; + +/** Normalized crop bounds in the cropper's visual coordinate space. */ +export type NormalizedCropBounds = CropBounds; + +/** + * Candidate crop rectangle expressed in snap-rotation crop pixels. + * + * This is the shape consumers provide for validation, conversion, or editing. + * Derived `right` / `bottom` edges are not accepted from consumers; they live + * on the resolved `CropPixelRect` shape returned by the helpers below. + */ +export interface CropPixelRectInput { + left: number; + top: number; + width: number; + height: number; +} + +/** + * Crop rectangle expressed in snap-rotation crop pixels. + * + * Always construct via `toCropPixelRect`, `getCropPixelRect`, + * `clampCropPixelRectToBounds`, or `applyCropEdit`. `right` and `bottom` are + * derived from `left + width` and `top + height`. + */ +export interface CropPixelRect extends CropPixelRectInput { + readonly right: number; + readonly bottom: number; +} + +/** + * Generic crop rectangle limits expressed in the same snap-rotation pixel + * space as `CropPixelRect`. + */ +export interface CropPixelRectBounds { + minLeft: number; + minTop: number; + maxRight: number; + maxBottom: number; + minWidth: number; + minHeight: number; + maxWidth: number; + maxHeight: number; +} + +export interface CropGeometryInput { + state: CropperState; + imageSize: Size; + imageBounds: NormalizedCropBounds | undefined; +} + +export interface CropGeometrySnapshot { + rect: CropPixelRect; + imageBounds: CropPixelRectBounds; + sourceRegion: SourceRegion; +} + +export type CropPixelRectViolation = + | 'non-finite' + | 'left-out-of-bounds' + | 'top-out-of-bounds' + | 'right-out-of-bounds' + | 'bottom-out-of-bounds' + | 'width-too-small' + | 'width-too-large' + | 'height-too-small' + | 'height-too-large'; + +/** + * Diagnostic result for validating a candidate rectangle against bounds. + * + * The `ok: false` branch still carries a `rect`, the clamped fallback, so + * consumers can recover without a second call. + */ +export type CropPixelRectCheck = + | { ok: true; rect: CropPixelRect } + | { + ok: false; + rect: CropPixelRect; + violations: CropPixelRectViolation[]; + }; + +/** The four directly-editable fields on a crop rectangle. */ +export type CropEditField = 'left' | 'top' | 'width' | 'height'; + +interface SnapGeometry { + width: number; + height: number; + imageLeft: number; + imageTop: number; +} + +function clamp( value: number, min: number, max: number ): number { + if ( max < min ) { + return min; + } + return Math.min( max, Math.max( min, value ) ); +} + +function clampFinite( + value: number, + min: number, + max: number, + fallback: number +): number { + return Number.isFinite( value ) ? clamp( value, min, max ) : fallback; +} + +function getAspectRatioWidthBounds( + bounds: CropPixelRectBounds, + aspectRatio: number +): { min: number; max: number } { + return { + min: Math.max( bounds.minWidth, bounds.minHeight * aspectRatio ), + max: Math.min( bounds.maxWidth, bounds.maxHeight * aspectRatio ), + }; +} + +function getAspectRatioHeightBounds( + bounds: CropPixelRectBounds, + aspectRatio: number +): { min: number; max: number } { + return { + min: Math.max( bounds.minHeight, bounds.minWidth / aspectRatio ), + max: Math.min( bounds.maxHeight, bounds.maxWidth / aspectRatio ), + }; +} + +function getSnapGeometry( state: CropperState, imageSize: Size ): SnapGeometry { + const snapRotation = Math.round( state.rotation / 90 ) * 90; + const { width, height } = getRotatedBBox( + imageSize.width, + imageSize.height, + snapRotation + ); + return { + width, + height, + imageLeft: 0.5 + state.pan.x - state.zoom / 2, + imageTop: 0.5 + state.pan.y - state.zoom / 2, + }; +} + +function normalizedXToPixel( + x: number, + state: CropperState, + snap: SnapGeometry +): number { + return ( ( x - snap.imageLeft ) / state.zoom ) * snap.width; +} + +function normalizedYToPixel( + y: number, + state: CropperState, + snap: SnapGeometry +): number { + return ( ( y - snap.imageTop ) / state.zoom ) * snap.height; +} + +function normalizedWidthToPixel( + width: number, + state: CropperState, + snap: SnapGeometry +): number { + return ( width / state.zoom ) * snap.width; +} + +function normalizedHeightToPixel( + height: number, + state: CropperState, + snap: SnapGeometry +): number { + return ( height / state.zoom ) * snap.height; +} + +function pixelXToNormalized( + left: number, + state: CropperState, + snap: SnapGeometry +): number { + return ( left / snap.width ) * state.zoom + snap.imageLeft; +} + +function pixelYToNormalized( + top: number, + state: CropperState, + snap: SnapGeometry +): number { + return ( top / snap.height ) * state.zoom + snap.imageTop; +} + +function pixelWidthToNormalized( + width: number, + state: CropperState, + snap: SnapGeometry +): number { + return ( width / snap.width ) * state.zoom; +} + +function pixelHeightToNormalized( + height: number, + state: CropperState, + snap: SnapGeometry +): number { + return ( height / snap.height ) * state.zoom; +} + +function toCropPixelRect( pixels: CropPixelRectInput ): CropPixelRect { + return { + left: pixels.left, + top: pixels.top, + width: pixels.width, + height: pixels.height, + right: pixels.left + pixels.width, + bottom: pixels.top + pixels.height, + }; +} + +/** + * Convert cropper state to the snap-rotation pixel rectangle used by crop + * controls and export/save math. + * + * @param state Cropper state. + * @param imageSize Natural source image size. + * @return Crop rectangle in snap-rotation pixels. + */ +export function getCropPixelRect( + state: CropperState, + imageSize: Size +): CropPixelRect { + if ( imageSize.width === 0 || imageSize.height === 0 ) { + return toCropPixelRect( { left: 0, top: 0, width: 0, height: 0 } ); + } + const snap = getSnapGeometry( state, imageSize ); + const { cropRect } = state; + return toCropPixelRect( { + left: normalizedXToPixel( cropRect.x, state, snap ), + top: normalizedYToPixel( cropRect.y, state, snap ), + width: normalizedWidthToPixel( cropRect.width, state, snap ), + height: normalizedHeightToPixel( cropRect.height, state, snap ), + } ); +} + +/** + * Convert a snap-rotation pixel rectangle back to normalized cropper space. + * + * @param pixels Crop rectangle in snap-rotation pixels. + * @param state Cropper state. + * @param imageSize Natural source image size. + * @return Normalized crop rectangle. + */ +export function cropPixelRectToNormalizedRect( + pixels: CropPixelRectInput, + state: CropperState, + imageSize: Size +): NormalizedRect { + if ( imageSize.width === 0 || imageSize.height === 0 ) { + return { x: 0, y: 0, width: 0, height: 0 }; + } + + const snap = getSnapGeometry( state, imageSize ); + return { + x: pixelXToNormalized( pixels.left, state, snap ), + y: pixelYToNormalized( pixels.top, state, snap ), + width: pixelWidthToNormalized( pixels.width, state, snap ), + height: pixelHeightToNormalized( pixels.height, state, snap ), + }; +} + +function isCropGeometryReady( input: CropGeometryInput ): boolean { + return ( + input.imageSize.width > 0 && + input.imageSize.height > 0 && + !! input.imageBounds + ); +} + +/** + * Convert normalized image crop bounds to snap-rotation pixel bounds. + * + * @param bounds Normalized crop bounds. + * @param state Cropper state. + * @param imageSize Natural source image size. + * @return Crop pixel bounds. + */ +function cropBoundsToPixelRectBounds( + bounds: NormalizedCropBounds, + state: CropperState, + imageSize: Size +): CropPixelRectBounds { + if ( imageSize.width === 0 || imageSize.height === 0 ) { + return { + minLeft: 0, + minTop: 0, + maxRight: 0, + maxBottom: 0, + minWidth: 0, + minHeight: 0, + maxWidth: 0, + maxHeight: 0, + }; + } + + const snap = getSnapGeometry( state, imageSize ); + const minLeft = normalizedXToPixel( bounds.minX, state, snap ); + const minTop = normalizedYToPixel( bounds.minY, state, snap ); + const maxRight = normalizedXToPixel( bounds.maxX, state, snap ); + const maxBottom = normalizedYToPixel( bounds.maxY, state, snap ); + const maxWidth = Math.max( 0, maxRight - minLeft ); + const maxHeight = Math.max( 0, maxBottom - minTop ); + const minWidth = Math.min( + normalizedWidthToPixel( DEFAULT_MIN_CROP_SIZE.width, state, snap ), + maxWidth + ); + const minHeight = Math.min( + normalizedHeightToPixel( DEFAULT_MIN_CROP_SIZE.height, state, snap ), + maxHeight + ); + + return { + minLeft, + minTop, + maxRight, + maxBottom, + minWidth, + minHeight, + maxWidth, + maxHeight, + }; +} + +function getCropPixelImageBounds( + input: CropGeometryInput +): CropPixelRectBounds | null { + if ( ! isCropGeometryReady( input ) ) { + return null; + } + + return cropBoundsToPixelRectBounds( + input.imageBounds as NormalizedCropBounds, + input.state, + input.imageSize + ); +} + +/** + * Fit a complete crop rectangle inside the provided bounds. This is + * deliberately rectangle-level logic rather than an operation API: callers + * decide whether a width change is left-anchored, center-anchored, + * aspect-ratio locked, etc., then clamp the resulting rectangle here. + * + * @param rect Candidate crop rectangle in snap-rotation pixels. + * @param bounds Crop pixel bounds to clamp against. + * @return Clamped crop rectangle in snap-rotation pixels. + */ +export function clampCropPixelRectToBounds( + rect: CropPixelRectInput, + bounds: CropPixelRectBounds +): CropPixelRect { + const fallback = { + left: bounds.minLeft, + top: bounds.minTop, + width: bounds.minWidth, + height: bounds.minHeight, + }; + const candidate = { + left: Number.isFinite( rect.left ) ? rect.left : fallback.left, + top: Number.isFinite( rect.top ) ? rect.top : fallback.top, + width: Number.isFinite( rect.width ) ? rect.width : fallback.width, + height: Number.isFinite( rect.height ) ? rect.height : fallback.height, + }; + const width = clamp( candidate.width, bounds.minWidth, bounds.maxWidth ); + const height = clamp( + candidate.height, + bounds.minHeight, + bounds.maxHeight + ); + const left = clamp( + candidate.left, + bounds.minLeft, + bounds.maxRight - width + ); + const top = clamp( + candidate.top, + bounds.minTop, + bounds.maxBottom - height + ); + + return toCropPixelRect( { left, top, width, height } ); +} + +/** + * Apply a single-field edit to a crop rectangle, optionally couple the + * dependent dimension via an aspect ratio, then clamp against bounds. + * + * This is the consumer-facing entry point for advanced crop controls: it + * keeps aspect-ratio coupling and bound clamping in one place so panels and + * automation can mutate a rectangle without re-implementing either policy. + * + * @param rect Current crop rectangle. + * @param field The field the user edited + * (`left` | `top` | `width` | `height`). + * @param value New value for the edited field. + * @param options Edit options. + * @param options.aspectRatio Optional width / height lock for size edits. + * @param options.bounds Crop pixel bounds to clamp the result against. + * @return Resulting crop rectangle after coupling and clamping. + */ +export function applyCropEdit( + rect: CropPixelRectInput, + field: CropEditField, + value: number, + options: { aspectRatio?: number; bounds: CropPixelRectBounds } +): CropPixelRect { + const next: CropPixelRectInput = { + left: rect.left, + top: rect.top, + width: rect.width, + height: rect.height, + }; + + if ( options.aspectRatio && options.aspectRatio > 0 ) { + if ( field === 'width' ) { + const widthBounds = getAspectRatioWidthBounds( + options.bounds, + options.aspectRatio + ); + next.width = clampFinite( + value, + widthBounds.min, + widthBounds.max, + next.width + ); + next.height = next.width / options.aspectRatio; + } else if ( field === 'height' ) { + const heightBounds = getAspectRatioHeightBounds( + options.bounds, + options.aspectRatio + ); + next.height = clampFinite( + value, + heightBounds.min, + heightBounds.max, + next.height + ); + next.width = next.height * options.aspectRatio; + } else { + next[ field ] = value; + } + } else { + next[ field ] = value; + } + + return clampCropPixelRectToBounds( next, options.bounds ); +} + +/** + * Validate a candidate crop rectangle against the provided crop pixel bounds. + * + * Used by diagnostics consumers (tests, AI agents) that need to know *why* an + * input was rejected. Panels that only want a clamped result should call + * `applyCropEdit` or `clampCropPixelRectToBounds` instead. + * + * @param rect Candidate crop rectangle in snap-rotation pixels. + * @param bounds Crop pixel bounds to validate against. + * @return Discriminated check result. The `ok: false` branch carries the + * clamped fallback rectangle so consumers can recover. + */ +export function validateCropPixelRectAgainstBounds( + rect: CropPixelRectInput, + bounds: CropPixelRectBounds +): CropPixelRectCheck { + const violations: CropPixelRectViolation[] = []; + + if ( + ! Number.isFinite( rect.left ) || + ! Number.isFinite( rect.top ) || + ! Number.isFinite( rect.width ) || + ! Number.isFinite( rect.height ) + ) { + violations.push( 'non-finite' ); + } + + const right = rect.left + rect.width; + const bottom = rect.top + rect.height; + + if ( rect.left < bounds.minLeft - EPSILON ) { + violations.push( 'left-out-of-bounds' ); + } + if ( rect.top < bounds.minTop - EPSILON ) { + violations.push( 'top-out-of-bounds' ); + } + if ( right > bounds.maxRight + EPSILON ) { + violations.push( 'right-out-of-bounds' ); + } + if ( bottom > bounds.maxBottom + EPSILON ) { + violations.push( 'bottom-out-of-bounds' ); + } + if ( rect.width < bounds.minWidth - EPSILON ) { + violations.push( 'width-too-small' ); + } + if ( rect.width > bounds.maxWidth + EPSILON ) { + violations.push( 'width-too-large' ); + } + if ( rect.height < bounds.minHeight - EPSILON ) { + violations.push( 'height-too-small' ); + } + if ( rect.height > bounds.maxHeight + EPSILON ) { + violations.push( 'height-too-large' ); + } + + const clamped = clampCropPixelRectToBounds( rect, bounds ); + if ( violations.length === 0 ) { + return { ok: true, rect: clamped }; + } + return { ok: false, rect: clamped, violations }; +} + +/** + * Get current crop geometry and source-region data for controls, automation, + * and AI workflows. + * + * @param input Crop geometry input. + * @return Crop geometry snapshot, or null when geometry is not ready. + */ +export function getCropGeometrySnapshot( + input: CropGeometryInput +): CropGeometrySnapshot | null { + const imageBounds = getCropPixelImageBounds( input ); + + if ( ! imageBounds ) { + return null; + } + + return { + rect: getCropPixelRect( input.state, input.imageSize ), + imageBounds, + sourceRegion: getSourceRegion( input.state, input.imageSize ), + }; +} diff --git a/packages/media-editor/src/image-editor/core/fine-rotation.ts b/packages/media-editor/src/image-editor/core/fine-rotation.ts new file mode 100644 index 00000000000000..df295e966ab678 --- /dev/null +++ b/packages/media-editor/src/image-editor/core/fine-rotation.ts @@ -0,0 +1,126 @@ +import { MAX_ROTATION_OFFSET } from './constants'; +import type { Flip } from './types'; + +const FINE_ROTATION_EPSILON = 1e-6; +/** + * Distance to keep absolute rotations strictly inside the ±MAX boundary. + * + * Landing rotation exactly on a 90° midpoint (e.g., 45°, -45°, 135°) makes + * the next render's `Math.round(rotation / 90) * 90` snap base flip, which + * reverses the derived offset sign and lets the cropper spiral past its + * intended ±MAX range on successive edits. A small pullback keeps the + * offset stably representable in the same snap base. + */ +const FINE_ROTATION_BOUNDARY_EPSILON = 0.01; +const FINE_ROTATION_SAFE_MAX = + MAX_ROTATION_OFFSET - FINE_ROTATION_BOUNDARY_EPSILON; + +/** + * Normalize the internal boundary pullback back to the advertised endpoint. + * + * The cropper stores ±44.99° instead of ±45° to keep snap-base derivation + * stable, but the fine-rotation control should still read that state as the + * public ±45° endpoint it committed. + * + * @param offset Signed fine-rotation offset in degrees. + * @return Offset normalized for display and consumers. + */ +function normalizeOffsetForDisplay( offset: number ): number { + const absOffset = Math.abs( offset ); + + if ( absOffset >= FINE_ROTATION_SAFE_MAX - FINE_ROTATION_EPSILON ) { + return Math.sign( offset ) * MAX_ROTATION_OFFSET; + } + + return offset; +} + +/** + * Fine-rotation policy: discrete `±MAX_ROTATION_OFFSET` adjustment around the + * current 90° snap, exposed to the advanced crop panel, the bottom toolbar + * ruler, and any automation that needs to read or write the visual rotation + * offset directly. + * + * `offset` is signed in viewport space: a positive offset rotates the framed + * content clockwise on screen regardless of the underlying flip state. Use + * `absoluteFromOffset` to convert back to the absolute angle the cropper + * stores in `state.rotation`. + */ +export const fineRotation = { + step: 0.5, + min: -MAX_ROTATION_OFFSET, + max: MAX_ROTATION_OFFSET, + + /** + * Visual rotation direction for the current flip state. + * + * Single-axis flips invert the apparent rotation direction; matching flips + * (none or both) leave it alone. + * + * @param flip Cropper flip state. + * @return 1 or -1. + */ + visualDirection( flip: Flip ): 1 | -1 { + return flip.horizontal !== flip.vertical ? -1 : 1; + }, + + /** + * Read the current fine-rotation offset from an absolute rotation angle. + * + * @param rotation Absolute rotation in degrees from cropper state. + * @param flip Cropper flip state. + * @return Signed offset in degrees relative to the nearest 90° snap. + */ + offsetFromState( rotation: number, flip: Flip ): number { + const baseAngle = Math.round( rotation / 90 ) * 90; + return normalizeOffsetForDisplay( + ( rotation - baseAngle ) * this.visualDirection( flip ) + ); + }, + + /** + * Compute the absolute rotation angle that produces the given offset. + * + * The offset is pulled strictly inside the ±MAX boundary by a small + * epsilon before being applied. Without this, an exact-boundary commit + * lands `state.rotation` on a 90° midpoint where the snap-base derivation + * flips on the next render, causing subsequent edits to spiral past the + * intended range. + * + * @param rotation Current absolute rotation (used to derive the snap base). + * @param flip Cropper flip state. + * @param offset Signed offset in degrees in viewport space. + * @return Absolute rotation angle to pass to `setRotation`. + */ + absoluteFromOffset( rotation: number, flip: Flip, offset: number ): number { + const baseAngle = Math.round( rotation / 90 ) * 90; + const safeOffset = Math.max( + -FINE_ROTATION_SAFE_MAX, + Math.min( FINE_ROTATION_SAFE_MAX, offset ) + ); + return baseAngle + safeOffset * this.visualDirection( flip ); + }, + + /** + * Clamp a candidate offset to the fine-rotation range, snapped to the + * commit step. + * + * @param value Candidate offset in degrees. + * @return Clamped, step-snapped offset. + */ + clamp( value: number ): number { + const snapped = Math.round( value / this.step ) * this.step; + return Math.max( this.min, Math.min( this.max, snapped ) ); + }, + + /** + * Whether two offsets differ by more than the floating-point tolerance. + * + * @param a First offset. + * @param b Second offset. + * @return True when the offsets are meaningfully different. + */ + hasChanged( a: number, b: number ): boolean { + return Math.abs( a - b ) >= FINE_ROTATION_EPSILON; + }, +} as const; diff --git a/packages/media-editor/src/image-editor/core/index.ts b/packages/media-editor/src/image-editor/core/index.ts index fefb9543130489..5f505bbaa677d9 100644 --- a/packages/media-editor/src/image-editor/core/index.ts +++ b/packages/media-editor/src/image-editor/core/index.ts @@ -37,6 +37,26 @@ export type { SourceRegion, SourceRegionPercent } from './source-region'; // Crop-rect helpers export { computeInscribedRect } from './crop-rect'; +// Crop geometry +export { + applyCropEdit, + clampCropPixelRectToBounds, + cropPixelRectToNormalizedRect, + getCropPixelRect, + validateCropPixelRectAgainstBounds, +} from './crop-geometry'; +export type { + CropEditField, + CropPixelRect, + CropPixelRectBounds, + CropPixelRectCheck, + CropPixelRectInput, + CropPixelRectViolation, +} from './crop-geometry'; + +// Fine rotation policy +export { fineRotation } from './fine-rotation'; + // Pipeline export { applyOperationToState, diff --git a/packages/media-editor/src/image-editor/core/test/crop-geometry.ts b/packages/media-editor/src/image-editor/core/test/crop-geometry.ts new file mode 100644 index 00000000000000..d3d7b4a99b39ea --- /dev/null +++ b/packages/media-editor/src/image-editor/core/test/crop-geometry.ts @@ -0,0 +1,294 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_STATE } from '../constants'; +import { + applyCropEdit, + clampCropPixelRectToBounds, + cropPixelRectToNormalizedRect, + getCropGeometrySnapshot, + getCropPixelRect, + validateCropPixelRectAgainstBounds, + type CropGeometryInput, + type CropPixelRectCheck, + type CropPixelRectViolation, + type NormalizedCropBounds, +} from '../crop-geometry'; +import type { CropperState, Size } from '../types'; + +function violationsOf( check: CropPixelRectCheck ): CropPixelRectViolation[] { + return check.ok ? [] : check.violations; +} + +const IMAGE: Size = { width: 1000, height: 500 }; +const IMAGE_BOUNDS: NormalizedCropBounds = { + minX: 0, + minY: 0, + maxX: 1, + maxY: 1, +}; + +function makeState( overrides: Partial< CropperState > = {} ): CropperState { + return { + ...DEFAULT_STATE, + image: { + src: 'test.jpg', + naturalWidth: IMAGE.width, + naturalHeight: IMAGE.height, + }, + ...overrides, + }; +} + +function makeInput( + overrides: Partial< CropGeometryInput > = {} +): CropGeometryInput { + return { + state: makeState( { + cropRect: { x: 0.2, y: 0.2, width: 0.4, height: 0.4 }, + } ), + imageSize: IMAGE, + imageBounds: IMAGE_BOUNDS, + ...overrides, + }; +} + +describe( 'crop pixel geometry', () => { + it( 'converts cropper state to snap-rotation pixels', () => { + const rect = getCropPixelRect( makeInput().state, IMAGE ); + + expect( rect.left ).toBeCloseTo( 200 ); + expect( rect.top ).toBeCloseTo( 100 ); + expect( rect.width ).toBeCloseTo( 400 ); + expect( rect.height ).toBeCloseTo( 200 ); + expect( rect.right ).toBeCloseTo( 600 ); + expect( rect.bottom ).toBeCloseTo( 300 ); + } ); + + it( 'round-trips pixel rectangles through normalized cropper space', () => { + const state = makeInput().state; + const rect = getCropPixelRect( state, IMAGE ); + const normalized = cropPixelRectToNormalizedRect( rect, state, IMAGE ); + + expect( normalized.x ).toBeCloseTo( state.cropRect.x ); + expect( normalized.y ).toBeCloseTo( state.cropRect.y ); + expect( normalized.width ).toBeCloseTo( state.cropRect.width ); + expect( normalized.height ).toBeCloseTo( state.cropRect.height ); + } ); + + it( 'computes image edge bounds in crop pixels', () => { + const imageBounds = getCropGeometrySnapshot( makeInput() )?.imageBounds; + + expect( imageBounds?.minLeft ).toBeCloseTo( 0 ); + expect( imageBounds?.minTop ).toBeCloseTo( 0 ); + expect( imageBounds?.maxRight ).toBeCloseTo( 1000 ); + expect( imageBounds?.maxBottom ).toBeCloseTo( 500 ); + expect( imageBounds?.minWidth ).toBeCloseTo( 50 ); + expect( imageBounds?.minHeight ).toBeCloseTo( 25 ); + expect( imageBounds?.maxWidth ).toBeCloseTo( 1000 ); + expect( imageBounds?.maxHeight ).toBeCloseTo( 500 ); + } ); + + it( 'returns null before image bounds are ready', () => { + const snapshot = getCropGeometrySnapshot( { + ...makeInput(), + imageBounds: undefined, + } ); + + expect( snapshot ).toBeNull(); + } ); + + it( 'returns a full geometry snapshot when geometry is ready', () => { + const snapshot = getCropGeometrySnapshot( makeInput() ); + + expect( snapshot?.rect.left ).toBeCloseTo( 200 ); + expect( snapshot?.imageBounds.maxRight ).toBeCloseTo( 1000 ); + expect( snapshot?.sourceRegion.width ).toBeCloseTo( 400 ); + } ); +} ); + +describe( 'validateCropPixelRectAgainstBounds', () => { + const imageBounds = getCropGeometrySnapshot( makeInput() )!.imageBounds; + + it( 'accepts rectangles within the provided bounds', () => { + const result = validateCropPixelRectAgainstBounds( + { left: 100, top: 50, width: 400, height: 200 }, + imageBounds + ); + + expect( result.ok ).toBe( true ); + expect( result.rect ).toEqual( { + left: 100, + top: 50, + width: 400, + height: 200, + right: 500, + bottom: 250, + } ); + } ); + + it( 'reports and clamps rectangles outside the provided bounds', () => { + const result = validateCropPixelRectAgainstBounds( + { left: -20, top: 10, width: 1200, height: 600 }, + imageBounds + ); + + expect( result.ok ).toBe( false ); + expect( violationsOf( result ) ).toEqual( + expect.arrayContaining( [ + 'left-out-of-bounds', + 'right-out-of-bounds', + 'bottom-out-of-bounds', + 'width-too-large', + 'height-too-large', + ] ) + ); + expect( result.rect ).toEqual( { + left: 0, + top: 0, + width: 1000, + height: 500, + right: 1000, + bottom: 500, + } ); + } ); + + it( 'reports and clamps rectangles smaller than the stencil minimum', () => { + const result = validateCropPixelRectAgainstBounds( + { left: 100, top: 50, width: 10, height: 10 }, + imageBounds + ); + + expect( result.ok ).toBe( false ); + expect( violationsOf( result ) ).toEqual( + expect.arrayContaining( [ 'width-too-small', 'height-too-small' ] ) + ); + expect( result.rect.width ).toBeCloseTo( imageBounds.minWidth ); + expect( result.rect.height ).toBeCloseTo( imageBounds.minHeight ); + } ); + + it( 'sanitizes non-finite values while reporting them', () => { + const result = validateCropPixelRectAgainstBounds( + { left: Number.NaN, top: 10, width: 100, height: Infinity }, + imageBounds + ); + + expect( result.ok ).toBe( false ); + expect( violationsOf( result ) ).toContain( 'non-finite' ); + expect( result.rect.left ).toBe( imageBounds.minLeft ); + expect( result.rect.height ).toBe( imageBounds.minHeight ); + } ); + + it( 'tolerates sub-epsilon drift without flagging it as invalid', () => { + const result = validateCropPixelRectAgainstBounds( + { + left: imageBounds.minLeft - 1e-9, + top: 50, + width: 400, + height: 200, + }, + imageBounds + ); + + expect( result.ok ).toBe( true ); + expect( result.rect.left ).toBe( imageBounds.minLeft ); + } ); +} ); + +describe( 'clampCropPixelRectToBounds', () => { + it( 'fits a rectangle into the provided bounds', () => { + const imageBounds = getCropGeometrySnapshot( makeInput() )!.imageBounds; + const rect = clampCropPixelRectToBounds( + { left: 900, top: 450, width: 200, height: 100 }, + imageBounds + ); + + expect( rect ).toEqual( { + left: 800, + top: 400, + width: 200, + height: 100, + right: 1000, + bottom: 500, + } ); + } ); +} ); + +describe( 'applyCropEdit', () => { + const imageBounds = getCropGeometrySnapshot( makeInput() )!.imageBounds; + const startRect = { left: 100, top: 50, width: 400, height: 200 }; + + it( 'applies a left edit and clamps to bounds', () => { + const rect = applyCropEdit( startRect, 'left', -50, { + bounds: imageBounds, + } ); + + expect( rect.left ).toBe( imageBounds.minLeft ); + expect( rect.width ).toBe( 400 ); + } ); + + it( 'applies a width edit', () => { + const rect = applyCropEdit( startRect, 'width', 600, { + bounds: imageBounds, + } ); + + expect( rect.width ).toBe( 600 ); + expect( rect.height ).toBe( 200 ); + } ); + + it( 'couples height to width under an aspect ratio lock', () => { + const rect = applyCropEdit( startRect, 'width', 600, { + aspectRatio: 2, + bounds: imageBounds, + } ); + + expect( rect.width ).toBe( 600 ); + expect( rect.height ).toBe( 300 ); + } ); + + it( 'couples width to height under an aspect ratio lock', () => { + const rect = applyCropEdit( startRect, 'height', 100, { + aspectRatio: 2, + bounds: imageBounds, + } ); + + expect( rect.height ).toBe( 100 ); + expect( rect.width ).toBe( 200 ); + } ); + + it( 'clamps an oversized width to the image bounds', () => { + const rect = applyCropEdit( startRect, 'width', 9999, { + bounds: imageBounds, + } ); + + expect( rect.width ).toBe( imageBounds.maxWidth ); + } ); + + it( 'clamps an oversized width to aspect-ratio-safe image bounds', () => { + const rect = applyCropEdit( startRect, 'width', 9999, { + aspectRatio: 4, + bounds: imageBounds, + } ); + + expect( rect.width ).toBe( imageBounds.maxWidth ); + expect( rect.height ).toBe( 250 ); + } ); + + it( 'clamps an oversized height to aspect-ratio-safe image bounds', () => { + const rect = applyCropEdit( startRect, 'height', 9999, { + aspectRatio: 4, + bounds: imageBounds, + } ); + + expect( rect.width ).toBe( imageBounds.maxWidth ); + expect( rect.height ).toBe( 250 ); + } ); + + it( 'clamps undersized aspect-ratio edits to the coupled minimum size', () => { + const rect = applyCropEdit( startRect, 'width', 1, { + aspectRatio: 4, + bounds: imageBounds, + } ); + + expect( rect.width ).toBe( 100 ); + expect( rect.height ).toBe( imageBounds.minHeight ); + } ); +} ); diff --git a/packages/media-editor/src/image-editor/core/test/fine-rotation.ts b/packages/media-editor/src/image-editor/core/test/fine-rotation.ts new file mode 100644 index 00000000000000..d34051b6ef2d57 --- /dev/null +++ b/packages/media-editor/src/image-editor/core/test/fine-rotation.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest'; +import { fineRotation } from '../fine-rotation'; + +const NO_FLIP = { horizontal: false, vertical: false }; +const HORIZONTAL_FLIP = { horizontal: true, vertical: false }; + +describe( 'fineRotation', () => { + it( 'stores a safe value at the positive boundary and reads it as the advertised endpoint', () => { + const rotation = fineRotation.absoluteFromOffset( + 0, + NO_FLIP, + fineRotation.max + ); + + expect( rotation ).toBe( 44.99 ); + expect( fineRotation.offsetFromState( rotation, NO_FLIP ) ).toBe( + fineRotation.max + ); + } ); + + it( 'stores a safe value at the negative boundary and reads it as the advertised endpoint', () => { + const rotation = fineRotation.absoluteFromOffset( + 0, + NO_FLIP, + fineRotation.min + ); + + expect( rotation ).toBe( -44.99 ); + expect( fineRotation.offsetFromState( rotation, NO_FLIP ) ).toBe( + fineRotation.min + ); + } ); + + it( 'normalizes boundary offsets through flipped visual direction', () => { + const rotation = fineRotation.absoluteFromOffset( + 0, + HORIZONTAL_FLIP, + fineRotation.max + ); + + expect( rotation ).toBe( -44.99 ); + expect( + fineRotation.offsetFromState( rotation, HORIZONTAL_FLIP ) + ).toBe( fineRotation.max ); + } ); +} ); diff --git a/packages/media-editor/src/image-editor/docs/recipes.md b/packages/media-editor/src/image-editor/docs/recipes.md index 49bcdcb6488b0e..0a51dfb09a095d 100644 --- a/packages/media-editor/src/image-editor/docs/recipes.md +++ b/packages/media-editor/src/image-editor/docs/recipes.md @@ -118,6 +118,38 @@ const percent = getSourceRegionPercent( controller.state, imageSize ); `getSourceRegionPercent()` matches the crop data shape used by the WordPress attachments `/edit` endpoint. +## Validate Pixel Crop Edits + +Use pixel geometry helpers when manual controls or automation need to validate a crop rectangle before committing it. +`useCropGeometry()` reads from `CropperProvider`, so call it from a component +rendered inside that provider. + +```ts +import { + applyCropEdit, + cropPixelRectToNormalizedRect, + useCropGeometry, +} from '../image-editor'; + +const geometry = useCropGeometry(); + +if ( geometry.isReady ) { + const next = applyCropEdit( geometry.rect, 'width', 640, { + aspectRatio, + bounds: geometry.imageBounds, + } ); + + controller.setCropRect( + cropPixelRectToNormalizedRect( next, controller.state, { + width: controller.state.image.naturalWidth, + height: controller.state.image.naturalHeight, + } ) + ); +} +``` + +The pixel helpers use the current image-bound constraints, so callers can reject, clamp, or preview generated crop values before mutating cropper state. + ## Export a Cropped Image ```ts diff --git a/packages/media-editor/src/image-editor/index.ts b/packages/media-editor/src/image-editor/index.ts index 27f754d2e5da1f..030942add29959 100644 --- a/packages/media-editor/src/image-editor/index.ts +++ b/packages/media-editor/src/image-editor/index.ts @@ -8,9 +8,17 @@ */ // React surface. -export { useCropperReducer, buildCropperSetters } from './react/hooks'; +export { + useCropperReducer, + buildCropperSetters, + useCropGeometry, +} from './react/hooks'; export { Cropper, CropperProvider, useCropper } from './react/components'; -export type { CropperController, CropperSetters } from './react/hooks'; +export type { + CropperController, + CropperSetters, + UseCropGeometryReturn, +} from './react/hooks'; export type { CropperProps } from './react/components'; // State and extension types. @@ -38,6 +46,12 @@ export { enforceContainment, areCropperStatesEqual, computeInscribedRect, + applyCropEdit, + clampCropPixelRectToBounds, + cropPixelRectToNormalizedRect, + getCropPixelRect, + validateCropPixelRectAgainstBounds, + fineRotation, getSourceRegion, getSourceRegionPercent, applyOperationToState, @@ -47,6 +61,12 @@ export { } from './core'; export type { AspectRatioPreset, + CropEditField, + CropPixelRect, + CropPixelRectBounds, + CropPixelRectCheck, + CropPixelRectInput, + CropPixelRectViolation, SourceRegion, SourceRegionPercent, } from './core'; diff --git a/packages/media-editor/src/image-editor/react/components/cropper-provider.tsx b/packages/media-editor/src/image-editor/react/components/cropper-provider.tsx index e0e16cace3fb0b..b3c87683583bf2 100644 --- a/packages/media-editor/src/image-editor/react/components/cropper-provider.tsx +++ b/packages/media-editor/src/image-editor/react/components/cropper-provider.tsx @@ -1,70 +1,167 @@ -import { createContext, useContext } from '@wordpress/element'; +import { + createContext, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from '@wordpress/element'; import { useCropperReducer, type CropperController, } from '../hooks/use-cropper-reducer'; -import type { CropperState } from '../../core/types'; +import { + useDerivedCropperMeasurements, + type CropperMeasurements, +} from '../hooks/use-derived-cropper-measurements'; +import type { CropperState, Size } from '../../core/types'; -/** - * The context value type for the CropperProvider. - * Contains the cropper controller from useCropperReducer. - */ -type CropperContextValue = CropperController | null; +export type { CropperMeasurements }; -const CropperContext = createContext< CropperContextValue >( null ); +interface CropperContextValue { + controller: CropperController; + canvasSize: Size; + setCanvasSize: ( size: Size ) => void; + measurements: CropperMeasurements; + previewCropRect: CropperState[ 'cropRect' ] | null; + setPreviewCropRect: ( rect: CropperState[ 'cropRect' ] | null ) => void; +} + +const CropperContext = createContext< CropperContextValue | null >( null ); + +const ZERO_SIZE: Size = { width: 0, height: 0 }; -/** - * Props for the CropperProvider component. - */ interface CropperProviderProps { /** Optional partial initial state to merge with defaults. */ initialState?: Partial< CropperState >; + /** Optional controller supplied by a composite store. */ + controller?: CropperController; /** Child components. */ children: React.ReactNode; } /** - * Convenience context provider that wraps `useCropperReducer`. + * Context provider for shared cropper state, measurements, and previews. * - * Provides the pure cropper controller (state + setters, NO undo - * history) to all descendant components via React context. + * By default this creates a pure `useCropperReducer` controller. Composite + * stores such as the media editor can pass their own controller so sidebar + * controls, geometry helpers, and the canvas all read the same state. * - * History is a higher-layer concern owned by composite stores - * (see `useMediaEditorState` in media-editor/state for the media - * editor's composite controller with undo/redo). - * - * @param props - * @param props.initialState - * @param props.children - * @return The provider element wrapping children. + * @param props Provider props. + * @param props.initialState Optional partial initial state. + * @param props.controller Optional externally owned controller. + * @param props.children Provider children. */ export function CropperProvider( { initialState, + controller: externalController, children, }: CropperProviderProps ) { - const cropperReturn = useCropperReducer( initialState ); + const ownedController = useCropperReducer( initialState ); + const controller = externalController ?? ownedController; + const [ canvasSize, setCanvasSize ] = useState< Size >( ZERO_SIZE ); + const [ previewCropRect, setPreviewCropRect ] = useState< + CropperState[ 'cropRect' ] | null + >( null ); + const previousStateRef = useRef( controller.state ); + const measurements = useDerivedCropperMeasurements( + controller.state, + canvasSize + ); + + useEffect( () => { + if ( previousStateRef.current === controller.state ) { + return; + } + previousStateRef.current = controller.state; + setPreviewCropRect( null ); + }, [ controller.state ] ); + + const value = useMemo< CropperContextValue >( + () => ( { + controller, + canvasSize, + setCanvasSize, + measurements, + previewCropRect, + setPreviewCropRect, + } ), + [ controller, canvasSize, measurements, previewCropRect ] + ); return ( - + { children } ); } +function useCropperContext(): CropperContextValue { + const context = useContext( CropperContext ); + if ( ! context ) { + throw new Error( + 'Cropper hooks must be used within a CropperProvider.' + ); + } + return context; +} + /** - * Hook to consume the CropperProvider context. + * Hook to consume the cropper state controller. * - * Must be used within a CropperProvider. Throws if used outside - * of the provider tree. + * Must be used within a `CropperProvider`. Throws if used outside. * - * @return The cropper controller. + * @return The cropper state and action creators. */ export function useCropper(): CropperController { - const context = useContext( CropperContext ); + return useCropperContext().controller; +} - if ( ! context ) { - throw new Error( 'useCropper must be used within a CropperProvider.' ); - } +/** + * Hook to consume the derived cropper measurements (`elementSize`, + * `visualSize`, `cropBounds`). + * + * @return Measurements derived from the cropper state and measured canvas. + */ +export function useCropperMeasurements(): CropperMeasurements { + return useCropperContext().measurements; +} - return context; +/** + * Hook used by panel components inside a `CropperProvider` to publish a + * non-committed crop rectangle preview. Throws without a Provider because + * there is no preview channel to publish to. + * + * @return Setter for the draft crop rectangle; pass `null` to clear it. + */ +export function useSetCropperPreviewRect(): ( + rect: CropperState[ 'cropRect' ] | null +) => void { + return useCropperContext().setPreviewCropRect; +} + +/** + * Hook used by `` to read the current draft crop rectangle. Also + * works for standalone `` mounts that have no Provider above them; + * those will always see `null`. + * + * @return Current draft crop rectangle, or null when no preview is active. + */ +export function useOptionalCropperPreviewRect(): + CropperState[ 'cropRect' ] | null { + return useContext( CropperContext )?.previewCropRect ?? null; } + +/** + * Hook used by `` to publish its measured canvas size into the + * Provider. When no Provider is mounted, returns a noop so the component + * still renders in standalone usage. + * + * @return Setter for the canvas size, or a noop outside a CropperProvider. + */ +export function useOptionalSetCropperCanvasSize(): ( size: Size ) => void { + const context = useContext( CropperContext ); + return context?.setCanvasSize ?? noopSetCanvasSize; +} + +function noopSetCanvasSize() {} diff --git a/packages/media-editor/src/image-editor/react/components/cropper.scss b/packages/media-editor/src/image-editor/react/components/cropper.scss index 2ac3f6fdb2e5b9..9de071a4fdd93d 100644 --- a/packages/media-editor/src/image-editor/react/components/cropper.scss +++ b/packages/media-editor/src/image-editor/react/components/cropper.scss @@ -62,6 +62,7 @@ $handle-touch-target-size: 44px; &__stencil { position: absolute; pointer-events: none; + transition: opacity 0.15s ease; } &__dimming { @@ -142,6 +143,23 @@ $handle-touch-target-size: 44px; transition: border-color 0.15s ease, box-shadow 0.15s ease; } + // Matches `__stencil-rect` deliberately. While a preview is active the + // real stencil is hidden so the preview rect stands in for it visually, + // reading as "the crop moved" rather than "a separate preview UI". + // No geometry transition: the dimming and grid update instantly when + // `cropRect` changes, so transitioning the rect alone makes the border + // visibly catch up to the rest of the framing. + &__preview-rect { + position: absolute; + border: 1px solid rgba(255, 255, 255, 0.7); + box-sizing: border-box; + pointer-events: none; + } + + &__canvas--previewing &__stencil { + opacity: 0; + } + // Blue border on the crop rectangle when the canvas has keyboard focus. // Uses a JS-controlled class rather than :focus-visible — browsers can // restore :focus-visible across programmatic focus calls, making pure diff --git a/packages/media-editor/src/image-editor/react/components/cropper.tsx b/packages/media-editor/src/image-editor/react/components/cropper.tsx index 4673d950baefbb..de5772f10652ce 100644 --- a/packages/media-editor/src/image-editor/react/components/cropper.tsx +++ b/packages/media-editor/src/image-editor/react/components/cropper.tsx @@ -18,8 +18,8 @@ import type { NormalizedRect, } from '../../core/types'; import type { CropperController } from '../hooks/use-cropper-reducer'; -import { getImageFit, getRotatedBBox, getViewScale } from '../../core/camera'; -import { getImageCropBounds, getMinZoom } from '../../core/containment'; +import { getRotatedBBox, getViewScale } from '../../core/camera'; +import { getMinZoom } from '../../core/containment'; import { MAX_VIEW_SCALE, PIXEL_SNAP_DISPLAY_SCALE, @@ -30,6 +30,7 @@ import { getMinCropPixels } from '../../core/stencil-math'; import { useInteraction } from '../hooks/use-interaction'; import { useTransformStyle } from '../hooks/use-transform-style'; import { useAriaAnnouncer } from '../hooks/use-aria-announcer'; +import { useDerivedCropperMeasurements } from '../hooks/use-derived-cropper-measurements'; import { RectangleStencil } from './stencils/rectangle-stencil'; import { DimmingOverlay } from './overlays/dimming-overlay'; import { GridOverlay } from './overlays/grid-overlay'; @@ -39,8 +40,13 @@ import { snapCropRectToSourcePixelGrid, snapCropRectToSourcePixels, } from '../../core/source-region'; +import { CropPreviewOverlay } from './overlays/crop-preview-overlay'; import { ViewportProvider, useViewport } from './viewport-provider'; import { VISUALLY_HIDDEN_STYLE } from '../visually-hidden-style'; +import { + useOptionalCropperPreviewRect, + useOptionalSetCropperCanvasSize, +} from './cropper-provider'; /** Threshold for comparing normalized crop rect values. */ const CROP_RECT_EPSILON = 1e-6; @@ -187,6 +193,8 @@ function CropperInner( setViewportPan, resetViewport, } = useViewport(); + const setCropperCanvasSize = useOptionalSetCropperCanvasSize(); + const previewCropRect = useOptionalCropperPreviewRect(); // 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. @@ -277,18 +285,29 @@ function CropperInner( // via the centralized @wordpress/a11y speak() API called inside the hook. useAriaAnnouncer( state ); - // Compute fitted image dimensions and visual bounds from camera math. const naturalWidth = state.image?.naturalWidth ?? 0; const naturalHeight = state.image?.naturalHeight ?? 0; - const { elementSize, visualSize } = useMemo( - () => - getImageFit( - canvasSize, - { width: naturalWidth, height: naturalHeight }, - state.rotation - ), - [ canvasSize, naturalWidth, naturalHeight, state.rotation ] - ); + + // Local derivation of fitted dimensions, visual bounds, and normalized + // crop bounds. The same hook runs inside `` when present, + // so sibling consumers (advanced panel, automation) see the same numbers + // without a separate derived-state write-back. + const { elementSize, visualSize, cropBounds } = + useDerivedCropperMeasurements( state, canvasSize ); + + // Publish raw `canvasSize` so the Provider's central derivation stays in + // sync. Silently noops outside a Provider. + useEffect( () => { + setCropperCanvasSize( canvasSize ); + }, [ canvasSize, setCropperCanvasSize ] ); + + // The Provider can outlive this canvas if the cropper is hidden + // conditionally; clear the measurement so consumers become unready. + useEffect( () => { + return () => { + setCropperCanvasSize( { width: 0, height: 0 } ); + }; + }, [ setCropperCanvasSize ] ); // Report the rendered image size to the controller. Composite // controllers need it to compute aspect-ratio reshapes from the @@ -374,17 +393,6 @@ function CropperInner( state.cropRect, ] ); - // Compute the crop handle bounds from the actual image footprint. - // Depends on the full state object because getImageCropBounds reads - // crop, zoom, rotation, flip, and image. React Compiler requires - // the complete dependency; the computation is lightweight (a few - // trig ops + 4 corner transforms). - const cropBounds = useMemo( () => { - if ( ! state.image || elementSize.width === 0 ) { - return undefined; - } - return getImageCropBounds( state, elementSize, visualSize ); - }, [ state, elementSize, visualSize ] ); const effectiveMinZoom = minZoom !== undefined ? minZoom : getMinZoom( state ); const [ isResizing, setIsResizing ] = useState( false ); @@ -1010,6 +1018,8 @@ function CropperInner( 'wp-media-editor-image-editor__canvas--show-grid', settling && 'wp-media-editor-image-editor__canvas--settling', + previewCropRect && + 'wp-media-editor-image-editor__canvas--previewing', // Marks the cropper as in keyboard-interaction mode. // CSS uses :focus on the canvas to show the stencil // outline and :focus on a handle to show its ring, @@ -1060,10 +1070,13 @@ function CropperInner( draggable={ false } /> - { /* Dimming overlay outside the crop area */ } + { /* Dimming overlay outside the crop area. Follows the + preview rect when one is active so the framed area + reads as "the crop moved" rather than a separate + overlay on top of the still-framed original. */ } { showDimming && ( - { /* Rule-of-thirds grid */ } + { /* Rule-of-thirds grid. Follows the preview rect when + one is active so the framing reads as "the crop + moved" together with the dimming overlay. */ } { ( showGrid === true || isInteractiveGrid ) && ( @@ -1109,6 +1124,14 @@ function CropperInner( outputHeight={ outputSize.height } /> ) } + + { previewCropRect && ( + + ) }
diff --git a/packages/media-editor/src/image-editor/react/components/index.ts b/packages/media-editor/src/image-editor/react/components/index.ts index b590b121f99621..3425efdb6be384 100644 --- a/packages/media-editor/src/image-editor/react/components/index.ts +++ b/packages/media-editor/src/image-editor/react/components/index.ts @@ -1,3 +1,8 @@ export { Cropper } from './cropper'; export type { CropperProps } from './cropper'; -export { CropperProvider, useCropper } from './cropper-provider'; +export { + CropperProvider, + useCropper, + useCropperMeasurements, +} from './cropper-provider'; +export type { CropperMeasurements } from './cropper-provider'; diff --git a/packages/media-editor/src/image-editor/react/components/overlays/crop-preview-overlay.tsx b/packages/media-editor/src/image-editor/react/components/overlays/crop-preview-overlay.tsx new file mode 100644 index 00000000000000..ac64d11a6f09c5 --- /dev/null +++ b/packages/media-editor/src/image-editor/react/components/overlays/crop-preview-overlay.tsx @@ -0,0 +1,42 @@ +import type { NormalizedRect, Size } from '../../../core/types'; + +interface CropPreviewOverlayProps { + cropRect: NormalizedRect; + containerSize: Size; + imageSize: Size; +} + +/** + * Renders a non-interactive draft crop rectangle while sidebar controls are + * being edited. + * + * @param props Component props. + * @param props.cropRect Draft crop rectangle in normalized coordinates. + * @param props.containerSize The container element dimensions in pixels. + * @param props.imageSize The rendered image dimensions in pixels. + * @return The preview overlay, or null before measurement. + */ +export function CropPreviewOverlay( { + cropRect, + containerSize, + imageSize, +}: CropPreviewOverlayProps ) { + if ( containerSize.width === 0 || containerSize.height === 0 ) { + return null; + } + + const offsetX = ( containerSize.width - imageSize.width ) / 2; + const offsetY = ( containerSize.height - imageSize.height ) / 2; + const left = offsetX + cropRect.x * imageSize.width; + const top = offsetY + cropRect.y * imageSize.height; + const width = cropRect.width * imageSize.width; + const height = cropRect.height * imageSize.height; + + return ( +
+ ); +} diff --git a/packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx b/packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx index 68abd699a4491f..5d60d982bc4565 100644 --- a/packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx +++ b/packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx @@ -2,8 +2,15 @@ import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'; import { userEvent } from 'vitest/browser'; import { act, fireEvent, screen, waitFor } from '@testing-library/react'; import { render } from 'vitest-browser-react'; +import { useEffect, useState } from '@wordpress/element'; import { Cropper } from '../cropper'; import type { CropperController } from '../../hooks/use-cropper-reducer'; +import { + CropperProvider, + useCropper, + useCropperMeasurements, + useSetCropperPreviewRect, +} from '../cropper-provider'; import { DEFAULT_STATE } from '../../../core/constants'; import { getSourceRegion } from '../../../core/source-region'; // Browser Mode needs the package's real styles for layout and transitions. @@ -11,6 +18,7 @@ import { getSourceRegion } from '../../../core/source-region'; import '../../../style.scss'; const GRID_TEST_ID = 'cropper-grid'; +const PREVIEW_RECT_TEST_ID = 'cropper-preview-rect'; const GRID_INTERACTIVE_CLASS = 'wp-media-editor-image-editor__canvas--grid-interactive'; const SHOW_GRID_CLASS = 'wp-media-editor-image-editor__canvas--show-grid'; @@ -44,6 +52,93 @@ function createController(): CropperController { }; } +function CropperWithPreview() { + const controller = useCropper(); + const setPreviewCropRect = useSetCropperPreviewRect(); + + useEffect( () => { + setPreviewCropRect( { + x: 0.2, + y: 0.2, + width: 0.3, + height: 0.3, + } ); + }, [ setPreviewCropRect ] ); + + return ( + + ); +} + +function CropperWithPreviewControls() { + const controller = useCropper(); + const setPreviewCropRect = useSetCropperPreviewRect(); + + return ( + <> + + + + + ); +} + +function CropperMeasurementLifecycle() { + const controller = useCropper(); + const { elementSize } = useCropperMeasurements(); + const [ isMounted, setIsMounted ] = useState( true ); + + return ( + <> + +
+ { elementSize.width > 0 ? 'ready' : 'unready' } +
+ { isMounted && ( + + ) } + + ); +} + function CropperFixture( { children }: { children: React.ReactNode } ) { return
{ children }
; } @@ -103,6 +198,91 @@ describe( 'Cropper', () => { expect( canvas ).not.toHaveClass( SHOW_GRID_CLASS ); } ); + it( 'renders a draft crop preview from provider state', async () => { + await renderCropper( + + + + ); + + expect( + await screen.findByTestId( PREVIEW_RECT_TEST_ID ) + ).toBeInTheDocument(); + } ); + + it( 'clears a draft crop preview when cropper state changes', async () => { + await renderCropper( + + + + ); + + await userEvent.click( + screen.getByRole( 'button', { name: 'Preview' } ) + ); + expect( + await screen.findByTestId( PREVIEW_RECT_TEST_ID ) + ).toBeInTheDocument(); + + await userEvent.click( + screen.getByRole( 'button', { name: 'Change crop' } ) + ); + + await waitFor( () => + expect( + screen.queryByTestId( PREVIEW_RECT_TEST_ID ) + ).not.toBeInTheDocument() + ); + } ); + + it( 'clears provider measurements when the cropper unmounts', async () => { + await renderCropper( + + + + ); + + await waitFor( () => { + expect( + screen.getByTestId( 'cropper-measurement-status' ) + ).toHaveTextContent( 'ready' ); + } ); + + await userEvent.click( + screen.getByRole( 'button', { name: 'Unmount cropper' } ) + ); + + await waitFor( () => { + expect( + screen.getByTestId( 'cropper-measurement-status' ) + ).toHaveTextContent( 'unready' ); + } ); + } ); + it( 'describes and focuses the crop area when requested', async () => { await renderCropper( = { + image: IMAGE, + cropRect: { x: 0.2, y: 0.2, width: 0.4, height: 0.4 }, +}; + +function CanvasSizePublisher( { size }: { size: Size } ) { + const setCanvasSize = useOptionalSetCropperCanvasSize(); + + useEffect( () => { + setCanvasSize( size ); + return () => { + setCanvasSize( { width: 0, height: 0 } ); + }; + }, [ size, setCanvasSize ] ); + + return null; +} + +function createWrapper( { + initialState = INITIAL_STATE, + canvasSize, +}: { + initialState?: Partial< CropperState >; + canvasSize?: Size; +} = {} ) { + return function Wrapper( { children }: { children: React.ReactNode } ) { + return ( + + { canvasSize && } + { children } + + ); + }; +} + +describe( 'useCropGeometry', () => { + it( 'returns not ready before an image is loaded', async () => { + const { result } = renderHook( () => useCropGeometry(), { + wrapper: createWrapper( { + initialState: { ...DEFAULT_STATE, image: null }, + canvasSize: CANVAS_SIZE, + } ), + } ); + + await waitFor( () => { + expect( result.current.isReady ).toBe( false ); + } ); + expect( result.current.rect ).toBeNull(); + expect( result.current.imageBounds ).toBeNull(); + expect( result.current.sourceRegion ).toBeNull(); + } ); + + it( 'returns not ready before the canvas has been measured', () => { + const { result } = renderHook( () => useCropGeometry(), { + wrapper: createWrapper(), + } ); + + expect( result.current.isReady ).toBe( false ); + expect( result.current.rect ).toBeNull(); + expect( result.current.imageBounds ).toBeNull(); + } ); + + it( 'returns the current crop pixels, image bounds, and source region after canvas size is published', async () => { + const { result } = renderHook( () => useCropGeometry(), { + wrapper: createWrapper( { canvasSize: CANVAS_SIZE } ), + } ); + + await waitFor( () => { + expect( result.current.isReady ).toBe( true ); + } ); + + expect( result.current.rect?.left ).toBeCloseTo( 200 ); + expect( result.current.rect?.top ).toBeCloseTo( 100 ); + expect( result.current.rect?.width ).toBeCloseTo( 400 ); + expect( result.current.imageBounds?.maxRight ).toBeCloseTo( 1000 ); + expect( result.current.imageBounds?.minWidth ).toBeCloseTo( 50 ); + expect( result.current.sourceRegion?.width ).toBeCloseTo( 400 ); + } ); +} ); diff --git a/packages/media-editor/src/image-editor/react/hooks/use-crop-geometry.ts b/packages/media-editor/src/image-editor/react/hooks/use-crop-geometry.ts new file mode 100644 index 00000000000000..857603543274b6 --- /dev/null +++ b/packages/media-editor/src/image-editor/react/hooks/use-crop-geometry.ts @@ -0,0 +1,76 @@ +import { useMemo } from '@wordpress/element'; +import { + getCropGeometrySnapshot, + type CropPixelRect, + type CropPixelRectBounds, +} from '../../core/crop-geometry'; +import type { SourceRegion } from '../../core/source-region'; +import { + useCropper, + useCropperMeasurements, +} from '../components/cropper-provider'; + +export type UseCropGeometryReturn = + | { + isReady: false; + rect: null; + imageBounds: null; + sourceRegion: null; + } + | { + isReady: true; + rect: CropPixelRect; + imageBounds: CropPixelRectBounds; + sourceRegion: SourceRegion; + }; + +/** + * Expose the current crop geometry for advanced crop controls and automation. + * + * Reads cropper state + measurements from the surrounding `CropperProvider` + * and produces a snap-rotation pixel snapshot suitable for editing, display, + * or programmatic crop generation. + * + * @return Current crop rectangle, image bounds, and source region. + */ +export function useCropGeometry(): UseCropGeometryReturn { + const cropper = useCropper(); + const { cropBounds } = useCropperMeasurements(); + const imageSize = useMemo( + () => + cropper.state.image + ? { + width: cropper.state.image.naturalWidth, + height: cropper.state.image.naturalHeight, + } + : { width: 0, height: 0 }, + [ cropper.state.image ] + ); + + const snapshot = useMemo( () => { + if ( ! cropBounds ) { + return null; + } + return getCropGeometrySnapshot( { + state: cropper.state, + imageSize, + imageBounds: cropBounds, + } ); + }, [ cropper.state, cropBounds, imageSize ] ); + + if ( ! snapshot ) { + return { + isReady: false, + rect: null, + imageBounds: null, + sourceRegion: null, + }; + } + + return { + isReady: true, + rect: snapshot.rect, + imageBounds: snapshot.imageBounds, + sourceRegion: snapshot.sourceRegion, + }; +} diff --git a/packages/media-editor/src/image-editor/react/hooks/use-derived-cropper-measurements.ts b/packages/media-editor/src/image-editor/react/hooks/use-derived-cropper-measurements.ts new file mode 100644 index 00000000000000..416da7ebe5f8b6 --- /dev/null +++ b/packages/media-editor/src/image-editor/react/hooks/use-derived-cropper-measurements.ts @@ -0,0 +1,59 @@ +import { useMemo } from '@wordpress/element'; +import type { CropperState, Size } from '../../core/types'; +import type { NormalizedCropBounds } from '../../core/crop-geometry'; +import { getImageFit } from '../../core/camera'; +import { getImageCropBounds } from '../../core/containment'; + +export interface CropperMeasurements { + /** Fitted (unrotated) image element dimensions in pixels. */ + elementSize: Size; + /** Visual (rotated) image bounding box in pixels. */ + visualSize: Size; + /** + * Normalized crop bounds describing how far a crop edge can reach in the + * cropper's normalized space. `undefined` until the canvas has been + * measured and an image has loaded. + */ + cropBounds: NormalizedCropBounds | undefined; +} + +/** + * Derive cropper measurements from state and a measured canvas size. + * + * Shared by `` (which always derives locally for its own rendering) + * and `` (which derives once for sibling consumers). Pure + * function of its inputs — same arguments always produce the same output. + * + * @param state Cropper state. + * @param canvasSize Measured canvas size in pixels. + * @return Derived element / visual / bounds measurements. + */ +export function useDerivedCropperMeasurements( + state: CropperState, + canvasSize: Size +): CropperMeasurements { + const naturalWidth = state.image?.naturalWidth ?? 0; + const naturalHeight = state.image?.naturalHeight ?? 0; + + const { elementSize, visualSize } = useMemo( + () => + getImageFit( + canvasSize, + { width: naturalWidth, height: naturalHeight }, + state.rotation + ), + [ canvasSize, naturalWidth, naturalHeight, state.rotation ] + ); + + const cropBounds = useMemo< NormalizedCropBounds | undefined >( () => { + if ( ! state.image || elementSize.width === 0 ) { + return undefined; + } + return getImageCropBounds( state, elementSize, visualSize ); + }, [ state, elementSize, visualSize ] ); + + return useMemo< CropperMeasurements >( + () => ( { elementSize, visualSize, cropBounds } ), + [ elementSize, visualSize, cropBounds ] + ); +}