Virtual whiteboard for sketching hand-drawn like diagrams
feat(editor): crop editor modifiers as resizing, and double-click a handle to uncrop (#12260)
David Luzaref53e5417b2d
diff --git a/packages/element/src/cropElement.ts b/packages/element/src/cropElement.tsindex 7111b679b7..c920d21149 100644--- a/packages/element/src/cropElement.ts+++ b/packages/element/src/cropElement.ts@@ -1,7 +1,6 @@import {type Radians,pointFrom,- pointCenter,pointRotateRads,vectorFromPoint,vectorNormalize,@@ -12,466 +11,198 @@ import {clamp,isCloseTo,} from "@excalidraw/math";-import { type Point } from "points-on-curve";-import {- elementCenterPoint,- getElementAbsoluteCoords,- getResizedElementAbsoluteCoords,-} from "./bounds";--import type { TransformHandleType } from "./transformHandles";-import type {- ElementsMap,- ExcalidrawElement,- ExcalidrawImageElement,- ImageCrop,-} from "./types";+import type { Bounds } from "@excalidraw/common";++import { elementCenterPoint, getElementAbsoluteCoords } from "./bounds";+import { getNextSingleWidthAndHeightFromPointer } from "./resizeElements";++import type { TransformHandleDirection } from "./transformHandles";+import type { ElementsMap, ExcalidrawImageElement, ImageCrop } from "./types";export const MINIMAL_CROP_SIZE = 10;+/**+ * Crops the image (as it was at the drag's start) as resizing it would+ * resize it, as far as the image reaches.+ */export const cropElement = (element: ExcalidrawImageElement,elementsMap: ElementsMap,- transformHandle: TransformHandleType,+ transformHandle: TransformHandleDirection,naturalWidth: number,naturalHeight: number,pointerX: number,pointerY: number,- widthAspectRatio?: number,+ {+ shouldMaintainAspectRatio = false,+ shouldResizeFromCenter = false,+ }: {+ shouldMaintainAspectRatio?: boolean;+ shouldResizeFromCenter?: boolean;+ } = {},) => {+ const { width, height } = element;const { width: uncroppedWidth, height: uncroppedHeight } =getUncroppedWidthAndHeight(element);-- const naturalWidthToUncropped = naturalWidth / uncroppedWidth;- const naturalHeightToUncropped = naturalHeight / uncroppedHeight;-- const croppedLeft = (element.crop?.x ?? 0) / naturalWidthToUncropped;- const croppedTop = (element.crop?.y ?? 0) / naturalHeightToUncropped;-- /**- * uncropped width- * *––––––––––––––––––––––––*- * | (x,y) (natural) |- * | *–––––––* |- * | |///////| height | uncropped height- * | *–––––––* |- * | width (natural) |- * *––––––––––––––––––––––––*- */-- const rotatedPointer = pointRotateRads(- pointFrom(pointerX, pointerY),- elementCenterPoint(element, elementsMap),- -element.angle as Radians,- );-- pointerX = rotatedPointer[0];- pointerY = rotatedPointer[1];-- let nextWidth = element.width;- let nextHeight = element.height;-- let crop: ImageCrop | null = element.crop ?? {+ const { x: left, y: top } = getFlipAdjustedCropPosition(element) ?? {x: 0,y: 0,- width: naturalWidth,- height: naturalHeight,- naturalWidth,- naturalHeight,};- const previousCropHeight = crop.height;- const previousCropWidth = crop.width;-- const isFlippedByX = element.scale[0] === -1;- const isFlippedByY = element.scale[1] === -1;-- let changeInHeight = pointerY - element.y;- let changeInWidth = pointerX - element.x;-- if (transformHandle.includes("n")) {- nextHeight = clamp(- element.height - changeInHeight,- MINIMAL_CROP_SIZE,- isFlippedByY ? uncroppedHeight - croppedTop : element.height + croppedTop,- );- }-- if (transformHandle.includes("s")) {- changeInHeight = pointerY - element.y - element.height;- nextHeight = clamp(- element.height + changeInHeight,- MINIMAL_CROP_SIZE,- isFlippedByY ? element.height + croppedTop : uncroppedHeight - croppedTop,- );- }-- if (transformHandle.includes("e")) {- changeInWidth = pointerX - element.x - element.width;+ let { nextWidth, nextHeight } = getNextSingleWidthAndHeightFromPointer(+ element,+ element,+ transformHandle,+ pointerX,+ pointerY,+ { shouldResizeFromCenter },+ );- nextWidth = clamp(- element.width + changeInWidth,- MINIMAL_CROP_SIZE,- isFlippedByX ? element.width + croppedLeft : uncroppedWidth - croppedLeft,- );- }+ // what stays put, as a fraction of the size: the opposite side (0 or 1),+ // or the center (also of a side handle's other axis, which keeping the+ // aspect ratio changes)+ const anchorX =+ shouldResizeFromCenter || !/[ew]/.test(transformHandle)+ ? 0.5+ : transformHandle.includes("w")+ ? 1+ : 0;+ const anchorY =+ shouldResizeFromCenter || !/[ns]/.test(transformHandle)+ ? 0.5+ : transformHandle.includes("n")+ ? 1+ : 0;+ // as far as the image reaches from what stays put+ const getMaxSize = (+ anchor: number,+ offset: number,+ size: number,+ uncroppedSize: number,+ ) => {+ const before = offset + anchor * size;+ const after = uncroppedSize - before;+ return anchor === 0+ ? after+ : anchor === 1+ ? before+ : Math.min(before, after) * 2;+ };+ const maxWidth = getMaxSize(anchorX, left, width, uncroppedWidth);+ const maxHeight = getMaxSize(anchorY, top, height, uncroppedHeight);+ // (an image already smaller than the minimal size crops no smaller)+ const minWidth = Math.min(MINIMAL_CROP_SIZE, width);+ const minHeight = Math.min(MINIMAL_CROP_SIZE, height);- if (transformHandle.includes("w")) {+ if (shouldMaintainAspectRatio) {+ const ratio = width / height;+ // as resizing, by a side handle's axis, or the one a corner grows most —+ // but an axis dragged past what stays put has no size (rather than flips)nextWidth = clamp(- element.width - changeInWidth,- MINIMAL_CROP_SIZE,- isFlippedByX ? uncroppedWidth - croppedLeft : element.width + croppedLeft,+ transformHandle === "n" || transformHandle === "s"+ ? nextHeight * ratio+ : transformHandle === "e" || transformHandle === "w"+ ? nextWidth+ : Math.max(nextWidth, nextHeight * ratio),+ Math.max(minWidth, minHeight * ratio),+ Math.min(maxWidth, maxHeight * ratio),);+ nextHeight = nextWidth / ratio;+ } else {+ nextWidth = clamp(nextWidth, minWidth, maxWidth);+ nextHeight = clamp(nextHeight, minHeight, maxHeight);}- const updateCropWidthAndHeight = (crop: ImageCrop) => {- crop.height = nextHeight * naturalHeightToUncropped;- crop.width = nextWidth * naturalWidthToUncropped;- };-- updateCropWidthAndHeight(crop);+ const x1 = anchorX * (width - nextWidth);+ const y1 = anchorY * (height - nextHeight);- const adjustFlipForHandle = (- handle: TransformHandleType,- crop: ImageCrop,- ) => {- updateCropWidthAndHeight(crop);- if (handle.includes("n")) {- if (!isFlippedByY) {- crop.y += previousCropHeight - crop.height;- }- }- if (handle.includes("s")) {- if (isFlippedByY) {- crop.y += previousCropHeight - crop.height;- }- }- if (handle.includes("e")) {- if (isFlippedByX) {- crop.x += previousCropWidth - crop.width;- }- }- if (handle.includes("w")) {- if (!isFlippedByX) {- crop.x += previousCropWidth - crop.width;- }- }- };-- switch (transformHandle) {- case "n": {- if (widthAspectRatio) {- const distanceToLeft = croppedLeft + element.width / 2;- const distanceToRight =- uncroppedWidth - croppedLeft - element.width / 2;-- const MAX_WIDTH = Math.min(distanceToLeft, distanceToRight) * 2;-- nextWidth = clamp(- nextHeight * widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_WIDTH,- );- nextHeight = nextWidth / widthAspectRatio;- }-- adjustFlipForHandle(transformHandle, crop);-- if (widthAspectRatio) {- crop.x += (previousCropWidth - crop.width) / 2;- }-- break;- }- case "s": {- if (widthAspectRatio) {- const distanceToLeft = croppedLeft + element.width / 2;- const distanceToRight =- uncroppedWidth - croppedLeft - element.width / 2;-- const MAX_WIDTH = Math.min(distanceToLeft, distanceToRight) * 2;-- nextWidth = clamp(- nextHeight * widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_WIDTH,- );- nextHeight = nextWidth / widthAspectRatio;- }-- adjustFlipForHandle(transformHandle, crop);-- if (widthAspectRatio) {- crop.x += (previousCropWidth - crop.width) / 2;- }-- break;- }- case "w": {- if (widthAspectRatio) {- const distanceToTop = croppedTop + element.height / 2;- const distanceToBottom =- uncroppedHeight - croppedTop - element.height / 2;-- const MAX_HEIGHT = Math.min(distanceToTop, distanceToBottom) * 2;-- nextHeight = clamp(- nextWidth / widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_HEIGHT,- );- nextWidth = nextHeight * widthAspectRatio;- }-- adjustFlipForHandle(transformHandle, crop);-- if (widthAspectRatio) {- crop.y += (previousCropHeight - crop.height) / 2;- }-- break;- }- case "e": {- if (widthAspectRatio) {- const distanceToTop = croppedTop + element.height / 2;- const distanceToBottom =- uncroppedHeight - croppedTop - element.height / 2;-- const MAX_HEIGHT = Math.min(distanceToTop, distanceToBottom) * 2;-- nextHeight = clamp(- nextWidth / widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_HEIGHT,- );- nextWidth = nextHeight * widthAspectRatio;- }-- adjustFlipForHandle(transformHandle, crop);-- if (widthAspectRatio) {- crop.y += (previousCropHeight - crop.height) / 2;- }-- break;- }- case "ne": {- if (widthAspectRatio) {- if (changeInWidth > -changeInHeight) {- const MAX_HEIGHT = isFlippedByY- ? uncroppedHeight - croppedTop- : croppedTop + element.height;-- nextHeight = clamp(- nextWidth / widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_HEIGHT,- );- nextWidth = nextHeight * widthAspectRatio;- } else {- const MAX_WIDTH = isFlippedByX- ? croppedLeft + element.width- : uncroppedWidth - croppedLeft;-- nextWidth = clamp(- nextHeight * widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_WIDTH,- );- nextHeight = nextWidth / widthAspectRatio;- }- }-- adjustFlipForHandle(transformHandle, crop);- break;- }- case "nw": {- if (widthAspectRatio) {- if (changeInWidth < changeInHeight) {- const MAX_HEIGHT = isFlippedByY- ? uncroppedHeight - croppedTop- : croppedTop + element.height;- nextHeight = clamp(- nextWidth / widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_HEIGHT,- );- nextWidth = nextHeight * widthAspectRatio;- } else {- const MAX_WIDTH = isFlippedByX- ? uncroppedWidth - croppedLeft- : croppedLeft + element.width;-- nextWidth = clamp(- nextHeight * widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_WIDTH,- );- nextHeight = nextWidth / widthAspectRatio;- }- }-- adjustFlipForHandle(transformHandle, crop);- break;- }- case "se": {- if (widthAspectRatio) {- if (changeInWidth > changeInHeight) {- const MAX_HEIGHT = isFlippedByY- ? croppedTop + element.height- : uncroppedHeight - croppedTop;-- nextHeight = clamp(- nextWidth / widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_HEIGHT,- );- nextWidth = nextHeight * widthAspectRatio;- } else {- const MAX_WIDTH = isFlippedByX- ? croppedLeft + element.width- : uncroppedWidth - croppedLeft;-- nextWidth = clamp(- nextHeight * widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_WIDTH,- );- nextHeight = nextWidth / widthAspectRatio;- }- }-- adjustFlipForHandle(transformHandle, crop);- break;- }- case "sw": {- if (widthAspectRatio) {- if (-changeInWidth > changeInHeight) {- const MAX_HEIGHT = isFlippedByY- ? croppedTop + element.height- : uncroppedHeight - croppedTop;-- nextHeight = clamp(- nextWidth / widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_HEIGHT,- );- nextWidth = nextHeight * widthAspectRatio;- } else {- const MAX_WIDTH = isFlippedByX- ? uncroppedWidth - croppedLeft- : croppedLeft + element.width;-- nextWidth = clamp(- nextHeight * widthAspectRatio,- MINIMAL_CROP_SIZE,- MAX_WIDTH,- );- nextHeight = nextWidth / widthAspectRatio;- }- }-- adjustFlipForHandle(transformHandle, crop);- break;- }- default:- break;- }-- const newOrigin = recomputeOrigin(+ return cropElementToBounds(element,- transformHandle,- nextWidth,- nextHeight,- !!widthAspectRatio,+ elementsMap,+ naturalWidth,+ naturalHeight,+ [x1, y1, x1 + nextWidth, y1 + nextHeight],);+};- // reset crop to null if we're back to orig size- if (- isCloseTo(crop.width, crop.naturalWidth) &&- isCloseTo(crop.height, crop.naturalHeight)- ) {- crop = null;- }+/**+ * Crops the image to `bounds`, relative to the element as shown (flipped).+ */+const cropElementToBounds = (+ element: ExcalidrawImageElement,+ elementsMap: ElementsMap,+ naturalWidth: number,+ naturalHeight: number,+ [x1, y1, x2, y2]: Bounds,+) => {+ // the image's natural pixels per element unit+ const scaleX = (element.crop?.width ?? naturalWidth) / element.width;+ const scaleY = (element.crop?.height ?? naturalHeight) / element.height;+ const width = x2 - x1;+ const height = y2 - y1;+ const [centerX, centerY] = pointRotateRads(+ pointFrom(element.x + (x1 + x2) / 2, element.y + (y1 + y2) / 2),+ elementCenterPoint(element, elementsMap),+ element.angle,+ );+ const crop = {+ x:+ (element.crop?.x ?? 0) ++ (element.scale[0] === -1 ? element.width - x2 : x1) * scaleX,+ y:+ (element.crop?.y ?? 0) ++ (element.scale[1] === -1 ? element.height - y2 : y1) * scaleY,+ width: width * scaleX,+ height: height * scaleY,+ naturalWidth,+ naturalHeight,+ };return {- x: newOrigin[0],- y: newOrigin[1],- width: nextWidth,- height: nextHeight,- crop,+ x: centerX - width / 2,+ y: centerY - height / 2,+ width,+ height,+ // reset crop to null if we're back to orig size+ crop:+ isCloseTo(crop.width, naturalWidth) &&+ isCloseTo(crop.height, naturalHeight)+ ? null+ : crop,};};-const recomputeOrigin = (- stateAtCropStart: ExcalidrawElement,- transformHandle: TransformHandleType,- width: number,- height: number,- shouldMaintainAspectRatio?: boolean,+/**+ * Uncrops the image on the handle's side (a corner's two); mirrored, on the+ * opposite side(s) too.+ */+export const uncropElementSides = (+ element: ExcalidrawImageElement,+ elementsMap: ElementsMap,+ handle: TransformHandleDirection,+ mirrored = false,) => {- const [x1, y1, x2, y2] = getResizedElementAbsoluteCoords(- stateAtCropStart,- stateAtCropStart.width,- stateAtCropStart.height,- true,- );- const startTopLeft = pointFrom(x1, y1);- const startBottomRight = pointFrom(x2, y2);- const startCenter: any = pointCenter(startTopLeft, startBottomRight);-- const [newBoundsX1, newBoundsY1, newBoundsX2, newBoundsY2] =- getResizedElementAbsoluteCoords(stateAtCropStart, width, height, true);- const newBoundsWidth = newBoundsX2 - newBoundsX1;- const newBoundsHeight = newBoundsY2 - newBoundsY1;-- // Calculate new topLeft based on fixed corner during resize- let newTopLeft = [...startTopLeft] as [number, number];-- if (["n", "w", "nw"].includes(transformHandle)) {- newTopLeft = [- startBottomRight[0] - Math.abs(newBoundsWidth),- startBottomRight[1] - Math.abs(newBoundsHeight),- ];- }- if (transformHandle === "ne") {- const bottomLeft = [startTopLeft[0], startBottomRight[1]];- newTopLeft = [bottomLeft[0], bottomLeft[1] - Math.abs(newBoundsHeight)];- }- if (transformHandle === "sw") {- const topRight = [startBottomRight[0], startTopLeft[1]];- newTopLeft = [topRight[0] - Math.abs(newBoundsWidth), topRight[1]];- }-- if (shouldMaintainAspectRatio) {- if (["s", "n"].includes(transformHandle)) {- newTopLeft[0] = startCenter[0] - newBoundsWidth / 2;- }- if (["e", "w"].includes(transformHandle)) {- newTopLeft[1] = startCenter[1] - newBoundsHeight / 2;- }+ if (!element.crop) {+ return null;}+ const { width, height } = getUncroppedWidthAndHeight(element);+ const { x: left, y: top } = getFlipAdjustedCropPosition(element)!;+ const uncrops = (side: string, opposite: string) =>+ handle.includes(side) || (mirrored && handle.includes(opposite));- // adjust topLeft to new rotation point- const angle = stateAtCropStart.angle;- const rotatedTopLeft = pointRotateRads(newTopLeft, startCenter, angle);- const newCenter: Point = [- newTopLeft[0] + Math.abs(newBoundsWidth) / 2,- newTopLeft[1] + Math.abs(newBoundsHeight) / 2,- ];- const rotatedNewCenter = pointRotateRads(newCenter, startCenter, angle);- newTopLeft = pointRotateRads(- rotatedTopLeft,- rotatedNewCenter,- -angle as Radians,+ return cropElementToBounds(+ element,+ elementsMap,+ element.crop.naturalWidth,+ element.crop.naturalHeight,+ [+ uncrops("w", "e") ? -left : 0,+ uncrops("n", "s") ? -top : 0,+ uncrops("e", "w") ? width - left : element.width,+ uncrops("s", "n") ? height - top : element.height,+ ],);-- const newOrigin = [...newTopLeft];- newOrigin[0] += stateAtCropStart.x - newBoundsX1;- newOrigin[1] += stateAtCropStart.y - newBoundsY1;-- return newOrigin;};// refer to https://link.excalidraw.com/l/6rfy1007QOo/6stx5PmRn0kdiff --git a/packages/element/src/renderElement.ts b/packages/element/src/renderElement.tsindex 0aa74b0b06..833743a217 100644--- a/packages/element/src/renderElement.ts+++ b/packages/element/src/renderElement.ts@@ -1217,49 +1217,76 @@ const drawElement = (context.imageSmoothingEnabled = false;}- if (+ const uncroppedElementCanvas =element.id === appState.croppingElementId &&isImageElement(elementWithCanvas.element) &&elementWithCanvas.element.crop !== null- ) {+ ? generateElementCanvas(+ getUncroppedImageElement(+ elementWithCanvas.element,+ elementsMap,+ ) as NonDeleted<ExcalidrawImageElement>,+ allElementsMap,+ appState.zoom,+ renderConfig,+ appState,+ )+ : null;++ if (uncroppedElementCanvas) {+ // the crop editor shows the uncropped image, faded outside the+ // crop: one bitmap, so cropping moves only the crop's edges over it+ // (the cropped image's own bitmap snaps to whole pixels by its own+ // corner, shifting the image by a pixel as that corner moves)context.save();context.globalAlpha = 0.1;+ drawElementFromCanvas(+ uncroppedElementCanvas,+ context,+ renderConfig,+ appState,+ allElementsMap,+ // The crop editor's uncropped preview stays at document coordinates.+ ZERO_RENDER_OFFSET,+ );+ context.restore();- const uncroppedElementCanvas = generateElementCanvas(- getUncroppedImageElement(- elementWithCanvas.element,- elementsMap,- ) as NonDeleted<ExcalidrawImageElement>,+ const [x1, y1, x2, y2] = getElementAbsoluteCoords(+ elementWithCanvas.element,allElementsMap,- appState.zoom,+ );+ context.save();+ // (built in the element's rotated box: save/restore leaves the path)+ context.save();+ context.translate(+ (x1 + x2) / 2 + renderState.offset.x + appState.scrollX,+ (y1 + y2) / 2 + renderState.offset.y + appState.scrollY,+ );+ context.rotate(elementWithCanvas.element.angle);+ context.beginPath();+ context.rect((x1 - x2) / 2, (y1 - y2) / 2, x2 - x1, y2 - y1);+ context.restore();+ context.clip();+ drawElementFromCanvas(+ uncroppedElementCanvas,+ context,renderConfig,appState,+ allElementsMap,+ renderState.offset,);-- if (uncroppedElementCanvas) {- drawElementFromCanvas(- uncroppedElementCanvas,- context,- renderConfig,- appState,- allElementsMap,- // The crop editor's uncropped preview stays at document coordinates.- ZERO_RENDER_OFFSET,- );- }-context.restore();+ } else {+ drawElementFromCanvas(+ elementWithCanvas,+ context,+ renderConfig,+ appState,+ allElementsMap,+ renderState.offset,+ );}- drawElementFromCanvas(- elementWithCanvas,- context,- renderConfig,- appState,- allElementsMap,- renderState.offset,- );-// resetcontext.imageSmoothingEnabled = currentImageSmoothingStatus;}diff --git a/packages/element/src/resizeElements.ts b/packages/element/src/resizeElements.tsindex b6d9a355ba..c252961bd2 100644--- a/packages/element/src/resizeElements.ts+++ b/packages/element/src/resizeElements.ts@@ -985,7 +985,7 @@ export const resizeSingleElement = (}};-const getNextSingleWidthAndHeightFromPointer = (+export const getNextSingleWidthAndHeightFromPointer = (latestElement: ExcalidrawElement,origElement: ExcalidrawElement,handleDirection: TransformHandleDirection,diff --git a/packages/element/src/resizeTest.ts b/packages/element/src/resizeTest.tsindex 22bb4abddf..a124707d28 100644--- a/packages/element/src/resizeTest.ts+++ b/packages/element/src/resizeTest.ts@@ -71,6 +71,8 @@ export const resizeTest = <Point extends GlobalPoint | LocalPoint>(if (rotationTransformHandle &&+ // (the crop editor has none, nor draws it)+ !appState.croppingElementId &&isInsideTransformHandle(rotationTransformHandle, x, y)) {return "rotation" as TransformHandleType;diff --git a/packages/element/tests/cropElement.test.tsx b/packages/element/tests/cropElement.test.tsxindex 843e745638..cab7fe35e7 100644--- a/packages/element/tests/cropElement.test.tsx+++ b/packages/element/tests/cropElement.test.tsx@@ -117,6 +117,38 @@ describe("Enter and leave the crop editor", () => {Keyboard.keyDown(KEYS.ESCAPE);expect(h.state.croppingElementId).toBe(null);});++ it("leave the editor by clicking where the rotation handle would be", () => {+ const image = h.elements[0];+ Keyboard.keyDown(KEYS.ENTER);++ // (the editor draws no rotation handle)+ mouse.clickAt(image.x + image.width / 2, image.y - 16);++ expect(h.state.croppingElementId).toBe(null);+ });++ it("stay in the editor on shift-clicking the image", () => {+ const image = h.elements[0];+ Keyboard.keyDown(KEYS.ENTER);++ Keyboard.withModifierKeys({ shift: true }, () => {+ mouse.clickAt(image.x + 50, image.y + 50);+ });++ expect(h.state.croppingElementId).toBe(image.id);+ expect(h.state.selectedElementIds).toEqual({ [image.id]: true });+ });++ it("stay in the editor on clicking a crop handle", () => {+ const image = h.elements[0];+ Keyboard.keyDown(KEYS.ENTER);++ // the east handle+ mouse.clickAt(image.x + image.width, image.y + image.height / 2);++ expect(h.state.croppingElementId).toBe(image.id);+ });});describe("Crop an image", () => {@@ -136,7 +168,7 @@ describe("Crop an image", () => {expect(image.height).toBeLessThan(initialHeight);});- it("In the crop editor, dragging a handle crops the image, and dragging the image moves it within its crop", () => {+ it("In the crop editor, dragging a handle crops the image, and dragging the image moves it within its crop (along one axis with shift)", () => {const image = API.createElement({type: "image",width: 200,@@ -158,18 +190,150 @@ describe("Crop an image", () => {Keyboard.keyDown(KEYS.ENTER);expect(h.state.croppingElementId).toBe(image.id);- UI.resize(image, "w", [50, 0]);+ UI.resize(image, "nw", [50, 25]);- expect(API.getElement(image)).toMatchObject({ x: 50, width: 150 });- expect(API.getElement(image).crop).toMatchObject({ x: 100, width: 300 });+ expect(API.getElement(image)).toMatchObject({ x: 50, y: 25, width: 150 });+ expect(API.getElement(image).crop).toMatchObject({ x: 100, y: 50 });// 20px to the right = 40px of the file, at twice the element's sizemouse.downAt(100, 50);mouse.move(20, 0);mouse.upAt();- expect(API.getElement(image)).toMatchObject({ x: 50, width: 150 });- expect(API.getElement(image).crop).toMatchObject({ x: 60, width: 300 });+ expect(API.getElement(image)).toMatchObject({ x: 50, y: 25, width: 150 });+ expect(API.getElement(image).crop).toMatchObject({ x: 60, y: 50 });++ Keyboard.withModifierKeys({ shift: true }, () => {+ mouse.downAt(100, 50);+ mouse.move(10, 4);+ mouse.upAt();+ });++ expect(API.getElement(image).crop).toMatchObject({ x: 40, y: 50 });++ // dragged past the file's edge, it moves back as soon as dragged back+ mouse.downAt(100, 50);+ mouse.move(40, 0);+ expect(API.getElement(image).crop).toMatchObject({ x: 0 });+ mouse.move(-10, 0);+ mouse.upAt();++ expect(API.getElement(image).crop).toMatchObject({ x: 20, y: 50 });+ });++ it("In the crop editor, alt-dragging a handle crops the image from its center", () => {+ const image = API.createElement({+ type: "image",+ width: 200,+ height: 100,+ fileId: "file",+ });+ API.setElements([image]);+ // the file loaded, at twice the element's size+ const htmlImage = new Image();+ Object.defineProperties(htmlImage, {+ naturalWidth: { value: 400 },+ naturalHeight: { value: 200 },+ });+ h.app.imageCache.set(image.fileId!, {+ image: htmlImage,+ mimeType: "image/png",+ });+ API.setSelectedElements([image]);+ Keyboard.keyDown(KEYS.ENTER);++ // as resizing, pressing alt mid-drag crops about the center the drag+ // started with, and releasing it, from the opposite side again+ mouse.downAt(200, 50);+ mouse.moveTo(170, 50);+ expect(API.getElement(image)).toMatchObject({ x: 0, width: 170 });+ Keyboard.withModifierKeys({ alt: true }, () => {+ Keyboard.keyDown(KEYS.ALT);+ });+ expect(API.getElement(image)).toMatchObject({ x: 30, width: 140 });+ Keyboard.keyUp(KEYS.ALT);+ expect(API.getElement(image)).toMatchObject({ x: 0, width: 170 });+ mouse.moveTo(200, 50);+ mouse.upAt();++ UI.resize(image, "e", [-30, 0], { alt: true });++ expect(API.getElement(image)).toMatchObject({ x: 30, width: 140 });+ // 30px off each side = 60px of the file, at twice the element's size+ expect(API.getElement(image).crop).toMatchObject({ x: 60, width: 280 });++ // keeping the aspect ratio too+ UI.resize(image, "e", [-35, 0], { alt: true, shift: true });++ expect(API.getElement(image)).toMatchObject({+ x: 65,+ y: 25,+ width: 70,+ height: 50,+ });+ });++ it("In the crop editor, double-clicking a handle uncrops its side(s), mirrored with alt", () => {+ // the middle of an image twice the element's size, at (0, 0)+ const image = API.createElement({+ type: "image",+ x: 50,+ y: 25,+ width: 100,+ height: 50,+ fileId: "file",+ });+ API.setElements([image]);+ API.updateElement(image, {+ crop: {+ x: 100,+ y: 50,+ width: 200,+ height: 100,+ naturalWidth: 400,+ naturalHeight: 200,+ },+ });+ // bound near the image's south-east corner+ const arrow = UI.createElement("arrow", {+ x: 140,+ y: 300,+ width: 0,+ height: -230,+ });+ API.setSelectedElements([image]);+ Keyboard.keyDown(KEYS.ENTER);++ // the north-east handle+ mouse.doubleClickAt(150, 25);++ expect(API.getElement(image)).toMatchObject({+ x: 50,+ y: 0,+ width: 150,+ height: 75,+ });+ expect(API.getElement(image).crop).toMatchObject({ y: 0, width: 300 });+ // the arrow following the image+ const { x, points } = API.getElement(arrow);+ expect(x + points[1][0]).toBeCloseTo(185);++ Keyboard.undo();++ expect(API.getElement(image)).toMatchObject({ y: 25, width: 100 });++ // the west handle, and so the east one+ Keyboard.withModifierKeys({ alt: true }, () => {+ mouse.doubleClickAt(50, 50);+ });++ expect(API.getElement(image)).toMatchObject({+ x: 0,+ y: 25,+ width: 200,+ height: 50,+ });+ expect(API.getElement(image).crop).toMatchObject({ x: 0, width: 400 });});it("Cropping has minimal sizes", async () => {@@ -308,13 +472,12 @@ describe("Cropping and other features", async () => {initialWidth / 2,initialHeight / 2,]);- const cropBeforeResizing = image.crop;const cropBeforeResizingCloned = cloneJSON(image.crop) as ImageCrop;- expect(cropBeforeResizing).not.toBe(null);+ expect(image.crop).not.toBe(null);UI.crop(image, "e", naturalWidth, naturalHeight, [200, 0]);- expect(cropBeforeResizing).toBe(image.crop);compareCrops(cropBeforeResizingCloned, image.crop!);+ const cropBeforeResizing = image.crop;UI.resize(image, "s", [0, -100]);expect(cropBeforeResizing).toBe(image.crop);diff --git a/packages/excalidraw/components/App.selectionTool.ts b/packages/excalidraw/components/App.selectionTool.tsindex 265ca51bf9..dbc67f301c 100644--- a/packages/excalidraw/components/App.selectionTool.ts+++ b/packages/excalidraw/components/App.selectionTool.ts@@ -42,6 +42,7 @@ import {LinearElementEditor,makeNextSelectedElementIds,transformElements,+ uncropElementSides,updateBoundElements,updateFrameMembershipOfSelectedElements,} from "@excalidraw/element";@@ -60,6 +61,7 @@ import {import type { TransformHandleType } from "@excalidraw/element";import type {ExcalidrawElement,+ ExcalidrawImageElement,NonDeleted,NonDeletedExcalidrawElement,NonDeletedSceneElementsMap,@@ -121,11 +123,7 @@ export class AppSelectionTool {);if (transformHandle) {// (in the crop editor, the handles crop the image rather than resize it)- if (- transformHandle.element &&- (transformHandle.transformHandleType === "rotation" ||- !this.app.state.croppingElementId)- ) {+ if (transformHandle.element && !this.app.state.croppingElementId) {this.app.setState({ resizingElement: transformHandle.element });}pointerDownState.resize.handleType =@@ -454,6 +452,7 @@ export class AppSelectionTool {if (transformHandleType &&+ transformHandleType !== "rotation" &&croppingElement &&isImageElement(croppingElement)) {@@ -496,23 +495,24 @@ export class AppSelectionTool {this.app.scene.mutateElement(croppingElement,cropElement(- croppingElement,+ croppingAtStateStart,this.app.scene.getNonDeletedElementsMap(),transformHandleType,image.naturalWidth,image.naturalHeight,x + snapOffset.x,y + snapOffset.y,- event.shiftKey- ? croppingAtStateStart.width / croppingAtStateStart.height- : undefined,+ {+ shouldMaintainAspectRatio: shouldMaintainAspectRatio(event),+ shouldResizeFromCenter: shouldResizeFromCenter(event),+ },),);updateBoundElements(croppingElement, this.app.scene);this.app.setState({- isCropping: transformHandleType && transformHandleType !== "rotation",+ isCropping: true,snapLines,});}@@ -523,10 +523,52 @@ export class AppSelectionTool {return false;};+ /**+ * In the crop editor, a double-click on a handle uncrops its side (a+ * corner's two), and mirrored, the opposite side(s) too.+ *+ * @returns whether the double-click has been handled+ */+ maybeUncropSides = (+ image: NonDeleted<ExcalidrawImageElement>,+ sceneX: number,+ sceneY: number,+ mirrored: boolean,+ ): boolean => {+ const handle =+ image.id === this.app.state.croppingElementId &&+ this.getTransformHandleAt(+ [image],+ sceneX,+ sceneY,+ this.app.state.lastPointerDownWith,+ )?.transformHandleType;+ if (!handle || handle === "rotation") {+ return false;+ }+ const updates = uncropElementSides(+ image,+ this.app.scene.getNonDeletedElementsMap(),+ handle,+ mirrored,+ );+ if (updates) {+ this.app.store.scheduleCapture();+ this.app.scene.mutateElement(image, updates);+ updateBoundElements(image, this.app.scene);+ }+ return true;+ };+maybeHandleResize = (pointerDownState: PointerDownState,event: MouseEvent | KeyboardEvent,): boolean => {+ // in the crop editor, the handles crop the image+ if (this.app.state.croppingElementId) {+ return this.maybeHandleCrop(pointerDownState, event);+ }+const selectedElements = this.app.scene.getSelectedElements(this.app.state);const selectedFrames = selectedElements.filter(isFrameLikeElement);@@ -536,9 +578,7 @@ export class AppSelectionTool {// Frames cannot be rotated.(selectedFrames.length > 0 && transformHandleType === "rotation") ||// Elbow arrows cannot be transformed (resized or rotated).- (selectedElements.length === 1 && isElbowArrow(selectedElements[0])) ||- // Do not resize when in crop mode- this.app.state.croppingElementId+ (selectedElements.length === 1 && isElbowArrow(selectedElements[0]))) {return false;}@@ -701,7 +741,6 @@ export class AppSelectionTool {event: PointerEvent,pointerDownState: PointerDownState,pointerCoords: { x: number; y: number },- lastPointerCoords: { x: number; y: number },elementsMap: NonDeletedSceneElementsMap,): boolean => {const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(@@ -843,10 +882,16 @@ export class AppSelectionTool {if (image && !(image instanceof Promise)) {const uncroppedSize = getUncroppedWidthAndHeight(croppingElement);+ // moved by what the drag moved since the previous pointer move+ // (locked to an axis with shift, as dragging elements is), so+ // that the image moves back right away after being dragged past+ // its edge+ const { lastOffset } = pointerDownState.drag;const instantDragOffset = vector(- pointerCoords.x - lastPointerCoords.x,- pointerCoords.y - lastPointerCoords.y,+ dragOffset.x - lastOffset.x,+ dragOffset.y - lastOffset.y,);+ pointerDownState.drag.lastOffset = dragOffset;// to reduce cursor:image drift, we need to take into account// the canvas image element scaling so we can accurately@@ -1282,7 +1327,9 @@ export class AppSelectionTool {// when inside line editor, shift selects points insteadif (childEvent.shiftKey &&- !this.app.state.selectedLinearElement?.isEditing+ !this.app.state.selectedLinearElement?.isEditing &&+ // (in the crop editor, the image stays the selection)+ hitElement.id !== this.app.state.croppingElementId) {if (this.app.state.selectedElementIds[hitElement.id]) {if (diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex beec1feb50..deb4b3f64b 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -707,8 +707,6 @@ class App extends React.Component<AppProps, AppState> {/** current frame pointer cords */lastPointerMoveCoords: { x: number; y: number } | null = null;private lastCompletedCanvasClicks: { x: number; y: number }[] = [];- /** previous frame pointer coords */- previousPointerMoveCoords: { x: number; y: number } | null = null;drawShape = new AppDrawShape(this);laserTrails = new LaserTrails(this);@@ -6187,8 +6185,13 @@ class App extends React.Component<AppProps, AppState> {return;}// alt-clicks cycle the selection, so their double-click does nothing- // (autoshape doesn't select, alt is its free-text-at-point escape hatch)- if (event.altKey && this.state.activeTool.type !== "autoshape") {+ // (autoshape doesn't select, alt is its free-text-at-point escape hatch;+ // the crop editor doesn't cycle, alt mirrors the sides it uncrops)+ if (+ event.altKey &&+ this.state.activeTool.type !== "autoshape" &&+ !this.state.croppingElementId+ ) {return;}// case: double-clicking with arrow/line tool selected would both create@@ -6301,7 +6304,16 @@ class App extends React.Component<AppProps, AppState> {}if (selectedElements.length === 1 && isImageElement(selectedElements[0])) {- this.startImageCropping(selectedElements[0]);+ if (+ !this.selectionTool.maybeUncropSides(+ selectedElements[0],+ sceneX,+ sceneY,+ event.altKey,+ )+ ) {+ this.startImageCropping(selectedElements[0]);+ }return;}@@ -8158,6 +8170,7 @@ class App extends React.Component<AppProps, AppState> {hasOccurred: false,offset: null,origin: { ...origin },+ lastOffset: { x: 0, y: 0 },blockDragging: false,},eventListeners: {@@ -9000,10 +9013,6 @@ class App extends React.Component<AppProps, AppState> {return;}- const lastPointerCoords =- this.previousPointerMoveCoords ?? pointerDownState.origin;- this.previousPointerMoveCoords = pointerCoords;-// We need to initialize dragOffsetXY only after we've updated// `state.selectedElementIds` on pointerDown. Doing it here in pointerMove// event handler should hopefully ensure we're already working with@@ -9052,9 +9061,6 @@ class App extends React.Component<AppProps, AppState> {if (pointerDownState.resize.isResizing) {pointerDownState.lastCoords.x = pointerCoords.x;pointerDownState.lastCoords.y = pointerCoords.y;- if (this.selectionTool.maybeHandleCrop(pointerDownState, event)) {- return true;- }if (this.selectionTool.maybeHandleResize(pointerDownState, event)) {return true;}@@ -9220,7 +9226,6 @@ class App extends React.Component<AppProps, AppState> {event,pointerDownState,pointerCoords,- lastPointerCoords,elementsMap,)) {@@ -9462,7 +9467,6 @@ class App extends React.Component<AppProps, AppState> {// just in case, tool changes mid drag, always clean upthis.lassoTrail.endPath();- this.previousPointerMoveCoords = null;SnapCache.setReferenceSnapPoints(null);SnapCache.setVisibleGaps(null);@@ -10062,8 +10066,10 @@ class App extends React.Component<AppProps, AppState> {!croppingElementId ||// in the cropping mode(croppingElementId &&- // not cropping and no hit element- ((!hitElement && !isCropping) ||+ // not cropping, nor clicking a crop handle, and no hit element+ ((!hitElement &&+ !isCropping &&+ !pointerDownState.resize.handleType) ||// hitting something else(hitElement && hitElement.id !== croppingElementId)))) {diff --git a/packages/excalidraw/tests/helpers/ui.ts b/packages/excalidraw/tests/helpers/ui.tsindex 63cf479aaa..c8921adfa0 100644--- a/packages/excalidraw/tests/helpers/ui.ts+++ b/packages/excalidraw/tests/helpers/ui.ts@@ -642,7 +642,7 @@ export class UI {naturalHeight,clientX + mouseMove[0],clientY + mouseMove[1],- keepAspectRatio ? element.width / element.height : undefined,+ { shouldMaintainAspectRatio: keepAspectRatio },);API.updateElement(element, mutations);diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.tsindex c34cfc9c97..e18a3e61f4 100644--- a/packages/excalidraw/types.ts+++ b/packages/excalidraw/types.ts@@ -1319,6 +1319,9 @@ export type PointerDownState = Readonly<{// by default same as PointerDownState.origin. On alt-duplication, reset// to current pointer position at time of duplication.origin: { x: number; y: number };+ // The offset from origin (axis-locked with shift) as of the previous+ // pointer move in the crop editor, which moves the image by the change+ lastOffset: { x: number; y: number };// explicit flag for specific scenarios such as:// - after lasso selection until the next pointer downblockDragging: boolean;