diff --git a/packages/excalidraw/actions/actionProperties.tsx b/packages/excalidraw/actions/actionProperties.tsx index df07960af..c62fd47e9 100644 --- a/packages/excalidraw/actions/actionProperties.tsx +++ b/packages/excalidraw/actions/actionProperties.tsx @@ -120,6 +120,8 @@ import { ArrowheadCrowfootIcon, ArrowheadCrowfootOneIcon, ArrowheadCrowfootOneOrManyIcon, + snapShapeEnabledIcon, + snapShapeDisabledIcon, } from "../components/icons"; import { Fonts } from "../fonts"; @@ -1807,3 +1809,41 @@ export const actionChangeArrowType = register({ ); }, }); + +export const actionToggleShapeSnap = register({ + name: "toggleShapeSnap", + label: "Toggle Snap to Shape", + trackEvent: false, + perform: (elements, appState) => { + return { + elements, + appState: { + ...appState, + isShapeSnapEnabled: !appState.isShapeSnapEnabled, + }, + captureUpdate: CaptureUpdateAction.IMMEDIATELY, + }; + }, + PanelComponent: ({ appState, updateData }) => ( +
+ {t("labels.shapeSnap")} + updateData(value)} + /> +
+ ), +}); diff --git a/packages/excalidraw/actions/types.ts b/packages/excalidraw/actions/types.ts index c4a4d2cce..ee52f0241 100644 --- a/packages/excalidraw/actions/types.ts +++ b/packages/excalidraw/actions/types.ts @@ -125,6 +125,7 @@ export type ActionName = | "toggleLinearEditor" | "toggleEraserTool" | "toggleHandTool" + | "toggleShapeSnap" | "selectAllElementsInFrame" | "removeAllElementsFromFrame" | "updateFrameRendering" diff --git a/packages/excalidraw/appState.ts b/packages/excalidraw/appState.ts index a75745f2a..bcf37868c 100644 --- a/packages/excalidraw/appState.ts +++ b/packages/excalidraw/appState.ts @@ -67,6 +67,7 @@ export const getDefaultAppState = (): Omit< gridStep: DEFAULT_GRID_STEP, gridModeEnabled: false, isBindingEnabled: true, + isShapeSnapEnabled: false, defaultSidebarDockedPreference: false, isLoading: false, isResizing: false, @@ -188,6 +189,7 @@ const APP_STATE_STORAGE_CONF = (< gridModeEnabled: { browser: true, export: true, server: true }, height: { browser: false, export: false, server: false }, isBindingEnabled: { browser: false, export: false, server: false }, + isShapeSnapEnabled: { browser: true, export: false, server: false }, defaultSidebarDockedPreference: { browser: true, export: false, diff --git a/packages/excalidraw/components/Actions.tsx b/packages/excalidraw/components/Actions.tsx index 3a7df37a8..156ff425f 100644 --- a/packages/excalidraw/components/Actions.tsx +++ b/packages/excalidraw/components/Actions.tsx @@ -169,9 +169,12 @@ export const SelectedShapeActions = ({ renderAction("changeStrokeWidth")} {(appState.activeTool.type === "freedraw" || - targetElements.some((element) => element.type === "freedraw")) && - renderAction("changeStrokeShape")} - + targetElements.some((element) => element.type === "freedraw")) && ( + <> + {renderAction("changeStrokeShape")} + {renderAction("toggleShapeSnap")} + + )} {(hasStrokeStyle(appState.activeTool.type) || targetElements.some((element) => hasStrokeStyle(element.type))) && ( <> diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx index ddb071981..249ed9e45 100644 --- a/packages/excalidraw/components/App.tsx +++ b/packages/excalidraw/components/App.tsx @@ -19,6 +19,7 @@ import { } from "@excalidraw/math"; import { isPointInShape } from "@excalidraw/utils/collision"; import { getSelectionBoxShape } from "@excalidraw/utils/shape"; +import { convertToShape } from "@excalidraw/utils/snapToShape"; import { COLOR_PALETTE, @@ -9098,6 +9099,34 @@ class App extends React.Component { lastCommittedPoint: pointFrom(dx, dy), }); + if (this.state.isShapeSnapEnabled) { + const detectedElement = convertToShape(newElement); + + if (detectedElement !== newElement) { + if (detectedElement.type === "arrow") { + mutateElement( + detectedElement, + { + startArrowhead: this.state.currentItemStartArrowhead, + endArrowhead: this.state.currentItemEndArrowhead, + }, + // TODO: Make arrows bind to nearby elements if possible + ); + } + + this.scene.replaceAllElements([ + ...this.scene + .getElementsIncludingDeleted() + .filter((el) => el.id !== newElement.id), + detectedElement, + ]); + + this.setState({ + selectedElementIds: { [detectedElement.id]: true }, + }); + } + } + this.actionManager.executeAction(actionFinalize); return; diff --git a/packages/excalidraw/components/icons.tsx b/packages/excalidraw/components/icons.tsx index f3808a69d..70d6a9a6d 100644 --- a/packages/excalidraw/components/icons.tsx +++ b/packages/excalidraw/components/icons.tsx @@ -1902,6 +1902,23 @@ export const eyeClosedIcon = createIcon( tablerIconProps, ); +export const snapShapeEnabledIcon = createIcon( + + + + , + tablerIconProps, +); + +export const snapShapeDisabledIcon = createIcon( + + + + + , + tablerIconProps, +); + export const brainIcon = createIcon( diff --git a/packages/excalidraw/locales/en.json b/packages/excalidraw/locales/en.json index 9a5211027..ea57c4fc0 100644 --- a/packages/excalidraw/locales/en.json +++ b/packages/excalidraw/locales/en.json @@ -103,6 +103,9 @@ "loadingScene": "Loading scene…", "loadScene": "Load scene from file", "align": "Align", + "shapeSnap": "Snap to shapes", + "shapeSnapDisable": "Disable snap to shapes", + "shapeSnapEnable": "Enable snap to shapes", "alignTop": "Align top", "alignBottom": "Align bottom", "alignLeft": "Align left", diff --git a/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap index 349dd9e64..112db3726 100644 --- a/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap +++ b/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap @@ -934,6 +934,7 @@ exports[`contextMenu element > right-clicking on a group should select whole gro "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -1144,6 +1145,7 @@ exports[`contextMenu element > selecting 'Add to library' in context menu adds e "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -1364,6 +1366,7 @@ exports[`contextMenu element > selecting 'Bring forward' in context menu brings "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -1699,6 +1702,7 @@ exports[`contextMenu element > selecting 'Bring to front' in context menu brings "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2034,6 +2038,7 @@ exports[`contextMenu element > selecting 'Copy styles' in context menu copies st "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2254,6 +2259,7 @@ exports[`contextMenu element > selecting 'Delete' in context menu deletes elemen "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2498,6 +2504,7 @@ exports[`contextMenu element > selecting 'Duplicate' in context menu duplicates "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2803,6 +2810,7 @@ exports[`contextMenu element > selecting 'Group selection' in context menu group "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -3176,6 +3184,7 @@ exports[`contextMenu element > selecting 'Paste styles' in context menu pastes s "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -3655,6 +3664,7 @@ exports[`contextMenu element > selecting 'Send backward' in context menu sends e "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -3982,6 +3992,7 @@ exports[`contextMenu element > selecting 'Send to back' in context menu sends el "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -4309,6 +4320,7 @@ exports[`contextMenu element > selecting 'Ungroup selection' in context menu ung "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -5590,6 +5602,7 @@ exports[`contextMenu element > shows 'Group selection' in context menu for multi "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -6812,6 +6825,7 @@ exports[`contextMenu element > shows 'Ungroup selection' in context menu for gro "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -7747,6 +7761,7 @@ exports[`contextMenu element > shows context menu for canvas > [end of test] app "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -8754,6 +8769,7 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -9743,6 +9759,7 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", diff --git a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap index 680cd82d5..e65d6adc8 100644 --- a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap +++ b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap @@ -60,6 +60,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -650,6 +651,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -1158,6 +1160,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -1530,6 +1533,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -1903,6 +1907,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -2174,6 +2179,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -2614,6 +2620,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -2917,6 +2924,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -3205,6 +3213,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -3503,6 +3512,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -3793,6 +3803,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -4032,6 +4043,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -4295,6 +4307,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -4572,6 +4585,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -4807,6 +4821,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -5042,6 +5057,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -5275,6 +5291,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -5508,6 +5525,7 @@ exports[`history > multiplayer undo/redo > conflicts in frames and their childre "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -5771,6 +5789,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -6106,6 +6125,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -6535,6 +6555,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -6917,6 +6938,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -7240,6 +7262,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -7542,6 +7565,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -7775,6 +7799,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -8134,6 +8159,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -8493,6 +8519,7 @@ exports[`history > multiplayer undo/redo > should not let remote changes to inte "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -8901,6 +8928,7 @@ exports[`history > multiplayer undo/redo > should not let remote changes to inte "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -9192,6 +9220,7 @@ exports[`history > multiplayer undo/redo > should not let remote changes to inte "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -9461,6 +9490,7 @@ exports[`history > multiplayer undo/redo > should not override remote changes on "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -9729,6 +9759,7 @@ exports[`history > multiplayer undo/redo > should not override remote changes on "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -9964,6 +9995,7 @@ exports[`history > multiplayer undo/redo > should override remotely added groups "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -10269,6 +10301,7 @@ exports[`history > multiplayer undo/redo > should override remotely added points "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -10613,6 +10646,7 @@ exports[`history > multiplayer undo/redo > should redistribute deltas when eleme "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -10852,6 +10886,7 @@ exports[`history > multiplayer undo/redo > should redraw arrows on undo > [end o "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -11305,6 +11340,7 @@ exports[`history > multiplayer undo/redo > should update history entries after r "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -11563,6 +11599,7 @@ exports[`history > singleplayer undo/redo > remounting undo/redo buttons should "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -11806,6 +11843,7 @@ exports[`history > singleplayer undo/redo > should clear the redo stack on eleme "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -12051,6 +12089,7 @@ exports[`history > singleplayer undo/redo > should create entry when selecting f "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -12456,6 +12495,7 @@ exports[`history > singleplayer undo/redo > should create new history entry on s "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -12707,6 +12747,7 @@ exports[`history > singleplayer undo/redo > should disable undo/redo buttons whe "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -12952,6 +12993,7 @@ exports[`history > singleplayer undo/redo > should end up with no history entry "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -13197,6 +13239,7 @@ exports[`history > singleplayer undo/redo > should iterate through the history w "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -13448,6 +13491,7 @@ exports[`history > singleplayer undo/redo > should not clear the redo stack on s "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -13784,6 +13828,7 @@ exports[`history > singleplayer undo/redo > should not collapse when applying co "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -13960,6 +14005,7 @@ exports[`history > singleplayer undo/redo > should not end up with history entry "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -14252,6 +14298,7 @@ exports[`history > singleplayer undo/redo > should not end up with history entry "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -14523,6 +14570,7 @@ exports[`history > singleplayer undo/redo > should not override appstate changes "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -14802,6 +14850,7 @@ exports[`history > singleplayer undo/redo > should support appstate name or view "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -14967,6 +15016,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -15665,6 +15715,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -16285,6 +16336,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -16905,6 +16957,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -17616,6 +17669,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -18364,6 +18418,7 @@ exports[`history > singleplayer undo/redo > should support changes in elements' "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -18842,6 +18897,7 @@ exports[`history > singleplayer undo/redo > should support duplication of groups "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -19368,6 +19424,7 @@ exports[`history > singleplayer undo/redo > should support element creation, del "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, @@ -19828,6 +19885,7 @@ exports[`history > singleplayer undo/redo > should support linear element creati "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "newElement": null, diff --git a/packages/excalidraw/tests/__snapshots__/regressionTests.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/regressionTests.test.tsx.snap index e98815d86..979ff1ad7 100644 --- a/packages/excalidraw/tests/__snapshots__/regressionTests.test.tsx.snap +++ b/packages/excalidraw/tests/__snapshots__/regressionTests.test.tsx.snap @@ -60,6 +60,7 @@ exports[`given element A and group of elements B and given both are selected whe "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -476,6 +477,7 @@ exports[`given element A and group of elements B and given both are selected whe "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -883,6 +885,7 @@ exports[`regression tests > Cmd/Ctrl-click exclusively select element under poin "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -1429,6 +1432,7 @@ exports[`regression tests > Drags selected element when hitting only bounding bo "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -1634,6 +1638,7 @@ exports[`regression tests > adjusts z order when grouping > [end of test] appSta "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2010,6 +2015,7 @@ exports[`regression tests > alt-drag duplicates an element > [end of test] appSt "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2246,6 +2252,7 @@ exports[`regression tests > arrow keys > [end of test] appState 1`] = ` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2427,6 +2434,7 @@ exports[`regression tests > can drag element that covers another element, while "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2748,6 +2756,7 @@ exports[`regression tests > change the properties of a shape > [end of test] app "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -2995,6 +3004,7 @@ exports[`regression tests > click on an element and drag it > [dragged] appState "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -3239,6 +3249,7 @@ exports[`regression tests > click on an element and drag it > [end of test] appS "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -3470,6 +3481,7 @@ exports[`regression tests > click to select a shape > [end of test] appState 1`] "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -3727,6 +3739,7 @@ exports[`regression tests > click-drag to select a group > [end of test] appStat "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -4039,6 +4052,7 @@ exports[`regression tests > deleting last but one element in editing group shoul "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -4462,6 +4476,7 @@ exports[`regression tests > deselects group of selected elements on pointer down "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -4746,6 +4761,7 @@ exports[`regression tests > deselects group of selected elements on pointer up w "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -5000,6 +5016,7 @@ exports[`regression tests > deselects selected element on pointer down when poin "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -5211,6 +5228,7 @@ exports[`regression tests > deselects selected element, on pointer up, when clic "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -5411,6 +5429,7 @@ exports[`regression tests > double click to edit a group > [end of test] appStat "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -5794,6 +5813,7 @@ exports[`regression tests > drags selected elements from point inside common bou "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -6085,6 +6105,7 @@ exports[`regression tests > draw every type of shape > [end of test] appState 1` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -6894,6 +6915,7 @@ exports[`regression tests > given a group of selected elements with an element t "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -7225,6 +7247,7 @@ exports[`regression tests > given a selected element A and a not selected elemen "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -7502,6 +7525,7 @@ exports[`regression tests > given selected element A with lower z-index than uns "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -7737,6 +7761,7 @@ exports[`regression tests > given selected element A with lower z-index than uns "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -7975,6 +8000,7 @@ exports[`regression tests > key 2 selects rectangle tool > [end of test] appStat "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -8156,6 +8182,7 @@ exports[`regression tests > key 3 selects diamond tool > [end of test] appState "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -8337,6 +8364,7 @@ exports[`regression tests > key 4 selects ellipse tool > [end of test] appState "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -8518,6 +8546,7 @@ exports[`regression tests > key 5 selects arrow tool > [end of test] appState 1` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -8742,6 +8771,7 @@ exports[`regression tests > key 6 selects line tool > [end of test] appState 1`] "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -8965,6 +8995,7 @@ exports[`regression tests > key 7 selects freedraw tool > [end of test] appState "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -9160,6 +9191,7 @@ exports[`regression tests > key a selects arrow tool > [end of test] appState 1` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -9384,6 +9416,7 @@ exports[`regression tests > key d selects diamond tool > [end of test] appState "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -9565,6 +9598,7 @@ exports[`regression tests > key l selects line tool > [end of test] appState 1`] "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -9788,6 +9822,7 @@ exports[`regression tests > key o selects ellipse tool > [end of test] appState "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -9969,6 +10004,7 @@ exports[`regression tests > key p selects freedraw tool > [end of test] appState "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -10164,6 +10200,7 @@ exports[`regression tests > key r selects rectangle tool > [end of test] appStat "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -10345,6 +10382,7 @@ exports[`regression tests > make a group and duplicate it > [end of test] appSta "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -10841,6 +10879,7 @@ exports[`regression tests > noop interaction after undo shouldn't create history "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -11119,6 +11158,7 @@ exports[`regression tests > pinch-to-zoom works > [end of test] appState 1`] = ` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "touch", "multiElement": null, "name": "Untitled-201933152653", @@ -11246,6 +11286,7 @@ exports[`regression tests > shift click on selected element should deselect it o "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -11446,6 +11487,7 @@ exports[`regression tests > shift-click to multiselect, then drag > [end of test "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -11758,6 +11800,7 @@ exports[`regression tests > should group elements and ungroup them > [end of tes "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -12171,6 +12214,7 @@ exports[`regression tests > single-clicking on a subgroup of a selected group sh "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -12785,6 +12829,7 @@ exports[`regression tests > spacebar + drag scrolls the canvas > [end of test] a "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -12915,6 +12960,7 @@ exports[`regression tests > supports nested groups > [end of test] appState 1`] "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -13500,6 +13546,7 @@ exports[`regression tests > switches from group of selected elements to another "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -13839,6 +13886,7 @@ exports[`regression tests > switches selected element on pointer down > [end of "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -14105,6 +14153,7 @@ exports[`regression tests > two-finger scroll works > [end of test] appState 1`] "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "touch", "multiElement": null, "name": "Untitled-201933152653", @@ -14232,6 +14281,7 @@ exports[`regression tests > undo/redo drawing an element > [end of test] appStat "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -14612,6 +14662,7 @@ exports[`regression tests > updates fontSize & fontFamily appState > [end of tes "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", @@ -14739,6 +14790,7 @@ exports[`regression tests > zoom hotkeys > [end of test] appState 1`] = ` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "Untitled-201933152653", diff --git a/packages/excalidraw/tests/packages/__snapshots__/utils.test.ts.snap b/packages/excalidraw/tests/packages/__snapshots__/utils.test.ts.snap index 610d97eb3..de8c7724c 100644 --- a/packages/excalidraw/tests/packages/__snapshots__/utils.test.ts.snap +++ b/packages/excalidraw/tests/packages/__snapshots__/utils.test.ts.snap @@ -53,6 +53,7 @@ exports[`exportToSvg > with default arguments 1`] = ` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "name", diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts index bd6e21fdc..d19c1265f 100644 --- a/packages/excalidraw/types.ts +++ b/packages/excalidraw/types.ts @@ -333,6 +333,7 @@ export interface AppState { currentHoveredFontFamily: FontFamilyValues | null; currentItemRoundness: StrokeRoundness; currentItemArrowType: "sharp" | "round" | "elbow"; + isShapeSnapEnabled: boolean; viewBackgroundColor: string; scrollX: number; scrollY: number; @@ -919,3 +920,17 @@ export type Offsets = Partial<{ bottom: number; left: number; }>; + +export type ShapeDetectionType = + | "rectangle" + | "ellipse" + | "diamond" + | "arrow" + | "line" + | "freedraw"; + +export interface ShapeDetectionResult { + type: ShapeDetectionType; + points: readonly (readonly [number, number])[]; + confidence: number; +} diff --git a/packages/math/src/point.ts b/packages/math/src/point.ts index b6054a10a..2687ea988 100644 --- a/packages/math/src/point.ts +++ b/packages/math/src/point.ts @@ -1,6 +1,6 @@ -import { degreesToRadians } from "./angle"; +import { degreesToRadians, radiansToDegrees } from "./angle"; import { PRECISION } from "./utils"; -import { vectorFromPoint, vectorScale } from "./vector"; +import { vectorDot, vectorFromPoint, vectorScale } from "./vector"; import type { LocalPoint, @@ -230,3 +230,67 @@ export const isPointWithinBounds =

( q[1] >= Math.min(p[1], r[1]) ); }; + +/** + * Calculates the perpendicular distance from a point to a line segment defined by two endpoints. + * + * If the segment is of zero length, the function returns the distance from the point to the start. + * + * @typeParam P - The point type, restricted to LocalPoint or GlobalPoint. + * @param p - The point from which the perpendicular distance is measured. + * @param start - The starting point of the line segment. + * @param end - The ending point of the line segment. + * @returns The perpendicular distance from point p to the line segment defined by start and end. + */ +export const perpendicularDistance =

( + p: P, + start: P, + end: P, +): number => { + const dx = end[0] - start[0]; + const dy = end[1] - start[1]; + if (dx === 0 && dy === 0) { + return Math.hypot(p[0] - start[0], p[1] - start[1]); + } + // Equation of line distance + const numerator = Math.abs( + dy * p[0] - dx * p[1] + end[0] * start[1] - end[1] * start[0], + ); + const denom = Math.hypot(dx, dy); + return numerator / denom; +}; + +/** * Calculates the angle between three points in degrees. + * The angle is calculated at the first point (p0) using the second (p1) and third (p2) points. + * The angle is measured in degrees and is always positive. + * The function uses the dot product and the arccosine function to calculate the angle. * The result is clamped to the range [-1, 1] to avoid precision errors. + * @param p0 The first point used to form the angle. + * @param p1 The vertex point where the angle is calculated. + * @param p2 The second point used to form the angle. + * @returns The angle in degrees between the three points. + **/ +export const angleBetween =

( + p0: P, + p1: P, + p2: P, +): Degrees => { + const v1 = vectorFromPoint(p0, p1); + const v2 = vectorFromPoint(p1, p2); + + // dot and cross product + const magnitude1 = Math.hypot(v1[0], v1[1]); + const magnitude2 = Math.hypot(v2[0], v2[1]); + + if (magnitude1 === 0 || magnitude2 === 0) { + return 0 as Degrees; + } + + const dot = vectorDot(v1, v2); + + let cos = dot / (magnitude1 * magnitude2); + // Clamp cos to [-1,1] to avoid precision errors + cos = Math.max(-1, Math.min(1, cos)); + const rad = Math.acos(cos) as Radians; + + return radiansToDegrees(rad); +}; diff --git a/packages/utils/src/snapToShape.ts b/packages/utils/src/snapToShape.ts new file mode 100644 index 000000000..9d900b78e --- /dev/null +++ b/packages/utils/src/snapToShape.ts @@ -0,0 +1,435 @@ +import { + getCenterForBounds, + getCommonBoundingBox, +} from "@excalidraw/element/bounds"; +import { + newArrowElement, + newElement, + newLinearElement, +} from "@excalidraw/element/newElement"; + +import { + angleBetween, + perpendicularDistance, + pointDistance, +} from "@excalidraw/math"; +import { ROUNDNESS } from "@excalidraw/common"; + +import type { LocalPoint } from "@excalidraw/math"; + +import type { BoundingBox, Bounds } from "@excalidraw/element/bounds"; +import type { + ExcalidrawArrowElement, + ExcalidrawDiamondElement, + ExcalidrawElement, + ExcalidrawEllipseElement, + ExcalidrawFreeDrawElement, + ExcalidrawLinearElement, + ExcalidrawRectangleElement, +} from "@excalidraw/element/types"; + +type Shape = + | ExcalidrawRectangleElement["type"] + | ExcalidrawEllipseElement["type"] + | ExcalidrawDiamondElement["type"] + | ExcalidrawArrowElement["type"] + | ExcalidrawLinearElement["type"] + | ExcalidrawFreeDrawElement["type"]; + +interface ShapeRecognitionResult { + type: Shape; + simplified: readonly LocalPoint[]; + boundingBox: BoundingBox; +} + +const QUADRILATERAL_SIDES = 4; +const QUADRILATERAL_MIN_POINTS = 4; // RDP simplified vertices +const QUADRILATERAL_MAX_POINTS = 5; // RDP might include closing point +const ARROW_EXPECTED_POINTS = 5; // RDP simplified vertices for arrow shape +const LINE_EXPECTED_POINTS = 2; // RDP simplified vertices for line shape + +const DEFAULT_OPTIONS = { + // Max distance between stroke start/end (as % of bbox diagonal) to consider closed + shapeIsClosedPercentThreshold: 20, + // Min distance (px) to consider shape closed (takes precedence if larger than %) + shapeIsClosedDistanceThreshold: 10, + // RDP simplification tolerance (% of bbox diagonal) + rdpTolerancePercent: 10, + // Arrow specific thresholds + arrowMinTipAngle: 30, // Min angle degrees for the tip + arrowMaxTipAngle: 150, // Max angle degrees for the tip + arrowHeadMaxShaftRatio: 0.8, // Max length ratio of arrowhead segment to shaft + // Quadrilateral specific thresholds + rectangleMinCornerAngle: 20, // Min deviation from 180 degrees for a valid corner + rectangleMaxCornerAngle: 160, // Max deviation from 0 degrees for a valid corner + // Angle difference (degrees) to nearest 0/90 orientation to classify as rectangle + rectangleOrientationAngleThreshold: 10, + // Max variance in radius (normalized) to consider a shape an ellipse + ellipseRadiusVarianceThreshold: 0.5, +} as const; // Use 'as const' for stricter typing of default values + +// Options for shape recognition, allowing partial overrides +type ShapeRecognitionOptions = typeof DEFAULT_OPTIONS; +type PartialShapeRecognitionOptions = Partial; + +interface Segment { + length: number; + angleDeg: number; // Angle in degrees [0, 180) representing the line's orientation +} + +/** + * Simplify a polyline using Ramer-Douglas-Peucker algorithm. + */ +function simplifyRDP( + points: readonly LocalPoint[], + epsilon: number, +): readonly LocalPoint[] { + if (points.length < 3) { + return points; + } + + const first = points[0]; + const last = points[points.length - 1]; + let index = -1; + let maxDist = 0; + + // Find the point with the maximum distance from the line segment between first and last + for (let i = 1; i < points.length - 1; i++) { + const dist = perpendicularDistance(points[i], first, last); + if (dist > maxDist) { + maxDist = dist; + index = i; + } + } + + // If max distance is greater than epsilon, recursively simplify + if (maxDist > epsilon && index !== -1) { + const left = simplifyRDP(points.slice(0, index + 1), epsilon); + const right = simplifyRDP(points.slice(index), epsilon); + // Concatenate results (omit duplicate point at junction) + return left.slice(0, -1).concat(right); + } + // Not enough deviation, return straight line segment (keep only endpoints) + return [first, last]; +} + +/** + * Calculates the properties (length, angle) of segments in a polygon. + */ +function calculateSegments(vertices: readonly LocalPoint[]): Segment[] { + const segments: Segment[] = []; + const numVertices = vertices.length; + for (let i = 0; i < numVertices; i++) { + const p1 = vertices[i]; + // Ensure wrapping for the last segment connecting back to the start + const p2 = vertices[(i + 1) % numVertices]; + const dx = p2[0] - p1[0]; + const dy = p2[1] - p1[1]; + const length = Math.hypot(dx, dy); + + // Calculate angle in degrees [0, 360) + let angleRad = Math.atan2(dy, dx); + if (angleRad < 0) { + angleRad += 2 * Math.PI; + } + let angleDeg = (angleRad * 180) / Math.PI; + + // Normalize angle to [0, 180) for undirected line orientation + if (angleDeg >= 180) { + angleDeg -= 180; + } + + segments.push({ length, angleDeg }); + } + return segments; +} + +/** + * Checks if the shape is closed based on the distance between start and end points. + */ +function isShapeClosed( + points: readonly LocalPoint[], + boundingBoxDiagonal: number, + options: ShapeRecognitionOptions, +): boolean { + const start = points[0]; + const end = points[points.length - 1]; + const closedDist = pointDistance(start, end); + const closedThreshold = Math.max( + options.shapeIsClosedDistanceThreshold, + boundingBoxDiagonal * (options.shapeIsClosedPercentThreshold / 100), + ); + return closedDist < closedThreshold; +} + +/** + * Checks if a quadrilateral is likely axis-aligned based on its segment angles. + */ +function isAxisAligned( + segments: Segment[], + orientationThreshold: number, +): boolean { + return segments.some((seg) => { + const angle = seg.angleDeg; + // Distance to horizontal (0 or 180 degrees) + const distToHoriz = Math.min(angle, 180 - angle); + // Distance to vertical (90 degrees) + const distToVert = Math.abs(angle - 90); + return ( + distToHoriz < orientationThreshold || distToVert < orientationThreshold + ); + }); +} + +/** + * Calculates the variance of the distance from points to a center point. + * Returns a normalized variance value (0 = perfectly round). + */ +function calculateRadiusVariance( + points: readonly LocalPoint[], + boundingBox: BoundingBox, +): number { + if (points.length === 0) { + return 0; // Or handle as an error/special case + } + + const [cx, cy] = getCenterForBounds([ + boundingBox.minX, + boundingBox.minY, + boundingBox.maxX, + boundingBox.maxY, + ] as Bounds); + + let totalDist = 0; + let maxDist = 0; + let minDist = Infinity; + + for (const p of points) { + const d = Math.hypot(p[0] - cx, p[1] - cy); + totalDist += d; + maxDist = Math.max(maxDist, d); + minDist = Math.min(minDist, d); + } + + const avgDist = totalDist / points.length; + + // Avoid division by zero if avgDist is 0 (e.g., all points are at the center) + if (avgDist === 0) { + return 0; + } + + const radiusVariance = (maxDist - minDist) / avgDist; + return radiusVariance; +} + +/** Checks if the points form a straight line segment. */ +function checkLine( + points: readonly LocalPoint[], + isClosed: boolean, +): Shape | null { + if (!isClosed && points.length === LINE_EXPECTED_POINTS) { + return "line"; + } + return null; +} + +/** Checks if the points form an arrow shape. */ +function checkArrow( + points: readonly LocalPoint[], + isClosed: boolean, + options: ShapeRecognitionOptions, +): Shape | null { + if (isClosed || points.length !== ARROW_EXPECTED_POINTS) { + return null; + } + + const shaftStart = points[0]; + const shaftEnd = points[1]; // Assuming RDP simplifies shaft to 2 points + const arrowBase = points[2]; + const arrowTip = points[3]; + const arrowTailEnd = points[4]; + + const tipAngle = angleBetween(arrowTip, arrowBase, arrowTailEnd); + + if ( + tipAngle <= options.arrowMinTipAngle || + tipAngle >= options.arrowMaxTipAngle + ) { + return null; + } + + const headSegment1Len = pointDistance(arrowBase, arrowTip); + const headSegment2Len = pointDistance(arrowTip, arrowTailEnd); + const shaftLen = pointDistance(shaftStart, shaftEnd); // Approx shaft length + + // Heuristic: Arrowhead segments should be significantly shorter than the shaft + const isHeadShortEnough = + headSegment1Len < shaftLen * options.arrowHeadMaxShaftRatio && + headSegment2Len < shaftLen * options.arrowHeadMaxShaftRatio; + + return isHeadShortEnough ? "arrow" : null; +} + +/** Checks if the points form a rectangle or diamond shape. */ +function checkQuadrilateral( + points: readonly LocalPoint[], + isClosed: boolean, + options: ShapeRecognitionOptions, +): Shape | null { + if ( + !isClosed || + points.length < QUADRILATERAL_MIN_POINTS || + points.length > QUADRILATERAL_MAX_POINTS + ) { + return null; + } + + // Take the first 4 points as vertices (RDP might add 5th closing point) + const vertices = points.slice(0, QUADRILATERAL_SIDES); + // console.log("Vertices (Quad Check):", vertices); + + // Calculate internal angles + const angles: number[] = []; + for (let i = 0; i < QUADRILATERAL_SIDES; i++) { + const p1 = vertices[i]; + const p2 = vertices[(i + 1) % QUADRILATERAL_SIDES]; + const p3 = vertices[(i + 2) % QUADRILATERAL_SIDES]; + + angles.push(angleBetween(p1, p2, p3)); + } + + const allCornersAreValid = angles.every( + (a) => + a > options.rectangleMinCornerAngle && + a < options.rectangleMaxCornerAngle, + ); + + if (!allCornersAreValid) { + return null; + } + + const segments = calculateSegments(vertices); + + if (isAxisAligned(segments, options.rectangleOrientationAngleThreshold)) { + return "rectangle"; + } + // Not axis-aligned, but quadrilateral => classify as diamond + return "diamond"; +} + +/** Checks if the points form an ellipse shape. */ +function checkEllipse( + points: readonly LocalPoint[], + isClosed: boolean, + boundingBox: BoundingBox, + options: ShapeRecognitionOptions, +): Shape | null { + if (!isClosed) { + return null; + } + + // Need a minimum number of points for it to be an ellipse + if (points.length < QUADRILATERAL_MAX_POINTS) { + return null; + } + + const radiusVariance = calculateRadiusVariance(points, boundingBox); + + return radiusVariance < options.ellipseRadiusVarianceThreshold + ? "ellipse" + : null; +} + +/** + * Recognizes common shapes from free-draw input points. + * @param element The freedraw element to analyze. + * @param opts Optional overrides for recognition thresholds. + * @returns Information about the recognized shape. + */ +export const recognizeShape = ( + element: ExcalidrawFreeDrawElement, + opts: PartialShapeRecognitionOptions = {}, +): ShapeRecognitionResult => { + const options = { ...DEFAULT_OPTIONS, ...opts }; + const { points } = element; + const boundingBox = getCommonBoundingBox([element]); + + // Need at least a few points to recognize a shape + if (!points || points.length < 3) { + return { type: "freedraw", simplified: points, boundingBox }; + } + + const boundingBoxDiagonal = Math.hypot(boundingBox.width, boundingBox.height); + const rdpTolerance = + boundingBoxDiagonal * (options.rdpTolerancePercent / 100); + const simplifiedPoints = simplifyRDP(points, rdpTolerance); + + const isClosed = isShapeClosed( + simplifiedPoints, + boundingBoxDiagonal, + options, + ); + + // --- Shape check order matters here --- + const recognizedType: Shape = + checkLine(simplifiedPoints, isClosed) ?? + checkArrow(simplifiedPoints, isClosed, options) ?? + checkQuadrilateral(simplifiedPoints, isClosed, options) ?? + checkEllipse(simplifiedPoints, isClosed, boundingBox, options) ?? + "freedraw"; // Default if no other shape matches + + return { + type: recognizedType, + simplified: simplifiedPoints, + boundingBox, + }; +}; + +/** + * Converts a freedraw element to the detected shape + */ +export const convertToShape = ( + freeDrawElement: ExcalidrawFreeDrawElement, +): ExcalidrawElement => { + const recognizedShape = recognizeShape(freeDrawElement); + + switch (recognizedShape.type) { + case "rectangle": + case "diamond": + case "ellipse": { + return newElement({ + ...freeDrawElement, + roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS }, + type: recognizedShape.type, + x: recognizedShape.boundingBox.minX, + y: recognizedShape.boundingBox.minY, + width: recognizedShape.boundingBox.width!, + height: recognizedShape.boundingBox.height!, + }); + } + case "arrow": { + return newArrowElement({ + ...freeDrawElement, + type: recognizedShape.type, + points: [ + recognizedShape.simplified[0], + recognizedShape.simplified[recognizedShape.simplified.length - 2], + ], + roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS }, + }); + } + case "line": { + return newLinearElement({ + ...freeDrawElement, + type: recognizedShape.type, + points: [ + recognizedShape.simplified[0], + recognizedShape.simplified[recognizedShape.simplified.length - 1], + ], + roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS }, + }); + } + default: + return freeDrawElement; + } +}; diff --git a/packages/utils/tests/__snapshots__/export.test.ts.snap b/packages/utils/tests/__snapshots__/export.test.ts.snap index 91108a600..2609e3f27 100644 --- a/packages/utils/tests/__snapshots__/export.test.ts.snap +++ b/packages/utils/tests/__snapshots__/export.test.ts.snap @@ -60,6 +60,7 @@ exports[`exportToSvg > with default arguments 1`] = ` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "name", diff --git a/packages/utils/tests/__snapshots__/utils.test.ts.snap b/packages/utils/tests/__snapshots__/utils.test.ts.snap index fdcb71295..3abde252a 100644 --- a/packages/utils/tests/__snapshots__/utils.test.ts.snap +++ b/packages/utils/tests/__snapshots__/utils.test.ts.snap @@ -53,6 +53,7 @@ exports[`exportToSvg > with default arguments 1`] = ` "isLoading": false, "isResizing": false, "isRotating": false, + "isShapeSnapEnabled": false, "lastPointerDownWith": "mouse", "multiElement": null, "name": "name",