Compare commits

..

6 Commits

Author SHA1 Message Date
Marcel Mraz 77c4eb6db4 Multiple base url fallbacks 2024-07-31 18:17:31 +02:00
Marcel Mraz 1ac2626e47 Docs for font picker 2024-07-24 19:50:59 +02:00
Marcel Mraz 43d6a7e286 Docs for font picker 2024-07-17 17:51:04 +02:00
Marcel Mraz 15b7d141c1 Fractional indices normalization docs 2024-05-21 16:16:01 +01:00
Marcel Mraz 550e23a2ab Expose StoreAction instead of StoreActionType 2024-04-22 11:01:04 +01:00
Marcel Mraz d4c6462ab1 Adding initial storeAction documentation 2024-04-18 23:16:51 +01:00
44 changed files with 4826 additions and 5808 deletions
@@ -8,15 +8,15 @@
import { FONT_FAMILY } from "@excalidraw/excalidraw";
```
`FONT_FAMILY` contains all the font families used in `Excalidraw` as explained below
`FONT_FAMILY` contains all the font families used in `Excalidraw`. The default families are the following:
| Font Family | Description |
| ----------- | ---------------------- |
| `Virgil` | The `handwritten` font |
| `Helvetica` | The `Normal` Font |
| `Cascadia` | The `Code` Font |
| `Excalifont` | The `Hand-drawn` font |
| `Nunito` | The `Normal` Font |
| `Comic Shanns` | The `Code` Font |
Defaults to `FONT_FAMILY.Virgil` unless passed in `initialData.appState.currentItemFontFamily`.
Pre-selected family is `FONT_FAMILY.Excalifont`, unless it's overriden with `initialData.appState.currentItemFontFamily`.
### THEME
@@ -65,7 +65,7 @@ You can use this function to update the scene with the sceneData. It accepts the
| `elements` | [`ImportedDataState["elements"]`](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/types.ts#L38) | The `elements` to be updated in the scene |
| `appState` | [`ImportedDataState["appState"]`](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/types.ts#L39) | The `appState` to be updated in the scene. |
| `collaborators` | <code>Map<string, <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L37">Collaborator></a></code> | The list of collaborators to be updated in the scene. |
| `commitToStore` | `boolean` | Implies if the change should be captured and commited to the `store`. Commited changes are emmitted and listened to by other components, such as `History` for undo / redo purposes. Defaults to `false`. |
| `storeAction` | [`StoreAction`](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/store.ts#L40) | Parameter to control which updates should be captured by the `Store`. Captured updates are emmitted as increments and listened to by other components, such as `History` for undo / redo purposes. |
```jsx live
function App() {
@@ -105,6 +105,7 @@ function App() {
appState: {
viewBackgroundColor: "#edf2ff",
},
storeAction: StoreAction.CAPTURE,
};
excalidrawAPI.updateScene(sceneData);
};
@@ -115,12 +116,25 @@ function App() {
<button className="custom-button" onClick={updateScene}>
Update Scene
</button>
<Excalidraw excalidrawAPI={(api) => setExcalidrawAPI(api)} />
<Excalidraw ref={(api) => setExcalidrawAPI(api)} />
</div>
);
}
```
#### storeAction
You can use the `storeAction` to influence undo / redo behaviour.
> **NOTE**: Some updates are not observed by the store / history - i.e. updates to `collaborators` object or parts of `AppState` which are not observed (not `ObservedAppState`). Such updates will never make it to the undo / redo stacks, regardless of the passed `storeAction` value.
| | `storeAction` value | Notes |
| --- | --- | --- |
| _Immediately undoable_ | `StoreAction.CAPTURE` | Use for updates which should be captured. Should be used for most of the local updates. These updates will _immediately_ make it to the local undo / redo stacks. |
| _Eventually undoable_ | `StoreAction.NONE` | Use for updates which should not be captured immediately - likely exceptions which are part of some async multi-step process. Otherwise, all such updates would end up being captured with the next `StoreAction.CAPTURE` - triggered either by the next `updateScene` or internally by the editor. These updates will _eventually_ make it to the local undo / redo stacks. |
| _Never undoable_ | `StoreAction.UPDATE` | Use for updates which should never be recorded, such as remote updates or scene initialization. These updates will _never_ make it to the local undo / redo stacks. |
### updateLibrary
<pre>
@@ -188,7 +202,7 @@ function App() {
Update Library
</button>
<Excalidraw
excalidrawAPI={(api) => setExcalidrawAPI(api)}
ref={(api) => setExcalidrawAPI(api)}
// initial data retrieved from https://github.com/excalidraw/excalidraw/blob/master/dev-docs/packages/excalidraw/initialData.js
initialData={{
libraryItems: initialData.libraryItems,
@@ -31,7 +31,7 @@ You can pass `null` / `undefined` if not applicable.
restoreElements(
elements: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">ImportedDataState["elements"]</a>,<br/>&nbsp;
localElements: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">ExcalidrawElement[]</a> | null | undefined): <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">ExcalidrawElement[]</a>,<br/>&nbsp;
opts: &#123; refreshDimensions?: boolean, repairBindings?: boolean }<br/>
opts: &#123; refreshDimensions?: boolean, repairBindings?: boolean, normalizeIndices?: boolean }<br/>
)
</pre>
@@ -51,8 +51,9 @@ The extra optional parameter to configure restored elements. It has the followin
| Prop | Type | Description|
| --- | --- | ------|
| `refreshDimensions` | `boolean` | Indicates whether we should also `recalculate` text element dimensions. Since this is a potentially costly operation, you may want to disable it if you restore elements in tight loops, such as during collaboration. |
| `repairBindings` |`boolean` | Indicates whether the `bindings` for the elements should be repaired. This is to make sure there are no containers with non existent bound text element id and no bound text elements with non existent container id. |
| `refreshDimensions` | `boolean` | Indicates whether we should also _recalculate_ text element dimensions. Since this is a potentially costly operation, you may want to disable it if you restore elements in tight loops, such as during collaboration. |
| `repairBindings` |`boolean` | Indicates whether the _bindings_ for the elements should be repaired. This is to make sure there are no containers with non existent bound text element id and no bound text elements with non existent container id. |
| `normalizeIndices` |`boolean` | Indicates whether _fractional indices_ for the elements should be normalized. This is to prevent possible issues caused by using stale (too old, too long) indices. |
**_How to use_**
@@ -73,7 +74,7 @@ restore(
data: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/types.ts#L34">ImportedDataState</a>,<br/>&nbsp;
localAppState: Partial&lt;<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95">AppState</a>> | null | undefined,<br/>&nbsp;
localElements: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">ExcalidrawElement[]</a> | null | undefined<br/>): <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/types.ts#L4">DataState</a><br/>
opts: &#123; refreshDimensions?: boolean, repairBindings?: boolean }<br/>
opts: &#123; refreshDimensions?: boolean, repairBindings?: boolean, normalizeIndices?: boolean }<br/>
)
</pre>
@@ -24,7 +24,7 @@ yarn add react react-dom @excalidraw/excalidraw
Excalidraw depends on assets such as localization files (if you opt to use them), fonts, and others.
By default these assets are loaded from a public CDN [`https://unpkg.com/@excalidraw/excalidraw/dist/`](https://unpkg.com/@excalidraw/excalidraw/dist), so you don't need to do anything on your end.
By default these assets are loaded from a public CDN [`https://unpkg.com/@excalidraw/excalidraw/dist/prod/`](https://unpkg.com/@excalidraw/excalidraw/dist/prod/), so you don't need to do anything on your end.
However, if you want to host these files yourself, you can find them in your `node_modules/@excalidraw/excalidraw/dist` directory, in folders `excalidraw-assets` (for production) and `excalidraw-assets-dev` (for development).
@@ -34,6 +34,26 @@ Copy these folders to your static assets directory, and add a `window.EXCALIDRAW
window.EXCALIDRAW_ASSET_PATH = "/";
```
or, if you serve your assets from the root of your CDN, you would do:
```js
// Vanilla
<head>
<script>
window.EXCALIDRAW_ASSET_PATH = "https://my.cdn.com/assets/";
</script>
</head>
```
or, if you prefer the path to be dynamicly set based on the `location.origin`, you could do the following:
```jsx
// Next.js
<Script id="load-env-variables" strategy="beforeInteractive" >
{ `window["EXCALIDRAW_ASSET_PATH"] = location.origin;` } // or use just "/"!
</Script>
```
### Dimensions of Excalidraw
Excalidraw takes _100%_ of `width` and `height` of the containing block so make sure the container in which you render Excalidraw has non zero dimensions.
+6 -7
View File
@@ -26,9 +26,7 @@ import {
LiveCollaborationTrigger,
TTDDialog,
TTDDialogTrigger,
StoreAction,
reconcileElements,
} from "../packages/excalidraw";
} from "../packages/excalidraw/index";
import {
AppState,
ExcalidrawImperativeAPI,
@@ -108,7 +106,10 @@ import { OverwriteConfirmDialog } from "../packages/excalidraw/components/Overwr
import Trans from "../packages/excalidraw/components/Trans";
import { ShareDialog, shareDialogStateAtom } from "./share/ShareDialog";
import CollabError, { collabErrorIndicatorAtom } from "./collab/CollabError";
import type { RemoteExcalidrawElement } from "../packages/excalidraw/data/reconcile";
import {
RemoteExcalidrawElement,
reconcileElements,
} from "../packages/excalidraw/data/reconcile";
import {
CommandPalette,
DEFAULT_CATEGORIES,
@@ -437,7 +438,7 @@ const ExcalidrawWrapper = () => {
excalidrawAPI.updateScene({
...data.scene,
...restore(data.scene, null, null, { repairBindings: true }),
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
}
});
@@ -468,7 +469,6 @@ const ExcalidrawWrapper = () => {
setLangCode(langCode);
excalidrawAPI.updateScene({
...localDataState,
storeAction: StoreAction.UPDATE,
});
LibraryIndexedDBAdapter.load().then((data) => {
if (data) {
@@ -604,7 +604,6 @@ const ExcalidrawWrapper = () => {
if (didChange) {
excalidrawAPI.updateScene({
elements,
storeAction: StoreAction.UPDATE,
});
}
}
+3 -7
View File
@@ -13,12 +13,10 @@ import {
OrderedExcalidrawElement,
} from "../../packages/excalidraw/element/types";
import {
StoreAction,
getSceneVersion,
restoreElements,
zoomToFitBounds,
reconcileElements,
} from "../../packages/excalidraw";
} from "../../packages/excalidraw/index";
import { Collaborator, Gesture } from "../../packages/excalidraw/types";
import {
assertNever,
@@ -81,9 +79,10 @@ import { Mutable, ValueOf } from "../../packages/excalidraw/utility-types";
import { getVisibleSceneBounds } from "../../packages/excalidraw/element/bounds";
import { withBatchedUpdates } from "../../packages/excalidraw/reactUtils";
import { collabErrorIndicatorAtom } from "./CollabError";
import type {
import {
ReconciledExcalidrawElement,
RemoteExcalidrawElement,
reconcileElements,
} from "../../packages/excalidraw/data/reconcile";
export const collabAPIAtom = atom<CollabAPI | null>(null);
@@ -357,7 +356,6 @@ class Collab extends PureComponent<CollabProps, CollabState> {
this.excalidrawAPI.updateScene({
elements,
storeAction: StoreAction.UPDATE,
});
}
};
@@ -508,7 +506,6 @@ class Collab extends PureComponent<CollabProps, CollabState> {
// to database even if deleted before creating the room.
this.excalidrawAPI.updateScene({
elements,
storeAction: StoreAction.UPDATE,
});
this.saveCollabRoomToFirebase(getSyncableElements(elements));
@@ -746,7 +743,6 @@ class Collab extends PureComponent<CollabProps, CollabState> {
) => {
this.excalidrawAPI.updateScene({
elements,
storeAction: StoreAction.UPDATE,
});
this.loadImageFiles();
-2
View File
@@ -19,7 +19,6 @@ import throttle from "lodash.throttle";
import { newElementWith } from "../../packages/excalidraw/element/mutateElement";
import { encryptData } from "../../packages/excalidraw/data/encryption";
import type { Socket } from "socket.io-client";
import { StoreAction } from "../../packages/excalidraw";
class Portal {
collab: TCollabClass;
@@ -128,7 +127,6 @@ class Portal {
}
return element;
}),
storeAction: StoreAction.UPDATE,
});
}, FILE_UPLOAD_TIMEOUT);
-2
View File
@@ -1,4 +1,3 @@
import { StoreAction } from "../../packages/excalidraw";
import { compressData } from "../../packages/excalidraw/data/encode";
import { newElementWith } from "../../packages/excalidraw/element/mutateElement";
import { isInitializedImageElement } from "../../packages/excalidraw/element/typeChecks";
@@ -239,6 +238,5 @@ export const updateStaleImageStatuses = (params: {
}
return element;
}),
storeAction: StoreAction.UPDATE,
});
};
+4 -2
View File
@@ -1,4 +1,3 @@
import { reconcileElements } from "../../packages/excalidraw";
import {
ExcalidrawElement,
FileId,
@@ -23,7 +22,10 @@ import { MIME_TYPES } from "../../packages/excalidraw/constants";
import { getSyncableElements, SyncableExcalidrawElement } from ".";
import { ResolutionType } from "../../packages/excalidraw/utility-types";
import type { Socket } from "socket.io-client";
import type { RemoteExcalidrawElement } from "../../packages/excalidraw/data/reconcile";
import {
RemoteExcalidrawElement,
reconcileElements,
} from "../../packages/excalidraw/data/reconcile";
// private
// -----------------------------------------------------------------------------
+1
View File
@@ -269,6 +269,7 @@ export const loadScene = async (
// in the scene database/localStorage, and instead fetch them async
// from a different database
files: data.files,
commitToStore: false,
};
};
+4 -6
View File
@@ -12,7 +12,7 @@ import {
createRedoAction,
createUndoAction,
} from "../../packages/excalidraw/actions/actionHistory";
import { StoreAction, newElementWith } from "../../packages/excalidraw";
import { newElementWith } from "../../packages/excalidraw";
const { h } = window;
@@ -90,7 +90,7 @@ describe("collaboration", () => {
updateSceneData({
elements: syncInvalidIndices([rect1, rect2]),
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
updateSceneData({
@@ -98,7 +98,7 @@ describe("collaboration", () => {
rect1,
newElementWith(h.elements[1], { isDeleted: true }),
]),
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
await waitFor(() => {
@@ -145,7 +145,6 @@ describe("collaboration", () => {
// simulate force deleting the element remotely
updateSceneData({
elements: syncInvalidIndices([rect1]),
storeAction: StoreAction.UPDATE,
});
await waitFor(() => {
@@ -183,7 +182,7 @@ describe("collaboration", () => {
h.elements[0],
newElementWith(h.elements[1], { x: 100 }),
]),
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
await waitFor(() => {
@@ -218,7 +217,6 @@ describe("collaboration", () => {
// simulate force deleting the element remotely
updateSceneData({
elements: syncInvalidIndices([rect1]),
storeAction: StoreAction.UPDATE,
});
// snapshot was correctly updated and marked the element as deleted
+4 -4
View File
@@ -26,8 +26,8 @@
"@types/chai": "4.3.0",
"@types/jest": "27.4.0",
"@types/lodash.throttle": "4.1.7",
"@types/react": "18.2.0",
"@types/react-dom": "18.2.0",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"@types/socket.io-client": "3.0.0",
"@vitejs/plugin-react": "3.1.0",
"@vitest/coverage-v8": "0.33.0",
@@ -50,11 +50,11 @@
"vite-plugin-ejs": "1.7.0",
"vite-plugin-pwa": "0.17.4",
"vite-plugin-svgr": "2.4.0",
"vitest": "1.5.3",
"vitest": "1.0.1",
"vitest-canvas-mock": "0.3.2"
},
"engines": {
"node": "18.0.0 - 22.x.x"
"node": "18.0.0 - 20.x.x"
},
"homepage": ".",
"prettier": "@excalidraw/prettier-config",
+4 -6
View File
@@ -29,19 +29,17 @@ Please add the latest change on the top under the correct section.
- Expose `getVisibleSceneBounds` helper to get scene bounds of visible canvas area. [#7450](https://github.com/excalidraw/excalidraw/pull/7450)
- Extended `window.EXCALIDRAW_ASSET_PATH` to accept array of paths `string[]` as a value, allowing to specify multiple base `URL` fallbacks. [#8286](https://github.com/excalidraw/excalidraw/pull/8286)
### Fixes
- Keep customData when converting to ExcalidrawElement. [#7656](https://github.com/excalidraw/excalidraw/pull/7656)
### Breaking Changes
- `updateScene` API has changed due to the added `Store` component as part of the multiplayer undo / redo initiative. Specifically, `sceneData` property `commitToHistory: boolean` was replaced with `storeAction: StoreActionType`. Make sure to update all instances of `updateScene` according to the _before / after_ table below. [#7898](https://github.com/excalidraw/excalidraw/pull/7898)
- Renamed required `updatedScene` parameter from `commitToHistory` into `commitToStore` [#7348](https://github.com/excalidraw/excalidraw/pull/7348).
| | Before `commitToHistory` | After `storeAction` | Notes |
| --- | --- | --- | --- |
| _Immediately undoable_ | `true` | `"capture"` | As before, use for all updates which should be recorded by the store & history. Should be used for the most of the local updates. These updates will _immediately_ make it to the local undo / redo stacks. |
| _Eventually undoable_ | `false` | `"none"` | Similar to before, use for all updates which should not be recorded immediately (likely exceptions which are part of some async multi-step process) or those not meant to be recorded at all (i.e. updates to `collaborators` object, parts of `AppState` which are not observed by the store & history - not `ObservedAppState`).<br/><br/>**IMPORTANT** It's likely you should switch to `"update"` in all the other cases. Otherwise, all such updates would end up being recorded with the next `"capture"` - triggered either by the next `updateScene` or internally by the editor. These updates will _eventually_ make it to the local undo / redo stacks. |
| _Never undoable_ | n/a | `"update"` | **NEW**: previously there was no equivalent for this value. Now, it's recommended to use `"update"` for all remote updates (from the other clients), scene initialization, or those updates, which should not be locally "undoable". These updates will _never_ make it to the local undo / redo stacks. |
### Breaking Changes
- `ExcalidrawEmbeddableElement.validated` was removed and moved to private editor state. This should largely not affect your apps unless you were reading from this attribute. We keep validating embeddable urls internally, and the public [`props.validateEmbeddable`](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/props#validateembeddable) still applies. [#7539](https://github.com/excalidraw/excalidraw/pull/7539)
+1 -1
View File
@@ -20,7 +20,7 @@ After installation you will see a folder `excalidraw-assets` and `excalidraw-ass
Move the folder `excalidraw-assets` and `excalidraw-assets-dev` to the path where your assets are served.
By default it will try to load the files from [`https://unpkg.com/@excalidraw/excalidraw/dist/`](https://unpkg.com/@excalidraw/excalidraw/dist)
By default it will try to load the files from [`https://unpkg.com/@excalidraw/excalidraw/dist/prod/`](https://unpkg.com/@excalidraw/excalidraw/dist/prod/)
If you want to load assets from a different path you can set a variable `window.EXCALIDRAW_ASSET_PATH` depending on environment (for example if you have different URL's for dev and prod) to the url from where you want to load the assets.
+7 -9
View File
@@ -12,13 +12,13 @@ import { arrayToMap } from "../utils";
import { CODES, KEYS } from "../keys";
import { getCommonBoundingBox } from "../element/bounds";
import {
bindOrUnbindLinearElements,
bindOrUnbindSelectedElements,
isBindingEnabled,
unbindLinearElements,
} from "../element/binding";
import { updateFrameMembershipOfSelectedElements } from "../frame";
import { flipHorizontal, flipVertical } from "../components/icons";
import { StoreAction } from "../store";
import { isLinearElement } from "../element/typeChecks";
export const actionFlipHorizontal = register({
name: "flipHorizontal",
@@ -89,6 +89,7 @@ const flipSelectedElements = (
const updatedElements = flipElements(
selectedElements,
elements,
elementsMap,
appState,
flipDirection,
@@ -104,6 +105,7 @@ const flipSelectedElements = (
const flipElements = (
selectedElements: NonDeleted<ExcalidrawElement>[],
elements: readonly ExcalidrawElement[],
elementsMap: NonDeletedSceneElementsMap,
appState: AppState,
flipDirection: "horizontal" | "vertical",
@@ -117,17 +119,13 @@ const flipElements = (
elementsMap,
"nw",
true,
true,
flipDirection === "horizontal" ? maxX : minX,
flipDirection === "horizontal" ? minY : maxY,
);
bindOrUnbindLinearElements(
selectedElements.filter(isLinearElement),
app,
isBindingEnabled(appState),
[],
);
isBindingEnabled(appState)
? bindOrUnbindSelectedElements(selectedElements, app)
: unbindLinearElements(selectedElements, elementsMap);
return selectedElements;
};
@@ -8,7 +8,7 @@ import { KEYS } from "../keys";
import { arrayToMap } from "../utils";
import { isWindows } from "../constants";
import { SceneElementsMap } from "../element/types";
import { Store, StoreAction } from "../store";
import { IStore, StoreAction } from "../store";
import { useEmitter } from "../hooks/useEmitter";
const writeData = (
@@ -40,7 +40,7 @@ const writeData = (
return { storeAction: StoreAction.NONE };
};
type ActionCreator = (history: History, store: Store) => Action;
type ActionCreator = (history: History, store: IStore) => Action;
export const createUndoAction: ActionCreator = (history, store) => ({
name: "undo",
+2 -2
View File
@@ -8,7 +8,7 @@ import {
UIAppState,
} from "../types";
import { MarkOptional } from "../utility-types";
import { StoreActionType } from "../store";
import { StoreAction } from "../store";
export type ActionSource =
| "ui"
@@ -26,7 +26,7 @@ export type ActionResult =
"offsetTop" | "offsetLeft" | "width" | "height"
> | null;
files?: BinaryFiles | null;
storeAction: StoreActionType;
storeAction: keyof typeof StoreAction;
replaceFiles?: boolean;
}
| false;
+114 -139
View File
@@ -90,7 +90,6 @@ import {
EDITOR_LS_KEYS,
isIOS,
supportsResizeObserver,
DEFAULT_COLLISION_THRESHOLD,
} from "../constants";
import { ExportedElements, exportCanvas, loadFromBlob } from "../data";
import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
@@ -122,16 +121,17 @@ import {
} from "../element";
import {
bindOrUnbindLinearElement,
bindOrUnbindLinearElements,
bindOrUnbindSelectedElements,
fixBindingsAfterDeletion,
fixBindingsAfterDuplication,
getEligibleElementsForBinding,
getHoveredElementForBinding,
isBindingEnabled,
isLinearElementSimpleAndAlreadyBound,
maybeBindLinearElement,
shouldEnableBindingForPointerEvent,
unbindLinearElements,
updateBoundElements,
getSuggestedBindingsForArrows,
} from "../element/binding";
import { LinearElementEditor } from "../element/linearElementEditor";
import { mutateElement, newElementWith } from "../element/mutateElement";
@@ -183,6 +183,7 @@ import {
ExcalidrawIframeElement,
ExcalidrawEmbeddableElement,
Ordered,
OrderedExcalidrawElement,
} from "../element/types";
import { getCenter, getDistance } from "../gesture";
import {
@@ -411,7 +412,7 @@ import { ElementCanvasButton } from "./MagicButton";
import { MagicIcon, copyIcon, fullscreenIcon } from "./icons";
import { EditorLocalStorage } from "../data/EditorLocalStorage";
import FollowMode from "./FollowMode/FollowMode";
import { Store, StoreAction } from "../store";
import { IStore, Store, StoreAction } from "../store";
import { AnimationFrameHandler } from "../animation-frame-handler";
import { AnimatedTrail } from "../animated-trail";
import { LaserTrails } from "../laser-trails";
@@ -542,7 +543,7 @@ class App extends React.Component<AppProps, AppState> {
public library: AppClassProperties["library"];
public libraryItemsFromStorage: LibraryItems | undefined;
public id: string;
private store: Store;
private store: IStore;
private history: History;
private excalidrawContainerValue: {
container: HTMLDivElement | null;
@@ -1703,7 +1704,6 @@ class App extends React.Component<AppProps, AppState> {
}
scale={window.devicePixelRatio}
appState={this.state}
device={this.device}
renderInteractiveSceneCallback={
this.renderInteractiveSceneCallback
}
@@ -2123,7 +2123,7 @@ class App extends React.Component<AppProps, AppState> {
}
return el;
}),
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
}
},
@@ -2810,7 +2810,7 @@ class App extends React.Component<AppProps, AppState> {
);
}
this.store.commit(elementsMap, this.state);
this.store.capture(elementsMap, this.state);
// Do not notify consumers if we're still loading the scene. Among other
// potential issues, this fixes a case where the tab isn't focused during
@@ -3683,39 +3683,51 @@ class App extends React.Component<AppProps, AppState> {
elements?: SceneData["elements"];
appState?: Pick<AppState, K> | null;
collaborators?: SceneData["collaborators"];
/** @default StoreAction.CAPTURE */
storeAction?: SceneData["storeAction"];
commitToStore?: SceneData["commitToStore"];
}) => {
const nextElements = syncInvalidIndices(sceneData.elements ?? []);
if (sceneData.storeAction && sceneData.storeAction !== StoreAction.NONE) {
const prevCommittedAppState = this.store.snapshot.appState;
const prevCommittedElements = this.store.snapshot.elements;
if (sceneData.commitToStore) {
this.store.shouldCaptureIncrement();
}
const nextCommittedAppState = sceneData.appState
? Object.assign({}, prevCommittedAppState, sceneData.appState) // new instance, with partial appstate applied to previously captured one, including hidden prop inside `prevCommittedAppState`
: prevCommittedAppState;
if (sceneData.elements || sceneData.appState) {
let nextCommittedAppState = this.state;
let nextCommittedElements: Map<string, OrderedExcalidrawElement>;
const nextCommittedElements = sceneData.elements
? this.store.filterUncomittedElements(
this.scene.getElementsMapIncludingDeleted(), // Only used to detect uncomitted local elements
arrayToMap(nextElements), // We expect all (already reconciled) elements
)
: prevCommittedElements;
// WARN: store action always performs deep clone of changed elements, for ephemeral remote updates (i.e. remote dragging, resizing, drawing) we might consider doing something smarter
// do NOT schedule store actions (execute after re-render), as it might cause unexpected concurrency issues if not handled well
if (sceneData.storeAction === StoreAction.CAPTURE) {
this.store.captureIncrement(
nextCommittedElements,
nextCommittedAppState,
);
} else if (sceneData.storeAction === StoreAction.UPDATE) {
this.store.updateSnapshot(
nextCommittedElements,
nextCommittedAppState,
);
if (sceneData.appState) {
nextCommittedAppState = {
...this.state,
...sceneData.appState, // Here we expect just partial appState
};
}
const prevElements = this.scene.getElementsIncludingDeleted();
if (sceneData.elements) {
/**
* We need to schedule a snapshot update, as in case `commitToStore` is false (i.e. remote update),
* as it's essential for computing local changes after the async action is completed (i.e. not to include remote changes in the diff).
*
* This is also a breaking change for all local `updateScene` calls without set `commitToStore` to true,
* as it makes such updates impossible to undo (previously they were undone coincidentally with the switch to the whole snapshot captured by the history).
*
* WARN: be careful here as moving it elsewhere could break the history for remote client without noticing
* - we need to find a way to test two concurrent client updates simultaneously, while having access to both stores & histories.
*/
this.store.shouldUpdateSnapshot();
// TODO#7348: deprecate once exchanging just store increments between clients
nextCommittedElements = this.store.ignoreUncomittedElements(
arrayToMap(prevElements),
arrayToMap(nextElements),
);
} else {
nextCommittedElements = arrayToMap(prevElements);
}
// WARN: Performs deep clone of changed elements, for ephemeral remote updates (i.e. remote dragging, resizing, drawing) we might consider doing something smarter
this.store.capture(nextCommittedElements, nextCommittedAppState);
}
if (sceneData.appState) {
@@ -3937,12 +3949,7 @@ class App extends React.Component<AppProps, AppState> {
});
});
this.setState({
suggestedBindings: getSuggestedBindingsForArrows(
selectedElements,
this,
),
});
this.maybeSuggestBindingForAll(selectedElements);
event.preventDefault();
} else if (event.key === KEYS.ENTER) {
@@ -4109,12 +4116,11 @@ class App extends React.Component<AppProps, AppState> {
this.setState({ isBindingEnabled: true });
}
if (isArrowKey(event.key)) {
bindOrUnbindLinearElements(
this.scene.getSelectedElements(this.state).filter(isLinearElement),
this,
isBindingEnabled(this.state),
this.state.selectedLinearElement?.selectedPointsIndices ?? [],
);
const selectedElements = this.scene.getSelectedElements(this.state);
const elementsMap = this.scene.getNonDeletedElementsMap();
isBindingEnabled(this.state)
? bindOrUnbindSelectedElements(selectedElements, this)
: unbindLinearElements(selectedElements, elementsMap);
this.setState({ suggestedBindings: [] });
}
});
@@ -4173,11 +4179,6 @@ class App extends React.Component<AppProps, AppState> {
originSnapOffset: null,
activeEmbeddable: null,
} as const;
if (nextActiveTool.type === "freedraw") {
this.store.shouldCaptureIncrement();
}
if (nextActiveTool.type !== "selection") {
return {
...prevState,
@@ -4535,7 +4536,7 @@ class App extends React.Component<AppProps, AppState> {
shape: this.getElementShape(elementWithHighestZIndex),
// when overlapping, we would like to be more precise
// this also avoids the need to update past tests
threshold: this.getElementHitThreshold() / 2,
threshold: this.getHitThreshold() / 2,
frameNameBound: isFrameLikeElement(elementWithHighestZIndex)
? this.frameNameBoundsCache.get(elementWithHighestZIndex)
: null,
@@ -4598,8 +4599,8 @@ class App extends React.Component<AppProps, AppState> {
return elements;
}
private getElementHitThreshold() {
return DEFAULT_COLLISION_THRESHOLD / this.state.zoom.value;
private getHitThreshold() {
return 10 / this.state.zoom.value;
}
private hitElement(
@@ -4617,7 +4618,7 @@ class App extends React.Component<AppProps, AppState> {
const selectionShape = getSelectionBoxShape(
element,
this.scene.getNonDeletedElementsMap(),
this.getElementHitThreshold(),
this.getHitThreshold(),
);
return isPointInShape([x, y], selectionShape);
@@ -4638,7 +4639,7 @@ class App extends React.Component<AppProps, AppState> {
y,
element,
shape: this.getElementShape(element),
threshold: this.getElementHitThreshold(),
threshold: this.getHitThreshold(),
frameNameBound: isFrameLikeElement(element)
? this.frameNameBoundsCache.get(element)
: null,
@@ -4670,7 +4671,7 @@ class App extends React.Component<AppProps, AppState> {
y,
element: elements[index],
shape: this.getElementShape(elements[index]),
threshold: this.getElementHitThreshold(),
threshold: this.getHitThreshold(),
})
) {
hitElement = elements[index];
@@ -4923,7 +4924,7 @@ class App extends React.Component<AppProps, AppState> {
y: sceneY,
element: container,
shape: this.getElementShape(container),
threshold: this.getElementHitThreshold(),
threshold: this.getHitThreshold(),
})
) {
const midPoint = getContainerCenter(
@@ -5338,41 +5339,24 @@ class App extends React.Component<AppProps, AppState> {
!isOverScrollBar &&
!this.state.editingLinearElement
) {
// for linear elements, we'd like to prioritize point dragging over edge resizing
// therefore, we update and check hovered point index first
if (this.state.selectedLinearElement) {
this.handleHoverSelectedLinearElement(
this.state.selectedLinearElement,
scenePointerX,
scenePointerY,
);
}
const elementWithTransformHandleType = getElementWithTransformHandleType(
elements,
this.state,
scenePointerX,
scenePointerY,
this.state.zoom,
event.pointerType,
this.scene.getNonDeletedElementsMap(),
);
if (
!this.state.selectedLinearElement ||
this.state.selectedLinearElement.hoverPointIndex === -1
elementWithTransformHandleType &&
elementWithTransformHandleType.transformHandleType
) {
const elementWithTransformHandleType =
getElementWithTransformHandleType(
elements,
this.state,
scenePointerX,
scenePointerY,
this.state.zoom,
event.pointerType,
this.scene.getNonDeletedElementsMap(),
this.device,
);
if (
elementWithTransformHandleType &&
elementWithTransformHandleType.transformHandleType
) {
setCursor(
this.interactiveCanvas,
getCursorForResizingElement(elementWithTransformHandleType),
);
return;
}
setCursor(
this.interactiveCanvas,
getCursorForResizingElement(elementWithTransformHandleType),
);
return;
}
} else if (selectedElements.length > 1 && !isOverScrollBar) {
const transformHandleType = getTransformHandleTypeFromCoords(
@@ -5381,7 +5365,6 @@ class App extends React.Component<AppProps, AppState> {
scenePointerY,
this.state.zoom,
event.pointerType,
this.device,
);
if (transformHandleType) {
setCursor(
@@ -5534,7 +5517,7 @@ class App extends React.Component<AppProps, AppState> {
scenePointer.x,
scenePointer.y,
);
const threshold = this.getElementHitThreshold();
const threshold = this.getHitThreshold();
const point = { ...pointerDownState.lastCoords };
let samplingInterval = 0;
while (samplingInterval <= distance) {
@@ -5631,7 +5614,7 @@ class App extends React.Component<AppProps, AppState> {
if (hoverPointIndex >= 0 || segmentMidPointHoveredCoords) {
setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
} else if (this.hitElement(scenePointerX, scenePointerY, element)) {
} else {
setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
}
} else if (this.hitElement(scenePointerX, scenePointerY, element)) {
@@ -5721,7 +5704,6 @@ class App extends React.Component<AppProps, AppState> {
this.state,
),
},
storeAction: StoreAction.UPDATE,
});
return;
}
@@ -6331,14 +6313,7 @@ class App extends React.Component<AppProps, AppState> {
const elementsMap = this.scene.getNonDeletedElementsMap();
const selectedElements = this.scene.getSelectedElements(this.state);
if (
selectedElements.length === 1 &&
!this.state.editingLinearElement &&
!(
this.state.selectedLinearElement &&
this.state.selectedLinearElement.hoverPointIndex !== -1
)
) {
if (selectedElements.length === 1 && !this.state.editingLinearElement) {
const elementWithTransformHandleType =
getElementWithTransformHandleType(
elements,
@@ -6348,7 +6323,6 @@ class App extends React.Component<AppProps, AppState> {
this.state.zoom,
event.pointerType,
this.scene.getNonDeletedElementsMap(),
this.device,
);
if (elementWithTransformHandleType != null) {
this.setState({
@@ -6364,7 +6338,6 @@ class App extends React.Component<AppProps, AppState> {
pointerDownState.origin.y,
this.state.zoom,
event.pointerType,
this.device,
);
}
if (pointerDownState.resize.handleType) {
@@ -6621,7 +6594,7 @@ class App extends React.Component<AppProps, AppState> {
}
// How many pixels off the shape boundary we still consider a hit
const threshold = this.getElementHitThreshold();
const threshold = this.getHitThreshold();
const [x1, y1, x2, y2] = getCommonBounds(selectedElements);
return (
point.x > x1 - threshold &&
@@ -7458,12 +7431,7 @@ class App extends React.Component<AppProps, AppState> {
event[KEYS.CTRL_OR_CMD] ? null : this.state.gridSize,
);
this.setState({
suggestedBindings: getSuggestedBindingsForArrows(
selectedElements,
this,
),
});
this.maybeSuggestBindingForAll(selectedElements);
// We duplicate the selected element if alt is pressed on pointer move
if (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {
@@ -8025,7 +7993,6 @@ class App extends React.Component<AppProps, AppState> {
appState: {
draggingElement: null,
},
storeAction: StoreAction.UPDATE,
});
return;
@@ -8198,7 +8165,6 @@ class App extends React.Component<AppProps, AppState> {
elements: this.scene
.getElementsIncludingDeleted()
.filter((el) => el.id !== resizingElement.id),
storeAction: StoreAction.UPDATE,
});
}
@@ -8451,7 +8417,7 @@ class App extends React.Component<AppProps, AppState> {
y: pointerDownState.origin.y,
element: hitElement,
shape: this.getElementShape(hitElement),
threshold: this.getElementHitThreshold(),
threshold: this.getHitThreshold(),
frameNameBound: isFrameLikeElement(hitElement)
? this.frameNameBoundsCache.get(hitElement)
: null,
@@ -8510,18 +8476,15 @@ class App extends React.Component<AppProps, AppState> {
}
if (pointerDownState.drag.hasOccurred || isResizing || isRotating) {
// We only allow binding via linear elements, specifically via dragging
// the endpoints ("start" or "end").
const linearElements = this.scene
.getSelectedElements(this.state)
.filter(isLinearElement);
bindOrUnbindLinearElements(
linearElements,
this,
isBindingEnabled(this.state),
this.state.selectedLinearElement?.selectedPointsIndices ?? [],
);
isBindingEnabled(this.state)
? bindOrUnbindSelectedElements(
this.scene.getSelectedElements(this.state),
this,
)
: unbindLinearElements(
this.scene.getNonDeletedElements(),
elementsMap,
);
}
if (activeTool.type === "laser") {
@@ -9053,6 +9016,19 @@ class App extends React.Component<AppProps, AppState> {
this.setState({ suggestedBindings });
};
private maybeSuggestBindingForAll(
selectedElements: NonDeleted<ExcalidrawElement>[],
): void {
if (selectedElements.length > 50) {
return;
}
const suggestedBindings = getEligibleElementsForBinding(
selectedElements,
this,
);
this.setState({ suggestedBindings });
}
private clearSelection(hitElement: ExcalidrawElement | null): void {
this.setState((prevState) => ({
selectedElementIds: makeNextSelectedElementIds({}, prevState),
@@ -9252,12 +9228,13 @@ class App extends React.Component<AppProps, AppState> {
}
if (ret.type === MIME_TYPES.excalidraw) {
// restore the fractional indices by mutating elements
// Restore the fractional indices by mutating elements and update the
// store snapshot, otherwise we would end up with duplicate indices
syncInvalidIndices(elements.concat(ret.data.elements));
// update the store snapshot for old elements, otherwise we would end up with duplicated fractional indices on undo
this.store.updateSnapshot(arrayToMap(elements), this.state);
this.store.snapshot = this.store.snapshot.clone(
arrayToMap(elements),
this.state,
);
this.setState({ isLoading: true });
this.syncActionResult({
...ret.data,
@@ -9439,6 +9416,8 @@ class App extends React.Component<AppProps, AppState> {
this.state.originSnapOffset,
);
this.maybeSuggestBindingForAll([draggingElement]);
// highlight elements that are to be added to frames on frames creation
if (
this.state.activeTool.type === TOOL_TYPE.frame ||
@@ -9552,7 +9531,7 @@ class App extends React.Component<AppProps, AppState> {
this.scene.getElementsMapIncludingDeleted(),
shouldRotateWithDiscreteAngle(event),
shouldResizeFromCenter(event),
selectedElements.some((element) => isImageElement(element))
selectedElements.length === 1 && isImageElement(selectedElements[0])
? !shouldMaintainAspectRatio(event)
: shouldMaintainAspectRatio(event),
resizeX,
@@ -9561,10 +9540,7 @@ class App extends React.Component<AppProps, AppState> {
pointerDownState.resize.center.y,
)
) {
const suggestedBindings = getSuggestedBindingsForArrows(
selectedElements,
this,
);
this.maybeSuggestBindingForAll(selectedElements);
const elementsToHighlight = new Set<ExcalidrawElement>();
selectedFrames.forEach((frame) => {
@@ -9578,7 +9554,6 @@ class App extends React.Component<AppProps, AppState> {
this.setState({
elementsToHighlight: [...elementsToHighlight],
suggestedBindings,
});
return true;
+1 -3
View File
@@ -1,5 +1,3 @@
@import "../css/variables.module.scss";
.excalidraw {
.SVGLayer {
pointer-events: none;
@@ -9,7 +7,7 @@
top: 0;
left: 0;
z-index: var(--zIndex-svgLayer);
z-index: 2;
& svg {
image-rendering: auto;
@@ -3,7 +3,7 @@ import { isShallowEqual, sceneCoordsToViewportCoords } from "../../utils";
import { CURSOR_TYPE } from "../../constants";
import { t } from "../../i18n";
import type { DOMAttributes } from "react";
import type { AppState, Device, InteractiveCanvasAppState } from "../../types";
import type { AppState, InteractiveCanvasAppState } from "../../types";
import type {
InteractiveCanvasRenderConfig,
RenderableElementsMap,
@@ -23,7 +23,6 @@ type InteractiveCanvasProps = {
selectionNonce: number | undefined;
scale: number;
appState: InteractiveCanvasAppState;
device: Device;
renderInteractiveSceneCallback: (
data: RenderInteractiveSceneCallback,
) => void;
@@ -133,7 +132,6 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
selectionColor,
renderScrollbars: false,
},
device: props.device,
callback: props.renderInteractiveSceneCallback,
},
isRenderThrottlingEnabled(),
-7
View File
@@ -148,13 +148,6 @@ export const DEFAULT_VERTICAL_ALIGN = "top";
export const DEFAULT_VERSION = "{version}";
export const DEFAULT_TRANSFORM_HANDLE_SPACING = 2;
export const SIDE_RESIZING_THRESHOLD = 2 * DEFAULT_TRANSFORM_HANDLE_SPACING;
// a small epsilon to make side resizing always take precedence
// (avoids an increase in renders and changes to tests)
const EPSILON = 0.00001;
export const DEFAULT_COLLISION_THRESHOLD =
2 * SIDE_RESIZING_THRESHOLD - EPSILON;
export const COLOR_WHITE = "#ffffff";
export const COLOR_CHARCOAL_BLACK = "#1e1e1e";
// keep this in sync with CSS
-1
View File
@@ -4,7 +4,6 @@
:root {
--zIndex-canvas: 1;
--zIndex-interactiveCanvas: 2;
--zIndex-svgLayer: 3;
--zIndex-wysiwyg: 3;
--zIndex-canvasButtons: 3;
--zIndex-layerUI: 4;
+173 -190
View File
@@ -131,193 +131,73 @@ const bindOrUnbindLinearElementEdge = (
unboundFromElementIds: Set<ExcalidrawBindableElement["id"]>,
elementsMap: NonDeletedSceneElementsMap,
): void => {
// "keep" is for method chaining convenience, a "no-op", so just bail out
if (bindableElement === "keep") {
return;
}
// null means break the bind, so nothing to consider here
if (bindableElement === null) {
const unbound = unbindLinearElement(linearElement, startOrEnd);
if (unbound != null) {
unboundFromElementIds.add(unbound);
}
return;
}
// While complext arrows can do anything, simple arrow with both ends trying
// to bind to the same bindable should not be allowed, start binding takes
// precedence
if (isLinearElementSimple(linearElement)) {
if (
otherEdgeBindableElement == null ||
(otherEdgeBindableElement === "keep"
? // TODO: Refactor - Needlessly complex
!isLinearElementSimpleAndAlreadyBoundOnOppositeEdge(
linearElement,
bindableElement,
startOrEnd,
)
: startOrEnd === "start" ||
otherEdgeBindableElement.id !== bindableElement.id)
) {
bindLinearElement(
linearElement,
bindableElement,
startOrEnd,
elementsMap,
);
boundToElementIds.add(bindableElement.id);
}
} else {
bindLinearElement(linearElement, bindableElement, startOrEnd, elementsMap);
boundToElementIds.add(bindableElement.id);
}
};
const getOriginalBindingIfStillCloseOfLinearElementEdge = (
linearElement: NonDeleted<ExcalidrawLinearElement>,
edge: "start" | "end",
app: AppClassProperties,
): NonDeleted<ExcalidrawElement> | null => {
const elementsMap = app.scene.getNonDeletedElementsMap();
const coors = getLinearElementEdgeCoors(linearElement, edge, elementsMap);
const elementId =
edge === "start"
? linearElement.startBinding?.elementId
: linearElement.endBinding?.elementId;
if (elementId) {
const element = elementsMap.get(
elementId,
) as NonDeleted<ExcalidrawBindableElement>;
if (bindingBorderTest(element, coors, app)) {
return element;
if (bindableElement !== "keep") {
if (bindableElement != null) {
// Don't bind if we're trying to bind or are already bound to the same
// element on the other edge already ("start" edge takes precedence).
if (
otherEdgeBindableElement == null ||
(otherEdgeBindableElement === "keep"
? !isLinearElementSimpleAndAlreadyBoundOnOppositeEdge(
linearElement,
bindableElement,
startOrEnd,
)
: startOrEnd === "start" ||
otherEdgeBindableElement.id !== bindableElement.id)
) {
bindLinearElement(
linearElement,
bindableElement,
startOrEnd,
elementsMap,
);
boundToElementIds.add(bindableElement.id);
}
} else {
const unbound = unbindLinearElement(linearElement, startOrEnd);
if (unbound != null) {
unboundFromElementIds.add(unbound);
}
}
}
return null;
};
const getOriginalBindingsIfStillCloseToArrowEnds = (
linearElement: NonDeleted<ExcalidrawLinearElement>,
export const bindOrUnbindSelectedElements = (
selectedElements: NonDeleted<ExcalidrawElement>[],
app: AppClassProperties,
): (NonDeleted<ExcalidrawElement> | null)[] =>
["start", "end"].map((edge) =>
getOriginalBindingIfStillCloseOfLinearElementEdge(
linearElement,
edge as "start" | "end",
app,
),
);
const getBindingStrategyForDraggingArrowEndpoints = (
selectedElement: NonDeleted<ExcalidrawLinearElement>,
isBindingEnabled: boolean,
draggingPoints: readonly number[],
app: AppClassProperties,
): (NonDeleted<ExcalidrawBindableElement> | null | "keep")[] => {
const startIdx = 0;
const endIdx = selectedElement.points.length - 1;
const startDragged = draggingPoints.findIndex((i) => i === startIdx) > -1;
const endDragged = draggingPoints.findIndex((i) => i === endIdx) > -1;
const start = startDragged
? isBindingEnabled
? getElligibleElementForBindingElement(selectedElement, "start", app)
: null // If binding is disabled and start is dragged, break all binds
: // We have to update the focus and gap of the binding, so let's rebind
getElligibleElementForBindingElement(selectedElement, "start", app);
const end = endDragged
? isBindingEnabled
? getElligibleElementForBindingElement(selectedElement, "end", app)
: null // If binding is disabled and end is dragged, break all binds
: // We have to update the focus and gap of the binding, so let's rebind
getElligibleElementForBindingElement(selectedElement, "end", app);
return [start, end];
};
const getBindingStrategyForDraggingArrowOrJoints = (
selectedElement: NonDeleted<ExcalidrawLinearElement>,
app: AppClassProperties,
isBindingEnabled: boolean,
): (NonDeleted<ExcalidrawBindableElement> | null | "keep")[] => {
const [startIsClose, endIsClose] = getOriginalBindingsIfStillCloseToArrowEnds(
selectedElement,
app,
);
const start = startIsClose
? isBindingEnabled
? getElligibleElementForBindingElement(selectedElement, "start", app)
: null
: null;
const end = endIsClose
? isBindingEnabled
? getElligibleElementForBindingElement(selectedElement, "end", app)
: null
: null;
return [start, end];
};
export const bindOrUnbindLinearElements = (
selectedElements: NonDeleted<ExcalidrawLinearElement>[],
app: AppClassProperties,
isBindingEnabled: boolean,
draggingPoints: readonly number[] | null,
): void => {
selectedElements.forEach((selectedElement) => {
const [start, end] = draggingPoints?.length
? // The arrow edge points are dragged (i.e. start, end)
getBindingStrategyForDraggingArrowEndpoints(
selectedElement,
isBindingEnabled,
draggingPoints ?? [],
app,
)
: // The arrow itself (the shaft) or the inner joins are dragged
getBindingStrategyForDraggingArrowOrJoints(
selectedElement,
app,
isBindingEnabled,
);
bindOrUnbindLinearElement(
selectedElement,
start,
end,
app.scene.getNonDeletedElementsMap(),
);
if (isBindingElement(selectedElement)) {
bindOrUnbindLinearElement(
selectedElement,
getElligibleElementForBindingElement(selectedElement, "start", app),
getElligibleElementForBindingElement(selectedElement, "end", app),
app.scene.getNonDeletedElementsMap(),
);
} else if (isBindableElement(selectedElement)) {
maybeBindBindableElement(
selectedElement,
app.scene.getNonDeletedElementsMap(),
app,
);
}
});
};
export const getSuggestedBindingsForArrows = (
selectedElements: NonDeleted<ExcalidrawElement>[],
const maybeBindBindableElement = (
bindableElement: NonDeleted<ExcalidrawBindableElement>,
elementsMap: NonDeletedSceneElementsMap,
app: AppClassProperties,
): SuggestedBinding[] => {
// HOT PATH: Bail out if selected elements list is too large
if (selectedElements.length > 50) {
return [];
}
return (
selectedElements
.filter(isLinearElement)
.flatMap((element) =>
getOriginalBindingsIfStillCloseToArrowEnds(element, app),
)
.filter(
(element): element is NonDeleted<ExcalidrawBindableElement> =>
element !== null,
)
// Filter out bind candidates which are in the
// same selection / group with the arrow
//
// TODO: Is it worth turning the list into a set to avoid dupes?
.filter(
(element) =>
selectedElements.filter((selected) => selected.id === element?.id)
.length === 0,
)
): void => {
getElligibleElementsForBindableElementAndWhere(bindableElement, app).forEach(
([linearElement, where]) =>
bindOrUnbindLinearElement(
linearElement,
where === "end" ? "keep" : bindableElement,
where === "start" ? "keep" : bindableElement,
elementsMap,
),
);
};
@@ -403,14 +283,20 @@ export const isLinearElementSimpleAndAlreadyBound = (
bindableElement: ExcalidrawBindableElement,
): boolean => {
return (
alreadyBoundToId === bindableElement.id &&
isLinearElementSimple(linearElement)
alreadyBoundToId === bindableElement.id && linearElement.points.length < 3
);
};
const isLinearElementSimple = (
linearElement: NonDeleted<ExcalidrawLinearElement>,
): boolean => linearElement.points.length < 3;
export const unbindLinearElements = (
elements: readonly NonDeleted<ExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
): void => {
elements.forEach((element) => {
if (isBindingElement(element)) {
bindOrUnbindLinearElement(element, null, null, elementsMap);
}
});
};
const unbindLinearElement = (
linearElement: NonDeleted<ExcalidrawLinearElement>,
@@ -657,6 +543,42 @@ const maybeCalculateNewGapWhenScaling = (
return { elementId, gap: newGap, focus };
};
// TODO: this is a bottleneck, optimise
export const getEligibleElementsForBinding = (
selectedElements: NonDeleted<ExcalidrawElement>[],
app: AppClassProperties,
): SuggestedBinding[] => {
const includedElementIds = new Set(selectedElements.map(({ id }) => id));
return selectedElements.flatMap((selectedElement) =>
isBindingElement(selectedElement, false)
? (getElligibleElementsForBindingElement(
selectedElement as NonDeleted<ExcalidrawLinearElement>,
app,
).filter(
(element) => !includedElementIds.has(element.id),
) as SuggestedBinding[])
: isBindableElement(selectedElement, false)
? getElligibleElementsForBindableElementAndWhere(
selectedElement,
app,
).filter((binding) => !includedElementIds.has(binding[0].id))
: [],
);
};
const getElligibleElementsForBindingElement = (
linearElement: NonDeleted<ExcalidrawLinearElement>,
app: AppClassProperties,
): NonDeleted<ExcalidrawBindableElement>[] => {
return [
getElligibleElementForBindingElement(linearElement, "start", app),
getElligibleElementForBindingElement(linearElement, "end", app),
].filter(
(element): element is NonDeleted<ExcalidrawBindableElement> =>
element != null,
);
};
const getElligibleElementForBindingElement = (
linearElement: NonDeleted<ExcalidrawLinearElement>,
startOrEnd: "start" | "end",
@@ -687,6 +609,67 @@ const getLinearElementEdgeCoors = (
);
};
const getElligibleElementsForBindableElementAndWhere = (
bindableElement: NonDeleted<ExcalidrawBindableElement>,
app: AppClassProperties,
): SuggestedPointBinding[] => {
const scene = Scene.getScene(bindableElement)!;
return scene
.getNonDeletedElements()
.map((element) => {
if (!isBindingElement(element, false)) {
return null;
}
const canBindStart = isLinearElementEligibleForNewBindingByBindable(
element,
"start",
bindableElement,
scene.getNonDeletedElementsMap(),
app,
);
const canBindEnd = isLinearElementEligibleForNewBindingByBindable(
element,
"end",
bindableElement,
scene.getNonDeletedElementsMap(),
app,
);
if (!canBindStart && !canBindEnd) {
return null;
}
return [
element,
canBindStart && canBindEnd ? "both" : canBindStart ? "start" : "end",
bindableElement,
];
})
.filter((maybeElement) => maybeElement != null) as SuggestedPointBinding[];
};
const isLinearElementEligibleForNewBindingByBindable = (
linearElement: NonDeleted<ExcalidrawLinearElement>,
startOrEnd: "start" | "end",
bindableElement: NonDeleted<ExcalidrawBindableElement>,
elementsMap: NonDeletedSceneElementsMap,
app: AppClassProperties,
): boolean => {
const existingBinding =
linearElement[startOrEnd === "start" ? "startBinding" : "endBinding"];
return (
existingBinding == null &&
!isLinearElementSimpleAndAlreadyBoundOnOppositeEdge(
linearElement,
bindableElement,
startOrEnd,
) &&
bindingBorderTest(
bindableElement,
getLinearElementEdgeCoors(linearElement, startOrEnd, elementsMap),
app,
)
);
};
// We need to:
// 1: Update elements not selected to point to duplicated elements
// 2: Update duplicated elements to point to other duplicated elements
@@ -822,7 +805,7 @@ const newBoundElements = (
return nextBoundElements;
};
const bindingBorderTest = (
export const bindingBorderTest = (
element: NonDeleted<ExcalidrawBindableElement>,
{ x, y }: { x: number; y: number },
app: AppClassProperties,
@@ -844,7 +827,7 @@ export const maxBindingGap = (
return Math.max(16, Math.min(0.25 * smallerDimension, 32));
};
const distanceToBindableElement = (
export const distanceToBindableElement = (
element: ExcalidrawBindableElement,
point: Point,
elementsMap: ElementsMap,
@@ -901,7 +884,7 @@ const distanceToDiamond = (
return GAPoint.distanceToLine(pointRel, side);
};
const distanceToEllipse = (
export const distanceToEllipse = (
element: ExcalidrawEllipseElement,
point: Point,
elementsMap: ElementsMap,
@@ -1020,7 +1003,7 @@ const coordsCenter = (
// all focus points lie, so it's a number between -1 and 1.
// The line going through `a` and `b` is a tangent to the "focus image"
// of the element.
const determineFocusDistance = (
export const determineFocusDistance = (
element: ExcalidrawBindableElement,
// Point on the line, in absolute coordinates
a: Point,
@@ -1061,7 +1044,7 @@ const determineFocusDistance = (
return ret || 0;
};
const determineFocusPoint = (
export const determineFocusPoint = (
element: ExcalidrawBindableElement,
// The oriented, relative distance from the center of `element` of the
// returned focusPoint
@@ -1101,7 +1084,7 @@ const determineFocusPoint = (
// Returns 2 or 0 intersection points between line going through `a` and `b`
// and the `element`, in ascending order of distance from `a`.
const intersectElementWithLine = (
export const intersectElementWithLine = (
element: ExcalidrawBindableElement,
// Point on the line, in absolute coordinates
a: Point,
@@ -1268,7 +1251,7 @@ const getEllipseIntersections = (
];
};
const getCircleIntersections = (
export const getCircleIntersections = (
center: GA.Point,
radius: number,
line: GA.Line,
@@ -1298,7 +1281,7 @@ const getCircleIntersections = (
// The focus point is the tangent point of the "focus image" of the
// `element`, where the tangent goes through `point`.
const findFocusPointForEllipse = (
export const findFocusPointForEllipse = (
ellipse: ExcalidrawEllipseElement,
// Between -1 and 1 (not 0) the relative size of the "focus image" of
// the element on which the focus point lies
@@ -1335,7 +1318,7 @@ const findFocusPointForEllipse = (
return GA.point(x, (-m * x - 1) / n);
};
const findFocusPointForRectangulars = (
export const findFocusPointForRectangulars = (
element:
| ExcalidrawRectangleElement
| ExcalidrawImageElement
@@ -49,7 +49,7 @@ import { getBoundTextElement, handleBindTextResize } from "./textElement";
import { DRAGGING_THRESHOLD } from "../constants";
import { Mutable } from "../utility-types";
import { ShapeCache } from "../scene/ShapeCache";
import { Store } from "../store";
import { IStore } from "../store";
const editorMidPointsCache: {
version: number | null;
@@ -642,7 +642,7 @@ export class LinearElementEditor {
static handlePointerDown(
event: React.PointerEvent<HTMLElement>,
appState: AppState,
store: Store,
store: IStore,
scenePointer: { x: number; y: number },
linearElementEditor: LinearElementEditor,
app: AppClassProperties,
+142 -139
View File
@@ -1,7 +1,12 @@
import { MIN_FONT_SIZE, SHIFT_LOCKING_ANGLE } from "../constants";
import { rescalePoints } from "../points";
import { rotate, centerPoint, rotatePoint } from "../math";
import {
rotate,
adjustXYWithRotation,
centerPoint,
rotatePoint,
} from "../math";
import {
ExcalidrawLinearElement,
ExcalidrawTextElement,
@@ -18,6 +23,7 @@ import {
getCommonBounds,
getResizedElementAbsoluteCoords,
getCommonBoundingBox,
getElementPointsCoords,
} from "./bounds";
import {
isArrowElement,
@@ -32,6 +38,7 @@ import { mutateElement } from "./mutateElement";
import { getFontString } from "../utils";
import { updateBoundElements } from "./binding";
import {
TransformHandleType,
MaybeTransformHandleType,
TransformHandleDirection,
} from "./transformHandles";
@@ -47,7 +54,6 @@ import {
getApproxMinLineHeight,
} from "./textElement";
import { LinearElementEditor } from "./linearElementEditor";
import { isInGroup } from "../groups";
export const normalizeAngle = (angle: number): number => {
if (angle < 0) {
@@ -127,14 +133,18 @@ export const transformElements = (
centerY,
);
return true;
} else if (transformHandleType) {
} else if (
transformHandleType === "nw" ||
transformHandleType === "ne" ||
transformHandleType === "sw" ||
transformHandleType === "se"
) {
resizeMultipleElements(
originalElements,
selectedElements,
elementsMap,
transformHandleType,
shouldResizeFromCenter,
shouldMaintainAspectRatio,
pointerX,
pointerY,
);
@@ -222,6 +232,26 @@ const measureFontSizeFromWidth = (
};
};
const getSidesForTransformHandle = (
transformHandleType: TransformHandleType,
shouldResizeFromCenter: boolean,
) => {
return {
n:
/^(n|ne|nw)$/.test(transformHandleType) ||
(shouldResizeFromCenter && /^(s|se|sw)$/.test(transformHandleType)),
s:
/^(s|se|sw)$/.test(transformHandleType) ||
(shouldResizeFromCenter && /^(n|ne|nw)$/.test(transformHandleType)),
w:
/^(w|nw|sw)$/.test(transformHandleType) ||
(shouldResizeFromCenter && /^(e|ne|se)$/.test(transformHandleType)),
e:
/^(e|ne|se)$/.test(transformHandleType) ||
(shouldResizeFromCenter && /^(w|nw|sw)$/.test(transformHandleType)),
};
};
const resizeSingleTextElement = (
element: NonDeleted<ExcalidrawTextElement>,
elementsMap: ElementsMap,
@@ -230,10 +260,9 @@ const resizeSingleTextElement = (
pointerX: number,
pointerY: number,
) => {
const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
element,
elementsMap,
);
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
// rotation pointer with reverse angle
const [rotatedX, rotatedY] = rotate(
pointerX,
@@ -242,24 +271,33 @@ const resizeSingleTextElement = (
cy,
-element.angle,
);
let scaleX = 0;
let scaleY = 0;
if (transformHandleType.includes("e")) {
scaleX = (rotatedX - x1) / (x2 - x1);
let scale: number;
switch (transformHandleType) {
case "se":
scale = Math.max(
(rotatedX - x1) / (x2 - x1),
(rotatedY - y1) / (y2 - y1),
);
break;
case "nw":
scale = Math.max(
(x2 - rotatedX) / (x2 - x1),
(y2 - rotatedY) / (y2 - y1),
);
break;
case "ne":
scale = Math.max(
(rotatedX - x1) / (x2 - x1),
(y2 - rotatedY) / (y2 - y1),
);
break;
case "sw":
scale = Math.max(
(x2 - rotatedX) / (x2 - x1),
(rotatedY - y1) / (y2 - y1),
);
break;
}
if (transformHandleType.includes("w")) {
scaleX = (x2 - rotatedX) / (x2 - x1);
}
if (transformHandleType.includes("n")) {
scaleY = (y2 - rotatedY) / (y2 - y1);
}
if (transformHandleType.includes("s")) {
scaleY = (rotatedY - y1) / (y2 - y1);
}
const scale = Math.max(scaleX, scaleY);
if (scale > 0) {
const nextWidth = element.width * scale;
const nextHeight = element.height * scale;
@@ -267,55 +305,32 @@ const resizeSingleTextElement = (
if (metrics === null) {
return;
}
const startTopLeft = [x1, y1];
const startBottomRight = [x2, y2];
const startCenter = [cx, cy];
let newTopLeft = [x1, y1] as [number, number];
if (["n", "w", "nw"].includes(transformHandleType)) {
newTopLeft = [
startBottomRight[0] - Math.abs(nextWidth),
startBottomRight[1] - Math.abs(nextHeight),
];
}
if (transformHandleType === "ne") {
const bottomLeft = [startTopLeft[0], startBottomRight[1]];
newTopLeft = [bottomLeft[0], bottomLeft[1] - Math.abs(nextHeight)];
}
if (transformHandleType === "sw") {
const topRight = [startBottomRight[0], startTopLeft[1]];
newTopLeft = [topRight[0] - Math.abs(nextWidth), topRight[1]];
}
if (["s", "n"].includes(transformHandleType)) {
newTopLeft[0] = startCenter[0] - nextWidth / 2;
}
if (["e", "w"].includes(transformHandleType)) {
newTopLeft[1] = startCenter[1] - nextHeight / 2;
}
if (shouldResizeFromCenter) {
newTopLeft[0] = startCenter[0] - Math.abs(nextWidth) / 2;
newTopLeft[1] = startCenter[1] - Math.abs(nextHeight) / 2;
}
const angle = element.angle;
const rotatedTopLeft = rotatePoint(newTopLeft, [cx, cy], angle);
const newCenter: Point = [
newTopLeft[0] + Math.abs(nextWidth) / 2,
newTopLeft[1] + Math.abs(nextHeight) / 2,
];
const rotatedNewCenter = rotatePoint(newCenter, [cx, cy], angle);
newTopLeft = rotatePoint(rotatedTopLeft, rotatedNewCenter, -angle);
const [nextX, nextY] = newTopLeft;
const [nextX1, nextY1, nextX2, nextY2] = getResizedElementAbsoluteCoords(
element,
nextWidth,
nextHeight,
false,
);
const deltaX1 = (x1 - nextX1) / 2;
const deltaY1 = (y1 - nextY1) / 2;
const deltaX2 = (x2 - nextX2) / 2;
const deltaY2 = (y2 - nextY2) / 2;
const [nextElementX, nextElementY] = adjustXYWithRotation(
getSidesForTransformHandle(transformHandleType, shouldResizeFromCenter),
element.x,
element.y,
element.angle,
deltaX1,
deltaY1,
deltaX2,
deltaY2,
);
mutateElement(element, {
fontSize: metrics.size,
width: nextWidth,
height: nextHeight,
x: nextX,
y: nextY,
x: nextElementX,
y: nextElementY,
});
}
};
@@ -621,9 +636,8 @@ export const resizeMultipleElements = (
originalElements: PointerDownState["originalElements"],
selectedElements: readonly NonDeletedExcalidrawElement[],
elementsMap: ElementsMap,
transformHandleType: TransformHandleDirection,
transformHandleType: "nw" | "ne" | "sw" | "se",
shouldResizeFromCenter: boolean,
shouldMaintainAspectRatio: boolean,
pointerX: number,
pointerY: number,
) => {
@@ -677,80 +691,43 @@ export const resizeMultipleElements = (
const { minX, minY, maxX, maxY, midX, midY } = getCommonBoundingBox(
targetElements.map(({ orig }) => orig).concat(boundTextElements),
);
const width = maxX - minX;
const height = maxY - minY;
// const originalHeight = maxY - minY;
// const originalWidth = maxX - minX;
const direction = transformHandleType;
const anchorsMap: Record<TransformHandleDirection, Point> = {
const mapDirectionsToAnchors: Record<typeof direction, Point> = {
ne: [minX, maxY],
se: [minX, minY],
sw: [maxX, minY],
nw: [maxX, maxY],
e: [minX, minY + height / 2],
w: [maxX, minY + height / 2],
n: [minX + width / 2, maxY],
s: [minX + width / 2, minY],
};
// anchor point must be on the opposite side of the dragged selection handle
// or be the center of the selection if shouldResizeFromCenter
const [anchorX, anchorY]: Point = shouldResizeFromCenter
? [midX, midY]
: anchorsMap[direction];
const resizeFromCenterScale = shouldResizeFromCenter ? 2 : 1;
: mapDirectionsToAnchors[direction];
const scale =
Math.max(
Math.abs(pointerX - anchorX) / width || 0,
Math.abs(pointerY - anchorY) / height || 0,
) * resizeFromCenterScale;
Math.abs(pointerX - anchorX) / (maxX - minX) || 0,
Math.abs(pointerY - anchorY) / (maxY - minY) || 0,
) * (shouldResizeFromCenter ? 2 : 1);
if (scale === 0) {
return;
}
let scaleX =
direction.includes("e") || direction.includes("w")
? (Math.abs(pointerX - anchorX) / width) * resizeFromCenterScale
: 1;
let scaleY =
direction.includes("n") || direction.includes("s")
? (Math.abs(pointerY - anchorY) / height) * resizeFromCenterScale
: 1;
const keepAspectRatio =
shouldMaintainAspectRatio ||
targetElements.some(
(item) =>
item.latest.angle !== 0 ||
isTextElement(item.latest) ||
isInGroup(item.latest),
);
if (keepAspectRatio) {
scaleX = scale;
scaleY = scale;
}
const flipConditionsMap: Record<
TransformHandleDirection,
// Condition for which we should flip or not flip the selected elements
// - when evaluated to `true`, we flip
// - therefore, setting it to always `false` means we do not flip (in that direction) at all
const mapDirectionsToPointerPositions: Record<
typeof direction,
[x: boolean, y: boolean]
> = {
ne: [pointerX < anchorX, pointerY > anchorY],
se: [pointerX < anchorX, pointerY < anchorY],
sw: [pointerX > anchorX, pointerY < anchorY],
nw: [pointerX > anchorX, pointerY > anchorY],
// e.g. when resizing from the "e" side, we do not need to consider changes in the `y` direction
// and therefore, we do not need to flip in the `y` direction at all
e: [pointerX < anchorX, false],
w: [pointerX > anchorX, false],
n: [false, pointerY > anchorY],
s: [false, pointerY < anchorY],
ne: [pointerX >= anchorX, pointerY <= anchorY],
se: [pointerX >= anchorX, pointerY >= anchorY],
sw: [pointerX <= anchorX, pointerY >= anchorY],
nw: [pointerX <= anchorX, pointerY <= anchorY],
};
/**
@@ -761,9 +738,9 @@ export const resizeMultipleElements = (
* mirror points in the case of linear & freedraw elemenets
* 3. adjust element angle
*/
const [flipFactorX, flipFactorY] = flipConditionsMap[direction].map(
(condition) => (condition ? -1 : 1),
);
const [flipFactorX, flipFactorY] = mapDirectionsToPointerPositions[
direction
].map((condition) => (condition ? 1 : -1));
const isFlippedByX = flipFactorX < 0;
const isFlippedByY = flipFactorY < 0;
@@ -785,8 +762,8 @@ export const resizeMultipleElements = (
continue;
}
const width = orig.width * scaleX;
const height = orig.height * scaleY;
const width = orig.width * scale;
const height = orig.height * scale;
const angle = normalizeAngle(orig.angle * flipFactorX * flipFactorY);
const isLinearOrFreeDraw = isLinearElement(orig) || isFreeDrawElement(orig);
@@ -794,8 +771,8 @@ export const resizeMultipleElements = (
const offsetY = orig.y - anchorY;
const shiftX = isFlippedByX && !isLinearOrFreeDraw ? width : 0;
const shiftY = isFlippedByY && !isLinearOrFreeDraw ? height : 0;
const x = anchorX + flipFactorX * (offsetX * scaleX + shiftX);
const y = anchorY + flipFactorY * (offsetY * scaleY + shiftY);
const x = anchorX + flipFactorX * (offsetX * scale + shiftX);
const y = anchorY + flipFactorY * (offsetY * scale + shiftY);
const rescaledPoints = rescalePointsInElement(
orig,
@@ -813,10 +790,40 @@ export const resizeMultipleElements = (
...rescaledPoints,
};
if (isImageElement(orig)) {
if (isImageElement(orig) && targetElements.length === 1) {
update.scale = [orig.scale[0] * flipFactorX, orig.scale[1] * flipFactorY];
}
if (isLinearElement(orig) && (isFlippedByX || isFlippedByY)) {
const origBounds = getElementPointsCoords(orig, orig.points);
const newBounds = getElementPointsCoords(
{ ...orig, x, y },
rescaledPoints.points!,
);
const origXY = [orig.x, orig.y];
const newXY = [x, y];
const linearShift = (axis: "x" | "y") => {
const i = axis === "x" ? 0 : 1;
return (
(newBounds[i + 2] -
newXY[i] -
(origXY[i] - origBounds[i]) * scale +
(origBounds[i + 2] - origXY[i]) * scale -
(newXY[i] - newBounds[i])) /
2
);
};
if (isFlippedByX) {
update.x -= linearShift("x");
}
if (isFlippedByY) {
update.y -= linearShift("y");
}
}
if (isTextElement(orig)) {
const metrics = measureFontSizeFromWidth(orig, elementsMap, width);
if (!metrics) {
@@ -830,15 +837,11 @@ export const resizeMultipleElements = (
) as ExcalidrawTextElementWithContainer | undefined;
if (boundTextElement) {
if (keepAspectRatio) {
const newFontSize = boundTextElement.fontSize * scale;
if (newFontSize < MIN_FONT_SIZE) {
return;
}
update.boundTextFontSize = newFontSize;
} else {
update.boundTextFontSize = boundTextElement.fontSize;
const newFontSize = boundTextElement.fontSize * scale;
if (newFontSize < MIN_FONT_SIZE) {
return;
}
update.boundTextFontSize = newFontSize;
}
elementsAndUpdates.push({
+6 -99
View File
@@ -6,24 +6,15 @@ import {
} from "./types";
import {
OMIT_SIDES_FOR_MULTIPLE_ELEMENTS,
getTransformHandlesFromCoords,
getTransformHandles,
TransformHandleType,
TransformHandle,
MaybeTransformHandleType,
getOmitSidesForDevice,
canResizeFromSides,
} from "./transformHandles";
import { AppState, Device, Zoom } from "../types";
import { Bounds, getElementAbsoluteCoords } from "./bounds";
import { SIDE_RESIZING_THRESHOLD } from "../constants";
import {
angleToDegrees,
pointOnLine,
pointRotate,
} from "../../utils/geometry/geometry";
import { Line, Point } from "../../utils/geometry/shape";
import { isLinearElement } from "./typeChecks";
import { AppState, Zoom } from "../types";
import { Bounds } from "./bounds";
const isInsideTransformHandle = (
transformHandle: TransformHandle,
@@ -43,20 +34,13 @@ export const resizeTest = (
y: number,
zoom: Zoom,
pointerType: PointerType,
device: Device,
): MaybeTransformHandleType => {
if (!appState.selectedElementIds[element.id]) {
return false;
}
const { rotation: rotationTransformHandle, ...transformHandles } =
getTransformHandles(
element,
zoom,
elementsMap,
pointerType,
getOmitSidesForDevice(device),
);
getTransformHandles(element, zoom, elementsMap, pointerType);
if (
rotationTransformHandle &&
@@ -78,35 +62,6 @@ export const resizeTest = (
return filter[0] as TransformHandleType;
}
if (canResizeFromSides(device)) {
const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
element,
elementsMap,
);
// Note that for a text element, when "resized" from the side
// we should make it wrap/unwrap
if (
element.type !== "text" &&
!(isLinearElement(element) && element.points.length <= 2)
) {
const SPACING = SIDE_RESIZING_THRESHOLD / zoom.value;
const sides = getSelectionBorders(
[x1 - SPACING, y1 - SPACING],
[x2 + SPACING, y2 + SPACING],
[cx, cy],
angleToDegrees(element.angle),
);
for (const [dir, side] of Object.entries(sides)) {
// test to see if x, y are on the line segment
if (pointOnLine([x, y], side as Line, SPACING)) {
return dir as TransformHandleType;
}
}
}
}
return false;
};
@@ -118,7 +73,6 @@ export const getElementWithTransformHandleType = (
zoom: Zoom,
pointerType: PointerType,
elementsMap: ElementsMap,
device: Device,
) => {
return elements.reduce((result, element) => {
if (result) {
@@ -132,7 +86,6 @@ export const getElementWithTransformHandleType = (
scenePointerY,
zoom,
pointerType,
device,
);
return transformHandleType ? { element, transformHandleType } : null;
}, null as { element: NonDeletedExcalidrawElement; transformHandleType: MaybeTransformHandleType } | null);
@@ -144,14 +97,13 @@ export const getTransformHandleTypeFromCoords = (
scenePointerY: number,
zoom: Zoom,
pointerType: PointerType,
device: Device,
): MaybeTransformHandleType => {
const transformHandles = getTransformHandlesFromCoords(
[x1, y1, x2, y2, (x1 + x2) / 2, (y1 + y2) / 2],
0,
zoom,
pointerType,
getOmitSidesForDevice(device),
OMIT_SIDES_FOR_MULTIPLE_ELEMENTS,
);
const found = Object.keys(transformHandles).find((key) => {
@@ -162,33 +114,7 @@ export const getTransformHandleTypeFromCoords = (
isInsideTransformHandle(transformHandle, scenePointerX, scenePointerY)
);
});
if (found) {
return found as MaybeTransformHandleType;
}
if (canResizeFromSides(device)) {
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
const SPACING = SIDE_RESIZING_THRESHOLD / zoom.value;
const sides = getSelectionBorders(
[x1 - SPACING, y1 - SPACING],
[x2 + SPACING, y2 + SPACING],
[cx, cy],
angleToDegrees(0),
);
for (const [dir, side] of Object.entries(sides)) {
// test to see if x, y are on the line segment
if (pointOnLine([scenePointerX, scenePointerY], side as Line, SPACING)) {
return dir as TransformHandleType;
}
}
}
return false;
return (found || false) as MaybeTransformHandleType;
};
const RESIZE_CURSORS = ["ns", "nesw", "ew", "nwse"];
@@ -248,22 +174,3 @@ export const getCursorForResizingElement = (resizingElement: {
return cursor ? `${cursor}-resize` : "";
};
const getSelectionBorders = (
[x1, y1]: Point,
[x2, y2]: Point,
center: Point,
angleInDegrees: number,
) => {
const topLeft = pointRotate([x1, y1], angleInDegrees, center);
const topRight = pointRotate([x2, y1], angleInDegrees, center);
const bottomLeft = pointRotate([x1, y2], angleInDegrees, center);
const bottomRight = pointRotate([x2, y2], angleInDegrees, center);
return {
n: [topLeft, topRight],
e: [topRight, bottomRight],
s: [bottomRight, bottomLeft],
w: [bottomLeft, topLeft],
};
};
@@ -7,14 +7,10 @@ import {
import { Bounds, getElementAbsoluteCoords } from "./bounds";
import { rotate } from "../math";
import { Device, InteractiveCanvasAppState, Zoom } from "../types";
import { InteractiveCanvasAppState, Zoom } from "../types";
import { isTextElement } from ".";
import { isFrameLikeElement, isLinearElement } from "./typeChecks";
import {
DEFAULT_TRANSFORM_HANDLE_SPACING,
isAndroid,
isIOS,
} from "../constants";
import { DEFAULT_TRANSFORM_HANDLE_SPACING } from "../constants";
export type TransformHandleDirection =
| "n"
@@ -42,13 +38,6 @@ const transformHandleSizes: { [k in PointerType]: number } = {
const ROTATION_RESIZE_HANDLE_GAP = 16;
export const DEFAULT_OMIT_SIDES = {
e: true,
s: true,
n: true,
w: true,
};
export const OMIT_SIDES_FOR_MULTIPLE_ELEMENTS = {
e: true,
s: true,
@@ -100,26 +89,6 @@ const generateTransformHandle = (
return [xx - width / 2, yy - height / 2, width, height];
};
export const canResizeFromSides = (device: Device) => {
if (device.viewport.isMobile) {
return false;
}
if (device.isTouchScreen && (isAndroid || isIOS)) {
return false;
}
return true;
};
export const getOmitSidesForDevice = (device: Device) => {
if (canResizeFromSides(device)) {
return DEFAULT_OMIT_SIDES;
}
return {};
};
export const getTransformHandlesFromCoords = (
[x1, y1, x2, y2, cx, cy]: [number, number, number, number, number, number],
angle: number,
@@ -263,8 +232,8 @@ export const getTransformHandles = (
element: ExcalidrawElement,
zoom: Zoom,
elementsMap: ElementsMap,
pointerType: PointerType = "mouse",
omitSides: { [T in TransformHandleType]?: boolean } = DEFAULT_OMIT_SIDES,
): TransformHandles => {
// so that when locked element is selected (especially when you toggle lock
// via keyboard) the locked element is visually distinct, indicating
@@ -273,6 +242,7 @@ export const getTransformHandles = (
return {};
}
let omitSides: { [T in TransformHandleType]?: boolean } = {};
if (element.type === "freedraw" || isLinearElement(element)) {
if (element.points.length === 2) {
// only check the last point because starting point is always (0,0)
@@ -293,7 +263,6 @@ export const getTransformHandles = (
omitSides = OMIT_SIDES_FOR_TEXT_ELEMENT;
} else if (isFrameLikeElement(element)) {
omitSides = {
...omitSides,
rotation: true,
};
}
-4
View File
@@ -387,7 +387,3 @@ export const elementsAreInSameGroup = (elements: ExcalidrawElement[]) => {
return maxGroup === elements.length;
};
export const isInGroup = (element: NonDeletedExcalidrawElement) => {
return element.groupIds.length > 0;
};
-4
View File
@@ -220,8 +220,6 @@ export {
restoreLibraryItems,
} from "./data/restore";
export { reconcileElements } from "./data/reconcile";
export {
exportToCanvas,
exportToBlob,
@@ -253,8 +251,6 @@ export {
bumpVersion,
} from "./element/mutateElement";
export { StoreAction } from "./store";
export { parseLibraryTokensFromUrl, useHandleLibrary } from "./data/library";
export {
@@ -1,5 +1,6 @@
import {
getElementAbsoluteCoords,
OMIT_SIDES_FOR_MULTIPLE_ELEMENTS,
getTransformHandlesFromCoords,
getTransformHandles,
getCommonBounds,
@@ -22,7 +23,7 @@ import {
selectGroupsFromGivenElements,
} from "../groups";
import {
getOmitSidesForDevice,
OMIT_SIDES_FOR_FRAME,
shouldShowBoundingBox,
TransformHandles,
TransformHandleType,
@@ -576,7 +577,6 @@ const _renderInteractiveScene = ({
scale,
appState,
renderConfig,
device,
}: InteractiveSceneRenderConfig) => {
if (canvas === null) {
return { atLeastOneVisibleElement: false, elementsMap };
@@ -806,7 +806,6 @@ const _renderInteractiveScene = ({
appState.zoom,
elementsMap,
"mouse", // when we render we don't know which pointer type so use mouse,
getOmitSidesForDevice(device),
);
if (!appState.viewModeEnabled && showBoundingBox) {
renderTransformHandles(
@@ -845,8 +844,8 @@ const _renderInteractiveScene = ({
appState.zoom,
"mouse",
isFrameSelected
? { ...getOmitSidesForDevice(device), rotation: true }
: getOmitSidesForDevice(device),
? OMIT_SIDES_FOR_FRAME
: OMIT_SIDES_FOR_MULTIPLE_ELEMENTS,
);
if (selectedElements.some((element) => !element.locked)) {
renderTransformHandles(
-2
View File
@@ -16,7 +16,6 @@ import {
StaticCanvasAppState,
SocketId,
UserIdleState,
Device,
} from "../types";
import { MakeBrand } from "../utility-types";
@@ -86,7 +85,6 @@ export type InteractiveSceneRenderConfig = {
scale: number;
appState: InteractiveCanvasAppState;
renderConfig: InteractiveCanvasRenderConfig;
device: Device;
callback: (data: RenderInteractiveSceneCallback) => void;
};
+98 -182
View File
@@ -1,6 +1,5 @@
import { getDefaultAppState } from "./appState";
import { AppStateChange, ElementsChange } from "./change";
import { ENV } from "./constants";
import { newElementWith } from "./element/mutateElement";
import { deepCopyElement } from "./element/newElement";
import { OrderedExcalidrawElement } from "./element/types";
@@ -8,11 +7,8 @@ import { Emitter } from "./emitter";
import { AppState, ObservedAppState } from "./types";
import { isShallowEqual } from "./utils";
// hidden non-enumerable property for runtime checks
const hiddenObservedAppStateProp = "__observedAppState";
export const getObservedAppState = (appState: AppState): ObservedAppState => {
const observedAppState = {
return {
name: appState.name,
editingGroupId: appState.editingGroupId,
viewBackgroundColor: appState.viewBackgroundColor,
@@ -21,40 +17,14 @@ export const getObservedAppState = (appState: AppState): ObservedAppState => {
editingLinearElementId: appState.editingLinearElement?.elementId || null,
selectedLinearElementId: appState.selectedLinearElement?.elementId || null,
};
Reflect.defineProperty(observedAppState, hiddenObservedAppStateProp, {
value: true,
enumerable: false,
});
return observedAppState;
};
const isObservedAppState = (
appState: AppState | ObservedAppState,
): appState is ObservedAppState =>
!!Reflect.get(appState, hiddenObservedAppStateProp);
export type StoreActionType = "capture" | "update" | "none";
export const StoreAction: {
[K in Uppercase<StoreActionType>]: StoreActionType;
} = {
CAPTURE: "capture",
UPDATE: "update",
NONE: "none",
export const StoreAction = {
NONE: "NONE",
UPDATE: "UPDATE",
CAPTURE: "CAPTURE",
} as const;
/**
* Represent an increment to the Store.
*/
class StoreIncrementEvent {
constructor(
public readonly elementsChange: ElementsChange,
public readonly appStateChange: AppStateChange,
) {}
}
/**
* Store which captures the observed changes and emits them as `StoreIncrementEvent` events.
*
@@ -71,18 +41,18 @@ export interface IStore {
shouldUpdateSnapshot(): void;
/**
* Use to schedule calculation of a store increment.
* Use to schedule calculation of a store increment on a next component update.
*/
shouldCaptureIncrement(): void;
/**
* Based on the scheduled operation, either only updates store snapshot or also calculates increment and emits the result as a `StoreIncrementEvent`.
* Capture changes to the `elements` and `appState` by calculating changes (based on a snapshot) and emitting resulting changes as a store increment.
*
* @emits StoreIncrementEvent when increment is calculated.
* @emits StoreIncrementEvent
*/
commit(
elements: Map<string, OrderedExcalidrawElement> | undefined,
appState: AppState | ObservedAppState | undefined,
capture(
elements: Map<string, OrderedExcalidrawElement>,
appState: AppState,
): void;
/**
@@ -94,19 +64,33 @@ export interface IStore {
* Filters out yet uncomitted elements from `nextElements`, which are part of in-progress local async actions (ephemerals) and thus were not yet commited to the snapshot.
*
* This is necessary in updates in which we receive reconciled elements, already containing elements which were not yet captured by the local store (i.e. collab).
*
* Once we will be exchanging just store increments for all ephemerals, this could be deprecated.
*/
filterUncomittedElements(
ignoreUncomittedElements(
prevElements: Map<string, OrderedExcalidrawElement>,
nextElements: Map<string, OrderedExcalidrawElement>,
): Map<string, OrderedExcalidrawElement>;
}
/**
* Represent an increment to the Store.
*/
class StoreIncrementEvent {
constructor(
public readonly elementsChange: ElementsChange,
public readonly appStateChange: AppStateChange,
) {}
}
export class Store implements IStore {
public readonly onStoreIncrementEmitter = new Emitter<
[StoreIncrementEvent]
>();
private scheduledActions: Set<StoreActionType> = new Set();
private calculatingIncrement: boolean = false;
private updatingSnapshot: boolean = false;
private _snapshot = Snapshot.empty();
public get snapshot() {
@@ -117,81 +101,64 @@ export class Store implements IStore {
this._snapshot = snapshot;
}
// TODO: Suspicious that this is called so many places. Seems error-prone.
public shouldCaptureIncrement = () => {
this.scheduleAction(StoreAction.CAPTURE);
};
public shouldUpdateSnapshot = () => {
this.scheduleAction(StoreAction.UPDATE);
this.updatingSnapshot = true;
};
private scheduleAction = (action: StoreActionType) => {
this.scheduledActions.add(action);
this.satisfiesScheduledActionsInvariant();
// Suspicious that this is called so many places. Seems error-prone.
public shouldCaptureIncrement = () => {
this.calculatingIncrement = true;
};
public commit = (
elements: Map<string, OrderedExcalidrawElement> | undefined,
appState: AppState | ObservedAppState | undefined,
public capture = (
elements: Map<string, OrderedExcalidrawElement>,
appState: AppState,
): void => {
// Quick exit for irrelevant changes
if (!this.calculatingIncrement && !this.updatingSnapshot) {
return;
}
try {
// Capture has precedence since it also performs update
if (this.scheduledActions.has(StoreAction.CAPTURE)) {
this.captureIncrement(elements, appState);
} else if (this.scheduledActions.has(StoreAction.UPDATE)) {
this.updateSnapshot(elements, appState);
const nextSnapshot = this._snapshot.clone(elements, appState);
// Optimisation, don't continue if nothing has changed
if (this._snapshot !== nextSnapshot) {
// Calculate and record the changes based on the previous and next snapshot
if (this.calculatingIncrement) {
const elementsChange = nextSnapshot.meta.didElementsChange
? ElementsChange.calculate(
this._snapshot.elements,
nextSnapshot.elements,
)
: ElementsChange.empty();
const appStateChange = nextSnapshot.meta.didAppStateChange
? AppStateChange.calculate(
this._snapshot.appState,
nextSnapshot.appState,
)
: AppStateChange.empty();
if (!elementsChange.isEmpty() || !appStateChange.isEmpty()) {
// Notify listeners with the increment
this.onStoreIncrementEmitter.trigger(
new StoreIncrementEvent(elementsChange, appStateChange),
);
}
}
// Update the snapshot
this._snapshot = nextSnapshot;
}
} finally {
this.satisfiesScheduledActionsInvariant();
// Defensively reset all scheduled actions, potentially cleans up other runtime garbage
this.scheduledActions = new Set();
// Reset props
this.updatingSnapshot = false;
this.calculatingIncrement = false;
}
};
public captureIncrement = (
elements: Map<string, OrderedExcalidrawElement> | undefined,
appState: AppState | ObservedAppState | undefined,
) => {
const prevSnapshot = this.snapshot;
const nextSnapshot = this.snapshot.maybeClone(elements, appState);
// Optimisation, don't continue if nothing has changed
if (prevSnapshot !== nextSnapshot) {
// Calculate and record the changes based on the previous and next snapshot
const elementsChange = nextSnapshot.meta.didElementsChange
? ElementsChange.calculate(prevSnapshot.elements, nextSnapshot.elements)
: ElementsChange.empty();
const appStateChange = nextSnapshot.meta.didAppStateChange
? AppStateChange.calculate(prevSnapshot.appState, nextSnapshot.appState)
: AppStateChange.empty();
if (!elementsChange.isEmpty() || !appStateChange.isEmpty()) {
// Notify listeners with the increment
this.onStoreIncrementEmitter.trigger(
new StoreIncrementEvent(elementsChange, appStateChange),
);
}
// Update snapshot
this.snapshot = nextSnapshot;
}
};
public updateSnapshot = (
elements: Map<string, OrderedExcalidrawElement> | undefined,
appState: AppState | ObservedAppState | undefined,
) => {
const nextSnapshot = this.snapshot.maybeClone(elements, appState);
if (this.snapshot !== nextSnapshot) {
// Update snapshot
this.snapshot = nextSnapshot;
}
};
public filterUncomittedElements = (
public ignoreUncomittedElements = (
prevElements: Map<string, OrderedExcalidrawElement>,
nextElements: Map<string, OrderedExcalidrawElement>,
) => {
@@ -203,7 +170,7 @@ export class Store implements IStore {
continue;
}
const elementSnapshot = this.snapshot.elements.get(id);
const elementSnapshot = this._snapshot.elements.get(id);
// Checks for in progress async user action
if (!elementSnapshot) {
@@ -219,19 +186,7 @@ export class Store implements IStore {
};
public clear = (): void => {
this.snapshot = Snapshot.empty();
this.scheduledActions = new Set();
};
private satisfiesScheduledActionsInvariant = () => {
if (!(this.scheduledActions.size >= 0 && this.scheduledActions.size <= 3)) {
const message = `There can be at most three store actions scheduled at the same time, but there are "${this.scheduledActions.size}".`;
console.error(message, this.scheduledActions.values());
if (import.meta.env.DEV || import.meta.env.MODE === ENV.TEST) {
throw new Error(message);
}
}
this._snapshot = Snapshot.empty();
};
}
@@ -263,32 +218,31 @@ export class Snapshot {
}
/**
* Efficiently clone the existing snapshot, only if we detected changes.
* Efficiently clone the existing snapshot.
*
* @returns same instance if there are no changes detected, new instance otherwise.
*/
public maybeClone(
elements: Map<string, OrderedExcalidrawElement> | undefined,
appState: AppState | ObservedAppState | undefined,
public clone(
elements: Map<string, OrderedExcalidrawElement>,
appState: AppState,
) {
const nextElementsSnapshot = this.maybeCreateElementsSnapshot(elements);
const nextAppStateSnapshot = this.maybeCreateAppStateSnapshot(appState);
const didElementsChange = this.detectChangedElements(elements);
let didElementsChange = false;
let didAppStateChange = false;
if (this.elements !== nextElementsSnapshot) {
didElementsChange = true;
}
if (this.appState !== nextAppStateSnapshot) {
didAppStateChange = true;
}
// Not watching over everything from app state, just the relevant props
const nextAppStateSnapshot = getObservedAppState(appState);
const didAppStateChange = this.detectChangedAppState(nextAppStateSnapshot);
// Nothing has changed, so there is no point of continuing further
if (!didElementsChange && !didAppStateChange) {
return this;
}
// Clone only if there was really a change
let nextElementsSnapshot = this.elements;
if (didElementsChange) {
nextElementsSnapshot = this.createElementsSnapshot(elements);
}
const snapshot = new Snapshot(nextElementsSnapshot, nextAppStateSnapshot, {
didElementsChange,
didAppStateChange,
@@ -297,55 +251,10 @@ export class Snapshot {
return snapshot;
}
private maybeCreateAppStateSnapshot(
appState: AppState | ObservedAppState | undefined,
) {
if (!appState) {
return this.appState;
}
// Not watching over everything from the app state, just the relevant props
const nextAppStateSnapshot = !isObservedAppState(appState)
? getObservedAppState(appState)
: appState;
const didAppStateChange = this.detectChangedAppState(nextAppStateSnapshot);
if (!didAppStateChange) {
return this.appState;
}
return nextAppStateSnapshot;
}
private detectChangedAppState(nextObservedAppState: ObservedAppState) {
return !isShallowEqual(this.appState, nextObservedAppState, {
selectedElementIds: isShallowEqual,
selectedGroupIds: isShallowEqual,
});
}
private maybeCreateElementsSnapshot(
elements: Map<string, OrderedExcalidrawElement> | undefined,
) {
if (!elements) {
return this.elements;
}
const didElementsChange = this.detectChangedElements(elements);
if (!didElementsChange) {
return this.elements;
}
const elementsSnapshot = this.createElementsSnapshot(elements);
return elementsSnapshot;
}
/**
* Detect if there any changed elements.
*
* NOTE: we shouldn't just use `sceneVersionNonce` instead, as we need to call this before the scene updates.
* NOTE: we shouldn't use `sceneVersionNonce` instead, as we need to call this before the scene updates.
*/
private detectChangedElements(
nextElements: Map<string, OrderedExcalidrawElement>,
@@ -377,6 +286,13 @@ export class Snapshot {
return false;
}
private detectChangedAppState(observedAppState: ObservedAppState) {
return !isShallowEqual(this.appState, observedAppState, {
selectedElementIds: isShallowEqual,
selectedGroupIds: isShallowEqual,
});
}
/**
* Perform structural clone, cloning only elements that changed.
*/
@@ -2170,14 +2170,14 @@ exports[`contextMenu element > selecting 'Delete' in context menu deletes elemen
"roundness": {
"type": 3,
},
"seed": 449462985,
"seed": 1278240551,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 4,
"versionNonce": 1014066025,
"versionNonce": 1150084233,
"width": 20,
"x": -10,
"y": 0,
@@ -2404,14 +2404,14 @@ exports[`contextMenu element > selecting 'Duplicate' in context menu duplicates
"roundness": {
"type": 3,
},
"seed": 449462985,
"seed": 1278240551,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 3,
"versionNonce": 1150084233,
"versionNonce": 401146281,
"width": 20,
"x": -10,
"y": 0,
@@ -2438,14 +2438,14 @@ exports[`contextMenu element > selecting 'Duplicate' in context menu duplicates
"roundness": {
"type": 3,
},
"seed": 1014066025,
"seed": 1150084233,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 4,
"versionNonce": 238820263,
"versionNonce": 1116226695,
"width": 20,
"x": 0,
"y": 10,
@@ -2704,14 +2704,14 @@ exports[`contextMenu element > selecting 'Group selection' in context menu group
"roundness": {
"type": 3,
},
"seed": 449462985,
"seed": 1278240551,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 4,
"versionNonce": 493213705,
"versionNonce": 1505387817,
"width": 20,
"x": -10,
"y": 0,
@@ -2740,14 +2740,14 @@ exports[`contextMenu element > selecting 'Group selection' in context menu group
"roundness": {
"type": 3,
},
"seed": 1014066025,
"seed": 1150084233,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 4,
"versionNonce": 915032327,
"versionNonce": 23633383,
"width": 20,
"x": 20,
"y": 30,
@@ -3060,14 +3060,14 @@ exports[`contextMenu element > selecting 'Paste styles' in context menu pastes s
"roundness": {
"type": 3,
},
"seed": 449462985,
"seed": 1278240551,
"strokeColor": "#e03131",
"strokeStyle": "dotted",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 4,
"versionNonce": 941653321,
"versionNonce": 640725609,
"width": 20,
"x": -10,
"y": 0,
@@ -3094,14 +3094,14 @@ exports[`contextMenu element > selecting 'Paste styles' in context menu pastes s
"roundness": {
"type": 3,
},
"seed": 289600103,
"seed": 760410951,
"strokeColor": "#e03131",
"strokeStyle": "dotted",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 9,
"versionNonce": 640725609,
"versionNonce": 1315507081,
"width": 20,
"x": 20,
"y": 30,
@@ -3840,14 +3840,14 @@ exports[`contextMenu element > selecting 'Send to back' in context menu sends el
"roundness": {
"type": 3,
},
"seed": 1014066025,
"seed": 1150084233,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 4,
"versionNonce": 23633383,
"versionNonce": 1604849351,
"width": 20,
"x": 20,
"y": 30,
@@ -3874,14 +3874,14 @@ exports[`contextMenu element > selecting 'Send to back' in context menu sends el
"roundness": {
"type": 3,
},
"seed": 449462985,
"seed": 1278240551,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 3,
"versionNonce": 1150084233,
"versionNonce": 401146281,
"width": 20,
"x": -10,
"y": 0,
@@ -5224,8 +5224,8 @@ exports[`contextMenu element > shows 'Group selection' in context menu for multi
},
},
],
"left": -17,
"top": -7,
"left": -19,
"top": -9,
},
"currentChartType": "bar",
"currentItemBackgroundColor": "transparent",
@@ -5342,14 +5342,14 @@ exports[`contextMenu element > shows 'Group selection' in context menu for multi
"roundness": {
"type": 3,
},
"seed": 453191,
"seed": 449462985,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 3,
"versionNonce": 1014066025,
"versionNonce": 1150084233,
"width": 10,
"x": -10,
"y": 0,
@@ -5376,16 +5376,16 @@ exports[`contextMenu element > shows 'Group selection' in context menu for multi
"roundness": {
"type": 3,
},
"seed": 400692809,
"seed": 1014066025,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 3,
"versionNonce": 23633383,
"versionNonce": 1604849351,
"width": 10,
"x": 12,
"x": 10,
"y": 0,
}
`;
@@ -5493,7 +5493,7 @@ History {
"strokeWidth": 2,
"type": "rectangle",
"width": 10,
"x": 12,
"x": 10,
"y": 0,
},
"inserted": {
@@ -6349,8 +6349,8 @@ exports[`contextMenu element > shows 'Ungroup selection' in context menu for gro
},
},
],
"left": -17,
"top": -7,
"left": -19,
"top": -9,
},
"currentChartType": "bar",
"currentItemBackgroundColor": "transparent",
@@ -6516,7 +6516,7 @@ exports[`contextMenu element > shows 'Ungroup selection' in context menu for gro
"version": 4,
"versionNonce": 747212839,
"width": 10,
"x": 12,
"x": 10,
"y": 0,
}
`;
@@ -6624,7 +6624,7 @@ History {
"strokeWidth": 2,
"type": "rectangle",
"width": 10,
"x": 12,
"x": 10,
"y": 0,
},
"inserted": {
@@ -8181,8 +8181,8 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap
},
},
],
"left": -17,
"top": -7,
"left": -19,
"top": -9,
},
"currentChartType": "bar",
"currentItemBackgroundColor": "transparent",
File diff suppressed because it is too large Load Diff
@@ -1400,7 +1400,9 @@ exports[`regression tests > Drags selected element when hitting only bounding bo
"penDetected": false,
"penMode": false,
"pendingImageElementId": null,
"previousSelectedElementIds": {},
"previousSelectedElementIds": {
"id0": true,
},
"resizingElement": null,
"scrollX": 0,
"scrollY": 0,
@@ -1520,7 +1522,7 @@ History {
exports[`regression tests > Drags selected element when hitting only bounding box and keeps element selected > [end of test] number of elements 1`] = `0`;
exports[`regression tests > Drags selected element when hitting only bounding box and keeps element selected > [end of test] number of renders 1`] = `11`;
exports[`regression tests > Drags selected element when hitting only bounding box and keeps element selected > [end of test] number of renders 1`] = `9`;
exports[`regression tests > adjusts z order when grouping > [end of test] appState 1`] = `
{
@@ -6568,27 +6570,12 @@ History {
"delta": Delta {
"deleted": {
"selectedElementIds": {},
"selectedLinearElementId": null,
},
"inserted": {
"selectedElementIds": {
"id6": true,
},
},
},
},
"elementsChange": ElementsChange {
"added": Map {},
"removed": Map {},
"updated": Map {},
},
},
HistoryEntry {
"appStateChange": AppStateChange {
"delta": Delta {
"deleted": {
"selectedLinearElementId": null,
},
"inserted": {
"selectedLinearElementId": "id6",
},
},
+17 -81
View File
@@ -20,7 +20,6 @@ describe("element binding", () => {
const rect = API.createElement({
type: "rectangle",
x: 0,
y: 0,
width: 50,
height: 50,
});
@@ -40,43 +39,31 @@ describe("element binding", () => {
h.elements = [rect, arrow];
expect(arrow.startBinding).toBe(null);
// select arrow
mouse.clickAt(150, 0);
// move arrow start to potential binding position
mouse.downAt(100, 0);
mouse.moveTo(55, 0);
mouse.up(0, 0);
// Point selection is evaluated like the points are rendered,
// from right to left. So clicking on the first point should move the joint,
// not the start point.
expect(arrow.startBinding).toBe(null);
// Now that the start point is free, move it into overlapping position
mouse.downAt(100, 0);
mouse.moveTo(55, 0);
mouse.up(0, 0);
API.setSelectedElements([arrow]);
expect(API.getSelectedElements()).toEqual([arrow]);
expect(arrow.startBinding).toEqual({
elementId: rect.id,
focus: expect.toBeNonNaNNumber(),
gap: expect.toBeNonNaNNumber(),
});
// Move the end point to the overlapping binding position
mouse.downAt(200, 0);
mouse.downAt(100, 0);
mouse.moveTo(55, 0);
mouse.up(0, 0);
// Both the start and the end points should be bound
expect(arrow.startBinding).toEqual({
elementId: rect.id,
focus: expect.toBeNonNaNNumber(),
gap: expect.toBeNonNaNNumber(),
});
mouse.downAt(100, 0);
mouse.move(-45, 0);
mouse.up();
expect(arrow.startBinding).toEqual({
elementId: rect.id,
focus: expect.toBeNonNaNNumber(),
gap: expect.toBeNonNaNNumber(),
});
mouse.down();
mouse.move(-50, 0);
mouse.up();
expect(arrow.startBinding).toBe(null);
expect(arrow.endBinding).toEqual({
elementId: rect.id,
focus: expect.toBeNonNaNNumber(),
@@ -156,7 +143,7 @@ describe("element binding", () => {
},
);
it("should unbind arrow when moving it with keyboard", () => {
it("should bind/unbind arrow when moving it with keyboard", () => {
const rectangle = UI.createElement("rectangle", {
x: 75,
y: 0,
@@ -172,23 +159,12 @@ describe("element binding", () => {
expect(arrow.endBinding).toBe(null);
mouse.downAt(50, 50);
mouse.moveTo(51, 0);
mouse.up(0, 0);
// Test sticky connection
expect(API.getSelectedElement().type).toBe("arrow");
Keyboard.keyPress(KEYS.ARROW_RIGHT);
expect(arrow.endBinding?.elementId).toBe(rectangle.id);
Keyboard.keyPress(KEYS.ARROW_LEFT);
expect(arrow.endBinding?.elementId).toBe(rectangle.id);
// Sever connection
expect(API.getSelectedElement().type).toBe("arrow");
Keyboard.keyPress(KEYS.ARROW_LEFT);
expect(arrow.endBinding).toBe(null);
Keyboard.keyPress(KEYS.ARROW_RIGHT);
expect(arrow.endBinding).toBe(null);
});
it("should unbind on bound element deletion", () => {
@@ -393,44 +369,4 @@ describe("element binding", () => {
expect(arrow2.startBinding?.elementId).toBe(container.id);
expect(arrow2.endBinding?.elementId).toBe(rectangle1.id);
});
// #6459
it("should unbind arrow only from the latest element", () => {
const rectLeft = UI.createElement("rectangle", {
x: 0,
width: 200,
height: 500,
});
const rectRight = UI.createElement("rectangle", {
x: 400,
width: 200,
height: 500,
});
const arrow = UI.createElement("arrow", {
x: 210,
y: 250,
width: 180,
height: 1,
});
expect(arrow.startBinding?.elementId).toBe(rectLeft.id);
expect(arrow.endBinding?.elementId).toBe(rectRight.id);
// Drag arrow off of bound rectangle range
const handles = getTransformHandles(
arrow,
h.state.zoom,
arrayToMap(h.elements),
"mouse",
).se!;
Keyboard.keyDown(KEYS.CTRL_OR_CMD);
const elX = handles[0] + handles[2] / 2;
const elY = handles[1] + handles[3] / 2;
mouse.downAt(elX, elY);
mouse.moveTo(300, 400);
mouse.up();
expect(arrow.startBinding).not.toBe(null);
expect(arrow.endBinding).toBe(null);
});
});
+22 -22
View File
@@ -108,8 +108,8 @@ describe("contextMenu element", () => {
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
const contextMenuOptions =
@@ -188,19 +188,19 @@ describe("contextMenu element", () => {
mouse.up(10, 10);
UI.clickTool("rectangle");
mouse.down(12, -10);
mouse.down(10, -10);
mouse.up(10, 10);
mouse.reset();
mouse.click(10, 10);
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.click(22, 0);
mouse.click(20, 0);
});
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
@@ -240,13 +240,13 @@ describe("contextMenu element", () => {
mouse.up(10, 10);
UI.clickTool("rectangle");
mouse.down(12, -10);
mouse.down(10, -10);
mouse.up(10, 10);
mouse.reset();
mouse.click(10, 10);
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.click(22, 0);
mouse.click(20, 0);
});
Keyboard.withModifierKeys({ ctrl: true }, () => {
@@ -255,8 +255,8 @@ describe("contextMenu element", () => {
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
@@ -297,8 +297,8 @@ describe("contextMenu element", () => {
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
expect(copiedStyles).toBe("{}");
@@ -382,8 +382,8 @@ describe("contextMenu element", () => {
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
fireEvent.click(queryAllByText(contextMenu!, "Delete")[0]);
@@ -398,8 +398,8 @@ describe("contextMenu element", () => {
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
fireEvent.click(queryByText(contextMenu!, "Add to library")!);
@@ -417,8 +417,8 @@ describe("contextMenu element", () => {
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
fireEvent.click(queryByText(contextMenu!, "Duplicate")!);
@@ -548,8 +548,8 @@ describe("contextMenu element", () => {
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
fireEvent.click(queryByText(contextMenu!, "Group selection")!);
@@ -578,8 +578,8 @@ describe("contextMenu element", () => {
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 3,
clientY: 3,
clientX: 1,
clientY: 1,
});
const contextMenu = UI.queryContextMenu();
-1
View File
@@ -315,7 +315,6 @@ const transform = (
h.state.zoom,
arrayToMap(h.elements),
"mouse",
{},
)[handle];
} else {
const [x1, y1, x2, y2] = getCommonBounds(elements);
+37 -178
View File
@@ -15,11 +15,7 @@ import { createUndoAction, createRedoAction } from "../actions/actionHistory";
import { EXPORT_DATA_TYPES, MIME_TYPES } from "../constants";
import { AppState, ExcalidrawImperativeAPI } from "../types";
import { arrayToMap, resolvablePromise } from "../utils";
import {
COLOR_PALETTE,
DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX,
DEFAULT_ELEMENT_STROKE_COLOR_INDEX,
} from "../colors";
import { COLOR_PALETTE } from "../colors";
import { KEYS } from "../keys";
import { newElementWith } from "../element/mutateElement";
import {
@@ -39,7 +35,7 @@ import { vi } from "vitest";
import { queryByText } from "@testing-library/react";
import { HistoryEntry } from "../history";
import { AppStateChange, ElementsChange } from "../change";
import { Snapshot, StoreAction } from "../store";
import { Snapshot } from "../store";
const { h } = window;
@@ -71,11 +67,10 @@ const checkpoint = (name: string) => {
const renderStaticScene = vi.spyOn(StaticScene, "renderStaticScene");
const transparent = COLOR_PALETTE.transparent;
const black = COLOR_PALETTE.black;
const red = COLOR_PALETTE.red[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
const blue = COLOR_PALETTE.blue[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
const yellow = COLOR_PALETTE.yellow[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
const violet = COLOR_PALETTE.violet[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
const red = COLOR_PALETTE.red[1];
const blue = COLOR_PALETTE.blue[1];
const yellow = COLOR_PALETTE.yellow[1];
const violet = COLOR_PALETTE.violet[1];
describe("history", () => {
beforeEach(() => {
@@ -181,7 +176,7 @@ describe("history", () => {
excalidrawAPI.updateScene({
elements: [rect1, rect2],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
expect(API.getUndoStack().length).toBe(1);
@@ -193,7 +188,7 @@ describe("history", () => {
excalidrawAPI.updateScene({
elements: [rect1, rect2],
storeAction: StoreAction.CAPTURE, // even though the flag is on, same elements are passed, nothing to commit
commitToStore: true, // even though the flag is on, same elements are passed, nothing to commit
});
expect(API.getUndoStack().length).toBe(1);
expect(API.getRedoStack().length).toBe(0);
@@ -561,7 +556,7 @@ describe("history", () => {
appState: {
name: "New name",
},
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
expect(API.getUndoStack().length).toBe(1);
@@ -572,7 +567,7 @@ describe("history", () => {
appState: {
viewBackgroundColor: "#000",
},
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
expect(API.getUndoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(0);
@@ -585,7 +580,7 @@ describe("history", () => {
name: "New name",
viewBackgroundColor: "#000",
},
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
expect(API.getUndoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(0);
@@ -978,69 +973,6 @@ describe("history", () => {
]);
});
it("should create entry when selecting freedraw", async () => {
await render(<Excalidraw handleKeyboardGlobally={true} />);
UI.clickTool("rectangle");
mouse.down(-10, -10);
mouse.up(10, 10);
UI.clickTool("freedraw");
mouse.down(40, -20);
mouse.up(50, 10);
const rectangle = h.elements[0];
const freedraw1 = h.elements[1];
expect(API.getUndoStack().length).toBe(3);
expect(API.getRedoStack().length).toBe(0);
expect(API.getSelectedElements().length).toBe(0);
expect(h.elements).toEqual([
expect.objectContaining({ id: rectangle.id }),
expect.objectContaining({ id: freedraw1.id, strokeColor: black }),
]);
Keyboard.undo();
expect(API.getUndoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(1);
expect(API.getSelectedElements().length).toBe(0);
expect(h.elements).toEqual([
expect.objectContaining({ id: rectangle.id }),
expect.objectContaining({
id: freedraw1.id,
strokeColor: black,
isDeleted: true,
}),
]);
togglePopover("Stroke");
UI.clickOnTestId("color-red");
mouse.down(40, -20);
mouse.up(50, 10);
const freedraw2 = h.elements[2];
expect(API.getUndoStack().length).toBe(3);
expect(API.getRedoStack().length).toBe(0);
expect(h.elements).toEqual([
expect.objectContaining({ id: rectangle.id }),
expect.objectContaining({
id: freedraw1.id,
strokeColor: black,
isDeleted: true,
}),
expect.objectContaining({
id: freedraw2.id,
strokeColor: COLOR_PALETTE.red[DEFAULT_ELEMENT_STROKE_COLOR_INDEX],
}),
]);
// ensure we don't end up with duplicated entries
UI.clickTool("freedraw");
expect(API.getUndoStack().length).toBe(3);
expect(API.getRedoStack().length).toBe(0);
});
it("should support duplication of groups, appstate group selection and editing group", async () => {
await render(<Excalidraw handleKeyboardGlobally={true} />);
const rect1 = API.createElement({
@@ -1303,7 +1235,7 @@ describe("history", () => {
excalidrawAPI.updateScene({
elements: [rect1, text, rect2],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
// bind text1 to rect1
@@ -1706,7 +1638,6 @@ describe("history", () => {
<Excalidraw
excalidrawAPI={(api) => excalidrawAPIPromise.resolve(api as any)}
handleKeyboardGlobally={true}
isCollaborating={true}
/>,
);
excalidrawAPI = await excalidrawAPIPromise;
@@ -1732,7 +1663,6 @@ describe("history", () => {
strokeColor: blue,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -1770,7 +1700,6 @@ describe("history", () => {
strokeColor: yellow,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -1818,7 +1747,6 @@ describe("history", () => {
backgroundColor: yellow,
}),
],
storeAction: StoreAction.UPDATE,
});
// At this point our entry gets updated from `red` -> `blue` into `red` -> `yellow`
@@ -1834,7 +1762,6 @@ describe("history", () => {
backgroundColor: violet,
}),
],
storeAction: StoreAction.UPDATE,
});
// At this point our (inversed) entry gets updated from `red` -> `yellow` into `violet` -> `yellow`
@@ -1863,7 +1790,6 @@ describe("history", () => {
// Initialize scene
excalidrawAPI.updateScene({
elements: [rect1, rect2],
storeAction: StoreAction.UPDATE,
});
// Simulate local update
@@ -1872,7 +1798,7 @@ describe("history", () => {
newElementWith(h.elements[0], { groupIds: ["A"] }),
newElementWith(h.elements[1], { groupIds: ["A"] }),
],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
const rect3 = API.createElement({ type: "rectangle", groupIds: ["B"] });
@@ -1886,7 +1812,6 @@ describe("history", () => {
rect3,
rect4,
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -1932,7 +1857,6 @@ describe("history", () => {
],
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo(); // undo `actionFinalize`
@@ -2027,7 +1951,6 @@ describe("history", () => {
isDeleted: false, // undeletion might happen due to concurrency between clients
}),
],
storeAction: StoreAction.UPDATE,
});
expect(API.getSelectedElements()).toEqual([]);
@@ -2104,7 +2027,6 @@ describe("history", () => {
isDeleted: true,
}),
],
storeAction: StoreAction.UPDATE,
});
expect(h.elements).toEqual([
@@ -2166,7 +2088,6 @@ describe("history", () => {
isDeleted: true,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -2242,7 +2163,6 @@ describe("history", () => {
isDeleted: true,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -2281,7 +2201,6 @@ describe("history", () => {
isDeleted: false,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.redo();
@@ -2327,7 +2246,6 @@ describe("history", () => {
// Simulate remote update
excalidrawAPI.updateScene({
elements: [rect1, rect2],
storeAction: StoreAction.UPDATE,
});
Keyboard.withModifierKeys({ ctrl: true }, () => {
@@ -2337,7 +2255,6 @@ describe("history", () => {
// Simulate remote update
excalidrawAPI.updateScene({
elements: [h.elements[0], h.elements[1], rect3, rect4],
storeAction: StoreAction.UPDATE,
});
Keyboard.withModifierKeys({ ctrl: true }, () => {
@@ -2358,7 +2275,6 @@ describe("history", () => {
isDeleted: true,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -2383,7 +2299,6 @@ describe("history", () => {
isDeleted: false,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.redo();
@@ -2394,7 +2309,6 @@ describe("history", () => {
// Simulate remote update
excalidrawAPI.updateScene({
elements: [h.elements[0], h.elements[1], rect3, rect4],
storeAction: StoreAction.UPDATE,
});
Keyboard.redo();
@@ -2440,7 +2354,6 @@ describe("history", () => {
isDeleted: true,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -2461,7 +2374,6 @@ describe("history", () => {
}),
h.elements[1],
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -2504,7 +2416,6 @@ describe("history", () => {
isDeleted: true,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -2547,7 +2458,6 @@ describe("history", () => {
h.elements[0],
h.elements[1],
],
storeAction: StoreAction.UPDATE,
});
expect(API.getUndoStack().length).toBe(2);
@@ -2586,7 +2496,6 @@ describe("history", () => {
h.elements[0],
h.elements[1],
],
storeAction: StoreAction.UPDATE,
});
expect(API.getUndoStack().length).toBe(2);
@@ -2637,7 +2546,6 @@ describe("history", () => {
h.elements[0], // rect2
h.elements[1], // rect1
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -2667,7 +2575,6 @@ describe("history", () => {
h.elements[0], // rect3
h.elements[2], // rect1
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -2697,7 +2604,6 @@ describe("history", () => {
// Simulate remote update
excalidrawAPI.updateScene({
elements: [...h.elements, rect],
storeAction: StoreAction.UPDATE,
});
mouse.moveTo(60, 60);
@@ -2749,7 +2655,6 @@ describe("history", () => {
// // Simulate remote update
excalidrawAPI.updateScene({
elements: [...h.elements, rect3],
storeAction: StoreAction.UPDATE,
});
mouse.moveTo(100, 100);
@@ -2839,7 +2744,6 @@ describe("history", () => {
// Simulate remote update
excalidrawAPI.updateScene({
elements: [...h.elements, rect3],
storeAction: StoreAction.UPDATE,
});
mouse.moveTo(100, 100);
@@ -3016,7 +2920,6 @@ describe("history", () => {
// Initialize the scene
excalidrawAPI.updateScene({
elements: [container, text],
storeAction: StoreAction.UPDATE,
});
// Simulate local update
@@ -3029,7 +2932,7 @@ describe("history", () => {
containerId: container.id,
}),
],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
Keyboard.undo();
@@ -3060,7 +2963,6 @@ describe("history", () => {
x: h.elements[1].x + 10,
}),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3103,7 +3005,6 @@ describe("history", () => {
// Initialize the scene
excalidrawAPI.updateScene({
elements: [container, text],
storeAction: StoreAction.UPDATE,
});
// Simulate local update
@@ -3116,7 +3017,7 @@ describe("history", () => {
containerId: container.id,
}),
],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
Keyboard.undo();
@@ -3150,7 +3051,6 @@ describe("history", () => {
remoteText,
h.elements[1],
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3206,7 +3106,6 @@ describe("history", () => {
// Initialize the scene
excalidrawAPI.updateScene({
elements: [container, text],
storeAction: StoreAction.UPDATE,
});
// Simulate local update
@@ -3219,7 +3118,7 @@ describe("history", () => {
containerId: container.id,
}),
],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
Keyboard.undo();
@@ -3256,7 +3155,6 @@ describe("history", () => {
containerId: remoteContainer.id,
}),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3314,7 +3212,7 @@ describe("history", () => {
// Simulate local update
excalidrawAPI.updateScene({
elements: [container],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
// Simulate remote update
@@ -3325,7 +3223,6 @@ describe("history", () => {
}),
newElementWith(text, { containerId: container.id }),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3375,7 +3272,7 @@ describe("history", () => {
// Simulate local update
excalidrawAPI.updateScene({
elements: [text],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
// Simulate remote update
@@ -3386,7 +3283,6 @@ describe("history", () => {
}),
newElementWith(text, { containerId: container.id }),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3435,7 +3331,7 @@ describe("history", () => {
// Simulate local update
excalidrawAPI.updateScene({
elements: [container],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
// Simulate remote update
@@ -3448,7 +3344,6 @@ describe("history", () => {
containerId: container.id,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -3485,7 +3380,6 @@ describe("history", () => {
// rebinding the container with a new text element!
remoteText,
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3542,7 +3436,7 @@ describe("history", () => {
// Simulate local update
excalidrawAPI.updateScene({
elements: [text],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
// Simulate remote update
@@ -3555,7 +3449,6 @@ describe("history", () => {
containerId: container.id,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.undo();
@@ -3592,7 +3485,6 @@ describe("history", () => {
containerId: container.id,
}),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3648,7 +3540,7 @@ describe("history", () => {
// Simulate local update
excalidrawAPI.updateScene({
elements: [container],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
// Simulate remote update
@@ -3662,7 +3554,6 @@ describe("history", () => {
isDeleted: true,
}),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3705,7 +3596,7 @@ describe("history", () => {
// Simulate local update
excalidrawAPI.updateScene({
elements: [text],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
// Simulate remote update
@@ -3719,7 +3610,6 @@ describe("history", () => {
containerId: container.id,
}),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -3762,7 +3652,6 @@ describe("history", () => {
// Initialize the scene
excalidrawAPI.updateScene({
elements: [container],
storeAction: StoreAction.UPDATE,
});
// Simulate local update
@@ -3774,7 +3663,7 @@ describe("history", () => {
angle: 90,
}),
],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
Keyboard.undo();
@@ -3787,7 +3676,6 @@ describe("history", () => {
}),
newElementWith(text, { containerId: container.id }),
],
storeAction: StoreAction.UPDATE,
});
expect(h.elements).toEqual([
@@ -3880,7 +3768,6 @@ describe("history", () => {
// Initialize the scene
excalidrawAPI.updateScene({
elements: [text],
storeAction: StoreAction.UPDATE,
});
// Simulate local update
@@ -3892,7 +3779,7 @@ describe("history", () => {
angle: 90,
}),
],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
Keyboard.undo();
@@ -3907,7 +3794,6 @@ describe("history", () => {
containerId: container.id,
}),
],
storeAction: StoreAction.UPDATE,
});
expect(API.getUndoStack().length).toBe(0);
@@ -3998,7 +3884,7 @@ describe("history", () => {
// Simulate local update
excalidrawAPI.updateScene({
elements: [rect1, rect2],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
mouse.reset();
@@ -4014,18 +3900,12 @@ describe("history", () => {
const arrowId = h.elements[2].id;
// create start binding
// create binding
mouse.downAt(0, 0);
mouse.moveTo(0, 1);
mouse.moveTo(0, 0);
mouse.up();
// create end binding
mouse.downAt(100, 0);
mouse.moveTo(100, 1);
mouse.moveTo(100, 0);
mouse.up();
expect(h.elements).toEqual([
expect.objectContaining({
id: rect1.id,
@@ -4050,10 +3930,9 @@ describe("history", () => {
}),
]);
Keyboard.undo(); // undo start binding
Keyboard.undo(); // undo end binding
Keyboard.undo();
expect(API.getUndoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(1);
expect(h.elements).toEqual([
expect.objectContaining({
id: rect1.id,
@@ -4083,13 +3962,11 @@ describe("history", () => {
x: h.elements[1].x + 50,
}),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
Keyboard.redo();
Keyboard.redo();
expect(API.getUndoStack().length).toBe(4);
expect(API.getUndoStack().length).toBe(3);
expect(API.getRedoStack().length).toBe(0);
expect(h.elements).toEqual([
expect.objectContaining({
@@ -4115,10 +3992,9 @@ describe("history", () => {
}),
]);
Keyboard.undo();
Keyboard.undo();
expect(API.getUndoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(1);
expect(h.elements).toEqual([
expect.objectContaining({
id: rect1.id,
@@ -4144,16 +4020,11 @@ describe("history", () => {
const arrowId = h.elements[2].id;
// create start binding
// create binding
mouse.downAt(0, 0);
mouse.moveTo(0, 1);
mouse.upAt(0, 0);
// create end binding
mouse.downAt(100, 0);
mouse.moveTo(100, 1);
mouse.upAt(100, 0);
expect(h.elements).toEqual([
expect.objectContaining({
id: rect1.id,
@@ -4178,10 +4049,9 @@ describe("history", () => {
}),
]);
Keyboard.undo();
Keyboard.undo();
expect(API.getUndoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(1);
expect(h.elements).toEqual([
expect.objectContaining({
id: rect1.id,
@@ -4212,13 +4082,11 @@ describe("history", () => {
}),
remoteContainer,
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
Keyboard.redo();
Keyboard.redo();
expect(API.getUndoStack().length).toBe(4);
expect(API.getUndoStack().length).toBe(3);
expect(API.getRedoStack().length).toBe(0);
expect(h.elements).toEqual([
expect.objectContaining({
@@ -4249,10 +4117,9 @@ describe("history", () => {
}),
]);
Keyboard.undo();
Keyboard.undo();
expect(API.getUndoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(2);
expect(API.getRedoStack().length).toBe(1);
expect(h.elements).toEqual([
expect.objectContaining({
id: rect1.id,
@@ -4299,7 +4166,6 @@ describe("history", () => {
boundElements: [{ id: arrow.id, type: "arrow" }],
}),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -4364,10 +4230,7 @@ describe("history", () => {
});
// Simulate local update
excalidrawAPI.updateScene({
elements: [arrow],
storeAction: StoreAction.CAPTURE,
});
excalidrawAPI.updateScene({ elements: [arrow], commitToStore: true });
// Simulate remote update
excalidrawAPI.updateScene({
@@ -4383,7 +4246,6 @@ describe("history", () => {
boundElements: [{ id: arrow.id, type: "arrow" }],
}),
],
storeAction: StoreAction.UPDATE,
});
runTwice(() => {
@@ -4495,7 +4357,6 @@ describe("history", () => {
newElementWith(h.elements[1], { x: 500, y: -500 }),
h.elements[2],
],
storeAction: StoreAction.UPDATE,
});
Keyboard.redo();
@@ -4563,13 +4424,12 @@ describe("history", () => {
// Initialize the scene
excalidrawAPI.updateScene({
elements: [frame],
storeAction: StoreAction.UPDATE,
});
// Simulate local update
excalidrawAPI.updateScene({
elements: [rect, h.elements[0]],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
// Simulate local update
@@ -4580,7 +4440,7 @@ describe("history", () => {
}),
h.elements[1],
],
storeAction: StoreAction.CAPTURE,
commitToStore: true,
});
Keyboard.undo();
@@ -4624,7 +4484,6 @@ describe("history", () => {
isDeleted: true,
}),
],
storeAction: StoreAction.UPDATE,
});
Keyboard.redo();
@@ -1,5 +1,5 @@
import { vi } from "vitest";
import { Excalidraw, StoreAction } from "../../index";
import { Excalidraw } from "../../index";
import { ExcalidrawImperativeAPI } from "../../types";
import { resolvablePromise } from "../../utils";
import { render } from "../test-utils";
@@ -27,10 +27,7 @@ describe("event callbacks", () => {
const origBackgroundColor = h.state.viewBackgroundColor;
excalidrawAPI.onChange(onChange);
excalidrawAPI.updateScene({
appState: { viewBackgroundColor: "red" },
storeAction: StoreAction.CAPTURE,
});
excalidrawAPI.updateScene({ appState: { viewBackgroundColor: "red" } });
expect(onChange).toHaveBeenCalledWith(
// elements
[],
@@ -199,6 +199,7 @@ describe("regression tests", () => {
expect(
h.elements.filter((element) => element.type === "rectangle").length,
).toBe(1);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(-8, -8);
mouse.up(10, 10);
@@ -724,7 +725,7 @@ describe("regression tests", () => {
mouse.up(10, 10);
const { x: prevX, y: prevY } = API.getSelectedElement();
API.clearSelection();
// drag element from point on bounding box that doesn't hit element
mouse.reset();
mouse.down(8, 8);
@@ -1014,22 +1015,12 @@ describe("regression tests", () => {
});
it("single-clicking on a subgroup of a selected group should not alter selection", () => {
const rect1 = UI.createElement("rectangle", {
x: 10,
});
const rect2 = UI.createElement("rectangle", {
x: 50,
});
const rect1 = UI.createElement("rectangle", { x: 10 });
const rect2 = UI.createElement("rectangle", { x: 50 });
UI.group([rect1, rect2]);
const rect3 = UI.createElement("rectangle", {
x: 10,
y: 50,
});
const rect4 = UI.createElement("rectangle", {
x: 50,
y: 50,
});
const rect3 = UI.createElement("rectangle", { x: 10, y: 50 });
const rect4 = UI.createElement("rectangle", { x: 50, y: 50 });
UI.group([rect3, rect4]);
Keyboard.withModifierKeys({ ctrl: true }, () => {
@@ -1088,9 +1079,8 @@ describe("regression tests", () => {
UI.group([rect1, rect3]);
assertSelectedElements(rect1, rect2, rect3);
mouse.reset();
Keyboard.withModifierKeys({ ctrl: true }, () => {
mouse.click(10, 5);
mouse.clickOn(rect1);
});
assertSelectedElements(rect1);
+10 -22
View File
@@ -544,9 +544,7 @@ describe("multiple selection", () => {
1 + move[1] / selectionHeight,
);
UI.resize([rectangle, diamond, ellipse], "se", move, {
shift: true,
});
UI.resize([rectangle, diamond, ellipse], "se", move);
expect(rectangle.x).toBeCloseTo(0);
expect(rectangle.y).toBeCloseTo(0);
@@ -615,9 +613,7 @@ describe("multiple selection", () => {
1 + move[1] / selectionHeight,
);
UI.resize([line, freedraw], "se", move, {
shift: true,
});
UI.resize([line, freedraw], "se", move);
expect(line.x).toBeCloseTo(60 * scale);
expect(line.y).toBeCloseTo(40 * scale);
@@ -657,9 +653,7 @@ describe("multiple selection", () => {
1 - move[1] / selectionHeight,
);
UI.resize([horizLine, vertLine, diagLine], "nw", move, {
shift: true,
});
UI.resize([horizLine, vertLine, diagLine], "nw", move);
expect(horizLine.x).toBeCloseTo(selectionWidth * (1 - scale));
expect(horizLine.y).toBeCloseTo(selectionHeight * (1 - scale));
@@ -709,9 +703,7 @@ describe("multiple selection", () => {
const rightArrowBinding = { ...rightBoundArrow.endBinding };
delete rightArrowBinding.gap;
UI.resize([rectangle, rightBoundArrow], "nw", move, {
shift: true,
});
UI.resize([rectangle, rightBoundArrow], "nw", move);
expect(leftBoundArrow.x).toBeCloseTo(-110);
expect(leftBoundArrow.y).toBeCloseTo(50);
@@ -759,9 +751,7 @@ describe("multiple selection", () => {
const move = [80, 0] as [number, number];
const scale = move[0] / selectionWidth + 1;
const elementsMap = arrayToMap(h.elements);
UI.resize([topArrow.get(), bottomArrow.get()], "se", move, {
shift: true,
});
UI.resize([topArrow.get(), bottomArrow.get()], "se", move);
const topArrowLabelPos = LinearElementEditor.getBoundTextElementPosition(
topArrow,
topArrowLabel,
@@ -825,7 +815,7 @@ describe("multiple selection", () => {
1 - move[1] / selectionHeight,
);
UI.resize([topText, bottomText], "ne", move, { shift: true });
UI.resize([topText, bottomText], "ne", move);
expect(topText.x).toBeCloseTo(0);
expect(topText.y).toBeCloseTo(-selectionHeight * (scale - 1));
@@ -838,7 +828,7 @@ describe("multiple selection", () => {
expect(bottomText.angle).toEqual(0);
});
it("resizes with images (proportional)", () => {
it("resizes with images", () => {
const topImage = API.createElement({
type: "image",
x: 0,
@@ -901,7 +891,7 @@ describe("multiple selection", () => {
1 + (2 * move[1]) / selectionHeight,
);
UI.resize([rectangle, ellipse], "se", move, { shift: true, alt: true });
UI.resize([rectangle, ellipse], "se", move, { alt: true });
expect(rectangle.x).toBeCloseTo(-200 * scale);
expect(rectangle.y).toBeCloseTo(-140 * scale);
@@ -964,9 +954,7 @@ describe("multiple selection", () => {
const scaleY = -scaleX;
const lineOrigBounds = getBoundsFromPoints(line);
const elementsMap = arrayToMap(h.elements);
UI.resize([line, image, rectangle, boundArrow], "se", move, {
shift: true,
});
UI.resize([line, image, rectangle, boundArrow], "se", move);
const lineNewBounds = getBoundsFromPoints(line);
const arrowLabelPos = LinearElementEditor.getBoundTextElementPosition(
boundArrow,
@@ -991,7 +979,7 @@ describe("multiple selection", () => {
expect(image.width).toBeCloseTo(100 * -scaleX);
expect(image.height).toBeCloseTo(100 * scaleY);
expect(image.angle).toBeCloseTo((Math.PI * 5) / 6);
expect(image.scale).toEqual([-1, 1]);
expect(image.scale).toEqual([1, 1]);
expect(rectangle.x).toBeCloseTo((180 + 160) * scaleX);
expect(rectangle.y).toBeCloseTo(60 * scaleY);
+1 -2
View File
@@ -40,7 +40,6 @@ import type { IMAGE_MIME_TYPES, MIME_TYPES } from "./constants";
import { ContextMenuItems } from "./components/ContextMenu";
import { SnapLine } from "./snapping";
import { Merge, MaybePromise, ValueOf } from "./utility-types";
import { StoreActionType } from "./store";
export type Point = Readonly<RoughPoint>;
@@ -508,7 +507,7 @@ export type SceneData = {
elements?: ImportedDataState["elements"];
appState?: ImportedDataState["appState"];
collaborators?: Map<SocketId, Collaborator>;
storeAction?: StoreActionType;
commitToStore?: boolean;
};
export enum UserIdleState {
+3517 -3512
View File
File diff suppressed because it is too large Load Diff