Compare commits

...

20 Commits

Author SHA1 Message Date
Mark Tolmacs 7d3f116e65 Merge branch 'master' into mtolmacs/transparent-bind-hit
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-06-04 15:27:07 +00:00
David Luzar c08be69618 ci(docker): fix docker dep bundling and pin remaining actions (#11398)
* docker: use slim alpine image to remove bundling deps in Docker image

* pin remaining yml actions

* use lockfile

* remove pulling
2026-05-25 14:39:21 +02:00
Márk Tolmács b42b1a193d fix(editor): excessive battery usage (#11377)
* fix: Excessive battery usage

* chore: Refactor Eraser, Lasso and Laser pointer to use AnimationController

* fix: Last laser trail element is not removed from SVG
---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-05-24 16:12:17 +02:00
David Luzar f6d85bc80f feat(packages/excalidraw): expose image size config and optimize resizing (#11332) 2026-05-14 22:45:03 +02:00
David Luzar 0457ac9063 fix(editor): handle invalid points on restore (#11321)
* fix: handle invalid points on restore

* move isValidPoint to @excalidraw/math
2026-05-12 18:44:49 +02:00
Mark Tolmacs 13d6f6cf1d fix: Lint
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-10 14:54:26 +00:00
Mark Tolmacs 73c940bcf6 chore: Refactor binding gap calc
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-10 14:51:05 +00:00
Mark Tolmacs 60f29dc188 fix: Common midpoint handling with render
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 14:53:35 +00:00
Mark Tolmacs 4a161c1764 fix: Centralized midpoint snap code
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 13:58:30 +00:00
Mark Tolmacs 4e94b02375 fix: Add back transparency check for bindables
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:42 +00:00
Mark Tolmacs d8e8d1aeda fix: Distance calc with absolute distance
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:41 +00:00
Mark Tolmacs d142190796 chore: Snapshots
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:41 +00:00
Mark Tolmacs 0598f945f6 feat: Overlap & distance based binding candidate selection
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:41 +00:00
Mark Tolmacs 47c2fa9a39 fix: Remove the rest of startBoundElement
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:40 +00:00
Mark Tolmacs b0339916ab fix: Remove startBoundElements
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:40 +00:00
Mark Tolmacs 5b7bcbec9c fix: Test snapshots
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:39 +00:00
Mark Tolmacs 3a2d147dbd fix: Binding hit test
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:39 +00:00
Mark Tolmacs 37603d8e0b fix: Test snapshots
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:39 +00:00
Mark Tolmacs 05e5b13466 fix: Clear up element dragging & binding
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:38 +00:00
Mark Tolmacs 281c99e2d1 fix: Binding hit test
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-05-08 10:59:33 +00:00
47 changed files with 1155 additions and 802 deletions
+2 -2
View File
@@ -9,11 +9,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
fetch-depth: 2
- name: Setup Node.js
uses: actions/setup-node@v2
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 20.x
- name: Set up publish access
+1 -1
View File
@@ -9,5 +9,5 @@ jobs:
build-docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- run: docker build -t excalidraw .
+2 -2
View File
@@ -7,10 +7,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Setup Node.js
uses: actions/setup-node@v2
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 20.x
+2 -2
View File
@@ -10,12 +10,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
token: ${{ secrets.PUSH_TRANSLATIONS_COVERAGE_PAT }}
- name: Setup Node.js
uses: actions/setup-node@v2
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 20.x
+1 -1
View File
@@ -11,7 +11,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Login to DockerHub
uses: docker/login-action@465a07811f14bebb1938fbed4728c6a1ff8901fc # v2
with:
+2 -2
View File
@@ -9,9 +9,9 @@ jobs:
sentry:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Setup Node.js
uses: actions/setup-node@v2
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 20.x
- name: Install and build
+2 -2
View File
@@ -10,9 +10,9 @@ jobs:
CI_JOB_NUMBER: 1
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Setup Node.js
uses: actions/setup-node@v3
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 20.x
- name: Install in packages/excalidraw
+2 -2
View File
@@ -10,9 +10,9 @@ jobs:
pull-requests: write
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: "Install Node"
uses: actions/setup-node@v2
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "20.x"
- name: "Install Deps"
+2 -2
View File
@@ -8,9 +8,9 @@ jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 20.x
- name: Install and test
+3 -3
View File
@@ -1,4 +1,4 @@
FROM --platform=${BUILDPLATFORM} node:24 AS build
FROM --platform=${BUILDPLATFORM} node:24@sha256:8530f76a96d88820d288761f022e318970dda93d01536919fbc16076b7983e63 AS build
WORKDIR /opt/node_app
@@ -7,13 +7,13 @@ COPY . .
# do not ignore optional dependencies:
# Error: Cannot find module @rollup/rollup-linux-x64-gnu
RUN --mount=type=cache,target=/root/.cache/yarn \
npm_config_target_arch=${TARGETARCH} yarn --network-timeout 600000
npm_config_target_arch=${TARGETARCH} yarn --frozen-lockfile --network-timeout 600000
ARG NODE_ENV=production
RUN npm_config_target_arch=${TARGETARCH} yarn build:app:docker
FROM nginx:1.27-alpine
FROM nginx:stable-alpine-slim@sha256:2c605dbeab79a6b2a63340474fe58119d0ef95bdc4b1f41df0aa689659b3d13b
COPY --from=build /opt/node_app/excalidraw-app/build /usr/share/nginx/html
+4 -3
View File
@@ -337,9 +337,10 @@ export const MAX_DECIMALS_FOR_SVG_EXPORT = 2;
export const EXPORT_SCALES = [1, 2, 3];
export const DEFAULT_EXPORT_PADDING = 10; // px
export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT = 1440;
export const MAX_ALLOWED_FILE_BYTES = 4 * 1024 * 1024;
export const DEFAULT_IMAGE_OPTIONS: AppProps["imageOptions"] = {
maxWidthOrHeight: 1440,
maxFileSizeBytes: 4 * 1024 * 1024,
};
export const SVG_NS = "http://www.w3.org/2000/svg";
export const SVG_DOCUMENT_PREAMBLE = `<?xml version="1.0" standalone="no"?>
+6 -6
View File
@@ -10,7 +10,6 @@ import {
getBindingGap,
getGlobalFixedPointForBindableElement,
isBindingEnabled,
maxBindingDistance_simple,
unbindBindingElement,
updateBoundPoint,
} from "../binding";
@@ -20,7 +19,7 @@ import {
isElbowArrow,
} from "../typeChecks";
import { LinearElementEditor } from "../linearElementEditor";
import { getHoveredElementForFocusPoint, hitElementItself } from "../collision";
import { getHoveredElementForBinding, hitElementItself } from "../collision";
import { moveArrowAboveBindable } from "../zindex";
import type {
@@ -92,7 +91,7 @@ export const isFocusPointVisible = (
element: bindableElement,
elementsMap,
point: focusPoint,
threshold: getBindingGap(bindableElement, arrow),
threshold: getBindingGap(bindableElement),
overrideShouldTestInside: true,
})
);
@@ -234,12 +233,12 @@ export const handleFocusPointDrag = (
pointerCoords.y - offsetY,
);
const bindingField = isStartBinding ? "startBinding" : "endBinding";
const hit = getHoveredElementForFocusPoint(
point,
const hit = getHoveredElementForBinding(
arrow,
point,
scene.getNonDeletedElements(),
elementsMap,
maxBindingDistance_simple(appState.zoom),
appState.zoom,
);
// Hovering a bindable element
@@ -270,6 +269,7 @@ export const handleFocusPointDrag = (
newMode || "orbit",
linearElementEditor.draggedFocusPointBinding,
scene,
appState.zoom,
point,
);
}
+38 -134
View File
@@ -60,6 +60,7 @@ import { updateElbowArrowPoints } from "./elbowArrow";
import {
deconstructDiamondElement,
deconstructRectanguloidElement,
getSnapOutlineMidPoint,
projectFixedPointOntoDiagonal,
} from "./utils";
@@ -110,18 +111,13 @@ export type BindingStrategy =
* IMPORTANT: currently must be > 0 (this also applies to the computed gap)
*/
export const BASE_BINDING_GAP = 5;
export const BASE_BINDING_GAP_ELBOW = 5;
export const BASE_ARROW_MIN_LENGTH = 10;
export const FOCUS_POINT_SIZE = 10 / 1.5;
export const getBindingGap = (
bindTarget: ExcalidrawBindableElement,
opts: Pick<ExcalidrawArrowElement, "elbowed">,
): number => {
return (
(opts.elbowed ? BASE_BINDING_GAP_ELBOW : BASE_BINDING_GAP) +
bindTarget.strokeWidth / 2
);
return BASE_BINDING_GAP + bindTarget.strokeWidth / 2;
};
export const maxBindingDistance_simple = (zoom?: AppState["zoom"]): number => {
@@ -175,6 +171,7 @@ export const bindOrUnbindBindingElement = (
start,
"start",
scene,
appState.zoom,
appState.isBindingEnabled,
);
bindOrUnbindBindingElementEdge(
@@ -182,6 +179,7 @@ export const bindOrUnbindBindingElement = (
end,
"end",
scene,
appState.zoom,
appState.isBindingEnabled,
);
if (start.focusPoint || end.focusPoint) {
@@ -226,6 +224,7 @@ const bindOrUnbindBindingElementEdge = (
{ mode, element, focusPoint }: BindingStrategy,
startOrEnd: "start" | "end",
scene: Scene,
zoom: AppState["zoom"],
shouldSnapToOutline = true,
): void => {
if (mode === null) {
@@ -238,6 +237,7 @@ const bindOrUnbindBindingElementEdge = (
mode,
startOrEnd,
scene,
zoom,
focusPoint,
shouldSnapToOutline,
);
@@ -270,10 +270,11 @@ const bindingStrategyForElbowArrowEndpointDragging = (
elementsMap,
);
const hit = getHoveredElementForBinding(
arrow,
globalPoint,
elements,
elementsMap,
maxBindingDistance_simple(zoom),
zoom,
);
const current = hit
@@ -321,7 +322,7 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
draggingPoints.get(startDragged ? startIdx : endIdx)!.point,
elementsMap,
);
const hit = getHoveredElementForBinding(point, elements, elementsMap);
const hit = getHoveredElementForBinding(arrow, point, elements, elementsMap);
// With new arrows this handles the binding at arrow creation
if (startDragged) {
@@ -366,7 +367,12 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
// Check and handle nested shapes
if (hit && arrow.startBinding) {
const startBinding = arrow.startBinding;
const allHits = getAllHoveredElementAtPoint(point, elements, elementsMap);
const allHits = getAllHoveredElementAtPoint(
arrow,
point,
elements,
elementsMap,
);
if (allHits.find((el) => el.id === startBinding.elementId)) {
const otherElement = elementsMap.get(
@@ -468,9 +474,9 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
let other: BindingStrategy = { mode: undefined };
const isMultiPoint = arrow.points.length > 2;
const hit = getHoveredElementForBinding(point, elements, elementsMap);
const hit = getHoveredElementForBinding(arrow, point, elements, elementsMap);
const isOverlapping = oppositeBinding
? getAllHoveredElementAtPoint(point, elements, elementsMap).some(
? getAllHoveredElementAtPoint(arrow, point, elements, elementsMap).some(
(el) => el.id === oppositeBinding.elementId,
)
: false;
@@ -695,10 +701,11 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
elementsMap,
);
const hit = getHoveredElementForBinding(
arrow,
globalPoint,
elements,
elementsMap,
maxBindingDistance_simple(appState.zoom),
appState.zoom,
);
const pointInElement =
hit &&
@@ -1019,6 +1026,7 @@ export const bindBindingElement = (
mode: BindMode,
startOrEnd: "start" | "end",
scene: Scene,
zoom: AppState["zoom"],
focusPoint?: GlobalPoint,
shouldSnapToOutline = true,
): void => {
@@ -1035,6 +1043,7 @@ export const bindBindingElement = (
hoveredElement,
startOrEnd,
elementsMap,
zoom,
shouldSnapToOutline,
),
};
@@ -1259,6 +1268,7 @@ const updateArrowBindings = (
strategy[strategyName].mode,
strategyName,
scene,
appState.zoom,
strategy[strategyName].focusPoint,
);
}
@@ -1368,6 +1378,7 @@ export const bindPointToSnapToElementOutline = (
bindableElement: ExcalidrawBindableElement,
startOrEnd: "start" | "end",
elementsMap: ElementsMap,
zoom: AppState["zoom"],
customIntersector?: LineSegment<GlobalPoint>,
isMidpointSnappingEnabled = true,
): GlobalPoint => {
@@ -1400,7 +1411,7 @@ export const bindPointToSnapToElementOutline = (
startOrEnd === "start" ? 1 : -2,
elementsMap,
);
const bindingGap = getBindingGap(bindableElement, arrowElement);
const bindingGap = getBindingGap(bindableElement);
const aabb = aabbForElement(bindableElement, elementsMap);
const bindableCenter = getCenterForBounds(aabb);
@@ -1410,7 +1421,13 @@ export const bindPointToSnapToElementOutline = (
headingForPointFromElement(bindableElement, aabb, point),
);
const snapPoint = isMidpointSnappingEnabled
? snapToMid(bindableElement, elementsMap, edgePoint, 0.05, arrowElement)
? getSnapOutlineMidPoint(
edgePoint,
bindableElement,
elementsMap,
zoom,
arrowElement,
)
: undefined;
const resolved = snapPoint || point;
const otherPoint = pointFrom<GlobalPoint>(
@@ -1455,7 +1472,7 @@ export const bindPointToSnapToElementOutline = (
bindableElement,
elementsMap,
anotherIntersector,
BASE_BINDING_GAP_ELBOW,
BASE_BINDING_GAP,
).sort(pointDistanceSq)[0];
}
} else {
@@ -1514,7 +1531,7 @@ export const avoidRectangularCorner = (
-bindTarget.angle as Radians,
);
const bindingGap = getBindingGap(bindTarget, arrowElement);
const bindingGap = getBindingGap(bindTarget);
if (nonRotatedPoint[0] < bindTarget.x && nonRotatedPoint[1] < bindTarget.y) {
// Top left
@@ -1592,121 +1609,6 @@ export const avoidRectangularCorner = (
return p;
};
export const snapToMid = (
bindTarget: ExcalidrawBindableElement,
elementsMap: ElementsMap,
p: GlobalPoint,
tolerance: number = 0.05,
arrowElement?: ExcalidrawArrowElement,
): GlobalPoint | undefined => {
const { x, y, width, height, angle } = bindTarget;
const center = elementCenterPoint(bindTarget, elementsMap, -0.1, -0.1);
const nonRotated = pointRotateRads(p, center, -angle as Radians);
const bindingGap = arrowElement ? getBindingGap(bindTarget, arrowElement) : 0;
// snap-to-center point is adaptive to element size, but we don't want to go
// above and below certain px distance
const verticalThreshold = clamp(tolerance * height, 5, 80);
const horizontalThreshold = clamp(tolerance * width, 5, 80);
// Too close to the center makes it hard to resolve direction precisely
if (pointDistance(center, nonRotated) < bindingGap) {
return undefined;
}
if (
nonRotated[0] <= x + width / 2 &&
nonRotated[1] > center[1] - verticalThreshold &&
nonRotated[1] < center[1] + verticalThreshold
) {
// LEFT
return pointRotateRads(
pointFrom<GlobalPoint>(x - bindingGap, center[1]),
center,
angle,
);
} else if (
nonRotated[1] <= y + height / 2 &&
nonRotated[0] > center[0] - horizontalThreshold &&
nonRotated[0] < center[0] + horizontalThreshold
) {
// TOP
return pointRotateRads(
pointFrom<GlobalPoint>(center[0], y - bindingGap),
center,
angle,
);
} else if (
nonRotated[0] >= x + width / 2 &&
nonRotated[1] > center[1] - verticalThreshold &&
nonRotated[1] < center[1] + verticalThreshold
) {
// RIGHT
return pointRotateRads(
pointFrom<GlobalPoint>(x + width + bindingGap, center[1]),
center,
angle,
);
} else if (
nonRotated[1] >= y + height / 2 &&
nonRotated[0] > center[0] - horizontalThreshold &&
nonRotated[0] < center[0] + horizontalThreshold
) {
// DOWN
return pointRotateRads(
pointFrom<GlobalPoint>(center[0], y + height + bindingGap),
center,
angle,
);
} else if (bindTarget.type === "diamond") {
const distance = bindingGap;
const topLeft = pointFrom<GlobalPoint>(
x + width / 4 - distance,
y + height / 4 - distance,
);
const topRight = pointFrom<GlobalPoint>(
x + (3 * width) / 4 + distance,
y + height / 4 - distance,
);
const bottomLeft = pointFrom<GlobalPoint>(
x + width / 4 - distance,
y + (3 * height) / 4 + distance,
);
const bottomRight = pointFrom<GlobalPoint>(
x + (3 * width) / 4 + distance,
y + (3 * height) / 4 + distance,
);
if (
pointDistance(topLeft, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return pointRotateRads(topLeft, center, angle);
}
if (
pointDistance(topRight, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return pointRotateRads(topRight, center, angle);
}
if (
pointDistance(bottomLeft, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return pointRotateRads(bottomLeft, center, angle);
}
if (
pointDistance(bottomRight, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return pointRotateRads(bottomRight, center, angle);
}
}
return undefined;
};
const extractBinding = (
arrow: ExcalidrawArrowElement,
startOrEnd: "startBinding" | "endBinding",
@@ -1807,7 +1709,7 @@ export const updateBoundPoint = (
otherBindable,
elementsMap,
intersector,
getBindingGap(otherBindable, arrow),
getBindingGap(otherBindable),
).sort(
(a, b) => pointDistanceSq(a, focusPoint) - pointDistanceSq(b, focusPoint),
)[0];
@@ -1817,7 +1719,7 @@ export const updateBoundPoint = (
bindableElement,
elementsMap,
intersector,
getBindingGap(bindableElement, arrow),
getBindingGap(bindableElement),
).sort(
(a, b) =>
pointDistanceSq(a, otherFocusPointOrArrowPoint) -
@@ -1845,7 +1747,7 @@ export const updateBoundPoint = (
element: otherBindable,
point: outlinePoint,
elementsMap,
threshold: getBindingGap(otherBindable, arrow),
threshold: getBindingGap(otherBindable),
overrideShouldTestInside: true,
})
) {
@@ -1906,6 +1808,7 @@ export const calculateFixedPointForElbowArrowBinding = (
hoveredElement: ExcalidrawBindableElement,
startOrEnd: "start" | "end",
elementsMap: ElementsMap,
zoom: AppState["zoom"],
shouldSnapToOutline = true,
isMidpointSnappingEnabled = true,
): { fixedPoint: FixedPoint } => {
@@ -1921,6 +1824,7 @@ export const calculateFixedPointForElbowArrowBinding = (
hoveredElement,
startOrEnd,
elementsMap,
zoom,
undefined,
isMidpointSnappingEnabled,
)
+90 -84
View File
@@ -25,7 +25,7 @@ import type {
Radians,
} from "@excalidraw/math";
import type { FrameNameBounds } from "@excalidraw/excalidraw/types";
import type { AppState, FrameNameBounds } from "@excalidraw/excalidraw/types";
import { isPathALoop } from "./utils";
import {
@@ -59,13 +59,12 @@ import { LinearElementEditor } from "./linearElementEditor";
import { distanceToElement } from "./distance";
import { getBindingGap } from "./binding";
import { getBindingGap, maxBindingDistance_simple } from "./binding";
import { hasBackground } from "./comparisons";
import type {
ElementsMap,
ExcalidrawArrowElement,
ExcalidrawBindableElement,
ExcalidrawDiamondElement,
ExcalidrawElement,
@@ -254,25 +253,20 @@ export const hitElementBoundText = (
return isPointInElement(point, boundTextElement, elementsMap);
};
const bindingBorderTest = (
const bindableElementBorderDistanceIfClose = (
element: NonDeleted<ExcalidrawBindableElement>,
[x, y]: Readonly<GlobalPoint>,
elementsMap: NonDeletedSceneElementsMap,
point: GlobalPoint,
elementsMap: ElementsMap,
tolerance: number = 0,
): boolean => {
const p = pointFrom<GlobalPoint>(x, y);
const shouldTestInside =
// disable fullshape snapping for frame elements so we
// can bind to frame children
!isFrameLikeElement(element);
) => {
// PERF: Run a cheap test to see if the binding element
// is even close to the element
const [x, y] = point;
const t = Math.max(1, tolerance);
const bounds = [x - t, y - t, x + t, y + t] as Bounds;
const elementBounds = getElementBounds(element, elementsMap);
if (!doBoundsIntersect(bounds, elementBounds)) {
return false;
return -Infinity;
}
// If the element is inside a frame, we should clip the element
@@ -283,33 +277,29 @@ const bindingBorderTest = (
enclosingFrame,
elementsMap,
);
if (!pointInsideBounds(p, enclosingFrameBounds)) {
return false;
if (!pointInsideBounds(point, enclosingFrameBounds)) {
return -Infinity;
}
}
}
// Do the intersection test against the element since it's close enough
const intersections = intersectElementWithLineSegment(
element,
elementsMap,
lineSegment(elementCenterPoint(element, elementsMap), p),
);
const distance = distanceToElement(element, elementsMap, p);
const distance = distanceToElement(element, elementsMap, point);
if (isPointInElement(point, element, elementsMap)) {
return distance;
}
return shouldTestInside
? intersections.length === 0 || distance <= tolerance
: intersections.length > 0 && distance <= t;
return distance > tolerance ? -Infinity : -distance;
};
export const getAllHoveredElementAtPoint = (
arrow: { elbowed: boolean },
point: Readonly<GlobalPoint>,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
tolerance?: number,
): NonDeleted<ExcalidrawBindableElement>[] => {
const candidateElements: NonDeleted<ExcalidrawBindableElement>[] = [];
// We need to to hit testing from front (end of the array) to back (beginning of the array)
// We need to do hit testing from front (end of the array) to back (beginning of the array)
// because array is ordered from lower z-index to highest and we want element z-index
// with higher z-index
for (let index = elements.length - 1; index >= 0; --index) {
@@ -322,7 +312,13 @@ export const getAllHoveredElementAtPoint = (
if (
isBindableElement(element, false) &&
bindingBorderTest(element, point, elementsMap, tolerance)
hitElementItself({
element,
point,
elementsMap,
threshold: tolerance ?? getBindingGap(element),
overrideShouldTestInside: true,
})
) {
candidateElements.push(element);
@@ -339,82 +335,92 @@ export const getAllHoveredElementAtPoint = (
};
export const getHoveredElementForBinding = (
arrow: { elbowed: boolean },
point: Readonly<GlobalPoint>,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
tolerance?: number,
zoom?: AppState["zoom"],
): NonDeleted<ExcalidrawBindableElement> | null => {
const candidateElements = getAllHoveredElementAtPoint(
point,
elements,
elementsMap,
tolerance,
);
type Candidate = {
element: NonDeleted<ExcalidrawBindableElement>;
distance: number;
overlapPercent?: number;
relativeArea?: number;
};
if (!candidateElements || candidateElements.length === 0) {
return null;
}
if (candidateElements.length === 1) {
return candidateElements[0];
}
// Prefer smaller shapes
return candidateElements
.sort(
(a, b) => b.width ** 2 + b.height ** 2 - (a.width ** 2 + a.height ** 2),
)
.pop() as NonDeleted<ExcalidrawBindableElement>;
};
export const getHoveredElementForFocusPoint = (
point: GlobalPoint,
arrow: ExcalidrawArrowElement,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
tolerance?: number,
): ExcalidrawBindableElement | null => {
const candidateElements: NonDeleted<ExcalidrawBindableElement>[] = [];
// We need to to hit testing from front (end of the array) to back (beginning of the array)
// because array is ordered from lower z-index to highest and we want element z-index
// with higher z-index
const candidates: Candidate[] = [];
for (let index = elements.length - 1; index >= 0; --index) {
const element = elements[index];
invariant(
!element.isDeleted,
"Elements in the function parameter for getAllElementsAtPositionForBinding() should not contain deleted elements",
if (!isBindableElement(element, false)) {
continue;
}
const maxDistance = maxBindingDistance_simple(zoom);
const distance = bindableElementBorderDistanceIfClose(
element,
point,
elementsMap,
maxDistance,
);
if (
isBindableElement(element, false) &&
bindingBorderTest(element, point, elementsMap, tolerance)
) {
candidateElements.push(element);
if (distance > -maxDistance) {
candidates.push({ element, distance });
if (!isTransparent(element.backgroundColor) && distance >= 0) {
break;
}
}
}
if (!candidateElements || candidateElements.length === 0) {
if (candidates.length === 0) {
return null;
}
if (candidateElements.length === 1) {
return candidateElements[0];
if (candidates.length === 1) {
return candidates[0].element;
}
const distanceFilteredCandidateElements = candidateElements
// Resolve by distance
.filter(
(el) =>
distanceToElement(el, elementsMap, point) <= getBindingGap(el, arrow) ||
isPointInElement(point, el, elementsMap),
);
const closestElements = candidates.sort(
(a, b) => Math.abs(a.distance) - Math.abs(b.distance),
);
if (distanceFilteredCandidateElements.length === 0) {
return null;
}
const candidate = closestElements[0];
const [cx1, cy1, cx2, cy2] = getElementBounds(candidate.element, elementsMap);
const candidateArea = Math.max(
0.00001,
Math.abs(cx2 - cx1) * Math.abs(cy2 - cy1),
);
const overlaps = closestElements
.map((c) => {
if (c.element === candidate.element) {
return { ...c, overlapPercent: 0, relativeArea: 1 };
}
return distanceFilteredCandidateElements[0] as NonDeleted<ExcalidrawBindableElement>;
const [x1, y1, x2, y2] = getElementBounds(c.element, elementsMap);
const overlapX1 = x1 > cx1 && x1 < cx2 ? x1 : cx1;
const overlapY1 = y1 > cy1 && y1 < cy2 ? y1 : cy1;
const overlapX2 = x2 < cx2 && x2 > cx1 ? x2 : cx2;
const overlapY2 = y2 < cy2 && y2 > cy1 ? y2 : cy2;
const overlapWdith =
overlapX1 !== cx1 || overlapX2 !== cx2 ? overlapX2 - overlapX1 : 0;
const overlapHeight =
overlapY1 !== cy1 || overlapY2 !== cy2 ? overlapY2 - overlapY1 : 0;
const area = Math.max(0.00001, Math.abs(x2 - x1) * Math.abs(y2 - y1));
const overlapPercent = Math.abs(overlapHeight * overlapWdith) / area;
return {
...c,
overlapPercent,
relativeArea:
overlapPercent === 0 ? 1 : Math.min(area / candidateArea, 1),
};
})
.filter((c) => c.overlapPercent > 0.25 && c.relativeArea < 0.75);
return candidate.distance >= 0 && overlaps.length > 0
? overlaps[0].element
: candidate.element;
};
/**
+8 -18
View File
@@ -21,7 +21,7 @@ import { getPerfectElementSize } from "./sizeHelpers";
import { getBoundTextElement } from "./textElement";
import { getMinTextElementWidth } from "./textMeasurements";
import {
isArrowElement,
isArrowElement as isBindingElement,
isElbowArrow,
isFrameLikeElement,
isImageElement,
@@ -108,19 +108,7 @@ export const dragSelectedElements = (
);
elementsToUpdate.forEach((element) => {
const isArrow = !isArrowElement(element);
const isStartBoundElementSelected =
isArrow ||
(element.startBinding
? elementsToUpdateIds.has(element.startBinding.elementId)
: false);
const isEndBoundElementSelected =
isArrow ||
(element.endBinding
? elementsToUpdateIds.has(element.endBinding.elementId)
: false);
if (!isArrowElement(element)) {
if (!isBindingElement(element)) {
updateElementCoords(pointerDownState, element, scene, adjustedOffset);
// skip arrow labels since we calculate its position during render
@@ -143,7 +131,6 @@ export const dragSelectedElements = (
// NOTE: Add a little initial drag to the arrow dragging when the arrow
// is the single element being dragged to avoid accidentally unbinding
// the arrow when the user just wants to select it.
elementsToUpdate.size > 1 ||
Math.max(Math.abs(adjustedOffset.x), Math.abs(adjustedOffset.y)) >
DRAGGING_THRESHOLD ||
@@ -151,9 +138,12 @@ export const dragSelectedElements = (
) {
updateElementCoords(pointerDownState, element, scene, adjustedOffset);
const shouldUnbindStart =
element.startBinding && !isStartBoundElementSelected;
const shouldUnbindEnd = element.endBinding && !isEndBoundElementSelected;
const shouldUnbindStart = element.startBinding
? !elementsToUpdateIds.has(element.startBinding.elementId)
: true;
const shouldUnbindEnd = element.endBinding
? !elementsToUpdateIds.has(element.endBinding.elementId)
: true;
if (shouldUnbindStart || shouldUnbindEnd) {
// NOTE: Moving the bound arrow should unbind it, otherwise we would
// have weird situations, like 0 lenght arrow when the user moves
+21 -20
View File
@@ -30,8 +30,7 @@ import {
getHeadingForElbowArrowSnap,
getGlobalFixedPointForBindableElement,
getBindingGap,
maxBindingDistance_simple,
BASE_BINDING_GAP_ELBOW,
BASE_BINDING_GAP,
} from "./binding";
import { distanceToElement } from "./distance";
import {
@@ -318,6 +317,7 @@ const handleSegmentRelease = (
...rest
} = getElbowArrowData(
{
...arrow,
x,
y,
startBinding,
@@ -1041,6 +1041,7 @@ export const updateElbowArrowPoints = (
...rest
} = getElbowArrowData(
{
...arrow,
x: arrow.x,
y: arrow.y,
startBinding,
@@ -1190,15 +1191,7 @@ export const updateElbowArrowPoints = (
* - hoveredEndElement: The element being hovered over at the end point.
*/
const getElbowArrowData = (
arrow: {
x: number;
y: number;
startBinding: FixedPointBinding | null;
endBinding: FixedPointBinding | null;
startArrowhead: Arrowhead | null;
endArrowhead: Arrowhead | null;
points: readonly LocalPoint[];
},
arrow: ExcalidrawElbowArrowElement,
elementsMap: NonDeletedSceneElementsMap,
nextPoints: readonly LocalPoint[],
options?: {
@@ -1223,6 +1216,7 @@ const getElbowArrowData = (
const elements = Array.from(elementsMap.values());
hoveredStartElement =
getHoveredElement(
arrow,
origStartGlobalPoint,
elementsMap,
elements,
@@ -1230,6 +1224,7 @@ const getElbowArrowData = (
) || null;
hoveredEndElement =
getHoveredElement(
arrow,
origEndGlobalPoint,
elementsMap,
elements,
@@ -1256,6 +1251,7 @@ const getElbowArrowData = (
"start",
arrow.startBinding?.fixedPoint,
origStartGlobalPoint,
options?.zoom || ({ value: 1 } as AppState["zoom"]),
hoveredStartElement,
elementsMap,
options?.isDragging,
@@ -1273,6 +1269,7 @@ const getElbowArrowData = (
"end",
arrow.endBinding?.fixedPoint,
origEndGlobalPoint,
options?.zoom || ({ value: 1 } as AppState["zoom"]),
hoveredEndElement,
elementsMap,
options?.isDragging,
@@ -1314,8 +1311,8 @@ const getElbowArrowData = (
offsetFromHeading(
startHeading,
arrow.startArrowhead
? getBindingGap(hoveredStartElement, { elbowed: true }) * 6
: getBindingGap(hoveredStartElement, { elbowed: true }) * 2,
? getBindingGap(hoveredStartElement) * 6
: getBindingGap(hoveredStartElement) * 2,
1,
),
)
@@ -1327,8 +1324,8 @@ const getElbowArrowData = (
offsetFromHeading(
endHeading,
arrow.endArrowhead
? getBindingGap(hoveredEndElement, { elbowed: true }) * 6
: getBindingGap(hoveredEndElement, { elbowed: true }) * 2,
? getBindingGap(hoveredEndElement) * 6
: getBindingGap(hoveredEndElement) * 2,
1,
),
)
@@ -1375,8 +1372,8 @@ const getElbowArrowData = (
? 0
: BASE_PADDING -
(arrow.startArrowhead
? BASE_BINDING_GAP_ELBOW * 6
: BASE_BINDING_GAP_ELBOW * 2),
? BASE_BINDING_GAP * 6
: BASE_BINDING_GAP * 2),
BASE_PADDING,
),
boundsOverlap
@@ -1391,8 +1388,8 @@ const getElbowArrowData = (
? 0
: BASE_PADDING -
(arrow.endArrowhead
? BASE_BINDING_GAP_ELBOW * 6
: BASE_BINDING_GAP_ELBOW * 2),
? BASE_BINDING_GAP * 6
: BASE_BINDING_GAP * 2),
BASE_PADDING,
),
boundsOverlap,
@@ -2218,6 +2215,7 @@ const getGlobalPoint = (
startOrEnd: "start" | "end",
fixedPointRatio: [number, number] | undefined | null,
initialPoint: GlobalPoint,
zoom: AppState["zoom"],
element?: ExcalidrawBindableElement | null,
elementsMap?: ElementsMap,
isDragging?: boolean,
@@ -2231,6 +2229,7 @@ const getGlobalPoint = (
element,
startOrEnd,
elementsMap,
zoom,
undefined,
isMidpointSnappingEnabled,
);
@@ -2279,16 +2278,18 @@ const getBindPointHeading = (
);
const getHoveredElement = (
arrow: ExcalidrawElbowArrowElement,
origPoint: GlobalPoint,
elementsMap: NonDeletedSceneElementsMap,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
zoom?: AppState["zoom"],
) => {
return getHoveredElementForBinding(
arrow,
origPoint,
elements,
elementsMap,
maxBindingDistance_simple(zoom),
zoom,
);
};
+9 -1
View File
@@ -452,8 +452,16 @@ const createBindingArrow = (
"orbit",
"start",
scene,
appState.zoom,
);
bindBindingElement(
bindingArrow,
endBindingElement,
"orbit",
"end",
scene,
appState.zoom,
);
bindBindingElement(bindingArrow, endBindingElement, "orbit", "end", scene);
const changedElements = new Map<string, OrderedExcalidrawElement>();
changedElements.set(
+37 -26
View File
@@ -48,7 +48,6 @@ import {
calculateFixedPointForNonElbowArrowBinding,
getBindingStrategyForDraggingBindingElementEndpoints,
isBindingEnabled,
snapToMid,
updateBoundPoint,
} from "./binding";
import {
@@ -344,7 +343,7 @@ export class LinearElementEditor {
// Apply the point movement if needed
let suggestedBinding: AppState["suggestedBinding"] = null;
const { positions, updates } = pointDraggingUpdates(
const { positions, updates, hit } = pointDraggingUpdates(
[idx],
deltaX,
deltaY,
@@ -382,17 +381,20 @@ export class LinearElementEditor {
// Move the arrow over the bindable object in terms of z-index
if (isBindingElement(element)) {
moveArrowAboveBindable(
LinearElementEditor.getPointGlobalCoordinates(
if (hit) {
moveArrowAboveBindable(
LinearElementEditor.getPointGlobalCoordinates(
element,
element.points[element.points.length - 1],
elementsMap,
),
element,
element.points[element.points.length - 1],
elements,
elementsMap,
),
element,
elements,
elementsMap,
app.scene,
);
app.scene,
hit,
);
}
}
// PERF: Avoid state updates if not absolutely necessary
@@ -539,7 +541,7 @@ export class LinearElementEditor {
// Apply the point movement if needed
let suggestedBinding: AppState["suggestedBinding"] = null;
const { positions, updates } = pointDraggingUpdates(
const { positions, updates, hit } = pointDraggingUpdates(
selectedPointsIndices,
deltaX,
deltaY,
@@ -578,19 +580,22 @@ export class LinearElementEditor {
// Move the arrow over the bindable object in terms of z-index
if (isBindingElement(element) && startIsSelected !== endIsSelected) {
moveArrowAboveBindable(
LinearElementEditor.getPointGlobalCoordinates(
if (hit) {
moveArrowAboveBindable(
LinearElementEditor.getPointGlobalCoordinates(
element,
startIsSelected
? element.points[0]
: element.points[element.points.length - 1],
elementsMap,
),
element,
startIsSelected
? element.points[0]
: element.points[element.points.length - 1],
elements,
elementsMap,
),
element,
elements,
elementsMap,
app.scene,
);
app.scene,
hit,
);
}
}
// Attached text might need to update if arrow dimensions change
@@ -2136,6 +2141,7 @@ const pointDraggingUpdates = (
): {
positions: PointsPositionUpdates;
updates?: PointMoveOtherUpdates;
hit?: ExcalidrawBindableElement | null;
} => {
const naiveDraggingPoints = new Map(
selectedPointsIndices.map((pointIndex) => {
@@ -2193,13 +2199,15 @@ const pointDraggingUpdates = (
? {
element: suggestedBindingElement,
midPoint: app.state.isMidpointSnappingEnabled
? snapToMid(
suggestedBindingElement,
elementsMap,
? getSnapOutlineMidPoint(
pointFrom<GlobalPoint>(
scenePointerX - linearElementEditor.pointerOffset.x,
scenePointerY - linearElementEditor.pointerOffset.y,
),
suggestedBindingElement,
elementsMap,
app.state.zoom,
element,
)
: undefined,
}
@@ -2306,6 +2314,7 @@ const pointDraggingUpdates = (
start.element,
elementsMap,
app.state.zoom,
element,
),
}
: null;
@@ -2345,6 +2354,7 @@ const pointDraggingUpdates = (
end.element,
elementsMap,
app.state.zoom,
element,
),
}
: null;
@@ -2497,6 +2507,7 @@ const pointDraggingUpdates = (
];
}),
),
hit: startIsDragged ? start.element : end.element,
};
};
+6
View File
@@ -17,6 +17,7 @@ import {
} from "@excalidraw/common";
import type { MarkOptional } from "@excalidraw/common/utility-types";
import type { Zoom } from "@excalidraw/excalidraw/types";
import { bindBindingElement } from "./binding";
import {
@@ -248,6 +249,7 @@ const bindLinearElementToElement = (
end: ValidLinearElement["end"],
elementStore: ElementStore,
scene: Scene,
zoom: Zoom,
): {
linearElement: ExcalidrawLinearElement;
startBoundElement?: ExcalidrawElement;
@@ -335,6 +337,7 @@ const bindLinearElementToElement = (
"orbit",
"start",
scene,
zoom,
);
}
}
@@ -411,6 +414,7 @@ const bindLinearElementToElement = (
"orbit",
"end",
scene,
zoom,
);
}
}
@@ -696,6 +700,7 @@ export const convertToExcalidrawElements = (
originalEnd,
elementStore,
scene,
{ value: 1 } as Zoom,
);
container = linearElement;
elementStore.add(linearElement);
@@ -721,6 +726,7 @@ export const convertToExcalidrawElements = (
end,
elementStore,
scene,
{ value: 1 } as Zoom,
);
elementStore.add(linearElement);
+181 -56
View File
@@ -8,6 +8,7 @@ import {
import {
bezierEquation,
clamp,
curve,
curveCatmullRomCubicApproxPoints,
curveOffsetPoints,
@@ -26,7 +27,7 @@ import {
type GlobalPoint,
} from "@excalidraw/math";
import type { Curve, LineSegment, LocalPoint } from "@excalidraw/math";
import type { Curve, LineSegment, LocalPoint, Radians } from "@excalidraw/math";
import type {
AppState,
@@ -41,7 +42,7 @@ import { generateLinearCollisionShape } from "./shape";
import { hitElementItself, isPointInElement } from "./collision";
import { LinearElementEditor } from "./linearElementEditor";
import { isRectangularElement } from "./typeChecks";
import { maxBindingDistance_simple } from "./binding";
import { getBindingGap, maxBindingDistance_simple } from "./binding";
import {
getGlobalFixedPointForBindableElement,
@@ -587,67 +588,193 @@ const getDiagonalsForBindableElement = (
return [diagonalOne, diagonalTwo];
};
export const getSnapOutlineMidPoint = (
point: GlobalPoint,
const getSnappedMidpointIndexForElbowArrow = (
element: ExcalidrawBindableElement,
elementsMap: ElementsMap,
zoom: AppState["zoom"],
point: GlobalPoint,
center: GlobalPoint,
horizontalThreshold: number,
verticalThreshold: number,
) => {
const center = elementCenterPoint(element, elementsMap);
const sideMidpoints =
element.type === "diamond"
? getDiamondBaseCorners(element).map((curve) => {
const point = bezierEquation(curve, 0.5);
const rotatedPoint = pointRotateRads(point, center, element.angle);
const { x, y, width, height, angle } = element;
const nonRotated = pointRotateRads(point, center, -angle as Radians);
return pointFrom<GlobalPoint>(rotatedPoint[0], rotatedPoint[1]);
})
: [
// RIGHT midpoint
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + element.width,
element.y + element.height / 2,
),
center,
element.angle,
),
// BOTTOM midpoint
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + element.width / 2,
element.y + element.height,
),
center,
element.angle,
),
// LEFT midpoint
pointRotateRads(
pointFrom<GlobalPoint>(element.x, element.y + element.height / 2),
center,
element.angle,
),
// TOP midpoint
pointRotateRads(
pointFrom<GlobalPoint>(element.x + element.width / 2, element.y),
center,
element.angle,
),
];
const candidate = sideMidpoints.find(
(midpoint) =>
pointDistance(point, midpoint) <=
maxBindingDistance_simple(zoom) + element.strokeWidth / 2 &&
const bindingGap = getBindingGap(element);
if (pointDistance(center, nonRotated) < bindingGap) {
return -1;
}
if (
nonRotated[0] <= x + width / 2 &&
nonRotated[1] > center[1] - verticalThreshold &&
nonRotated[1] < center[1] + verticalThreshold
) {
return 2;
} else if (
nonRotated[1] <= y + height / 2 &&
nonRotated[0] > center[0] - horizontalThreshold &&
nonRotated[0] < center[0] + horizontalThreshold
) {
return 3;
} else if (
nonRotated[0] >= x + width / 2 &&
nonRotated[1] > center[1] - verticalThreshold &&
nonRotated[1] < center[1] + verticalThreshold
) {
return 0;
} else if (
nonRotated[1] >= y + height / 2 &&
nonRotated[0] > center[0] - horizontalThreshold &&
nonRotated[0] < center[0] + horizontalThreshold
) {
return 1;
} else if (element.type === "diamond") {
const distance = bindingGap;
const topLeft = pointFrom<GlobalPoint>(
x + width / 4 - distance,
y + height / 4 - distance,
);
const topRight = pointFrom<GlobalPoint>(
x + (3 * width) / 4 + distance,
y + height / 4 - distance,
);
const bottomLeft = pointFrom<GlobalPoint>(
x + width / 4 - distance,
y + (3 * height) / 4 + distance,
);
const bottomRight = pointFrom<GlobalPoint>(
x + (3 * width) / 4 + distance,
y + (3 * height) / 4 + distance,
);
if (
pointDistance(bottomLeft, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return 1;
}
if (
pointDistance(bottomRight, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return 0;
}
if (
pointDistance(topLeft, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return 2;
}
if (
pointDistance(topRight, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return 3;
}
}
return -1;
};
const getSnappedMidpointIndexForSimpleArrow = (
element: ExcalidrawBindableElement,
point: GlobalPoint,
elementsMap: ElementsMap,
horizontalThreshold: number,
verticalThreshold: number,
) => {
const baseMidpoints = getAllMidpoints(element, elementsMap);
for (let i = 0; i < baseMidpoints.length; i++) {
const threshold = i % 2 === 0 ? horizontalThreshold : verticalThreshold;
if (
pointDistance(baseMidpoints[i], point) <= threshold &&
!hitElementItself({
point,
element,
threshold: 0,
elementsMap,
overrideShouldTestInside: true,
}),
);
})
) {
return i;
}
}
return candidate;
return -1;
};
export const getAllMidpoints = (
element: ExcalidrawBindableElement,
elementsMap: ElementsMap,
): GlobalPoint[] => {
const center = elementCenterPoint(element, elementsMap);
if (element.type === "diamond") {
return getDiamondBaseCorners(element).map((curve) =>
pointRotateRads(bezierEquation(curve, 0.5), center, element.angle),
);
}
return [
pointFrom(element.width, element.height / 2),
pointFrom(element.width / 2, element.height),
pointFrom(0, element.height / 2),
pointFrom(element.width / 2, 0),
].map(([x, y]) =>
pointRotateRads(
pointFrom<GlobalPoint>(element.x + x, element.y + y),
center,
element.angle,
),
);
};
export const getSnapOutlineMidPoint = (
point: GlobalPoint,
element: ExcalidrawBindableElement,
elementsMap: ElementsMap,
zoom: AppState["zoom"],
arrow: { elbowed: boolean },
): GlobalPoint | undefined => {
const center = elementCenterPoint(element, elementsMap);
const baseMidpoints = getAllMidpoints(element, elementsMap);
const sideMidpoints =
element.type === "diamond"
? baseMidpoints.map((midpoint) => {
return pointFrom<GlobalPoint>(
midpoint[0] + (midpoint[0] - center[0]) * 0.1,
midpoint[1] + (midpoint[1] - center[1]) * 0.1,
);
})
: baseMidpoints;
const TOLERANCE = 0.05;
const maxDistance = maxBindingDistance_simple(zoom) + element.strokeWidth / 2;
const verticalThreshold = clamp(TOLERANCE * element.height, 5, maxDistance);
const horizontalThreshold = clamp(TOLERANCE * element.width, 5, maxDistance);
const idx = arrow.elbowed
? getSnappedMidpointIndexForElbowArrow(
element,
point,
center,
horizontalThreshold,
verticalThreshold,
)
: getSnappedMidpointIndexForSimpleArrow(
element,
point,
elementsMap,
horizontalThreshold,
verticalThreshold,
);
if (idx === -1) {
return undefined;
}
return sideMidpoints[idx];
};
export const projectFixedPointOntoDiagonal = (
@@ -660,9 +787,6 @@ export const projectFixedPointOntoDiagonal = (
isMidpointSnappingEnabled: boolean = true,
): GlobalPoint | null => {
invariant(arrow.points.length >= 2, "Arrow must have at least two points");
if (arrow.width < 3 && arrow.height < 3) {
return null;
}
if (isMidpointSnappingEnabled) {
const sideMidPoint = getSnapOutlineMidPoint(
@@ -670,6 +794,7 @@ export const projectFixedPointOntoDiagonal = (
element,
elementsMap,
zoom,
arrow,
);
if (sideMidPoint) {
return sideMidPoint;
+1 -6
View File
@@ -8,7 +8,6 @@ import { getElementsInGroup } from "./groups";
import { syncMovedIndices } from "./fractionalIndex";
import { getSelectedElements } from "./selection";
import { getBoundTextElement, getContainerElement } from "./textElement";
import { getHoveredElementForBinding } from "./collision";
import type { Scene } from "./Scene";
import type {
@@ -156,12 +155,8 @@ export const moveArrowAboveBindable = (
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
scene: Scene,
hit?: NonDeletedExcalidrawElement,
hoveredElement: NonDeletedExcalidrawElement,
): readonly OrderedExcalidrawElement[] => {
const hoveredElement = hit
? hit
: getHoveredElementForBinding(point, elements, elementsMap);
if (!hoveredElement) {
return elements;
}
+7 -2
View File
@@ -16,6 +16,7 @@ import "@excalidraw/utils/test-utils";
import { bindBindingElement } from "@excalidraw/element";
import type { LocalPoint } from "@excalidraw/math";
import type { Zoom } from "@excalidraw/excalidraw/types";
import { Scene } from "../src/Scene";
@@ -187,8 +188,12 @@ describe("elbow arrow routing", () => {
}) as ExcalidrawElbowArrowElement;
API.setElements([rectangle1, rectangle2, arrow]);
bindBindingElement(arrow, rectangle1, "orbit", "start", h.scene);
bindBindingElement(arrow, rectangle2, "orbit", "end", h.scene);
bindBindingElement(arrow, rectangle1, "orbit", "start", h.scene, {
value: 1,
} as Zoom);
bindBindingElement(arrow, rectangle2, "orbit", "end", h.scene, {
value: 1,
} as Zoom);
expect(arrow.startBinding).not.toBe(null);
expect(arrow.endBinding).not.toBe(null);
@@ -1897,6 +1897,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
startElement,
"start",
elementsMap,
appState.zoom,
appState.isBindingEnabled,
),
}
@@ -1911,6 +1912,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
endElement,
"end",
elementsMap,
appState.zoom,
appState.isBindingEnabled,
),
}
@@ -1943,6 +1945,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
appState.bindMode === "inside" ? "inside" : "orbit",
"start",
app.scene,
appState.zoom,
);
}
}
@@ -1957,6 +1960,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
appState.bindMode === "inside" ? "inside" : "orbit",
"end",
app.scene,
appState.zoom,
);
}
}
@@ -1,5 +1,4 @@
import { LaserPointer } from "@excalidraw/laser-pointer";
import {
SVG_NS,
getSvgPathFromStroke,
@@ -8,7 +7,8 @@ import {
import type { LaserPointerOptions } from "@excalidraw/laser-pointer";
import type { AnimationFrameHandler } from "./animation-frame-handler";
import { AnimationController } from "./renderer/animation";
import type App from "./components/App";
import type { AppState } from "./types";
@@ -34,15 +34,16 @@ export class AnimatedTrail implements Trail {
private container?: SVGSVGElement;
private trailElement: SVGPathElement;
private trailAnimation?: SVGAnimateElement;
private key: string;
private static counter = 0;
constructor(
private animationFrameHandler: AnimationFrameHandler,
protected app: App,
private options: Partial<LaserPointerOptions> &
Partial<AnimatedTrailOptions>,
) {
this.animationFrameHandler.register(this, this.onFrame.bind(this));
this.key = `animated-trail-${AnimatedTrail.counter++}`;
this.trailElement = document.createElementNS(SVG_NS, "path");
if (this.options.animateTrail) {
this.trailAnimation = document.createElementNS(SVG_NS, "animate");
@@ -73,6 +74,15 @@ export class AnimatedTrail implements Trail {
return false;
}
private cleanup() {
this.pastTrails = [];
this.currentTrail = undefined;
if (this.trailElement.parentNode === this.container) {
this.container?.removeChild(this.trailElement);
}
}
start(container?: SVGSVGElement) {
if (container) {
this.container = container;
@@ -82,15 +92,23 @@ export class AnimatedTrail implements Trail {
this.container.appendChild(this.trailElement);
}
this.animationFrameHandler.start(this);
if (!AnimationController.running(this.key)) {
AnimationController.start(this.key, () => {
const needsNext = this.onFrame();
if (needsNext) {
return { keep: true };
}
this.cleanup();
return null;
});
}
}
stop() {
this.animationFrameHandler.stop(this);
if (this.trailElement.parentNode === this.container) {
this.container?.removeChild(this.trailElement);
}
AnimationController.cancel(this.key);
this.cleanup();
}
startPath(x: number, y: number) {
@@ -145,21 +163,25 @@ export class AnimatedTrail implements Trail {
if (this.currentTrail) {
const currentPath = this.drawTrail(this.currentTrail, this.app.state);
paths.push(currentPath);
}
this.pastTrails = this.pastTrails.filter((trail) => {
return trail.getStrokeOutline().length !== 0;
});
this.pastTrails = this.pastTrails.filter(
(t) =>
t.getStrokeOutline(t.options.size / this.app.state.zoom.value)
.length !== 0,
);
if (paths.length === 0) {
this.stop();
// Clean up the SVG path if there are no trails to render
this.trailElement.setAttribute("d", "");
return false;
}
const svgPaths = paths.join(" ").trim();
this.trailElement.setAttribute("d", svgPaths);
if (this.trailAnimation) {
this.trailElement.setAttribute(
"fill",
@@ -175,6 +197,8 @@ export class AnimatedTrail implements Trail {
(this.options.fill ?? (() => "black"))(this),
);
}
return true;
}
private drawTrail(trail: LaserPointer, state: AppState): string {
@@ -1,79 +0,0 @@
export type AnimationCallback = (timestamp: number) => void | boolean;
export type AnimationTarget = {
callback: AnimationCallback;
stopped: boolean;
};
export class AnimationFrameHandler {
private targets = new WeakMap<object, AnimationTarget>();
private rafIds = new WeakMap<object, number>();
register(key: object, callback: AnimationCallback) {
this.targets.set(key, { callback, stopped: true });
}
start(key: object) {
const target = this.targets.get(key);
if (!target) {
return;
}
if (this.rafIds.has(key)) {
return;
}
this.targets.set(key, { ...target, stopped: false });
this.scheduleFrame(key);
}
stop(key: object) {
const target = this.targets.get(key);
if (target && !target.stopped) {
this.targets.set(key, { ...target, stopped: true });
}
this.cancelFrame(key);
}
private constructFrame(key: object): FrameRequestCallback {
return (timestamp: number) => {
const target = this.targets.get(key);
if (!target) {
return;
}
const shouldAbort = this.onFrame(target, timestamp);
if (!target.stopped && !shouldAbort) {
this.scheduleFrame(key);
} else {
this.cancelFrame(key);
}
};
}
private scheduleFrame(key: object) {
const rafId = requestAnimationFrame(this.constructFrame(key));
this.rafIds.set(key, rafId);
}
private cancelFrame(key: object) {
if (this.rafIds.has(key)) {
const rafId = this.rafIds.get(key)!;
cancelAnimationFrame(rafId);
}
this.rafIds.delete(key);
}
private onFrame(target: AnimationTarget, timestamp: number): boolean {
const shouldAbort = target.callback(timestamp);
return shouldAbort ?? false;
}
}
+51 -36
View File
@@ -28,7 +28,6 @@ import {
APP_NAME,
CURSOR_TYPE,
DEFAULT_TRANSFORM_HANDLE_SPACING,
DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
DEFAULT_VERTICAL_ALIGN,
DRAGGING_THRESHOLD,
ELEMENT_SHIFT_TRANSLATE_AMOUNT,
@@ -38,7 +37,6 @@ import {
IMAGE_MIME_TYPES,
IMAGE_RENDER_TIMEOUT,
LINE_CONFIRM_THRESHOLD,
MAX_ALLOWED_FILE_BYTES,
MIME_TYPES,
MQ_RIGHT_SIDEBAR_MIN_WIDTH,
POINTER_BUTTON,
@@ -250,7 +248,6 @@ import {
getElementBounds,
doBoundsIntersect,
isPointInElement,
maxBindingDistance_simple,
convertToExcalidrawElements,
type ExcalidrawElementSkeleton,
getSnapOutlineMidPoint,
@@ -345,7 +342,6 @@ import { ActionManager } from "../actions/manager";
import { actions } from "../actions/register";
import { getShortcutFromShortcutName } from "../actions/shortcuts";
import { trackEvent } from "../analytics";
import { AnimationFrameHandler } from "../animation-frame-handler";
import {
getDefaultAppState,
isEraserActive,
@@ -419,7 +415,7 @@ import {
setCursorForShape,
} from "../cursor";
import { ElementCanvasButtons } from "../components/ElementCanvasButtons";
import { LaserTrails } from "../laser-trails";
import { LaserTrails } from "../laserTrails";
import { withBatchedUpdates, withBatchedUpdatesThrottled } from "../reactUtils";
import { isPointHittingTextAutoResizeHandle } from "../textAutoResizeHandle";
import { textWysiwyg } from "../wysiwyg/textWysiwyg";
@@ -705,11 +701,9 @@ class App extends React.Component<AppProps, AppState> {
previousPointerMoveCoords: { x: number; y: number } | null = null;
lastViewportPosition = { x: 0, y: 0 };
animationFrameHandler = new AnimationFrameHandler();
laserTrails = new LaserTrails(this.animationFrameHandler, this);
eraserTrail = new EraserTrail(this.animationFrameHandler, this);
lassoTrail = new LassoTrail(this.animationFrameHandler, this);
laserTrails = new LaserTrails(this);
eraserTrail = new EraserTrail(this);
lassoTrail = new LassoTrail(this);
onChangeEmitter = new Emitter<
[
@@ -939,14 +933,20 @@ class App extends React.Component<AppProps, AppState> {
"Missing last pointer move coords when changing bind skip mode for arrow start",
);
const elementsMap = this.scene.getNonDeletedElementsMap();
const hoveredElement = getHoveredElementForBinding(
pointFrom<GlobalPoint>(
this.lastPointerMoveCoords.x,
this.lastPointerMoveCoords.y,
),
this.scene.getNonDeletedElements(),
elementsMap,
);
const arrow = elementsMap.get(
this.state.selectedLinearElement.elementId,
) as ExcalidrawArrowElement | undefined;
const hoveredElement =
arrow &&
getHoveredElementForBinding(
arrow,
pointFrom<GlobalPoint>(
this.lastPointerMoveCoords.x,
this.lastPointerMoveCoords.y,
),
this.scene.getNonDeletedElements(),
elementsMap,
);
const element = LinearElementEditor.getElement(
this.state.selectedLinearElement.elementId,
elementsMap,
@@ -1076,6 +1076,7 @@ class App extends React.Component<AppProps, AppState> {
const { x, y } = this.lastPointerMoveCoords;
const hoveredElement = getHoveredElementForBinding(
arrow,
pointFrom<GlobalPoint>(x, y),
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
@@ -4617,6 +4618,7 @@ class App extends React.Component<AppProps, AppState> {
}
if (collaborators) {
this.laserTrails.updateCollabTrails(collaborators);
this.setState({ collaborators });
}
},
@@ -5381,12 +5383,6 @@ class App extends React.Component<AppProps, AppState> {
this.state,
);
const hoveredElement = getHoveredElementForBinding(
pointFrom<GlobalPoint>(scenePointer.x, scenePointer.y),
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
);
if (this.state.selectedLinearElement) {
const element = LinearElementEditor.getElement(
this.state.selectedLinearElement.elementId,
@@ -5394,6 +5390,13 @@ class App extends React.Component<AppProps, AppState> {
);
if (isBindingElement(element)) {
const hoveredElement = getHoveredElementForBinding(
element,
pointFrom<GlobalPoint>(scenePointer.x, scenePointer.y),
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
);
this.handleDelayedBindModeChange(element, hoveredElement);
}
}
@@ -7080,10 +7083,11 @@ class App extends React.Component<AppProps, AppState> {
);
const elementsMap = this.scene.getNonDeletedElementsMap();
const hoveredElement = getHoveredElementForBinding(
globalPoint,
{ elbowed: this.state.currentItemArrowType === ARROW_TYPE.elbow },
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
this.scene.getNonDeletedElements(),
elementsMap,
maxBindingDistance_simple(this.state.zoom),
this.state.zoom,
);
if (hoveredElement) {
this.setState({
@@ -7094,6 +7098,9 @@ class App extends React.Component<AppProps, AppState> {
hoveredElement,
elementsMap,
this.state.zoom,
{
elbowed: this.state.currentItemArrowType === ARROW_TYPE.elbow,
},
),
},
});
@@ -7119,10 +7126,11 @@ class App extends React.Component<AppProps, AppState> {
isArrowElement(this.state.newElement) &&
isBindingEnabled(this.state) &&
getHoveredElementForBinding(
this.state.newElement,
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
maxBindingDistance_simple(this.state.zoom),
this.state.zoom,
);
if (hoveredElement) {
this.actionManager.executeAction(actionFinalize, "ui", {
@@ -7237,6 +7245,7 @@ class App extends React.Component<AppProps, AppState> {
if (isSimpleArrow(multiElement)) {
const hoveredElement = getHoveredElementForBinding(
multiElement,
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
this.scene.getNonDeletedElements(),
elementsMap,
@@ -7269,10 +7278,11 @@ class App extends React.Component<AppProps, AppState> {
if (this.state.activeTool.type === "arrow") {
const hit = getHoveredElementForBinding(
{ elbowed: this.state.currentItemArrowType === ARROW_TYPE.elbow },
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
maxBindingDistance_simple(this.state.zoom),
this.state.zoom,
);
const scenePointer = pointFrom<GlobalPoint>(scenePointerX, scenePointerY);
const elementsMap = this.scene.getNonDeletedElementsMap();
@@ -7285,6 +7295,7 @@ class App extends React.Component<AppProps, AppState> {
hit,
elementsMap,
this.state.zoom,
{ elbowed: this.state.currentItemArrowType === ARROW_TYPE.elbow },
),
},
});
@@ -9271,6 +9282,7 @@ class App extends React.Component<AppProps, AppState> {
const hoveredElementForBinding =
isBindingEnabled(this.state) &&
getHoveredElementForBinding(
{ elbowed: isElbowArrow(multiElement) },
pointFrom<GlobalPoint>(
this.lastPointerMoveCoords?.x ??
rx + multiElement.points[multiElement.points.length - 1][0],
@@ -9393,6 +9405,7 @@ class App extends React.Component<AppProps, AppState> {
const elementsMap = this.scene.getNonDeletedElementsMap();
const boundElement = isBindingEnabled(this.state)
? getHoveredElementForBinding(
{ elbowed: this.state.currentItemArrowType === ARROW_TYPE.elbow },
point,
this.scene.getNonDeletedElements(),
elementsMap,
@@ -9468,7 +9481,6 @@ class App extends React.Component<AppProps, AppState> {
...prevState,
bindMode: "orbit",
newElement: element,
startBoundElement: boundElement,
suggestedBinding:
boundElement && isBindingElement(element)
? {
@@ -9478,6 +9490,7 @@ class App extends React.Component<AppProps, AppState> {
boundElement,
elementsMap,
this.state.zoom,
element,
),
}
: null,
@@ -9874,16 +9887,16 @@ class App extends React.Component<AppProps, AppState> {
return;
}
if (isBindingElement(element)) {
if (isBindingElement(element) && getFeatureFlag("COMPLEX_BINDINGS")) {
const hoveredElement = getHoveredElementForBinding(
element,
pointFrom<GlobalPoint>(pointerCoords.x, pointerCoords.y),
this.scene.getNonDeletedElements(),
elementsMap,
this.state.zoom,
);
if (getFeatureFlag("COMPLEX_BINDINGS")) {
this.handleDelayedBindModeChange(element, hoveredElement);
}
this.handleDelayedBindModeChange(element, hoveredElement);
}
if (
@@ -11721,9 +11734,11 @@ class App extends React.Component<AppProps, AppState> {
const existingFileData = this.files[fileId];
if (!existingFileData?.dataURL) {
const { maxWidthOrHeight, maxFileSizeBytes } = this.props.imageOptions;
try {
imageFile = await resizeImageFile(imageFile, {
maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
maxWidthOrHeight,
});
} catch (error: any) {
console.error(
@@ -11732,10 +11747,10 @@ class App extends React.Component<AppProps, AppState> {
);
}
if (imageFile.size > MAX_ALLOWED_FILE_BYTES) {
if (imageFile.size > maxFileSizeBytes) {
throw new Error(
t("errors.fileTooBig", {
maxSize: `${Math.trunc(MAX_ALLOWED_FILE_BYTES / 1024 / 1024)}MB`,
maxSize: `${Math.trunc(maxFileSizeBytes / 1024 / 1024)}MB`,
}),
);
}
+1 -1
View File
@@ -2,7 +2,7 @@ import { useEffect, useRef } from "react";
import "./SVGLayer.scss";
import type { Trail } from "../animated-trail";
import type { Trail } from "../animatedTrail";
type SVGLayerProps = {
trails: Trail[];
+56 -4
View File
@@ -311,6 +311,48 @@ export const dataURLToString = (dataURL: DataURL) => {
return base64ToString(dataURL.slice(dataURL.indexOf(",") + 1));
};
const getImageFileDimensions = async (file: File) => {
const browserURL = typeof window !== "undefined" ? window.URL : undefined;
let objectURL: string | null = null;
let imageSource: string;
try {
imageSource = browserURL?.createObjectURL
? (objectURL = browserURL.createObjectURL(file))
: await getDataURL(file);
} catch {
objectURL = null;
imageSource = await getDataURL(file);
}
return new Promise<{ width: number; height: number }>((resolve, reject) => {
const image = new Image();
const cleanup = () => {
image.onload = null;
image.onerror = null;
if (objectURL && browserURL?.revokeObjectURL) {
browserURL.revokeObjectURL(objectURL);
}
};
image.onload = () => {
cleanup();
resolve({
width: image.naturalWidth || image.width,
height: image.naturalHeight || image.height,
});
};
image.onerror = (error) => {
cleanup();
reject(error);
};
image.src = imageSource;
});
};
export const resizeImageFile = async (
file: File,
opts: {
@@ -324,6 +366,20 @@ export const resizeImageFile = async (
return file;
}
if (!isSupportedImageFile(file)) {
throw new Error("Error: unsupported file type", { cause: "UNSUPPORTED" });
}
if (!opts.outputType || opts.outputType === file.type) {
const dimensions = await getImageFileDimensions(file);
if (
Math.max(dimensions.width, dimensions.height) <= opts.maxWidthOrHeight
) {
return file;
}
}
const [pica, imageBlobReduce] = await Promise.all([
import("pica").then((res) => res.default),
// a wrapper for pica for better API
@@ -347,10 +403,6 @@ export const resizeImageFile = async (
};
}
if (!isSupportedImageFile(file)) {
throw new Error("Error: unsupported file type", { cause: "UNSUPPORTED" });
}
return new File(
[await reduce.toBlob(file, { max: opts.maxWidthOrHeight, alpha: true })],
file.name,
+94 -15
View File
@@ -1,4 +1,4 @@
import { isFiniteNumber, pointFrom } from "@excalidraw/math";
import { isFiniteNumber, isValidPoint, pointFrom } from "@excalidraw/math";
import {
type CombineBrandsIfNeeded,
@@ -98,6 +98,67 @@ type RestoredAppState = Omit<
const MAX_ARROW_PX = 75_000;
const restoreLinearElementPoints = (
points: unknown,
width: unknown,
height: unknown,
): LocalPoint[] => {
const restoredPoints = Array.isArray(points)
? points.reduce<LocalPoint[]>((acc, point) => {
if (isValidPoint(point)) {
acc.push(pointFrom<LocalPoint>(point[0], point[1]));
}
return acc;
}, [])
: [];
return restoredPoints.length < 2
? [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(
isFiniteNumber(width) ? width : 0,
isFiniteNumber(height) ? height : 0,
),
]
: restoredPoints;
};
const restoreFreedrawPoints = (
points: unknown,
pressures: unknown,
): {
points: LocalPoint[];
pressures: number[];
} => {
if (!Array.isArray(points)) {
return {
points: [],
pressures: [],
};
}
const pressureValues: readonly unknown[] = Array.isArray(pressures)
? pressures
: [];
const restoredPoints: LocalPoint[] = [];
const restoredPressures: number[] = [];
points.forEach((point, index) => {
if (isValidPoint(point)) {
restoredPoints.push(pointFrom<LocalPoint>(point[0], point[1]));
if (index in pressureValues) {
const pressure = pressureValues[index];
restoredPressures.push(isFiniteNumber(pressure) ? pressure : 0.5);
}
}
});
return {
points: restoredPoints,
pressures: restoredPressures,
};
};
export const AllowedExcalidrawActiveTools: Record<
AppState["activeTool"]["type"],
boolean
@@ -414,10 +475,15 @@ export const restoreElement = (
return element;
case "freedraw": {
const { points, pressures } = restoreFreedrawPoints(
element.points,
element.pressures,
);
return restoreElementWithProperties(element, {
points: element.points,
points,
simulatePressure: element.simulatePressure,
pressures: element.pressures,
pressures,
});
}
case "image":
@@ -435,14 +501,20 @@ export const restoreElement = (
const endArrowhead = normalizeArrowhead(element.endArrowhead);
let x = element.x;
let y = element.y;
let points = // migrate old arrow model to new one
!Array.isArray(element.points) || element.points.length < 2
? [pointFrom(0, 0), pointFrom(element.width, element.height)]
: element.points;
let points = restoreLinearElementPoints(
element.points,
element.width,
element.height,
);
if (points[0][0] !== 0 || points[0][1] !== 0) {
({ points, x, y } =
LinearElementEditor.getNormalizeElementPointsAndCoords(element));
LinearElementEditor.getNormalizeElementPointsAndCoords({
...element,
points,
x: x ?? 0,
y: y ?? 0,
} as ExcalidrawLinearElement));
}
return restoreElementWithProperties(element, {
@@ -456,7 +528,7 @@ export const restoreElement = (
y,
...(isLineElement(element)
? {
polygon: isValidPolygon(element.points)
polygon: isValidPolygon(points)
? element.polygon ?? false
: false,
}
@@ -471,22 +543,29 @@ export const restoreElement = (
: normalizeArrowhead(element.endArrowhead);
const x = element.x as number | undefined;
const y = element.y as number | undefined;
const points: readonly LocalPoint[] | undefined = // migrate old arrow model to new one
!Array.isArray(element.points) || element.points.length < 2
? [pointFrom(0, 0), pointFrom(element.width, element.height)]
: element.points;
const points = restoreLinearElementPoints(
element.points,
element.width,
element.height,
);
const elementWithRestoredPoints = {
...element,
points,
x: x ?? 0,
y: y ?? 0,
} as ExcalidrawArrowElement;
const base = {
type: element.type,
startBinding: repairBinding(
element as ExcalidrawArrowElement,
elementWithRestoredPoints,
element.startBinding,
targetElementsMap,
existingElementsMap,
"start",
),
endBinding: repairBinding(
element as ExcalidrawArrowElement,
elementWithRestoredPoints,
element.endBinding,
targetElementsMap,
existingElementsMap,
+3 -5
View File
@@ -33,9 +33,7 @@ import type { Bounds } from "@excalidraw/common";
import type { GlobalPoint, LineSegment } from "@excalidraw/math/types";
import type { ElementsMap, ExcalidrawElement } from "@excalidraw/element/types";
import { AnimatedTrail } from "../animated-trail";
import type { AnimationFrameHandler } from "../animation-frame-handler";
import { AnimatedTrail } from "../animatedTrail";
import type App from "../components/App";
@@ -43,8 +41,8 @@ export class EraserTrail extends AnimatedTrail {
private elementsToErase: Set<ExcalidrawElement["id"]> = new Set();
private groupsToErase: Set<ExcalidrawElement["id"]> = new Set();
constructor(animationFrameHandler: AnimationFrameHandler, app: App) {
super(animationFrameHandler, app, {
constructor(app: App) {
super(app, {
streamline: 0.2,
size: 5,
keepHead: true,
+27 -2
View File
@@ -6,7 +6,11 @@ import React, {
useState,
} from "react";
import { DEFAULT_UI_OPTIONS, isShallowEqual } from "@excalidraw/common";
import {
DEFAULT_IMAGE_OPTIONS,
DEFAULT_UI_OPTIONS,
isShallowEqual,
} from "@excalidraw/common";
import App, {
ExcalidrawAPIContext,
@@ -98,6 +102,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
aiEnabled,
showDeprecatedFonts,
renderScrollbars,
imageOptions,
} = props;
const canvasActions = props.UIOptions?.canvasActions;
@@ -128,6 +133,13 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
UIOptions.canvasActions.toggleTheme = true;
}
const normalizedImageOptions: AppProps["imageOptions"] = {
maxFileSizeBytes:
imageOptions?.maxFileSizeBytes ?? DEFAULT_IMAGE_OPTIONS.maxFileSizeBytes,
maxWidthOrHeight:
imageOptions?.maxWidthOrHeight ?? DEFAULT_IMAGE_OPTIONS.maxWidthOrHeight,
};
const setExcalidrawAPI = useContext(ExcalidrawAPISetContext);
const onExcalidrawAPIRef = useRef(onExcalidrawAPI);
@@ -208,6 +220,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
aiEnabled={aiEnabled !== false}
showDeprecatedFonts={showDeprecatedFonts}
renderScrollbars={renderScrollbars}
imageOptions={normalizedImageOptions}
>
{children}
</App>
@@ -225,11 +238,13 @@ const areEqual = (prevProps: ExcalidrawProps, nextProps: ExcalidrawProps) => {
const {
initialData: prevInitialData,
UIOptions: prevUIOptions = {},
imageOptions: prevImageOptions,
...prev
} = prevProps;
const {
initialData: nextInitialData,
UIOptions: nextUIOptions = {},
imageOptions: nextImageOptions,
...next
} = nextProps;
@@ -273,7 +288,17 @@ const areEqual = (prevProps: ExcalidrawProps, nextProps: ExcalidrawProps) => {
return prevUIOptions[key] === nextUIOptions[key];
});
return isUIOptionsSame && isShallowEqual(prev, next);
const isImageOptionsSame =
(prevImageOptions?.maxWidthOrHeight ??
DEFAULT_IMAGE_OPTIONS.maxWidthOrHeight) ===
(nextImageOptions?.maxWidthOrHeight ??
DEFAULT_IMAGE_OPTIONS.maxWidthOrHeight) &&
(prevImageOptions?.maxFileSizeBytes ??
DEFAULT_IMAGE_OPTIONS.maxFileSizeBytes) ===
(nextImageOptions?.maxFileSizeBytes ??
DEFAULT_IMAGE_OPTIONS.maxFileSizeBytes);
return isUIOptionsSame && isImageOptionsSame && isShallowEqual(prev, next);
};
export const Excalidraw = React.memo(ExcalidrawBase, areEqual);
@@ -2,27 +2,20 @@ import { DEFAULT_LASER_COLOR, easeOut } from "@excalidraw/common";
import type { LaserPointerOptions } from "@excalidraw/laser-pointer";
import { AnimatedTrail } from "./animated-trail";
import { AnimatedTrail } from "./animatedTrail";
import { getClientColor } from "./clients";
import type { Trail } from "./animated-trail";
import type { AnimationFrameHandler } from "./animation-frame-handler";
import type { Trail } from "./animatedTrail";
import type App from "./components/App";
import type { SocketId } from "./types";
export class LaserTrails implements Trail {
public localTrail: AnimatedTrail;
private collabTrails = new Map<SocketId, AnimatedTrail>();
private container?: SVGSVGElement;
constructor(
private animationFrameHandler: AnimationFrameHandler,
private app: App,
) {
this.animationFrameHandler.register(this, this.onFrame.bind(this));
this.localTrail = new AnimatedTrail(animationFrameHandler, app, {
constructor(private app: App) {
this.localTrail = new AnimatedTrail(app, {
...this.getTrailOptions(),
fill: () => DEFAULT_LASER_COLOR,
});
@@ -63,30 +56,45 @@ export class LaserTrails implements Trail {
start(container: SVGSVGElement) {
this.container = container;
this.animationFrameHandler.start(this);
this.localTrail.start(container);
}
stop() {
this.animationFrameHandler.stop(this);
this.localTrail.stop();
this.stopCollabTrails();
this.container = undefined;
}
onFrame() {
this.updateCollabTrails();
private stopCollabTrails(collaborators?: App["state"]["collaborators"]) {
for (const [key, trail] of this.collabTrails) {
const collaborator = collaborators?.get(key);
if (!collaborator) {
trail.stop();
this.collabTrails.delete(key);
}
}
}
private updateCollabTrails() {
if (!this.container || this.app.state.collaborators.size === 0) {
updateCollabTrails(collaborators: App["state"]["collaborators"]) {
this.stopCollabTrails(collaborators);
if (!this.container || collaborators.size === 0) {
return;
}
for (const [key, collaborator] of this.app.state.collaborators.entries()) {
let trail!: AnimatedTrail;
for (const [key, collaborator] of collaborators.entries()) {
// Current user has their own trail drawn via localTrail
if (collaborator.isCurrentUser) {
continue;
}
if (!this.collabTrails.has(key)) {
trail = new AnimatedTrail(this.animationFrameHandler, this.app, {
// IDEA: Use the collaborator pointer coordinates to trace out the
// laser pointer trail when 1) the selected collab tool is the laser
// pointer and 2) the collab pointer button is in the "down" state.
let trail = this.collabTrails.get(key);
if (!trail) {
trail = new AnimatedTrail(this.app, {
...this.getTrailOptions(),
fill: () =>
collaborator.pointer?.laserColor ||
@@ -95,36 +103,33 @@ export class LaserTrails implements Trail {
trail.start(this.container);
this.collabTrails.set(key, trail);
} else {
trail = this.collabTrails.get(key)!;
}
if (collaborator.pointer && collaborator.pointer.tool === "laser") {
if (collaborator.button === "down" && !trail.hasCurrentTrail) {
const buttonDown = collaborator.button === "down";
const buttonUp = collaborator.button === "up";
const hasTrail = trail.hasCurrentTrail;
// Initialize a new trail
if (buttonDown && !hasTrail) {
trail.startPath(collaborator.pointer.x, collaborator.pointer.y);
}
if (
collaborator.button === "down" &&
trail.hasCurrentTrail &&
!trail.hasLastPoint(collaborator.pointer.x, collaborator.pointer.y)
) {
// Add only original points
const lastPointOriginal = !trail.hasLastPoint(
collaborator.pointer.x,
collaborator.pointer.y,
);
if (buttonDown && lastPointOriginal) {
trail.addPointToPath(collaborator.pointer.x, collaborator.pointer.y);
}
if (collaborator.button === "up" && trail.hasCurrentTrail) {
// End the trail on button up
if (buttonUp && hasTrail) {
trail.addPointToPath(collaborator.pointer.x, collaborator.pointer.y);
trail.endPath();
}
}
}
for (const key of this.collabTrails.keys()) {
if (!this.app.state.collaborators.has(key)) {
const trail = this.collabTrails.get(key)!;
trail.stop();
this.collabTrails.delete(key);
}
}
}
}
+3 -5
View File
@@ -25,9 +25,7 @@ import type {
NonDeleted,
} from "@excalidraw/element/types";
import { type AnimationFrameHandler } from "../animation-frame-handler";
import { AnimatedTrail } from "../animated-trail";
import { AnimatedTrail } from "../animatedTrail";
import { getLassoSelectedElementIds } from "./utils";
@@ -47,8 +45,8 @@ export class LassoTrail extends AnimatedTrail {
private canvasTranslate: CanvasTranslate | null = null;
private keepPreviousSelection: boolean = false;
constructor(animationFrameHandler: AnimationFrameHandler, app: App) {
super(animationFrameHandler, app, {
constructor(app: App) {
super(app, {
animateTrail: true,
streamline: 0.4,
sizeMapping: (c) => {
+58 -16
View File
@@ -6,7 +6,10 @@ export type Animation<R extends object> = (params: {
}) => R | null | undefined;
export class AnimationController {
private static isRunning = false;
private static scheduledFrame:
| { id: ReturnType<typeof requestAnimationFrame>; type: "raf" }
| { id: ReturnType<typeof setTimeout>; type: "timeout" }
| null = null;
private static animations = new Map<
string,
{
@@ -17,6 +20,10 @@ export class AnimationController {
>();
static start<R extends object>(key: string, animation: Animation<R>) {
if (AnimationController.animations.has(key)) {
return;
}
const initialState = animation({
deltaTime: 0,
state: undefined,
@@ -29,19 +36,54 @@ export class AnimationController {
state: initialState,
});
if (!AnimationController.isRunning) {
AnimationController.isRunning = true;
if (isRenderThrottlingEnabled()) {
requestAnimationFrame(AnimationController.tick);
} else {
setTimeout(AnimationController.tick, 0);
}
}
AnimationController.scheduleNextFrame();
}
}
private static scheduleNextFrame() {
if (AnimationController.scheduledFrame) {
return;
}
if (isRenderThrottlingEnabled()) {
AnimationController.scheduledFrame = {
id: requestAnimationFrame(AnimationController.tick),
type: "raf",
};
} else {
AnimationController.scheduledFrame = {
id: setTimeout(AnimationController.tick, 0),
type: "timeout",
};
}
}
private static cancelScheduledFrame() {
if (!AnimationController.scheduledFrame) {
return;
}
if (AnimationController.scheduledFrame.type === "raf") {
cancelAnimationFrame(AnimationController.scheduledFrame.id);
} else {
clearTimeout(AnimationController.scheduledFrame.id);
}
AnimationController.scheduledFrame = null;
}
private static cancelScheduledFrameIfIdle() {
if (AnimationController.animations.size > 0) {
return false;
}
AnimationController.cancelScheduledFrame();
return true;
}
private static tick() {
AnimationController.scheduledFrame = null;
if (AnimationController.animations.size > 0) {
for (const [key, animation] of AnimationController.animations) {
const now = performance.now();
@@ -56,8 +98,7 @@ export class AnimationController {
if (!state) {
AnimationController.animations.delete(key);
if (AnimationController.animations.size === 0) {
AnimationController.isRunning = false;
if (AnimationController.cancelScheduledFrameIfIdle()) {
return;
}
} else {
@@ -66,11 +107,11 @@ export class AnimationController {
}
}
if (isRenderThrottlingEnabled()) {
requestAnimationFrame(AnimationController.tick);
} else {
setTimeout(AnimationController.tick, 0);
if (AnimationController.cancelScheduledFrameIfIdle()) {
return;
}
AnimationController.scheduleNextFrame();
}
}
@@ -80,5 +121,6 @@ export class AnimationController {
static cancel(key: string) {
AnimationController.animations.delete(key);
AnimationController.cancelScheduledFrameIfIdle();
}
}
+29 -135
View File
@@ -7,7 +7,6 @@ import {
type Radians,
bezierEquation,
pointRotateRads,
pointDistance,
} from "@excalidraw/math";
import {
@@ -24,13 +23,12 @@ import {
deconstructDiamondElement,
deconstructRectanguloidElement,
elementCenterPoint,
getDiamondBaseCorners,
getAllMidpoints,
FOCUS_POINT_SIZE,
getOmitSidesForEditorInterface,
getTransformHandles,
getTransformHandlesFromCoords,
hasBoundingBox,
hitElementItself,
isArrowElement,
isBindableElement,
isElbowArrow,
@@ -38,7 +36,6 @@ import {
isImageElement,
isLinearElement,
isLineElement,
maxBindingDistance_simple,
isTextElement,
LinearElementEditor,
getActiveTextElement,
@@ -413,145 +410,42 @@ const renderBindingHighlightForBindableElement_simple = (
break;
}
// Draw midpoint indicators
if (
appState.isMidpointSnappingEnabled &&
(isFrameLikeElement(suggestedBinding.element) ||
isBindableElement(suggestedBinding.element))
) {
// Draw midpoint indicators
const linearElement = appState.selectedLinearElement;
const arrow =
linearElement?.elementId &&
LinearElementEditor.getElement(linearElement?.elementId, elementsMap);
const cursorIsInsideBindable =
pointerCoords &&
hitElementItself({
point: pointerCoords,
element: suggestedBinding.element,
elementsMap,
threshold: 0,
overrideShouldTestInside: true,
});
context.save();
const isElbow =
(arrow && isElbowArrow(arrow)) ||
(appState.activeTool.type === "arrow" &&
appState.currentItemArrowType === "elbow");
const midpointRadius = 4 / appState.zoom.value;
if (!cursorIsInsideBindable || isElbow) {
context.save();
const center = elementCenterPoint(suggestedBinding.element, elementsMap);
let midpoints: GlobalPoint[];
if (suggestedBinding.element.type === "diamond") {
const center = elementCenterPoint(
suggestedBinding.element,
elementsMap,
);
midpoints = getDiamondBaseCorners(suggestedBinding.element).map(
(curve) => {
const point = bezierEquation(curve, 0.5);
const rotatedPoint = pointRotateRads(
point,
center,
suggestedBinding.element.angle,
);
return pointFrom<GlobalPoint>(rotatedPoint[0], rotatedPoint[1]);
},
);
} else {
const basePoints = [
{
x: suggestedBinding.element.width,
y: suggestedBinding.element.height / 2,
}, // RIGHT
{
x: suggestedBinding.element.width / 2,
y: suggestedBinding.element.height,
}, // BOTTOM
{ x: 0, y: suggestedBinding.element.height / 2 }, // LEFT
{ x: suggestedBinding.element.width / 2, y: 0 }, // TOP
];
midpoints = basePoints.map((point) => {
const globalPoint = pointFrom<GlobalPoint>(
point.x + suggestedBinding.element.x,
point.y + suggestedBinding.element.y,
);
const rotatedPoint = pointRotateRads(
globalPoint,
center,
suggestedBinding.element.angle,
);
return pointFrom<GlobalPoint>(rotatedPoint[0], rotatedPoint[1]);
});
}
const hoveredMidpoint =
pointerCoords &&
midpoints.reduce(
(
closestIdx: {
idx: number;
distance: number;
},
point,
idx,
) => {
const distance = pointDistance(point, pointerCoords);
if (idx === -1 || distance < closestIdx.distance) {
return { idx, distance };
}
return closestIdx;
},
{
idx: -1,
distance: Infinity,
},
);
const midpointRadius = 4 / appState.zoom.value;
const highlightThreshold =
maxBindingDistance_simple(appState.zoom) +
suggestedBinding.element.strokeWidth / 2;
midpoints.forEach((midpoint, idx) => {
const isHighlighted =
(!cursorIsInsideBindable || isElbow) &&
hoveredMidpoint?.idx === idx &&
hoveredMidpoint.distance <= highlightThreshold;
// also render midpoint if cursor close but not highlighted
// (for elbows, always show all points)
const isShown =
!isHighlighted &&
(isElbow ||
(idx === hoveredMidpoint?.idx &&
hoveredMidpoint.distance <= highlightThreshold * 2));
if (isHighlighted) {
context.fillStyle =
appState.theme === THEME.DARK
? `rgba(3, 93, 161, 1)`
: `rgba(106, 189, 252, 1)`;
context.beginPath();
context.arc(midpoint[0], midpoint[1], midpointRadius, 0, 2 * Math.PI);
context.fill();
} else if (isShown) {
context.fillStyle =
appState.theme === THEME.DARK
? `rgba(0, 0, 0, 0.8)`
: `rgba(65, 65, 65, 0.5)`;
context.beginPath();
context.arc(midpoint[0], midpoint[1], midpointRadius, 0, 2 * Math.PI);
context.fill();
}
});
context.restore();
// Render base midpoints
const midpoints = getAllMidpoints(suggestedBinding.element, elementsMap);
for (const midpoint of midpoints) {
context.fillStyle =
appState.theme === THEME.DARK
? `rgba(0, 0, 0, 0.8)`
: `rgba(65, 65, 65, 0.5)`;
context.beginPath();
context.arc(midpoint[0], midpoint[1], midpointRadius, 0, 2 * Math.PI);
context.fill();
}
// Render the highlighted midpoint if any
const midpoint = appState.suggestedBinding?.midPoint;
if (midpoint) {
context.fillStyle =
appState.theme === THEME.DARK
? `rgba(3, 93, 161, 1)`
: `rgba(106, 189, 252, 1)`;
context.beginPath();
context.arc(midpoint[0], midpoint[1], midpointRadius, 0, 2 * Math.PI);
context.fill();
}
context.restore();
}
};
@@ -83,6 +83,26 @@ mockMermaidToExcalidraw({
},
});
const normalizeDialogSnapshot = (dialog: Element) => {
const dialogClone = dialog.cloneNode(true) as HTMLElement;
dialogClone
.querySelectorAll<HTMLElement>(".ttd-dialog-content")
.forEach((element) => {
// Radix Tabs injects this during initial mount animation prevention.
// Its presence depends on render timing and is unrelated to this test.
if (element.style.animationDuration === "0s") {
element.style.removeProperty("animation-duration");
}
if (!element.getAttribute("style")) {
element.removeAttribute("style");
}
});
return dialogClone.outerHTML;
};
describe("Test <MermaidToExcalidraw/>", () => {
beforeEach(async () => {
await render(
@@ -99,7 +119,7 @@ describe("Test <MermaidToExcalidraw/>", () => {
it("should open mermaid popup when active tool is mermaid", async () => {
const dialog = document.querySelector(".ttd-dialog")!;
await waitFor(() => expect(dialog.querySelector("canvas")).not.toBeNull());
expect(dialog.outerHTML).toMatchSnapshot();
expect(normalizeDialogSnapshot(dialog)).toMatchSnapshot();
});
it("should show error in preview when mermaid library throws error", async () => {
@@ -1,6 +1,6 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Test <MermaidToExcalidraw/> > should open mermaid popup when active tool is mermaid 1`] = `"<div class="Modal Dialog ttd-dialog" role="dialog" aria-modal="true" aria-labelledby="dialog-title"><div class="Modal__background"></div><div class="Modal__content" style="--max-width: 1520px;" tabindex="0"><div class="Island"><div class="Dialog__content"><div dir="ltr" data-orientation="horizontal" class="ttd-dialog-tabs-root"><p class="dialog-mermaid-title">Mermaid to Excalidraw</p><div data-state="active" data-orientation="horizontal" role="tabpanel" aria-labelledby="radix-:r4:-trigger-mermaid" id="radix-:r4:-content-mermaid" tabindex="0" class="ttd-dialog-content" style=""><div class="ttd-dialog-desc">Currently only <a href="https://mermaid.js.org/syntax/flowchart.html" target="_blank" rel="noreferrer">Flowchart</a>, <a href="https://mermaid.js.org/syntax/sequenceDiagram.html" target="_blank" rel="noreferrer">Sequence</a>, <a href="https://mermaid.js.org/syntax/classDiagram.html" target="_blank" rel="noreferrer">Class</a>, and <a href="https://mermaid.js.org/syntax/entityRelationshipDiagram.html" target="_blank" rel="noreferrer">Entity Relationship</a> Diagrams are supported. The other types will be rendered as image in Excalidraw.</div><div class="ttd-dialog-panels"><div class="ttd-dialog-panel"><div class="ttd-dialog-panel-button-container invisible" style="justify-content: flex-start;"></div></div><div class="ttd-dialog-panel"><div class="ttd-dialog-output-wrapper "><div class="ttd-dialog-output-canvas-container"><div class="ttd-dialog-output-canvas-content"><canvas width="89" height="158" dir="ltr"></canvas></div></div></div><div class="ttd-dialog-panel-button-container" style="justify-content: flex-start;"><button type="button" class="excalidraw-button ttd-dialog-panel-button"><div class="">Insert<span><svg aria-hidden="true" focusable="false" role="img" viewBox="0 0 20 20" class="" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="1.25"><path d="M4.16602 10H15.8327"></path><path d="M12.5 13.3333L15.8333 10"></path><path d="M12.5 6.66666L15.8333 9.99999"></path></g></svg></span></div></button><div class="ttd-dialog-submit-shortcut"><div class="ttd-dialog-submit-shortcut__key">Ctrl</div><div class="ttd-dialog-submit-shortcut__key">Enter</div></div></div></div></div></div></div></div></div></div></div>"`;
exports[`Test <MermaidToExcalidraw/> > should open mermaid popup when active tool is mermaid 1`] = `"<div class="Modal Dialog ttd-dialog" role="dialog" aria-modal="true" aria-labelledby="dialog-title"><div class="Modal__background"></div><div class="Modal__content" style="--max-width: 1520px;" tabindex="0"><div class="Island"><div class="Dialog__content"><div dir="ltr" data-orientation="horizontal" class="ttd-dialog-tabs-root"><p class="dialog-mermaid-title">Mermaid to Excalidraw</p><div data-state="active" data-orientation="horizontal" role="tabpanel" aria-labelledby="radix-:r4:-trigger-mermaid" id="radix-:r4:-content-mermaid" tabindex="0" class="ttd-dialog-content"><div class="ttd-dialog-desc">Currently only <a href="https://mermaid.js.org/syntax/flowchart.html" target="_blank" rel="noreferrer">Flowchart</a>, <a href="https://mermaid.js.org/syntax/sequenceDiagram.html" target="_blank" rel="noreferrer">Sequence</a>, <a href="https://mermaid.js.org/syntax/classDiagram.html" target="_blank" rel="noreferrer">Class</a>, and <a href="https://mermaid.js.org/syntax/entityRelationshipDiagram.html" target="_blank" rel="noreferrer">Entity Relationship</a> Diagrams are supported. The other types will be rendered as image in Excalidraw.</div><div class="ttd-dialog-panels"><div class="ttd-dialog-panel"><div class="ttd-dialog-panel-button-container invisible" style="justify-content: flex-start;"></div></div><div class="ttd-dialog-panel"><div class="ttd-dialog-output-wrapper "><div class="ttd-dialog-output-canvas-container"><div class="ttd-dialog-output-canvas-content"><canvas width="89" height="158" dir="ltr"></canvas></div></div></div><div class="ttd-dialog-panel-button-container" style="justify-content: flex-start;"><button type="button" class="excalidraw-button ttd-dialog-panel-button"><div class="">Insert<span><svg aria-hidden="true" focusable="false" role="img" viewBox="0 0 20 20" class="" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="1.25"><path d="M4.16602 10H15.8327"></path><path d="M12.5 13.3333L15.8333 10"></path><path d="M12.5 6.66666L15.8333 9.99999"></path></g></svg></span></div></button><div class="ttd-dialog-submit-shortcut"><div class="ttd-dialog-submit-shortcut__key">Ctrl</div><div class="ttd-dialog-submit-shortcut__key">Enter</div></div></div></div></div></div></div></div></div></div></div>"`;
exports[`Test <MermaidToExcalidraw/> > should show error in preview when mermaid library throws error 1`] = `
"flowchart TD
@@ -98,7 +98,6 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -732,7 +731,6 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -2277,40 +2275,6 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": {
"angle": 0,
"backgroundColor": "transparent",
"boundElements": [
{
"id": "id4",
"type": "arrow",
},
],
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
"groupIds": [],
"height": 100,
"id": "id0",
"index": "a0",
"isDeleted": false,
"link": null,
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": null,
"seed": 1,
"strokeColor": "#1e1e1e",
"strokeStyle": "solid",
"strokeWidth": 2,
"type": "rectangle",
"updated": 1,
"version": 3,
"versionNonce": 493213705,
"width": 100,
"x": -100,
"y": -50,
},
"stats": {
"open": false,
"panels": 3,
@@ -2410,7 +2374,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"endBinding": {
"elementId": "id1",
"fixedPoint": [
0,
"0.50010",
"0.50010",
],
"mode": "orbit",
@@ -2418,7 +2382,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"fillStyle": "solid",
"frameId": null,
"groupIds": [],
"height": "439.20000",
"height": "399.26547",
"id": "id4",
"index": "a2",
"isDeleted": false,
@@ -2432,8 +2396,8 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
0,
],
[
488,
"-439.20000",
"488.00000",
"-399.26547",
],
],
"roughness": 1,
@@ -2455,9 +2419,9 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"type": "arrow",
"updated": 1,
"version": 11,
"width": 488,
"width": "488.00000",
"x": 6,
"y": "-5.39000",
"y": "-4.89900",
}
`;
@@ -2578,7 +2542,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"endBinding": {
"elementId": "id1",
"fixedPoint": [
0,
"0.50010",
"0.50010",
],
"mode": "orbit",
@@ -2586,7 +2550,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"fillStyle": "solid",
"frameId": null,
"groupIds": [],
"height": "439.20000",
"height": "399.26547",
"index": "a2",
"isDeleted": false,
"link": null,
@@ -2598,8 +2562,8 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
0,
],
[
488,
"-439.20000",
"488.00000",
"-399.26547",
],
],
"roughness": 1,
@@ -2620,9 +2584,9 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
"strokeWidth": 2,
"type": "arrow",
"version": 11,
"width": 488,
"width": "488.00000",
"x": 6,
"y": "-5.39000",
"y": "-4.89900",
},
"inserted": {
"isDeleted": true,
@@ -7388,7 +7352,6 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -10360,7 +10323,6 @@ exports[`history > multiplayer undo/redo > should override remotely added points
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -16591,7 +16553,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -17340,7 +17301,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -17987,7 +17947,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -18632,7 +18591,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -19385,7 +19343,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -21603,7 +21560,6 @@ exports[`history > singleplayer undo/redo > should support linear element creati
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -6243,7 +6243,6 @@ exports[`regression tests > draw every type of shape > [end of test] appState 1`
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -8692,7 +8691,6 @@ exports[`regression tests > key 5 selects arrow tool > [end of test] appState 1`
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -8925,7 +8923,6 @@ exports[`regression tests > key 6 selects line tool > [end of test] appState 1`]
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -9348,7 +9345,6 @@ exports[`regression tests > key a selects arrow tool > [end of test] appState 1`
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -9761,7 +9757,6 @@ exports[`regression tests > key l selects line tool > [end of test] appState 1`]
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -14519,7 +14514,6 @@ exports[`regression tests > undo/redo drawing an element > [end of test] appStat
"showHyperlinkPopup": false,
"showWelcomeScreen": true,
"snapLines": [],
"startBoundElement": null,
"stats": {
"open": false,
"panels": 3,
@@ -0,0 +1,73 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AnimationController } from "../renderer/animation";
const FIRST_KEY = "animation-test-first";
const SECOND_KEY = "animation-test-second";
describe("AnimationController", () => {
beforeEach(() => {
vi.useFakeTimers();
window.EXCALIDRAW_THROTTLE_RENDER = false;
});
afterEach(() => {
AnimationController.cancel(FIRST_KEY);
AnimationController.cancel(SECOND_KEY);
window.EXCALIDRAW_THROTTLE_RENDER = undefined;
vi.useRealTimers();
});
it("starts a new animation after the previous last animation was cancelled", async () => {
let firstFrames = 0;
AnimationController.start(FIRST_KEY, () => {
firstFrames++;
return { keep: true };
});
expect(firstFrames).toBe(1);
AnimationController.cancel(FIRST_KEY);
await vi.runOnlyPendingTimersAsync();
let secondFrames = 0;
AnimationController.start(SECOND_KEY, () => {
secondFrames++;
return secondFrames === 1 ? { keep: true } : null;
});
expect(secondFrames).toBe(1);
await vi.runOnlyPendingTimersAsync();
expect(secondFrames).toBe(2);
expect(AnimationController.running(SECOND_KEY)).toBe(false);
});
it("cancels a frame scheduled during a tick if no animations remain", async () => {
let firstFrames = 0;
let secondFrames = 0;
AnimationController.start(FIRST_KEY, ({ state }) => {
if (!state) {
return { keep: true };
}
firstFrames++;
AnimationController.start(SECOND_KEY, () => {
secondFrames++;
return { keep: true };
});
AnimationController.cancel(SECOND_KEY);
return null;
});
await vi.runOnlyPendingTimersAsync();
expect(firstFrames).toBe(1);
expect(secondFrames).toBe(1);
expect(vi.getTimerCount()).toBe(0);
});
});
@@ -160,6 +160,39 @@ describe("restoreElements", () => {
});
});
it("should restore only valid freedraw points and keep pressures aligned", () => {
const freedrawElement = API.createElement({
type: "freedraw",
id: "id-freedraw-invalid-points",
points: [pointFrom(0, 0), pointFrom(10, 10)],
});
const restoredFreedraw = restore.restoreElements(
[
{
...freedrawElement,
simulatePressure: false,
points: [
pointFrom(0, 0),
[Infinity, 10],
null,
pointFrom(20, 20),
[NaN, 30],
[40, null],
],
pressures: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6],
} as any,
],
null,
)[0] as ExcalidrawFreeDrawElement;
expect(restoredFreedraw.points).toEqual([
pointFrom(0, 0),
pointFrom(20, 20),
]);
expect(restoredFreedraw.pressures).toEqual([0.1, 0.4]);
});
it("should restore line and draw elements correctly", () => {
const lineElement = API.createElement({ type: "line", id: "id-line01" });
@@ -400,6 +433,52 @@ describe("restoreElements", () => {
expect(restoredLine.points).toMatchObject(expectedLinePoints);
});
it("should restore only valid linear points", () => {
const lineElement: any = API.createElement({
type: "line",
x: 10,
y: 20,
width: 100,
height: 200,
});
const arrowElement: any = API.createElement({
type: "arrow",
width: 100,
height: 200,
});
lineElement.points = [
[2, 3],
null,
[Infinity, 4],
[5, 7],
[NaN, 8],
[9, null],
];
arrowElement.points = [
[null, 0],
[Infinity, 4],
];
const restoredElements = restore.restoreElements(
[lineElement, arrowElement],
null,
);
const restoredLine = restoredElements[0] as ExcalidrawLinearElement;
const restoredArrow = restoredElements[1] as ExcalidrawArrowElement;
expect(restoredLine.points).toEqual([pointFrom(0, 0), pointFrom(3, 4)]);
expect(restoredLine.x).toBe(12);
expect(restoredLine.y).toBe(23);
expect(restoredLine.width).toBe(3);
expect(restoredLine.height).toBe(4);
expect(restoredArrow.points).toEqual([
pointFrom(0, 0),
pointFrom(100, 200),
]);
});
it("when the number of points of a line is greater or equal 2", () => {
const lineElement_0 = API.createElement({
type: "line",
+1 -1
View File
@@ -5132,7 +5132,7 @@ describe("history", () => {
}),
endBinding: expect.objectContaining({
elementId: rect2.id,
fixedPoint: expect.arrayContaining([0, 0.5001]),
fixedPoint: expect.arrayContaining([0.5001, 0.5001]),
}),
isDeleted: true,
}),
+63 -2
View File
@@ -1,4 +1,4 @@
import { randomId, reseed } from "@excalidraw/common";
import { MIME_TYPES, randomId, reseed } from "@excalidraw/common";
import type { FileId } from "@excalidraw/element/types";
@@ -17,18 +17,41 @@ import {
} from "./fixtures/constants";
import { INITIALIZED_IMAGE_PROPS } from "./helpers/constants";
import type { ExcalidrawProps } from "../types";
const { h } = window;
export const setupImageTest = async (
sizes: { width: number; height: number }[],
props?: ExcalidrawProps,
) => {
await render(<Excalidraw autoFocus={true} handleKeyboardGlobally={true} />);
await render(
<Excalidraw autoFocus={true} handleKeyboardGlobally={true} {...props} />,
);
h.state.height = 1000;
mockMultipleHTMLImageElements(sizes.map((size) => [size.width, size.height]));
};
describe("resizeImageFile", () => {
beforeEach(() => {
vi.unstubAllGlobals();
});
it("returns the original file when it already fits the max dimensions", async () => {
mockMultipleHTMLImageElements([[100, 100]]);
const imageFile = new File([new Uint8Array([1, 2, 3])], "image.png", {
type: MIME_TYPES.png,
});
await expect(
blobModule.resizeImageFile(imageFile, { maxWidthOrHeight: 200 }),
).resolves.toBe(imageFile);
});
});
describe("image insertion", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -112,4 +135,42 @@ describe("image insertion", () => {
await assert();
});
it("passes host-configured max image dimensions to the resize helper", async () => {
await setupImageTest([DEER_IMAGE_DIMENSIONS], {
imageOptions: { maxWidthOrHeight: 2048 },
});
await API.drop([
{ kind: "file", file: await API.loadFile("./fixtures/deer.png") },
]);
await waitFor(() => {
expect(blobModule.resizeImageFile).toHaveBeenCalledWith(
expect.any(File),
{ maxWidthOrHeight: 2048 },
);
});
});
it("enforces host-configured max image file size", async () => {
await setupImageTest([DEER_IMAGE_DIMENSIONS], {
imageOptions: { maxFileSizeBytes: 1024 * 1024 },
});
await API.drop([
{
kind: "file",
file: new File([new Uint8Array(2 * 1024 * 1024)], "image.png", {
type: MIME_TYPES.png,
}),
},
]);
await waitFor(() => {
expect(h.state.errorMessage).toBe(
"File is too big. Maximum allowed size is 1MB.",
);
});
});
});
+33 -1
View File
@@ -10,7 +10,7 @@ import { API } from "./helpers/api";
import { Pointer } from "./helpers/ui";
import { act, GlobalTestState, render, waitFor } from "./test-utils";
import type { ExcalidrawProps } from "../types";
import type { Collaborator, ExcalidrawProps, SocketId } from "../types";
describe("laser tool interactions", () => {
const h = window.h;
@@ -128,4 +128,36 @@ describe("laser tool interactions", () => {
expect(h.state.scrollY).toBe(initialScrollY);
expect(GlobalTestState.interactiveCanvas.style.cursor).toContain("");
});
it("cleans up remote laser trails when the last collaborator leaves", async () => {
await render(<Excalidraw />);
const socketId = "socket-id" as SocketId;
const collaborators = new Map<SocketId, Collaborator>([
[
socketId,
{
pointer: {
x: 10,
y: 10,
tool: "laser",
},
button: "down",
},
],
]);
const svgLayer = document.querySelector(".SVGLayer svg")!;
act(() => {
h.app.updateScene({ collaborators });
});
expect(svgLayer.querySelectorAll("path")).toHaveLength(1);
act(() => {
h.app.updateScene({ collaborators: new Map() });
});
expect(svgLayer.querySelectorAll("path")).toHaveLength(0);
});
});
+14 -4
View File
@@ -16,6 +16,8 @@ import * as StaticScene from "../renderer/staticScene";
import { UI, Pointer, Keyboard } from "./helpers/ui";
import { render, fireEvent, act, unmountComponent } from "./test-utils";
import type { Zoom } from "../types";
unmountComponent();
const renderInteractiveScene = vi.spyOn(
@@ -88,6 +90,7 @@ describe("move element", () => {
"orbit",
"start",
h.app.scene,
{ value: 1 } as Zoom,
);
bindBindingElement(
arrow.get() as NonDeleted<ExcalidrawArrowElement>,
@@ -95,6 +98,7 @@ describe("move element", () => {
"orbit",
"end",
h.app.scene,
{ value: 1 } as Zoom,
);
});
@@ -111,10 +115,13 @@ describe("move element", () => {
expect([rectA.x, rectA.y]).toEqual([0, 0]);
expect([rectB.x, rectB.y]).toEqual([200, 0]);
expect([[arrow.x, arrow.y]]).toCloselyEqualPoints(
[[106.00000000000001, 55.6867741935484]],
[[106, 56.011199999998695]],
0,
);
expect([[arrow.width, arrow.height]]).toCloselyEqualPoints(
[[88, 88.01760000000121]],
0,
);
expect([[arrow.width, arrow.height]]).toCloselyEqualPoints([[88, 88]], 0);
renderInteractiveScene.mockClear();
renderStaticScene.mockClear();
@@ -133,10 +140,13 @@ describe("move element", () => {
expect([rectA.x, rectA.y]).toEqual([0, 0]);
expect([rectB.x, rectB.y]).toEqual([201, 2]);
expect([[arrow.x, arrow.y]]).toCloselyEqualPoints(
[[106, 55.6867741935484]],
[[106, 56.011199999998695]],
0,
);
expect([[arrow.width, arrow.height]]).toCloselyEqualPoints(
[[89, 90.01760000000121]],
0,
);
expect([[arrow.width, arrow.height]]).toCloselyEqualPoints([[89, 90]], 0);
h.elements.forEach((element) => expect(element).toMatchSnapshot());
});
+10
View File
@@ -645,6 +645,10 @@ export interface ExcalidrawProps {
appState: UIAppState,
) => JSX.Element;
UIOptions?: Partial<UIOptions>;
/**
* dimensions and size constraints for inserted images
*/
imageOptions?: ImageOptions;
detectScroll?: boolean;
handleKeyboardGlobally?: boolean;
onLibraryChange?: (libraryItems: LibraryItems) => void | Promise<any>;
@@ -731,6 +735,11 @@ export type ExportOpts = {
) => JSX.Element;
};
export type ImageOptions = Partial<{
maxWidthOrHeight: number;
maxFileSizeBytes: number;
}>;
// NOTE at the moment, if action name corresponds to canvasAction prop, its
// truthiness value will determine whether the action is rendered or not
// (see manager renderAction). We also override canvasAction values in
@@ -772,6 +781,7 @@ export type AppProps = Merge<
canvasActions: Required<CanvasActions> & { export: ExportOpts };
}
>;
imageOptions: Required<ImageOptions>;
detectScroll: boolean;
handleKeyboardGlobally: boolean;
isCollaborating: boolean;
+10 -1
View File
@@ -1,5 +1,5 @@
import { degreesToRadians } from "./angle";
import { PRECISION } from "./utils";
import { isFiniteNumber, PRECISION } from "./utils";
import { vectorFromPoint, vectorScale } from "./vector";
import type {
@@ -253,3 +253,12 @@ export const isPointWithinBounds = <P extends GlobalPoint | LocalPoint>(
q[1] >= Math.min(p[1], r[1])
);
};
export const isValidPoint = (point: unknown): point is LocalPoint => {
return (
Array.isArray(point) &&
point.length === 2 &&
isFiniteNumber(point[0]) &&
isFiniteNumber(point[1])
);
};