Compare commits

..
Author SHA1 Message Date
dwelle 0256559b68 improve balls 2026-04-03 19:51:41 +02:00
dwelle c9d29ea600 improve miter 2026-04-03 19:36:06 +02:00
dwelle 90c4770a5b improve smoothing 2026-04-03 19:23:26 +02:00
dwelle e48043aef5 remove raf & batching 2026-04-03 19:18:45 +02:00
dwelle 3e53dcd956 wip 2026-04-03 16:34:26 +02:00
d9e8a33aa4 feat(editor): implement overlap box selection (#11053)
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
2026-04-01 18:41:11 +02:00
dageckoandGitHub 4be4cc0ed0 fix: pin 9 actions to commit SHA (#11075) 2026-03-30 16:49:27 +02:00
57 changed files with 1734 additions and 700 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 3 timeout-minutes: 3
steps: steps:
- uses: styfle/cancel-workflow-action@0.6.0 - uses: styfle/cancel-workflow-action@ce177499ccf9fd2aded3b0426c97e5434c2e8a73 # 0.6.0
with: with:
workflow_id: 400555, 400556, 905313, 1451724, 1710116, 3185001, 3438604 workflow_id: 400555, 400556, 905313, 1451724, 1710116, 3185001, 3438604
access_token: ${{ secrets.GITHUB_TOKEN }} access_token: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -40,7 +40,7 @@ jobs:
echo ::set-output name=body::$body echo ::set-output name=body::$body
- name: Update description with coverage - name: Update description with coverage
uses: kt3k/update-pr-description@v1.0.1 uses: kt3k/update-pr-description@1b35a6dcd84d81aa0bc1889610efdcde7f37b0c0 # v1.0.1
with: with:
pr_body: ${{ steps.getCommentBody.outputs.body }} pr_body: ${{ steps.getCommentBody.outputs.body }}
pr_title: "chore: Update translations from Crowdin" pr_title: "chore: Update translations from Crowdin"
+4 -4
View File
@@ -13,16 +13,16 @@ jobs:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Login to DockerHub - name: Login to DockerHub
uses: docker/login-action@v2 uses: docker/login-action@465a07811f14bebb1938fbed4728c6a1ff8901fc # v2
with: with:
username: ${{ secrets.DOCKER_USERNAME }} username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }} password: ${{ secrets.DOCKER_PASSWORD }}
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@v3 uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3 uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Build and push - name: Build and push
uses: docker/build-push-action@v5 uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5
with: with:
context: . context: .
push: true push: true
+1 -1
View File
@@ -11,6 +11,6 @@ jobs:
semantic: semantic:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: amannn/action-semantic-pull-request@v5 - uses: amannn/action-semantic-pull-request@e32d7e603df1aa1ba07e981f2a23455dee596825 # v5
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
working-directory: packages/excalidraw working-directory: packages/excalidraw
env: env:
CI: true CI: true
- uses: andresz1/size-limit-action@v1 - uses: andresz1/size-limit-action@e7493a72a44b113341c0cf6186ab49c17c4b65c1 # v1
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
build_script: build:esm build_script: build:esm
+1 -1
View File
@@ -21,6 +21,6 @@ jobs:
run: yarn test:coverage run: yarn test:coverage
- name: "Report Coverage" - name: "Report Coverage"
if: always() # Also generate the report if tests are failing if: always() # Also generate the report if tests are failing
uses: davelosert/vitest-coverage-report-action@v2 uses: davelosert/vitest-coverage-report-action@2500dafcee7dd64f85ab689c0b83798a8359770e # v2
with: with:
github-token: ${{ secrets.GITHUB_TOKEN }} github-token: ${{ secrets.GITHUB_TOKEN }}
+1 -36
View File
@@ -1,5 +1,3 @@
import type { Radians } from "@excalidraw/math";
/** /**
* x and y position of top left corner, x and y position of bottom right corner * x and y position of top left corner, x and y position of bottom right corner
*/ */
@@ -8,31 +6,7 @@ export type Bounds = readonly [
minY: number, minY: number,
maxX: number, maxX: number,
maxY: number, maxY: number,
] & { _brand: "excalidraw__bounds" }; ];
export type RotatedBounds = readonly [
minX: number,
minY: number,
maxX: number,
maxY: number,
angle: Radians,
] & {
_brand_rotated: "excalidraw__rotated_bounds";
};
export const bounds = <T extends Radians | undefined = undefined>(
minX: number,
minY: number,
maxX: number,
maxY: number,
angle: T = undefined as T,
) => {
return (
angle
? ([minX, minY, maxX, maxY, angle] as unknown)
: ([minX, minY, maxX, maxY] as unknown)
) as T extends Radians ? RotatedBounds : Bounds;
};
export const isBounds = (box: unknown): box is Bounds => export const isBounds = (box: unknown): box is Bounds =>
Array.isArray(box) && Array.isArray(box) &&
@@ -41,12 +15,3 @@ export const isBounds = (box: unknown): box is Bounds =>
typeof box[1] === "number" && typeof box[1] === "number" &&
typeof box[2] === "number" && typeof box[2] === "number" &&
typeof box[3] === "number"; typeof box[3] === "number";
export const isRotatedBounds = (box: unknown): box is RotatedBounds =>
Array.isArray(box) &&
box.length === 5 &&
typeof box[0] === "number" &&
typeof box[1] === "number" &&
typeof box[2] === "number" &&
typeof box[3] === "number" &&
typeof box[4] === "number";
+5 -2
View File
@@ -405,8 +405,9 @@ export const ROUGHNESS = {
export const STROKE_WIDTH = { export const STROKE_WIDTH = {
thin: 1, thin: 1,
bold: 2, medium: 2,
extraBold: 4, bold: 4,
extraBold: 8,
} as const; } as const;
export const DEFAULT_ELEMENT_PROPS: { export const DEFAULT_ELEMENT_PROPS: {
@@ -429,6 +430,8 @@ export const DEFAULT_ELEMENT_PROPS: {
locked: false, locked: false,
}; };
export const DEFAULT_FREE_DRAW_STROKE_SHAPE = "variable" as const;
export const LIBRARY_SIDEBAR_TAB = "library"; export const LIBRARY_SIDEBAR_TAB = "library";
export const CANVAS_SEARCH_TAB = "search"; export const CANVAS_SEARCH_TAB = "search";
+92 -83
View File
@@ -2,11 +2,9 @@ import rough from "roughjs/bin/rough";
import { import {
arrayToMap, arrayToMap,
bounds,
type Bounds, type Bounds,
invariant, invariant,
rescalePoints, rescalePoints,
type RotatedBounds,
sizeOf, sizeOf,
} from "@excalidraw/common"; } from "@excalidraw/common";
@@ -92,7 +90,7 @@ export class ElementBounds {
private static boundsCache = new WeakMap< private static boundsCache = new WeakMap<
ExcalidrawElement, ExcalidrawElement,
{ {
bounds: RotatedBounds; bounds: Bounds;
version: ExcalidrawElement["version"]; version: ExcalidrawElement["version"];
} }
>(); >();
@@ -104,11 +102,11 @@ export class ElementBounds {
} }
>(); >();
static getBounds<T extends boolean = false>( static getBounds(
element: ExcalidrawElement, element: ExcalidrawElement,
elementsMap: ElementsMap, elementsMap: ElementsMap,
nonRotated: T = false as T, nonRotated: boolean = false,
): T extends true ? Bounds : RotatedBounds { ) {
const cachedBounds = const cachedBounds =
nonRotated && element.angle !== 0 nonRotated && element.angle !== 0
? ElementBounds.nonRotatedBoundsCache.get(element) ? ElementBounds.nonRotatedBoundsCache.get(element)
@@ -121,41 +119,40 @@ export class ElementBounds {
// which is causing problems down the line. Fix TBA. // which is causing problems down the line. Fix TBA.
!isBoundToContainer(element) !isBoundToContainer(element)
) { ) {
return cachedBounds.bounds as T extends true ? Bounds : RotatedBounds; return cachedBounds.bounds;
} }
if (nonRotated && element.angle !== 0) { if (nonRotated && element.angle !== 0) {
const [minX, minY, maxX, maxY] = ElementBounds.calculateBounds( const nonRotatedBounds = ElementBounds.calculateBounds(
{ {
...element, ...element,
angle: 0 as Radians, angle: 0 as Radians,
}, },
elementsMap, elementsMap,
); );
const nonRotatedBounds = bounds(minX, minY, maxX, maxY);
ElementBounds.nonRotatedBoundsCache.set(element, { ElementBounds.nonRotatedBoundsCache.set(element, {
version: element.version, version: element.version,
bounds: nonRotatedBounds, bounds: nonRotatedBounds,
}); });
return nonRotatedBounds as T extends true ? Bounds : RotatedBounds; return nonRotatedBounds;
} }
const _bounds = ElementBounds.calculateBounds(element, elementsMap); const bounds = ElementBounds.calculateBounds(element, elementsMap);
ElementBounds.boundsCache.set(element, { ElementBounds.boundsCache.set(element, {
version: element.version, version: element.version,
bounds: _bounds, bounds,
}); });
return _bounds as T extends true ? Bounds : RotatedBounds; return bounds;
} }
private static calculateBounds( private static calculateBounds(
element: ExcalidrawElement, element: ExcalidrawElement,
elementsMap: ElementsMap, elementsMap: ElementsMap,
): RotatedBounds { ): Bounds {
let _bounds: RotatedBounds; let bounds: Bounds;
const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords( const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
element, element,
@@ -171,16 +168,17 @@ export class ElementBounds {
), ),
), ),
); );
const padding =
element.strokeShape === "fixed" ? element.strokeWidth / 2 : 0;
return bounds( return [
minX + element.x, minX + element.x - padding,
minY + element.y, minY + element.y - padding,
maxX + element.x, maxX + element.x + padding,
maxY + element.y, maxY + element.y + padding,
element.angle, ];
);
} else if (isLinearElement(element)) { } else if (isLinearElement(element)) {
_bounds = getLinearElementRotatedBounds(element, cx, cy, elementsMap); bounds = getLinearElementRotatedBounds(element, cx, cy, elementsMap);
} else if (element.type === "diamond") { } else if (element.type === "diamond") {
const [x11, y11] = pointRotateRads( const [x11, y11] = pointRotateRads(
pointFrom(cx, y1), pointFrom(cx, y1),
@@ -206,7 +204,7 @@ export class ElementBounds {
const minY = Math.min(y11, y12, y22, y21); const minY = Math.min(y11, y12, y22, y21);
const maxX = Math.max(x11, x12, x22, x21); const maxX = Math.max(x11, x12, x22, x21);
const maxY = Math.max(y11, y12, y22, y21); const maxY = Math.max(y11, y12, y22, y21);
_bounds = bounds(minX, minY, maxX, maxY, element.angle); bounds = [minX, minY, maxX, maxY];
} else if (element.type === "ellipse") { } else if (element.type === "ellipse") {
const w = (x2 - x1) / 2; const w = (x2 - x1) / 2;
const h = (y2 - y1) / 2; const h = (y2 - y1) / 2;
@@ -214,7 +212,7 @@ export class ElementBounds {
const sin = Math.sin(element.angle); const sin = Math.sin(element.angle);
const ww = Math.hypot(w * cos, h * sin); const ww = Math.hypot(w * cos, h * sin);
const hh = Math.hypot(h * cos, w * sin); const hh = Math.hypot(h * cos, w * sin);
_bounds = bounds(cx - ww, cy - hh, cx + ww, cy + hh, element.angle); bounds = [cx - ww, cy - hh, cx + ww, cy + hh];
} else { } else {
const [x11, y11] = pointRotateRads( const [x11, y11] = pointRotateRads(
pointFrom(x1, y1), pointFrom(x1, y1),
@@ -240,10 +238,10 @@ export class ElementBounds {
const minY = Math.min(y11, y12, y22, y21); const minY = Math.min(y11, y12, y22, y21);
const maxX = Math.max(x11, x12, x22, x21); const maxX = Math.max(x11, x12, x22, x21);
const maxY = Math.max(y11, y12, y22, y21); const maxY = Math.max(y11, y12, y22, y21);
_bounds = bounds(minX, minY, maxX, maxY, element.angle); bounds = [minX, minY, maxX, maxY];
} }
return _bounds; return bounds;
} }
} }
@@ -628,7 +626,7 @@ export const getCubicBezierCurveBound = (
minY = Math.min(minY, ...ys); minY = Math.min(minY, ...ys);
maxY = Math.max(maxY, ...ys); maxY = Math.max(maxY, ...ys);
} }
return bounds(minX, minY, maxX, maxY); return [minX, minY, maxX, maxY];
}; };
export const getMinMaxXYFromCurvePathOps = ( export const getMinMaxXYFromCurvePathOps = (
@@ -681,11 +679,12 @@ export const getMinMaxXYFromCurvePathOps = (
}, },
{ minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }, { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity },
); );
return bounds(minX, minY, maxX, maxY); return [minX, minY, maxX, maxY];
}; };
export const getBoundsFromPoints = ( export const getBoundsFromPoints = <P extends GlobalPoint | LocalPoint>(
points: ExcalidrawFreeDrawElement["points"], points: readonly P[],
padding: number = 0,
): Bounds => { ): Bounds => {
let minX = Infinity; let minX = Infinity;
let minY = Infinity; let minY = Infinity;
@@ -699,17 +698,18 @@ export const getBoundsFromPoints = (
maxY = Math.max(maxY, y); maxY = Math.max(maxY, y);
} }
return bounds(minX, minY, maxX, maxY); return [minX - padding, minY - padding, maxX + padding, maxY + padding];
}; };
const getFreeDrawElementAbsoluteCoords = ( const getFreeDrawElementAbsoluteCoords = (
element: ExcalidrawFreeDrawElement, element: ExcalidrawFreeDrawElement,
): [number, number, number, number, number, number] => { ): [number, number, number, number, number, number] => {
const [minX, minY, maxX, maxY] = getBoundsFromPoints(element.points); const [minX, minY, maxX, maxY] = getBoundsFromPoints(element.points);
const x1 = minX + element.x; const padding = element.strokeShape === "fixed" ? element.strokeWidth / 2 : 0;
const y1 = minY + element.y; const x1 = minX + element.x - padding;
const x2 = maxX + element.x; const y1 = minY + element.y - padding;
const y2 = maxY + element.y; const x2 = maxX + element.x + padding;
const y2 = maxY + element.y + padding;
return [x1, y1, x2, y2, (x1 + x2) / 2, (y1 + y2) / 2]; return [x1, y1, x2, y2, (x1 + x2) / 2, (y1 + y2) / 2];
}; };
@@ -942,7 +942,7 @@ const getLinearElementRotatedBounds = (
cx: number, cx: number,
cy: number, cy: number,
elementsMap: ElementsMap, elementsMap: ElementsMap,
): RotatedBounds => { ): Bounds => {
const boundTextElement = getBoundTextElement(element, elementsMap); const boundTextElement = getBoundTextElement(element, elementsMap);
if (element.points.length < 2) { if (element.points.length < 2) {
@@ -953,21 +953,20 @@ const getLinearElementRotatedBounds = (
element.angle, element.angle,
); );
let coords: RotatedBounds = bounds(x, y, x, y, element.angle); let coords: Bounds = [x, y, x, y];
if (boundTextElement) { if (boundTextElement) {
const coordsWithBoundText = LinearElementEditor.getMinMaxXYWithBoundText( const coordsWithBoundText = LinearElementEditor.getMinMaxXYWithBoundText(
element, element,
elementsMap, elementsMap,
bounds(x, y, x, y, element.angle), [x, y, x, y],
boundTextElement, boundTextElement,
); );
coords = bounds( coords = [
coordsWithBoundText[0], coordsWithBoundText[0],
coordsWithBoundText[1], coordsWithBoundText[1],
coordsWithBoundText[2], coordsWithBoundText[2],
coordsWithBoundText[3], coordsWithBoundText[3],
element.angle, ];
);
} }
return coords; return coords;
} }
@@ -983,13 +982,7 @@ const getLinearElementRotatedBounds = (
element.angle, element.angle,
); );
const res = getMinMaxXYFromCurvePathOps(ops, transformXY); const res = getMinMaxXYFromCurvePathOps(ops, transformXY);
let coords: RotatedBounds = bounds( let coords: Bounds = [res[0], res[1], res[2], res[3]];
res[0],
res[1],
res[2],
res[3],
element.angle,
);
if (boundTextElement) { if (boundTextElement) {
const coordsWithBoundText = LinearElementEditor.getMinMaxXYWithBoundText( const coordsWithBoundText = LinearElementEditor.getMinMaxXYWithBoundText(
element, element,
@@ -997,23 +990,22 @@ const getLinearElementRotatedBounds = (
coords, coords,
boundTextElement, boundTextElement,
); );
coords = bounds( coords = [
coordsWithBoundText[0], coordsWithBoundText[0],
coordsWithBoundText[1], coordsWithBoundText[1],
coordsWithBoundText[2], coordsWithBoundText[2],
coordsWithBoundText[3], coordsWithBoundText[3],
element.angle, ];
);
} }
return coords; return coords;
}; };
export const getElementBounds = <T extends boolean = false>( export const getElementBounds = (
element: ExcalidrawElement, element: ExcalidrawElement,
elementsMap: ElementsMap, elementsMap: ElementsMap,
nonRotated: T = false as T, nonRotated: boolean = false,
) => { ): Bounds => {
return ElementBounds.getBounds<T>(element, elementsMap, nonRotated); return ElementBounds.getBounds(element, elementsMap, nonRotated);
}; };
export const getCommonBounds = ( export const getCommonBounds = (
@@ -1021,7 +1013,7 @@ export const getCommonBounds = (
elementsMap?: ElementsMap, elementsMap?: ElementsMap,
): Bounds => { ): Bounds => {
if (!sizeOf(elements)) { if (!sizeOf(elements)) {
return bounds(0, 0, 0, 0); return [0, 0, 0, 0];
} }
let minX = Infinity; let minX = Infinity;
@@ -1039,7 +1031,7 @@ export const getCommonBounds = (
maxY = Math.max(maxY, y2); maxY = Math.max(maxY, y2);
}); });
return bounds(minX, minY, maxX, maxY); return [minX, minY, maxX, maxY];
}; };
export const getDraggedElementsBounds = ( export const getDraggedElementsBounds = (
@@ -1062,12 +1054,12 @@ export const getResizedElementAbsoluteCoords = (
normalizePoints: boolean, normalizePoints: boolean,
): Bounds => { ): Bounds => {
if (!(isLinearElement(element) || isFreeDrawElement(element))) { if (!(isLinearElement(element) || isFreeDrawElement(element))) {
return bounds( return [
element.x, element.x,
element.y, element.y,
element.x + nextWidth, element.x + nextWidth,
element.y + nextHeight, element.y + nextHeight,
); ];
} }
const points = rescalePoints( const points = rescalePoints(
@@ -1077,11 +1069,11 @@ export const getResizedElementAbsoluteCoords = (
normalizePoints, normalizePoints,
); );
let _bounds: Bounds; let bounds: Bounds;
if (isFreeDrawElement(element)) { if (isFreeDrawElement(element)) {
// Free Draw // Free Draw
_bounds = getBoundsFromPoints(points); bounds = getBoundsFromPoints(points);
} else { } else {
// Line // Line
const gen = rough.generator(); const gen = rough.generator();
@@ -1093,16 +1085,16 @@ export const getResizedElementAbsoluteCoords = (
: gen.curve(points as [number, number][], generateRoughOptions(element)); : gen.curve(points as [number, number][], generateRoughOptions(element));
const ops = getCurvePathOps(curve); const ops = getCurvePathOps(curve);
_bounds = getMinMaxXYFromCurvePathOps(ops); bounds = getMinMaxXYFromCurvePathOps(ops);
} }
const [minX, minY, maxX, maxY] = _bounds; const [minX, minY, maxX, maxY] = bounds;
return bounds( return [
minX + element.x, minX + element.x,
minY + element.y, minY + element.y,
maxX + element.x, maxX + element.x,
maxY + element.y, maxY + element.y,
); ];
}; };
export const getElementPointsCoords = ( export const getElementPointsCoords = (
@@ -1120,20 +1112,20 @@ export const getElementPointsCoords = (
: gen.curve(points as [number, number][], generateRoughOptions(element)); : gen.curve(points as [number, number][], generateRoughOptions(element));
const ops = getCurvePathOps(curve); const ops = getCurvePathOps(curve);
const [minX, minY, maxX, maxY] = getMinMaxXYFromCurvePathOps(ops); const [minX, minY, maxX, maxY] = getMinMaxXYFromCurvePathOps(ops);
return bounds( return [
minX + element.x, minX + element.x,
minY + element.y, minY + element.y,
maxX + element.x, maxX + element.x,
maxY + element.y, maxY + element.y,
); ];
}; };
export const getClosestElementBounds = ( export const getClosestElementBounds = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
from: { x: number; y: number }, from: { x: number; y: number },
): RotatedBounds => { ): Bounds => {
if (!elements.length) { if (!elements.length) {
return bounds(0, 0, 0, 0, 0 as Radians); return [0, 0, 0, 0];
} }
let minDistance = Infinity; let minDistance = Infinity;
@@ -1202,9 +1194,7 @@ export const getVisibleSceneBounds = ({
]; ];
}; };
export const getCenterForBounds = ( export const getCenterForBounds = (bounds: Bounds): GlobalPoint =>
bounds: Bounds | RotatedBounds,
): GlobalPoint =>
pointFrom( pointFrom(
bounds[0] + (bounds[2] - bounds[0]) / 2, bounds[0] + (bounds[2] - bounds[0]) / 2,
bounds[1] + (bounds[3] - bounds[1]) / 2, bounds[1] + (bounds[3] - bounds[1]) / 2,
@@ -1249,24 +1239,24 @@ export const aabbForElement = (
element.angle, element.angle,
); );
const _bounds = bounds( const bounds = [
Math.min(topLeftX, topRightX, bottomRightX, bottomLeftX), Math.min(topLeftX, topRightX, bottomRightX, bottomLeftX),
Math.min(topLeftY, topRightY, bottomRightY, bottomLeftY), Math.min(topLeftY, topRightY, bottomRightY, bottomLeftY),
Math.max(topLeftX, topRightX, bottomRightX, bottomLeftX), Math.max(topLeftX, topRightX, bottomRightX, bottomLeftX),
Math.max(topLeftY, topRightY, bottomRightY, bottomLeftY), Math.max(topLeftY, topRightY, bottomRightY, bottomLeftY),
); ] as Bounds;
if (offset) { if (offset) {
const [topOffset, rightOffset, downOffset, leftOffset] = offset; const [topOffset, rightOffset, downOffset, leftOffset] = offset;
return bounds( return [
_bounds[0] - leftOffset, bounds[0] - leftOffset,
_bounds[1] - topOffset, bounds[1] - topOffset,
_bounds[2] + rightOffset, bounds[2] + rightOffset,
_bounds[3] + downOffset, bounds[3] + downOffset,
); ] as Bounds;
} }
return _bounds; return bounds;
}; };
export const pointInsideBounds = <P extends GlobalPoint | LocalPoint>( export const pointInsideBounds = <P extends GlobalPoint | LocalPoint>(
@@ -1275,7 +1265,18 @@ export const pointInsideBounds = <P extends GlobalPoint | LocalPoint>(
): boolean => ): boolean =>
p[0] > bounds[0] && p[0] < bounds[2] && p[1] > bounds[1] && p[1] < bounds[3]; p[0] > bounds[0] && p[0] < bounds[2] && p[1] > bounds[1] && p[1] < bounds[3];
export const doNonRotatedBoundsIntersect = ( // TODO make pointInsideBounds inclusive and remove this function once we
// test nothing is breaking
export const pointInsideBoundsInclusive = <P extends GlobalPoint | LocalPoint>(
p: P,
bounds: Bounds,
): boolean =>
p[0] >= bounds[0] &&
p[0] <= bounds[2] &&
p[1] >= bounds[1] &&
p[1] <= bounds[3];
export const doBoundsIntersect = (
bounds1: Bounds | null, bounds1: Bounds | null,
bounds2: Bounds | null, bounds2: Bounds | null,
): boolean => { ): boolean => {
@@ -1289,6 +1290,14 @@ export const doNonRotatedBoundsIntersect = (
return minX1 < maxX2 && maxX1 > minX2 && minY1 < maxY2 && maxY1 > minY2; return minX1 < maxX2 && maxX1 > minX2 && minY1 < maxY2 && maxY1 > minY2;
}; };
export const boundsContainBounds = (outerBounds: Bounds, innerBounds: Bounds) =>
[
pointFrom<GlobalPoint>(innerBounds[0], innerBounds[1]),
pointFrom<GlobalPoint>(innerBounds[0], innerBounds[3]),
pointFrom<GlobalPoint>(innerBounds[2], innerBounds[1]),
pointFrom<GlobalPoint>(innerBounds[2], innerBounds[3]),
].every((point) => pointInsideBoundsInclusive(point, outerBounds));
export const elementCenterPoint = ( export const elementCenterPoint = (
element: ExcalidrawElement, element: ExcalidrawElement,
elementsMap: ElementsMap, elementsMap: ElementsMap,
+22 -105
View File
@@ -1,9 +1,4 @@
import { import { invariant, isTransparent, type Bounds } from "@excalidraw/common";
bounds,
invariant,
isTransparent,
type Bounds,
} from "@excalidraw/common";
import { import {
curveIntersectLineSegment, curveIntersectLineSegment,
isPointWithinBounds, isPointWithinBounds,
@@ -32,9 +27,10 @@ import type {
import type { FrameNameBounds } from "@excalidraw/excalidraw/types"; import type { FrameNameBounds } from "@excalidraw/excalidraw/types";
import { isLoopFreeDrawElement } from "./freedraw";
import { isPathALoop } from "./utils"; import { isPathALoop } from "./utils";
import { import {
doNonRotatedBoundsIntersect, doBoundsIntersect,
elementCenterPoint, elementCenterPoint,
getCenterForBounds, getCenterForBounds,
getCubicBezierCurveBound, getCubicBezierCurveBound,
@@ -98,7 +94,7 @@ export const shouldTestInside = (element: ExcalidrawElement) => {
} }
if (element.type === "freedraw") { if (element.type === "freedraw") {
return isDraggableFromInside && isPathALoop(element.points); return isDraggableFromInside && isLoopFreeDrawElement(element);
} }
return isDraggableFromInside || isImageElement(element); return isDraggableFromInside || isImageElement(element);
@@ -194,48 +190,6 @@ export const hitElementItself = ({
return result; return result;
}; };
export function getBoundsCorners(
bounds: Bounds,
): readonly [GlobalPoint, GlobalPoint, GlobalPoint, GlobalPoint];
export function getBoundsCorners(
bounds: Bounds,
angle: Radians,
): readonly [GlobalPoint, GlobalPoint, GlobalPoint, GlobalPoint];
export function getBoundsCorners(
bounds: Bounds,
angle: Radians = 0 as Radians,
) {
const [x1, y1, x2, y2] = bounds;
const center = getCenterForBounds(bounds);
const corners = [
pointFrom<GlobalPoint>(x1, y1),
pointFrom<GlobalPoint>(x2, y1),
pointFrom<GlobalPoint>(x2, y2),
pointFrom<GlobalPoint>(x1, y2),
] as const;
if (angle === 0) {
return corners;
}
return corners.map((point) => pointRotateRads(point, center, angle)) as [
GlobalPoint,
GlobalPoint,
GlobalPoint,
GlobalPoint,
];
}
export const getBoundsEdges = (
corners: readonly [GlobalPoint, GlobalPoint, GlobalPoint, GlobalPoint],
) =>
[
lineSegment(corners[0], corners[1]),
lineSegment(corners[1], corners[2]),
lineSegment(corners[2], corners[3]),
lineSegment(corners[3], corners[0]),
] as const;
const isPointInRotatedBounds = ( const isPointInRotatedBounds = (
point: GlobalPoint, point: GlobalPoint,
bounds: Bounds, bounds: Bounds,
@@ -264,40 +218,6 @@ export const hitElementBoundingBox = (
return isPointInRotatedBounds(point, bounds, element.angle, tolerance); return isPointInRotatedBounds(point, bounds, element.angle, tolerance);
}; };
export const doBoundsIntersectElementBoundingBox = (
intersectorBounds: Bounds,
element: ExcalidrawElement,
elementsMap: ElementsMap,
) => {
const [x1, y1, x2, y2] = intersectorBounds;
const intersectorCorners = [
pointFrom<GlobalPoint>(x1, y1),
pointFrom<GlobalPoint>(x2, y1),
pointFrom<GlobalPoint>(x2, y2),
pointFrom<GlobalPoint>(x1, y2),
] as const;
const intersectorEdges = getBoundsEdges(intersectorCorners);
const elementBounds = getElementBounds(element, elementsMap, true);
const elementBoundsCorners = getBoundsCorners(elementBounds, element.angle);
const elementBoundsEdges = getBoundsEdges(elementBoundsCorners);
return (
elementBoundsCorners.some((point) =>
isPointWithinBounds(intersectorCorners[0], point, intersectorCorners[2]),
) ||
intersectorCorners.some((point) =>
isPointInRotatedBounds(point, elementBounds, element.angle),
) ||
intersectorEdges.some((selectionEdge) =>
elementBoundsEdges.some(
(elementBoundsEdge) =>
!!lineSegmentIntersectionPoints(selectionEdge, elementBoundsEdge),
),
)
);
};
export const hitElementBoundingBoxOnly = ( export const hitElementBoundingBoxOnly = (
hitArgs: HitTestArgs, hitArgs: HitTestArgs,
elementsMap: ElementsMap, elementsMap: ElementsMap,
@@ -348,13 +268,9 @@ const bindingBorderTest = (
// PERF: Run a cheap test to see if the binding element // PERF: Run a cheap test to see if the binding element
// is even close to the element // is even close to the element
const t = Math.max(1, tolerance); const t = Math.max(1, tolerance);
const elementBounds = getElementBounds(element, elementsMap, true); const bounds = [x - t, y - t, x + t, y + t] as Bounds;
if ( const elementBounds = getElementBounds(element, elementsMap);
!doNonRotatedBoundsIntersect( if (!doBoundsIntersect(bounds, elementBounds)) {
bounds(x - t, y - t, x + t, y + t),
elementBounds,
)
) {
return false; return false;
} }
@@ -365,7 +281,6 @@ const bindingBorderTest = (
const enclosingFrameBounds = getElementBounds( const enclosingFrameBounds = getElementBounds(
enclosingFrame, enclosingFrame,
elementsMap, elementsMap,
true,
); );
if (!pointInsideBounds(p, enclosingFrameBounds)) { if (!pointInsideBounds(p, enclosingFrameBounds)) {
return false; return false;
@@ -515,15 +430,15 @@ export const intersectElementWithLineSegment = (
): GlobalPoint[] => { ): GlobalPoint[] => {
// First check if the line intersects the element's axis-aligned bounding box // First check if the line intersects the element's axis-aligned bounding box
// as it is much faster than checking intersection against the element's shape // as it is much faster than checking intersection against the element's shape
const intersectorBounds = bounds( const intersectorBounds = [
Math.min(line[0][0] - offset, line[1][0] - offset), Math.min(line[0][0] - offset, line[1][0] - offset),
Math.min(line[0][1] - offset, line[1][1] - offset), Math.min(line[0][1] - offset, line[1][1] - offset),
Math.max(line[0][0] + offset, line[1][0] + offset), Math.max(line[0][0] + offset, line[1][0] + offset),
Math.max(line[0][1] + offset, line[1][1] + offset), Math.max(line[0][1] + offset, line[1][1] + offset),
); ] as Bounds;
const elementBounds = getElementBounds(element, elementsMap, true); const elementBounds = getElementBounds(element, elementsMap);
if (!doNonRotatedBoundsIntersect(intersectorBounds, elementBounds)) { if (!doBoundsIntersect(intersectorBounds, elementBounds)) {
return []; return [];
} }
@@ -582,14 +497,14 @@ const curveIntersections = (
for (const c of curves) { for (const c of curves) {
// Optimize by doing a cheap bounding box check first // Optimize by doing a cheap bounding box check first
const b1 = getCubicBezierCurveBound(c[0], c[1], c[2], c[3]); const b1 = getCubicBezierCurveBound(c[0], c[1], c[2], c[3]);
const b2 = bounds( const b2 = [
Math.min(segment[0][0], segment[1][0]), Math.min(segment[0][0], segment[1][0]),
Math.min(segment[0][1], segment[1][1]), Math.min(segment[0][1], segment[1][1]),
Math.max(segment[0][0], segment[1][0]), Math.max(segment[0][0], segment[1][0]),
Math.max(segment[0][1], segment[1][1]), Math.max(segment[0][1], segment[1][1]),
); ] as Bounds;
if (!doNonRotatedBoundsIntersect(b1, b2)) { if (!doBoundsIntersect(b1, b2)) {
continue; continue;
} }
@@ -659,18 +574,20 @@ const intersectLinearOrFreeDrawWithLineSegment = (
for (const c of curves) { for (const c of curves) {
// Optimize by doing a cheap bounding box check first // Optimize by doing a cheap bounding box check first
const b1 = getCubicBezierCurveBound(c[0], c[1], c[2], c[3]); const b1 = getCubicBezierCurveBound(c[0], c[1], c[2], c[3]);
const b2 = bounds( const b2 = [
Math.min(segment[0][0], segment[1][0]), Math.min(segment[0][0], segment[1][0]),
Math.min(segment[0][1], segment[1][1]), Math.min(segment[0][1], segment[1][1]),
Math.max(segment[0][0], segment[1][0]), Math.max(segment[0][0], segment[1][0]),
Math.max(segment[0][1], segment[1][1]), Math.max(segment[0][1], segment[1][1]),
); ] as Bounds;
if (!doNonRotatedBoundsIntersect(b1, b2)) { if (!doBoundsIntersect(b1, b2)) {
continue; continue;
} }
const hits = curveIntersectLineSegment(c, segment); const hits = curveIntersectLineSegment(c, segment, {
iterLimit: 10,
});
if (hits.length > 0) { if (hits.length > 0) {
intersections.push(...hits); intersections.push(...hits);
@@ -838,8 +755,8 @@ export const isPointInElement = (
elementsMap: ElementsMap, elementsMap: ElementsMap,
) => { ) => {
if ( if (
(isLinearElement(element) || isFreeDrawElement(element)) && (isLinearElement(element) && !isPathALoop(element.points)) ||
!isPathALoop(element.points) (isFreeDrawElement(element) && !isLoopFreeDrawElement(element))
) { ) {
// There isn't any "inside" for a non-looping path // There isn't any "inside" for a non-looping path
return false; return false;
+13 -11
View File
@@ -1,7 +1,6 @@
import { arrayToMap } from "@excalidraw/common"; import { arrayToMap } from "@excalidraw/common";
import { isPointWithinBounds, pointFrom } from "@excalidraw/math"; import { isPointWithinBounds, pointFrom } from "@excalidraw/math";
import { doLineSegmentsIntersect } from "@excalidraw/utils/bbox"; import { doLineSegmentsIntersect } from "@excalidraw/utils/bbox";
import { elementsOverlappingBBox } from "@excalidraw/utils/withinBounds";
import type { import type {
AppClassProperties, AppClassProperties,
@@ -18,6 +17,8 @@ import {
getElementLineSegments, getElementLineSegments,
getCommonBounds, getCommonBounds,
getElementAbsoluteCoords, getElementAbsoluteCoords,
doBoundsIntersect,
getElementBounds,
} from "./bounds"; } from "./bounds";
import { mutateElement } from "./mutateElement"; import { mutateElement } from "./mutateElement";
import { getBoundTextElement, getContainerElement } from "./textElement"; import { getBoundTextElement, getContainerElement } from "./textElement";
@@ -99,7 +100,7 @@ export const isElementContainingFrame = (
element: ExcalidrawElement, element: ExcalidrawElement,
frame: ExcalidrawFrameLikeElement, frame: ExcalidrawFrameLikeElement,
elementsMap: ElementsMap, elementsMap: ElementsMap,
): boolean => { ) => {
return getElementsWithinSelection([frame], element, elementsMap).some( return getElementsWithinSelection([frame], element, elementsMap).some(
(e) => e.id === frame.id, (e) => e.id === frame.id,
); );
@@ -140,7 +141,7 @@ export const elementOverlapsWithFrame = (
element: ExcalidrawElement, element: ExcalidrawElement,
frame: ExcalidrawFrameLikeElement, frame: ExcalidrawFrameLikeElement,
elementsMap: ElementsMap, elementsMap: ElementsMap,
): boolean => { ) => {
return ( return (
elementsAreInFrameBounds([element], frame, elementsMap) || elementsAreInFrameBounds([element], frame, elementsMap) ||
isElementIntersectingFrame(element, frame, elementsMap) || isElementIntersectingFrame(element, frame, elementsMap) ||
@@ -920,16 +921,17 @@ export const getFrameLikeTitle = (element: ExcalidrawFrameLikeElement) => {
export const getElementsOverlappingFrame = ( export const getElementsOverlappingFrame = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
frame: ExcalidrawFrameLikeElement, frame: ExcalidrawFrameLikeElement,
elementsMap: ElementsMap,
) => { ) => {
return ( return elements.filter(
elementsOverlappingBBox({ (el) =>
elements, // exclude elements which are overlapping, but are in a different frame,
bounds: frame,
type: "overlap",
})
// removes elements who are overlapping, but are in a different frame,
// and thus invisible in target frame // and thus invisible in target frame
.filter((el) => !el.frameId || el.frameId === frame.id) (!el.frameId || el.frameId === frame.id) &&
doBoundsIntersect(
getElementBounds(el, elementsMap),
getElementBounds(frame, elementsMap),
),
); );
}; };
+181
View File
@@ -0,0 +1,181 @@
import {
pointDistance,
vectorCross,
vectorDot,
vectorFromPoint,
} from "@excalidraw/math";
import type { LocalPoint } from "@excalidraw/math";
import { isPathALoop } from "./utils";
import type { ExcalidrawFreeDrawElement } from "./types";
type ZoomValue = NonNullable<Parameters<typeof isPathALoop>[1]>;
type FixedFreeDrawSimplificationProfile = {
minPointDistancePx: number;
maxPointDistance: number;
strokeDistanceFactor: number;
collinearityFactor: number;
minAlignment: number;
zoomScaling: "sqrt" | "none";
};
const FIXED_FREEDRAW_CAPTURE_PROFILE: FixedFreeDrawSimplificationProfile = {
minPointDistancePx: 0.35,
maxPointDistance: 0.85,
strokeDistanceFactor: 0.08,
collinearityFactor: 0.3,
minAlignment: 0.985,
zoomScaling: "sqrt",
};
const hasSyntheticLoopClosure = (
points: readonly LocalPoint[],
): points is readonly [LocalPoint, LocalPoint, ...LocalPoint[]] => {
if (points.length < 3) {
return false;
}
const firstPoint = points[0];
const lastPoint = points[points.length - 1];
return firstPoint[0] === lastPoint[0] && firstPoint[1] === lastPoint[1];
};
const stripSyntheticLoopClosure = (points: readonly LocalPoint[]) =>
hasSyntheticLoopClosure(points) ? points.slice(0, -1) : points;
export const isLoopFreeDrawElement = (
element: ExcalidrawFreeDrawElement,
zoomValue: ZoomValue = 1 as ZoomValue,
) => element.strokeShape !== "fixed" && isPathALoop(element.points, zoomValue);
export const getFixedFreeDrawPoints = (
element: ExcalidrawFreeDrawElement,
): readonly LocalPoint[] => stripSyntheticLoopClosure(element.points);
export const getFixedFreeDrawPointSamplingDistance = (
strokeWidth: number,
zoomValue: ZoomValue = 1 as ZoomValue,
profile: FixedFreeDrawSimplificationProfile = FIXED_FREEDRAW_CAPTURE_PROFILE,
) =>
Math.min(
Math.max(
profile.minPointDistancePx /
(profile.zoomScaling === "sqrt"
? Math.max(1, Math.sqrt(zoomValue))
: 1),
strokeWidth * profile.strokeDistanceFactor,
),
profile.maxPointDistance,
);
const isRedundantFixedFreeDrawPoint = (
previousPoint: LocalPoint,
currentPoint: LocalPoint,
nextPoint: LocalPoint,
strokeWidth: number,
zoomValue: ZoomValue,
profile: FixedFreeDrawSimplificationProfile,
) => {
const previousSegmentLength = pointDistance(previousPoint, currentPoint);
const nextSegmentLength = pointDistance(currentPoint, nextPoint);
if (!previousSegmentLength || !nextSegmentLength) {
return true;
}
const previousVector = vectorFromPoint(currentPoint, previousPoint);
const nextVector = vectorFromPoint(nextPoint, currentPoint);
const alignment =
vectorDot(previousVector, nextVector) /
(previousSegmentLength * nextSegmentLength);
if (alignment < profile.minAlignment) {
return false;
}
const chord = vectorFromPoint(nextPoint, previousPoint);
const chordLength = pointDistance(previousPoint, nextPoint);
if (!chordLength) {
return true;
}
const distanceToChord =
Math.abs(vectorCross(vectorFromPoint(currentPoint, previousPoint), chord)) /
chordLength;
return (
distanceToChord <=
getFixedFreeDrawPointSamplingDistance(strokeWidth, zoomValue, profile) *
profile.collinearityFactor
);
};
export const getFixedFreeDrawPointAction = ({
points,
nextPoint,
strokeWidth,
zoomValue,
isFinalPoint = false,
profile,
}: {
points: readonly LocalPoint[];
nextPoint: LocalPoint;
strokeWidth: number;
zoomValue: ZoomValue;
isFinalPoint?: boolean;
profile?: FixedFreeDrawSimplificationProfile;
}) => {
const simplificationProfile = profile ?? FIXED_FREEDRAW_CAPTURE_PROFILE;
const lastPoint = points[points.length - 1];
if (!lastPoint) {
return "append" as const;
}
if (lastPoint[0] === nextPoint[0] && lastPoint[1] === nextPoint[1]) {
return "discard" as const;
}
const samplingDistance = getFixedFreeDrawPointSamplingDistance(
strokeWidth,
zoomValue,
simplificationProfile,
);
if (points.length === 1) {
return !isFinalPoint &&
pointDistance(lastPoint, nextPoint) < samplingDistance
? ("discard" as const)
: ("append" as const);
}
const previousPoint = points[points.length - 2];
if (
isRedundantFixedFreeDrawPoint(
previousPoint,
lastPoint,
nextPoint,
strokeWidth,
zoomValue,
simplificationProfile,
)
) {
return "replace" as const;
}
if (!isFinalPoint && pointDistance(lastPoint, nextPoint) < samplingDistance) {
return "discard" as const;
}
return "append" as const;
};
export const getRenderableFixedFreeDrawPoints = (
element: ExcalidrawFreeDrawElement,
): readonly LocalPoint[] => getFixedFreeDrawPoints(element);
+1
View File
@@ -69,6 +69,7 @@ export * from "./duplicate";
export * from "./elbowArrow"; export * from "./elbowArrow";
export * from "./elementLink"; export * from "./elementLink";
export * from "./embeddable"; export * from "./embeddable";
export * from "./freedraw";
export * from "./flowchart"; export * from "./flowchart";
export * from "./arrows/focus"; export * from "./arrows/focus";
export * from "./fractionalIndex"; export * from "./fractionalIndex";
+3 -4
View File
@@ -21,7 +21,6 @@ import {
invariant, invariant,
isShallowEqual, isShallowEqual,
getFeatureFlag, getFeatureFlag,
bounds,
} from "@excalidraw/common"; } from "@excalidraw/common";
import { import {
@@ -43,7 +42,7 @@ import type {
NullableGridSize, NullableGridSize,
Zoom, Zoom,
} from "@excalidraw/excalidraw/types"; } from "@excalidraw/excalidraw/types";
import type { RotatedBounds } from "@excalidraw/common"; import type { Bounds } from "@excalidraw/common";
import { import {
calculateFixedPointForNonElbowArrowBinding, calculateFixedPointForNonElbowArrowBinding,
@@ -1880,7 +1879,7 @@ export class LinearElementEditor {
static getMinMaxXYWithBoundText = ( static getMinMaxXYWithBoundText = (
element: ExcalidrawLinearElement, element: ExcalidrawLinearElement,
elementsMap: ElementsMap, elementsMap: ElementsMap,
elementBounds: RotatedBounds, elementBounds: Bounds,
boundTextElement: ExcalidrawTextElementWithContainer, boundTextElement: ExcalidrawTextElementWithContainer,
): [number, number, number, number, number, number] => { ): [number, number, number, number, number, number] => {
let [x1, y1, x2, y2] = elementBounds; let [x1, y1, x2, y2] = elementBounds;
@@ -2005,7 +2004,7 @@ export class LinearElementEditor {
return LinearElementEditor.getMinMaxXYWithBoundText( return LinearElementEditor.getMinMaxXYWithBoundText(
element, element,
elementsMap, elementsMap,
bounds(x1, y1, x2, y2, element.angle), [x1, y1, x2, y2],
boundTextElement, boundTextElement,
); );
} }
+27
View File
@@ -1,4 +1,5 @@
import { import {
DEFAULT_FREE_DRAW_STROKE_SHAPE,
getSizeFromPoints, getSizeFromPoints,
randomInteger, randomInteger,
getUpdatedTimestamp, getUpdatedTimestamp,
@@ -18,6 +19,8 @@ import type {
ElementsMap, ElementsMap,
ExcalidrawElbowArrowElement, ExcalidrawElbowArrowElement,
ExcalidrawElement, ExcalidrawElement,
ExcalidrawFreeDrawElement,
FreeDrawStrokeShape,
NonDeletedSceneElementsMap, NonDeletedSceneElementsMap,
} from "./types"; } from "./types";
@@ -177,6 +180,30 @@ export const newElementWith = <TElement extends ExcalidrawElement>(
}; };
}; };
export const newFreeDrawElementWithStrokeShape = <
TElement extends ExcalidrawFreeDrawElement,
>(
element: TElement,
strokeShape: FreeDrawStrokeShape,
): TElement => {
if (strokeShape === DEFAULT_FREE_DRAW_STROKE_SHAPE) {
if (!("strokeShape" in element)) {
return element;
}
const nextElement = newElementWith(
element,
{} as ElementUpdate<TElement>,
true,
);
delete (nextElement as Mutable<Partial<TElement>>).strokeShape;
return nextElement;
}
return newElementWith(element, {
strokeShape,
} as ElementUpdate<TElement>);
};
/** /**
* Mutates element, bumping `version`, `versionNonce`, and `updated`. * Mutates element, bumping `version`, `versionNonce`, and `updated`.
* *
+2
View File
@@ -445,6 +445,7 @@ export const newFreeDrawElement = (
points?: ExcalidrawFreeDrawElement["points"]; points?: ExcalidrawFreeDrawElement["points"];
simulatePressure: boolean; simulatePressure: boolean;
pressures?: ExcalidrawFreeDrawElement["pressures"]; pressures?: ExcalidrawFreeDrawElement["pressures"];
strokeShape?: ExcalidrawFreeDrawElement["strokeShape"];
} & ElementConstructorOpts, } & ElementConstructorOpts,
): NonDeleted<ExcalidrawFreeDrawElement> => { ): NonDeleted<ExcalidrawFreeDrawElement> => {
return { return {
@@ -452,6 +453,7 @@ export const newFreeDrawElement = (
points: opts.points || [], points: opts.points || [],
pressures: opts.pressures || [], pressures: opts.pressures || [],
simulatePressure: opts.simulatePressure, simulatePressure: opts.simulatePressure,
...(opts.strokeShape === "fixed" ? { strokeShape: opts.strokeShape } : {}),
}; };
}; };
+13 -2
View File
@@ -417,16 +417,27 @@ const drawElementOnCanvas = (
case "freedraw": { case "freedraw": {
// Draw directly to canvas // Draw directly to canvas
context.save(); context.save();
context.lineJoin = "round";
context.lineCap = "round";
const shapes = ShapeCache.generateElementShape(element, renderConfig); const shapes = ShapeCache.generateElementShape(element, renderConfig);
const isFixedStroke = element.strokeShape === "fixed";
for (const shape of shapes) { for (const shape of shapes) {
if (typeof shape === "string") { if (typeof shape === "string") {
context.fillStyle = const strokeColor =
renderConfig.theme === THEME.DARK renderConfig.theme === THEME.DARK
? applyDarkModeFilter(element.strokeColor) ? applyDarkModeFilter(element.strokeColor)
: element.strokeColor; : element.strokeColor;
context.fill(new Path2D(shape));
if (isFixedStroke) {
context.strokeStyle = strokeColor;
context.lineWidth = element.strokeWidth;
context.stroke(new Path2D(shape));
} else {
context.fillStyle = strokeColor;
context.fill(new Path2D(shape));
}
} else { } else {
rc.draw(shape); rc.draw(shape);
} }
+228 -334
View File
@@ -2,8 +2,8 @@ import { arrayToMap, isShallowEqual, type Bounds } from "@excalidraw/common";
import { import {
lineSegment, lineSegment,
pointFrom, pointFrom,
pointRotateRads,
type GlobalPoint, type GlobalPoint,
type LineSegment,
} from "@excalidraw/math"; } from "@excalidraw/math";
import type { import type {
@@ -13,20 +13,17 @@ import type {
} from "@excalidraw/excalidraw/types"; } from "@excalidraw/excalidraw/types";
import { import {
boundsContainBounds,
doBoundsIntersect,
elementCenterPoint,
getElementAbsoluteCoords, getElementAbsoluteCoords,
getElementBounds, getElementBounds,
getElementLineSegments, pointInsideBounds,
} from "./bounds"; } from "./bounds";
import { import { intersectElementWithLineSegment } from "./collision";
doBoundsIntersectElementBoundingBox,
getBoundsCorners,
getBoundsEdges,
intersectElementWithLineSegment,
isPointInElement,
shouldTestInside,
} from "./collision";
import { isElementInViewport } from "./sizeHelpers"; import { isElementInViewport } from "./sizeHelpers";
import { import {
isArrowElement,
isBoundToContainer, isBoundToContainer,
isFrameLikeElement, isFrameLikeElement,
isFreeDrawElement, isFreeDrawElement,
@@ -37,218 +34,38 @@ import {
elementOverlapsWithFrame, elementOverlapsWithFrame,
getContainingFrame, getContainingFrame,
getFrameChildren, getFrameChildren,
isElementIntersectingFrame,
} from "./frame"; } from "./frame";
import { LinearElementEditor } from "./linearElementEditor"; import { LinearElementEditor } from "./linearElementEditor";
import { selectGroupsForSelectedElements } from "./groups"; import { selectGroupsForSelectedElements } from "./groups";
import { getBoundTextElement } from "./textElement";
import type { import type {
ElementsMap, ElementsMap,
ElementsMapOrArray, ElementsMapOrArray,
ExcalidrawElement, ExcalidrawElement,
ExcalidrawFrameLikeElement,
NonDeleted, NonDeleted,
NonDeletedExcalidrawElement, NonDeletedExcalidrawElement,
} from "./types"; } from "./types";
// Broad-phase only for overlap mode. Rotated closed shapes should not select const shouldIgnoreElementFromSelection = (
// from the empty corners of their axis-aligned bounds. Linear elements and
// freedraw already rely on the outline-specific path below, so exclude them.
const shouldUseRotatedOverlapBroadPhase = (
element: NonDeletedExcalidrawElement, element: NonDeletedExcalidrawElement,
) => ) => element.locked || isBoundToContainer(element);
element.angle !== 0 &&
!isLinearElement(element) &&
!isFreeDrawElement(element);
const clipLineSegmentToBounds = ( const excludeElementsFromFrames = <T extends ExcalidrawElement>(
segment: LineSegment<GlobalPoint>, selectedElements: readonly T[],
bounds: Bounds, framesInSelection: Set<ExcalidrawFrameLikeElement["id"]>,
): LineSegment<GlobalPoint> | null => { ) => {
const [minX, minY, maxX, maxY] = bounds; return selectedElements.filter((element) => {
const [[x1, y1], [x2, y2]] = segment; if (element.frameId && framesInSelection.has(element.frameId)) {
const deltaX = x2 - x1;
const deltaY = y2 - y1;
let tMin = 0;
let tMax = 1;
const clip = (p: number, q: number) => {
if (p === 0) {
return q >= 0;
}
const ratio = q / p;
if (p < 0) {
if (ratio > tMax) {
return false;
}
tMin = Math.max(tMin, ratio);
return true;
}
if (ratio < tMin) {
return false; return false;
} }
tMax = Math.min(tMax, ratio);
return true;
};
if (
!clip(-deltaX, x1 - minX) ||
!clip(deltaX, maxX - x1) ||
!clip(-deltaY, y1 - minY) ||
!clip(deltaY, maxY - y1)
) {
return null;
}
return lineSegment(
pointFrom<GlobalPoint>(x1 + tMin * deltaX, y1 + tMin * deltaY),
pointFrom<GlobalPoint>(x1 + tMax * deltaX, y1 + tMax * deltaY),
);
};
const isPointWithinAabb = (point: GlobalPoint, bounds: Bounds) =>
point[0] >= bounds[0] &&
point[0] <= bounds[2] &&
point[1] >= bounds[1] &&
point[1] <= bounds[3];
const shouldUsePreciseFilledOverlap = (element: NonDeletedExcalidrawElement) =>
element.type === "ellipse" ||
element.type === "diamond" ||
(element.type === "rectangle" && !!element.roundness);
const shouldSkipElementFromSelection = (element: NonDeletedExcalidrawElement) =>
element.locked || element.type === "selection" || isBoundToContainer(element);
const getFrameBoundsForSelection = (
element: NonDeletedExcalidrawElement,
elementsMap: ElementsMap,
): Bounds | null => {
if (!element.frameId) {
return null;
}
const containingFrame = getContainingFrame(element, elementsMap);
return containingFrame
? (getElementBounds(containingFrame, elementsMap) as Bounds)
: null;
};
const finalizeElementsInSelection = (
elementsInSelection: NonDeletedExcalidrawElement[],
excludeElementsInFrames: boolean,
elementsMap: ElementsMap,
): NonDeletedExcalidrawElement[] => {
elementsInSelection = excludeElementsInFrames
? excludeElementsInFramesFromSelection(elementsInSelection)
: elementsInSelection;
return elementsInSelection.filter((element) => {
const containingFrame = getContainingFrame(element, elementsMap);
if (containingFrame) {
return elementOverlapsWithFrame(element, containingFrame, elementsMap);
}
return true; return true;
}); });
}; };
const getVisibleElementOutlineSegments = (
element: NonDeletedExcalidrawElement,
frameBounds: Bounds | null,
elementsMap: ElementsMap,
) =>
frameBounds
? getElementLineSegments(element, elementsMap).flatMap((segment) => {
const clippedSegment = clipLineSegmentToBounds(segment, frameBounds);
return clippedSegment ? [clippedSegment] : [];
})
: getElementLineSegments(element, elementsMap);
const doesSelectionIntersectElementOutline = (
element: NonDeletedExcalidrawElement,
frameBounds: Bounds | null,
selectionEdges: readonly LineSegment<GlobalPoint>[],
elementsMap: ElementsMap,
) =>
selectionEdges.some((selectionEdge) =>
intersectElementWithLineSegment(
element,
elementsMap,
selectionEdge,
0,
true,
).some((point) => !frameBounds || isPointWithinAabb(point, frameBounds)),
);
const doesSelectionContainElementOutline = (
outlineSegments: readonly LineSegment<GlobalPoint>[],
selectionBounds: Bounds,
) =>
outlineSegments.length > 0 &&
outlineSegments.every(
(outlineSegment) =>
isPointWithinAabb(outlineSegment[0], selectionBounds) &&
isPointWithinAabb(outlineSegment[1], selectionBounds),
);
const doesSelectionContainElementInterior = (
element: NonDeletedExcalidrawElement,
frameBounds: Bounds | null,
selectionCorners: readonly GlobalPoint[],
elementsMap: ElementsMap,
) =>
selectionCorners.some(
(selectionCorner) =>
(!frameBounds || isPointWithinAabb(selectionCorner, frameBounds)) &&
isPointInElement(selectionCorner, element, elementsMap),
);
const doesSelectionOverlapFilledElement = (
element: NonDeletedExcalidrawElement,
frameBounds: Bounds | null,
selectionBounds: Bounds,
selectionCorners: readonly GlobalPoint[],
selectionEdges: readonly LineSegment<GlobalPoint>[],
elementsMap: ElementsMap,
) => {
if (
doesSelectionContainElementInterior(
element,
frameBounds,
selectionCorners,
elementsMap,
)
) {
return true;
}
if (
doesSelectionIntersectElementOutline(
element,
frameBounds,
selectionEdges,
elementsMap,
)
) {
return true;
}
const outlineSegments = getVisibleElementOutlineSegments(
element,
frameBounds,
elementsMap,
);
return (
outlineSegments.length > 0 &&
doesSelectionContainElementOutline(outlineSegments, selectionBounds)
);
};
/** /**
* Frames and their containing elements are not to be selected at the same time. * Frames and their containing elements are not to be selected at the same time.
* Given an array of selected elements, if there are frames and their containing elements * Given an array of selected elements, if there are frames and their containing elements
@@ -268,18 +85,14 @@ export const excludeElementsInFramesFromSelection = <
} }
}); });
return selectedElements.filter((element) => { return excludeElementsFromFrames(selectedElements, framesInSelection);
if (element.frameId && framesInSelection.has(element.frameId)) {
return false;
}
return true;
});
}; };
export const getElementsWithinSelection = ( export const getElementsWithinSelection = (
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
selection: NonDeletedExcalidrawElement, selection: NonDeletedExcalidrawElement,
elementsMap: ElementsMap, elementsMap: ElementsMap,
// TODO remove (this flag is effectively unused AFAIK)
excludeElementsInFrames: boolean = true, excludeElementsInFrames: boolean = true,
boxSelectionMode: BoxSelectionMode = "contain", boxSelectionMode: BoxSelectionMode = "contain",
): NonDeletedExcalidrawElement[] => { ): NonDeletedExcalidrawElement[] => {
@@ -295,152 +108,233 @@ export const getElementsWithinSelection = (
selectionX2, selectionX2,
selectionY2, selectionY2,
] as Bounds; ] as Bounds;
const selectionEdges = [
lineSegment<GlobalPoint>(
pointFrom(selectionX1, selectionY1),
pointFrom(selectionX2, selectionY1),
),
lineSegment<GlobalPoint>(
pointFrom(selectionX2, selectionY1),
pointFrom(selectionX2, selectionY2),
),
lineSegment<GlobalPoint>(
pointFrom(selectionX2, selectionY2),
pointFrom(selectionX1, selectionY2),
),
lineSegment<GlobalPoint>(
pointFrom(selectionX1, selectionY2),
pointFrom(selectionX1, selectionY1),
),
];
if (boxSelectionMode !== "overlap") { const framesInSelection = excludeElementsInFrames
const elementsInSelection: NonDeletedExcalidrawElement[] = []; ? new Set<NonDeletedExcalidrawElement["id"]>()
: null;
for (const element of elements) { let elementsInSelection: NonDeletedExcalidrawElement[] = [];
if (shouldSkipElementFromSelection(element)) {
continue;
}
const elementBounds = getElementBounds(element, elementsMap) as Bounds;
const frameBounds = getFrameBoundsForSelection(element, elementsMap);
let elementX1 = elementBounds[0];
let elementY1 = elementBounds[1];
let elementX2 = elementBounds[2];
let elementY2 = elementBounds[3];
if (frameBounds) {
elementX1 = Math.max(frameBounds[0], elementX1);
elementY1 = Math.max(frameBounds[1], elementY1);
elementX2 = Math.min(frameBounds[2], elementX2);
elementY2 = Math.min(frameBounds[3], elementY2);
}
if (
selectionX1 <= elementX1 &&
selectionY1 <= elementY1 &&
selectionX2 >= elementX2 &&
selectionY2 >= elementY2
) {
elementsInSelection.push(element);
}
}
return finalizeElementsInSelection(
elementsInSelection,
excludeElementsInFrames,
elementsMap,
);
}
const selectionCorners = getBoundsCorners(selectionBounds);
const selectionEdges = getBoundsEdges(selectionCorners);
const elementsInSelection: NonDeletedExcalidrawElement[] = [];
for (const element of elements) { for (const element of elements) {
if (shouldSkipElementFromSelection(element)) { if (shouldIgnoreElementFromSelection(element)) {
continue; continue;
} }
const elementBounds = getElementBounds(element, elementsMap) as Bounds; const strokeWidth = element.strokeWidth;
const frameBounds = getFrameBoundsForSelection(element, elementsMap); let labelAABB: Bounds | null = null;
let elementX1 = elementBounds[0]; let elementAABB = getElementBounds(element, elementsMap);
let elementY1 = elementBounds[1];
let elementX2 = elementBounds[2];
let elementY2 = elementBounds[3];
if (frameBounds) { elementAABB = [
elementX1 = Math.max(frameBounds[0], elementX1); elementAABB[0] - strokeWidth / 2,
elementY1 = Math.max(frameBounds[1], elementY1); elementAABB[1] - strokeWidth / 2,
elementX2 = Math.min(frameBounds[2], elementX2); elementAABB[2] + strokeWidth / 2,
elementY2 = Math.min(frameBounds[3], elementY2); elementAABB[3] + strokeWidth / 2,
] as Bounds;
// Whether the element bounds should include the bound text element bounds
const boundTextElement =
isArrowElement(element) && getBoundTextElement(element, elementsMap);
if (boundTextElement) {
const { x, y } = LinearElementEditor.getBoundTextElementPosition(
element,
boundTextElement,
elementsMap,
);
labelAABB = [
x,
y,
x + boundTextElement.width,
y + boundTextElement.height,
] as Bounds;
} }
const isSelectionContainingElement = // Clip element bounds by its containing frame (if any), since only the
selectionX1 <= elementX1 && // visible (frame-clipped) portion of the element is relevant for selection.
selectionY1 <= elementY1 && const associatedFrame = getContainingFrame(element, elementsMap);
selectionX2 >= elementX2 && if (
selectionY2 >= elementY2; associatedFrame &&
isElementIntersectingFrame(element, associatedFrame, elementsMap)
) {
const frameAABB = getElementBounds(associatedFrame, elementsMap);
elementAABB = [
Math.max(elementAABB[0], frameAABB[0]),
Math.max(elementAABB[1], frameAABB[1]),
Math.min(elementAABB[2], frameAABB[2]),
Math.min(elementAABB[3], frameAABB[3]),
] as Bounds;
const isSelectionOverlappingElementAabb = labelAABB = labelAABB
selectionX1 <= elementX2 && ? ([
selectionY1 <= elementY2 && Math.max(labelAABB[0], frameAABB[0]),
selectionX2 >= elementX1 && Math.max(labelAABB[1], frameAABB[1]),
selectionY2 >= elementY1; Math.min(labelAABB[2], frameAABB[2]),
const isSelectionOverlappingElement = shouldUseRotatedOverlapBroadPhase( Math.min(labelAABB[3], frameAABB[3]),
element, ] as Bounds)
) : null;
? isSelectionOverlappingElementAabb && }
doBoundsIntersectElementBoundingBox(
selectionBounds, const commonAABB = labelAABB
? ([
Math.min(labelAABB[0], elementAABB[0]),
Math.min(labelAABB[1], elementAABB[1]),
Math.max(labelAABB[2], elementAABB[2]),
Math.max(labelAABB[3], elementAABB[3]),
] as Bounds)
: elementAABB;
// ============== Evaluation ==============
// 1. If the selection box WRAPs the element's AABB, then add it to the
// selection and move on, regardless of the selection mode.
//
// PERF: This trick only works with axis-aligned box selection and the
// current convex element shapes!
if (boundsContainBounds(selectionBounds, commonAABB)) {
if (framesInSelection && isFrameLikeElement(element)) {
framesInSelection.add(element.id);
} else {
elementsInSelection.push(element);
continue;
}
}
// 2. Handle the case where the label is overlapped by the selection box
if (
boxSelectionMode === "overlap" &&
labelAABB &&
doBoundsIntersect(selectionBounds, labelAABB)
) {
elementsInSelection.push(element);
continue;
}
// 3. Handle the case where the selection is not wrapping the element, but
// it does intersect the element's outline (non-AABB).
if (
boxSelectionMode === "overlap" &&
doBoundsIntersect(selectionBounds, elementAABB)
) {
let hasIntersection = false;
// Preliminary check potential intersection imprecision
if (isLinearElement(element) || isFreeDrawElement(element)) {
const center = elementCenterPoint(element, elementsMap);
hasIntersection = element.points.some((point) => {
const rotatedPoint = pointRotateRads(
pointFrom<GlobalPoint>(element.x + point[0], element.y + point[1]),
center,
element.angle,
);
return pointInsideBounds(rotatedPoint, selectionBounds);
});
} else {
const nonRotatedElementBounds = getElementBounds(
element, element,
elementsMap, elementsMap,
) true,
: isSelectionOverlappingElementAabb; );
const center = elementCenterPoint(element, elementsMap);
const shouldSelectFromInside = shouldTestInside(element); hasIntersection = [
pointRotateRads(
if (shouldSelectFromInside) { pointFrom<GlobalPoint>(
if ( (nonRotatedElementBounds[0] + nonRotatedElementBounds[2]) / 2,
isSelectionOverlappingElement && nonRotatedElementBounds[1],
(!shouldUsePreciseFilledOverlap(element) || ),
isSelectionContainingElement || center,
doesSelectionOverlapFilledElement( element.angle,
element, ),
frameBounds, pointRotateRads(
pointFrom<GlobalPoint>(
nonRotatedElementBounds[2],
(nonRotatedElementBounds[1] + nonRotatedElementBounds[3]) / 2,
),
center,
element.angle,
),
pointRotateRads(
pointFrom<GlobalPoint>(
(nonRotatedElementBounds[0] + nonRotatedElementBounds[2]) / 2,
nonRotatedElementBounds[3],
),
center,
element.angle,
),
pointRotateRads(
pointFrom<GlobalPoint>(
nonRotatedElementBounds[0],
(nonRotatedElementBounds[1] + nonRotatedElementBounds[3]) / 2,
),
center,
element.angle,
),
].some((point) => {
return pointInsideBounds(
pointRotateRads(point, center, element.angle),
selectionBounds, selectionBounds,
selectionCorners, );
selectionEdges, });
elementsMap, }
))
) { if (!hasIntersection) {
hasIntersection = selectionEdges.some(
(selectionEdge) =>
intersectElementWithLineSegment(
element,
elementsMap,
selectionEdge,
strokeWidth / 2,
true, // Stop at first hit for better performance
).length > 0,
);
}
if (hasIntersection) {
if (framesInSelection && isFrameLikeElement(element)) {
framesInSelection.add(element.id);
}
elementsInSelection.push(element); elementsInSelection.push(element);
continue;
} }
continue;
} }
if (!isSelectionOverlappingElement) { // 4. We don't need to handle when the selection is inside the element
continue; // as it is separately handled in App.
}
if (isSelectionContainingElement) {
elementsInSelection.push(element);
continue;
}
if (
doesSelectionIntersectElementOutline(
element,
frameBounds,
selectionEdges,
elementsMap,
)
) {
elementsInSelection.push(element);
continue;
}
const outlineSegments = getVisibleElementOutlineSegments(
element,
frameBounds,
elementsMap,
);
if (
outlineSegments.length > 0 &&
doesSelectionContainElementOutline(outlineSegments, selectionBounds)
) {
elementsInSelection.push(element);
}
} }
return finalizeElementsInSelection( elementsInSelection = framesInSelection
elementsInSelection, ? excludeElementsFromFrames(elementsInSelection, framesInSelection)
excludeElementsInFrames, : elementsInSelection;
elementsMap,
); elementsInSelection = elementsInSelection.filter((element) => {
const containingFrame = getContainingFrame(element, elementsMap);
if (containingFrame) {
return elementOverlapsWithFrame(element, containingFrame, elementsMap);
}
return true;
});
return elementsInSelection;
}; };
export const getVisibleAndNonSelectedElements = ( export const getVisibleAndNonSelectedElements = (
+236 -9
View File
@@ -1,4 +1,5 @@
import { simplify } from "points-on-curve"; import { simplify } from "points-on-curve";
import { DEFAULT_FREE_DRAW_STROKE_SHAPE } from "@excalidraw/common";
import { getStroke } from "perfect-freehand"; import { getStroke } from "perfect-freehand";
import { import {
@@ -13,6 +14,7 @@ import {
import { import {
pointFrom, pointFrom,
pointDistance, pointDistance,
round,
type LocalPoint, type LocalPoint,
pointRotateRads, pointRotateRads,
} from "@excalidraw/math"; } from "@excalidraw/math";
@@ -52,6 +54,10 @@ import {
isIframeLikeElement, isIframeLikeElement,
isLinearElement, isLinearElement,
} from "./typeChecks"; } from "./typeChecks";
import {
getRenderableFixedFreeDrawPoints,
isLoopFreeDrawElement,
} from "./freedraw";
import { getCornerRadius, isPathALoop } from "./utils"; import { getCornerRadius, isPathALoop } from "./utils";
import { headingForPointIsHorizontal } from "./heading"; import { headingForPointIsHorizontal } from "./heading";
@@ -244,7 +250,12 @@ export const generateRoughOptions = (
} }
case "line": case "line":
case "freedraw": { case "freedraw": {
if (isPathALoop(element.points)) { const isLoop =
element.type === "freedraw"
? isLoopFreeDrawElement(element)
: isPathALoop(element.points);
if (isLoop) {
options.fillStyle = element.fillStyle; options.fillStyle = element.fillStyle;
options.fill = options.fill =
element.backgroundColor === "transparent" element.backgroundColor === "transparent"
@@ -966,7 +977,7 @@ const _generateElementShape = (
const shapes: ElementShapes[typeof element.type] = []; const shapes: ElementShapes[typeof element.type] = [];
// (1) background fill (rc shape), optional // (1) background fill (rc shape), optional
if (isPathALoop(element.points)) { if (isLoopFreeDrawElement(element)) {
// generate rough polygon to fill freedraw shape // generate rough polygon to fill freedraw shape
const simplifiedPoints = simplify( const simplifiedPoints = simplify(
element.points as Mutable<LocalPoint[]>, element.points as Mutable<LocalPoint[]>,
@@ -1173,6 +1184,13 @@ export const toggleLinePolygonState = (
// NOTE not cached (-> for SVG export) // NOTE not cached (-> for SVG export)
const getFreeDrawSvgPath = (element: ExcalidrawFreeDrawElement) => { const getFreeDrawSvgPath = (element: ExcalidrawFreeDrawElement) => {
if (element.strokeShape === "fixed") {
return getSvgPathFromFixedFreeDrawPoints(
getRenderableFixedFreeDrawPoints(element),
element.strokeWidth,
) as SVGPathString;
}
return getSvgPathFromStroke( return getSvgPathFromStroke(
getFreedrawOutlinePoints(element), getFreedrawOutlinePoints(element),
) as SVGPathString; ) as SVGPathString;
@@ -1181,34 +1199,243 @@ const getFreeDrawSvgPath = (element: ExcalidrawFreeDrawElement) => {
export const getFreedrawOutlinePoints = ( export const getFreedrawOutlinePoints = (
element: ExcalidrawFreeDrawElement, element: ExcalidrawFreeDrawElement,
) => { ) => {
const strokeShape = element.strokeShape ?? DEFAULT_FREE_DRAW_STROKE_SHAPE;
const isFixedStroke = strokeShape === "fixed";
// If input points are empty (should they ever be?) return a dot // If input points are empty (should they ever be?) return a dot
const inputPoints = element.simulatePressure const inputPoints = isFixedStroke
? element.points.length
? element.points
: [[0, 0]]
: element.simulatePressure
? element.points ? element.points
: element.points.length : element.points.length
? element.points.map(([x, y], i) => [x, y, element.pressures[i]]) ? element.points.map(([x, y], i) => [x, y, element.pressures[i]])
: [[0, 0, 0.5]]; : [[0, 0, 0.5]];
return getStroke(inputPoints as number[][], { return getStroke(inputPoints as number[][], {
simulatePressure: element.simulatePressure, simulatePressure: isFixedStroke ? false : element.simulatePressure,
size: element.strokeWidth * 4.25, size: isFixedStroke ? element.strokeWidth : element.strokeWidth * 4.25,
thinning: 0.6, thinning: isFixedStroke ? 0 : 0.6,
smoothing: 0.5, smoothing: 0.5,
streamline: 0.5, streamline: 0.5,
easing: (t) => Math.sin((t * Math.PI) / 2), // https://easings.net/#easeOutSine easing: isFixedStroke ? (t) => t : (t) => Math.sin((t * Math.PI) / 2), // https://easings.net/#easeOutSine
last: true, last: true,
}) as [number, number][]; }) as [number, number][];
}; };
const med = (A: number[], B: number[]) => { const med = (A: readonly number[], B: readonly number[]) => {
return [(A[0] + B[0]) / 2, (A[1] + B[1]) / 2]; return [(A[0] + B[0]) / 2, (A[1] + B[1]) / 2];
}; };
const roundPoint = (point: readonly number[]) =>
`${round(point[0], 2)},${round(point[1], 2)} `;
const averagePoint = (A: readonly number[], B: readonly number[]) =>
`${round((A[0] + B[0]) / 2, 2)},${round((A[1] + B[1]) / 2, 2)} `;
const getReadonlyPointDistance = (
pointA: readonly number[],
pointB: readonly number[],
) => Math.hypot(pointA[0] - pointB[0], pointA[1] - pointB[1]);
// Trim SVG path data so number are each two decimal points. This // Trim SVG path data so number are each two decimal points. This
// improves SVG exports, and prevents rendering errors on points // improves SVG exports, and prevents rendering errors on points
// with long decimals. // with long decimals.
const TO_FIXED_PRECISION = /(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g; const TO_FIXED_PRECISION = /(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g;
const getSvgPathFromStroke = (points: number[][]): string => { const getSvgPathFromPoints = (
points: ReadonlyArray<readonly number[]>,
closed = false,
): string => {
const len = points.length;
if (len < 2) {
return "";
}
const path = points
.slice(1)
.map((point) => `L${roundPoint(point)}`)
.join("");
return `M${roundPoint(points[0])}${path}${closed ? "Z" : ""}`;
};
const FIXED_FREEDRAW_MIN_SMOOTH_ALIGNMENT = 0.6;
const FIXED_FREEDRAW_MIN_SMOOTH_SEGMENT_LENGTH = 0.2;
const FIXED_FREEDRAW_MIN_CORNER_ALIGNMENT = -0.25;
const FIXED_FREEDRAW_MIN_CORNER_ROUNDING = 0.75;
const FIXED_FREEDRAW_MAX_CORNER_ROUNDING = 6;
const FIXED_FREEDRAW_CORNER_ROUNDING_FACTOR = 0.35;
const FIXED_FREEDRAW_CORNER_ROUNDING_WIDTH_FACTOR = 1.5;
const FIXED_FREEDRAW_MIN_TERMINAL_STUB = 0.75;
const FIXED_FREEDRAW_MAX_TERMINAL_STUB = 2.5;
const FIXED_FREEDRAW_TERMINAL_STUB_WIDTH_FACTOR = 1.5;
const shouldSmoothFixedFreeDrawPoint = (
previousPoint: readonly number[],
currentPoint: readonly number[],
nextPoint: readonly number[],
) => {
const previousDeltaX = currentPoint[0] - previousPoint[0];
const previousDeltaY = currentPoint[1] - previousPoint[1];
const nextDeltaX = nextPoint[0] - currentPoint[0];
const nextDeltaY = nextPoint[1] - currentPoint[1];
const previousSegmentLength = Math.hypot(previousDeltaX, previousDeltaY);
const nextSegmentLength = Math.hypot(nextDeltaX, nextDeltaY);
if (
previousSegmentLength < FIXED_FREEDRAW_MIN_SMOOTH_SEGMENT_LENGTH ||
nextSegmentLength < FIXED_FREEDRAW_MIN_SMOOTH_SEGMENT_LENGTH
) {
return false;
}
const alignment =
(previousDeltaX * nextDeltaX + previousDeltaY * nextDeltaY) /
(previousSegmentLength * nextSegmentLength);
return alignment >= FIXED_FREEDRAW_MIN_SMOOTH_ALIGNMENT;
};
const getFixedFreeDrawRoundedCorner = (
previousPoint: readonly number[],
currentPoint: readonly number[],
nextPoint: readonly number[],
strokeWidth: number,
) => {
const previousDeltaX = currentPoint[0] - previousPoint[0];
const previousDeltaY = currentPoint[1] - previousPoint[1];
const nextDeltaX = nextPoint[0] - currentPoint[0];
const nextDeltaY = nextPoint[1] - currentPoint[1];
const previousSegmentLength = Math.hypot(previousDeltaX, previousDeltaY);
const nextSegmentLength = Math.hypot(nextDeltaX, nextDeltaY);
if (!previousSegmentLength || !nextSegmentLength) {
return null;
}
const alignment =
(previousDeltaX * nextDeltaX + previousDeltaY * nextDeltaY) /
(previousSegmentLength * nextSegmentLength);
if (
alignment >= FIXED_FREEDRAW_MIN_SMOOTH_ALIGNMENT ||
alignment <= FIXED_FREEDRAW_MIN_CORNER_ALIGNMENT
) {
return null;
}
const cornerRounding = Math.min(
Math.max(
strokeWidth * FIXED_FREEDRAW_CORNER_ROUNDING_WIDTH_FACTOR,
FIXED_FREEDRAW_MIN_CORNER_ROUNDING,
),
previousSegmentLength * FIXED_FREEDRAW_CORNER_ROUNDING_FACTOR,
nextSegmentLength * FIXED_FREEDRAW_CORNER_ROUNDING_FACTOR,
FIXED_FREEDRAW_MAX_CORNER_ROUNDING,
);
if (!cornerRounding) {
return null;
}
return {
entryPoint: [
currentPoint[0] - (previousDeltaX / previousSegmentLength) * cornerRounding,
currentPoint[1] - (previousDeltaY / previousSegmentLength) * cornerRounding,
] as const,
exitPoint: [
currentPoint[0] + (nextDeltaX / nextSegmentLength) * cornerRounding,
currentPoint[1] + (nextDeltaY / nextSegmentLength) * cornerRounding,
] as const,
};
};
const getFixedFreeDrawTerminalStubThreshold = (strokeWidth: number) =>
Math.min(
Math.max(
strokeWidth * FIXED_FREEDRAW_TERMINAL_STUB_WIDTH_FACTOR,
FIXED_FREEDRAW_MIN_TERMINAL_STUB,
),
FIXED_FREEDRAW_MAX_TERMINAL_STUB,
);
const getSvgPathFromFixedFreeDrawPoints = (
points: ReadonlyArray<readonly number[]>,
strokeWidth: number,
): string => {
const len = points.length;
if (len < 2) {
return "";
}
if (len === 2) {
return `M${roundPoint(points[0])}L${roundPoint(points[1])}`;
}
let path = `M${roundPoint(points[0])}`;
const lastPoint = points[len - 1];
let endsAtLastPoint = false;
for (let index = 1; index < len - 1; index++) {
const previousPoint = points[index - 1];
const currentPoint = points[index];
const nextPoint = points[index + 1];
const isLastCurveSegment = index === len - 2;
const terminalStubThreshold = getFixedFreeDrawTerminalStubThreshold(
strokeWidth,
);
const shouldSmooth = shouldSmoothFixedFreeDrawPoint(
previousPoint,
currentPoint,
nextPoint,
);
const roundedCorner = shouldSmooth
? null
: getFixedFreeDrawRoundedCorner(
previousPoint,
currentPoint,
nextPoint,
strokeWidth,
);
const shouldCollapseSmoothTerminalStub =
isLastCurveSegment &&
shouldSmooth &&
getReadonlyPointDistance(currentPoint, nextPoint) / 2 <=
terminalStubThreshold;
const shouldCollapseRoundedTerminalStub =
isLastCurveSegment &&
!!roundedCorner &&
getReadonlyPointDistance(roundedCorner.exitPoint, lastPoint) <=
terminalStubThreshold;
path += shouldSmooth
? `Q${roundPoint(currentPoint)}${
shouldCollapseSmoothTerminalStub
? roundPoint(lastPoint)
: averagePoint(currentPoint, nextPoint)
}`
: roundedCorner
? `L${roundPoint(roundedCorner.entryPoint)}Q${roundPoint(
currentPoint,
)}${
shouldCollapseRoundedTerminalStub
? roundPoint(lastPoint)
: roundPoint(roundedCorner.exitPoint)
}`
: `L${roundPoint(currentPoint)}`;
endsAtLastPoint =
shouldCollapseSmoothTerminalStub || shouldCollapseRoundedTerminalStub;
}
return endsAtLastPoint ? path : `${path}L${roundPoint(lastPoint)}`;
};
const getSvgPathFromStroke = (
points: ReadonlyArray<readonly number[]>,
): string => {
if (!points.length) { if (!points.length) {
return ""; return "";
} }
+2
View File
@@ -26,6 +26,7 @@ export type PointerType = "mouse" | "pen" | "touch";
export type StrokeRoundness = "round" | "sharp"; export type StrokeRoundness = "round" | "sharp";
export type RoundnessType = ValueOf<typeof ROUNDNESS>; export type RoundnessType = ValueOf<typeof ROUNDNESS>;
export type StrokeStyle = "solid" | "dashed" | "dotted"; export type StrokeStyle = "solid" | "dashed" | "dotted";
export type FreeDrawStrokeShape = "variable" | "fixed";
export type TextAlign = typeof TEXT_ALIGN[keyof typeof TEXT_ALIGN]; export type TextAlign = typeof TEXT_ALIGN[keyof typeof TEXT_ALIGN];
type VerticalAlignKeys = keyof typeof VERTICAL_ALIGN; type VerticalAlignKeys = keyof typeof VERTICAL_ALIGN;
@@ -390,6 +391,7 @@ export type ExcalidrawFreeDrawElement = _ExcalidrawElementBase &
points: readonly LocalPoint[]; points: readonly LocalPoint[];
pressures: readonly number[]; pressures: readonly number[];
simulatePressure: boolean; simulatePressure: boolean;
strokeShape?: FreeDrawStrokeShape;
}>; }>;
export type FileId = string & { _brand: "FileId" }; export type FileId = string & { _brand: "FileId" };
+30 -1
View File
@@ -6,7 +6,11 @@ import type { LocalPoint } from "@excalidraw/math";
import { getElementAbsoluteCoords, getElementBounds } from "../src/bounds"; import { getElementAbsoluteCoords, getElementBounds } from "../src/bounds";
import type { ExcalidrawElement, ExcalidrawLinearElement } from "../src/types"; import type {
ExcalidrawElement,
ExcalidrawFreeDrawElement,
ExcalidrawLinearElement,
} from "../src/types";
const _ce = ({ const _ce = ({
x, x,
@@ -117,6 +121,31 @@ describe("getElementBounds", () => {
expect(y2).toEqual(42.90569415042095); expect(y2).toEqual(42.90569415042095);
}); });
it("fixed freedraw", () => {
const element = {
..._ce({
x: 40,
y: 30,
w: 10,
h: 0,
a: 0,
t: "freedraw",
}),
strokeWidth: 8,
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(10, 0)],
pressures: [],
simulatePressure: true,
strokeShape: "fixed",
} as unknown as ExcalidrawFreeDrawElement;
const [x1, y1, x2, y2] = getElementBounds(element, arrayToMap([element]));
expect(x1).toEqual(36);
expect(y1).toEqual(26);
expect(x2).toEqual(54);
expect(y2).toEqual(34);
});
it("curved line", () => { it("curved line", () => {
const element = { const element = {
..._ce({ ..._ce({
+4 -2
View File
@@ -1,4 +1,4 @@
import { arrayToMap } from "@excalidraw/common"; import { arrayToMap, reseed } from "@excalidraw/common";
import { type GlobalPoint, type LocalPoint, pointFrom } from "@excalidraw/math"; import { type GlobalPoint, type LocalPoint, pointFrom } from "@excalidraw/math";
import { Excalidraw } from "@excalidraw/excalidraw"; import { Excalidraw } from "@excalidraw/excalidraw";
import { API } from "@excalidraw/excalidraw/tests/helpers/api"; import { API } from "@excalidraw/excalidraw/tests/helpers/api";
@@ -12,6 +12,7 @@ import { hitElementItself } from "../src/collision";
describe("check rotated elements can be hit:", () => { describe("check rotated elements can be hit:", () => {
beforeEach(async () => { beforeEach(async () => {
localStorage.clear(); localStorage.clear();
reseed(7);
await render(<Excalidraw handleKeyboardGlobally={true} />); await render(<Excalidraw handleKeyboardGlobally={true} />);
}); });
@@ -29,7 +30,7 @@ describe("check rotated elements can be hit:", () => {
] as LocalPoint[], ] as LocalPoint[],
}); });
const hit = hitElementItself({ const hit = hitElementItself({
point: pointFrom<GlobalPoint>(87, -67), point: pointFrom<GlobalPoint>(88, -68),
element: window.h.elements[0], element: window.h.elements[0],
threshold: 10, threshold: 10,
elementsMap: window.h.scene.getNonDeletedElementsMap(), elementsMap: window.h.scene.getNonDeletedElementsMap(),
@@ -56,6 +57,7 @@ describe("hitElementItself cache", () => {
}); });
localStorage.clear(); localStorage.clear();
reseed(7);
await render(<Excalidraw handleKeyboardGlobally={true} />); await render(<Excalidraw handleKeyboardGlobally={true} />);
}); });
+160
View File
@@ -0,0 +1,160 @@
import { pointFrom } from "@excalidraw/math";
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { vi } from "vitest";
vi.mock("perfect-freehand", () => ({
getStroke: vi.fn(() => []),
}));
import { getStroke } from "perfect-freehand";
import { getFreedrawOutlinePoints, ShapeCache } from "../src/shape";
describe("freedraw stroke shape", () => {
beforeEach(() => {
vi.mocked(getStroke).mockClear();
ShapeCache.destroy();
});
it("renders fixed strokes from the centerline path", () => {
const element = API.createElement({
type: "freedraw",
strokeShape: "fixed",
points: [pointFrom(0, 0), pointFrom(10, 10), pointFrom(20, 15)],
});
const shapes = ShapeCache.generateElementShape(element, null);
expect(shapes).toEqual([expect.any(String)]);
expect(shapes[0]).not.toContain("Z");
expect(vi.mocked(getStroke)).not.toHaveBeenCalled();
});
it("rounds fixed stroke corners without flattening them", () => {
const element = API.createElement({
type: "freedraw",
strokeShape: "fixed",
strokeWidth: 1,
points: [pointFrom(0, 0), pointFrom(10, 0), pointFrom(10, 10)],
});
const [path] = ShapeCache.generateElementShape(element, null);
expect(path).toBe("M0,0 L8.5,0 Q10,0 10,1.5 L10,10 ");
});
it("does not round fixed stroke hairpin turns", () => {
const element = API.createElement({
type: "freedraw",
strokeShape: "fixed",
strokeWidth: 1,
points: [pointFrom(0, 0), pointFrom(10, 0), pointFrom(9, 1)],
});
const [path] = ShapeCache.generateElementShape(element, null);
expect(path).toBe("M0,0 L10,0 L9,1 ");
});
it("curves directly to the endpoint for tiny final smooth segments", () => {
const element = API.createElement({
type: "freedraw",
strokeShape: "fixed",
strokeWidth: 1,
points: [pointFrom(0, 0), pointFrom(0.5, 0.1), pointFrom(0.8, 0.3)],
});
const [path] = ShapeCache.generateElementShape(element, null);
expect(path).toBe("M0,0 Q0.5,0.1 0.8,0.3 ");
});
it("curves directly to the endpoint for tiny final rounded corners", () => {
const element = API.createElement({
type: "freedraw",
strokeShape: "fixed",
strokeWidth: 1,
points: [pointFrom(0, 0), pointFrom(10, 0), pointFrom(10, 1)],
});
const [path] = ShapeCache.generateElementShape(element, null);
expect(path).toBe("M0,0 L9.65,0 Q10,0 10,1 ");
});
it("smooths dense fixed stroke points without dropping them", () => {
const element = API.createElement({
type: "freedraw",
strokeShape: "fixed",
points: [
pointFrom(0, 0),
pointFrom(0.3, 0.1),
pointFrom(0.6, 0.35),
pointFrom(1, 0.9),
],
});
const [path] = ShapeCache.generateElementShape(element, null);
expect(path).toContain("Q0.3,0.1 ");
expect(path).toContain("Q0.6,0.35 ");
});
it("drops synthetic loop closure for fixed strokes", () => {
const element = API.createElement({
type: "freedraw",
strokeShape: "fixed",
points: [pointFrom(0, 0), pointFrom(10, 0), pointFrom(0, 0)],
});
const [path] = ShapeCache.generateElementShape(element, null);
expect(path).toBe("M0,0 L10,0 ");
});
it("uses fixed perfect-freehand settings for fixed strokes", () => {
const element = API.createElement({
type: "freedraw",
strokeShape: "fixed",
strokeWidth: 8,
points: [pointFrom(0, 0), pointFrom(10, 10), pointFrom(20, 15)],
});
getFreedrawOutlinePoints(element);
expect(vi.mocked(getStroke)).toHaveBeenCalledWith(
element.points,
expect.objectContaining({
simulatePressure: false,
size: element.strokeWidth,
thinning: 0,
}),
);
});
it("keeps pressure-aware perfect-freehand settings for variable strokes", () => {
const element = API.createElement({
type: "freedraw",
points: [pointFrom(0, 0), pointFrom(10, 10), pointFrom(20, 15)],
});
getFreedrawOutlinePoints({
...element,
simulatePressure: false,
pressures: [0.2, 0.8, 0.4],
});
expect(vi.mocked(getStroke)).toHaveBeenCalledWith(
[
[0, 0, 0.2],
[10, 10, 0.8],
[20, 15, 0.4],
],
expect.objectContaining({
simulatePressure: false,
size: element.strokeWidth * 4.25,
thinning: 0.6,
}),
);
});
});
@@ -2,6 +2,7 @@ import { pointFrom } from "@excalidraw/math";
import { bindOrUnbindBindingElement } from "@excalidraw/element/binding"; import { bindOrUnbindBindingElement } from "@excalidraw/element/binding";
import { import {
isLoopFreeDrawElement,
isValidPolygon, isValidPolygon,
LinearElementEditor, LinearElementEditor,
newElementWith, newElementWith,
@@ -242,7 +243,11 @@ export const actionFinalize = register<FormData>({
// If the multi point line closes the loop, // If the multi point line closes the loop,
// set the last point to first point. // set the last point to first point.
// This ensures that loop remains closed at different scales. // This ensures that loop remains closed at different scales.
const isLoop = isPathALoop(element.points, appState.zoom.value); const isLoop = isLineElement(element)
? isPathALoop(element.points, appState.zoom.value)
: isFreeDrawElement(element)
? isLoopFreeDrawElement(element, appState.zoom.value)
: false;
if (isLoop && (isLineElement(element) || isFreeDrawElement(element))) { if (isLoop && (isLineElement(element) || isFreeDrawElement(element))) {
const linePoints = element.points; const linePoints = element.points;
@@ -1,4 +1,5 @@
import { queryByTestId } from "@testing-library/react"; import { queryByTestId } from "@testing-library/react";
import { pointFrom } from "@excalidraw/math";
import { import {
COLOR_PALETTE, COLOR_PALETTE,
@@ -10,7 +11,7 @@ import {
import { Excalidraw } from "../index"; import { Excalidraw } from "../index";
import { API } from "../tests/helpers/api"; import { API } from "../tests/helpers/api";
import { UI } from "../tests/helpers/ui"; import { UI } from "../tests/helpers/ui";
import { render } from "../tests/test-utils"; import { act, render } from "../tests/test-utils";
describe("element locking", () => { describe("element locking", () => {
beforeEach(async () => { beforeEach(async () => {
@@ -80,6 +81,20 @@ describe("element locking", () => {
const centerTextAlign = queryByTestId(document.body, `align-right`); const centerTextAlign = queryByTestId(document.body, `align-right`);
expect(centerTextAlign).toBeChecked(); expect(centerTextAlign).toBeChecked();
}); });
it("should show the active freedraw stroke type", () => {
UI.clickTool("freedraw");
API.setAppState({
currentItemStrokeShape: "fixed",
});
const fixedStrokeShape = queryByTestId(
document.body,
"strokeShape-fixed",
);
expect(fixedStrokeShape).toBeChecked();
});
}); });
describe("properties when elements selected", () => { describe("properties when elements selected", () => {
@@ -144,6 +159,9 @@ describe("element locking", () => {
expect( expect(
queryByTestId(document.body, `strokeWidth-thin`), queryByTestId(document.body, `strokeWidth-thin`),
).not.toBeChecked(); ).not.toBeChecked();
expect(
queryByTestId(document.body, `strokeWidth-medium`),
).not.toBeChecked();
expect( expect(
queryByTestId(document.body, `strokeWidth-bold`), queryByTestId(document.body, `strokeWidth-bold`),
).not.toBeChecked(); ).not.toBeChecked();
@@ -159,6 +177,7 @@ describe("element locking", () => {
}); });
const text = API.createElement({ const text = API.createElement({
type: "text", type: "text",
strokeWidth: STROKE_WIDTH.bold,
fontFamily: FONT_FAMILY["Comic Shanns"], fontFamily: FONT_FAMILY["Comic Shanns"],
}); });
API.setElements([rect, text]); API.setElements([rect, text]);
@@ -169,5 +188,35 @@ describe("element locking", () => {
"active", "active",
); );
}); });
it("should highlight the fixed freedraw stroke type for selected elements", () => {
const freedraw = API.createElement({
type: "freedraw",
strokeShape: "fixed",
points: [pointFrom(0, 0), pointFrom(10, 10), pointFrom(20, 15)],
});
API.setElements([freedraw]);
API.setSelectedElements([freedraw]);
const fixedStrokeShape = queryByTestId(
document.body,
"strokeShape-fixed",
);
expect(fixedStrokeShape).toBeChecked();
});
it("should apply fixed freedraw stroke type to newly drawn strokes", () => {
UI.clickTool("freedraw");
act(() => {
queryByTestId(document.body, "strokeShape-fixed")?.click();
});
const freedraw = UI.createElement("freedraw", {
points: [pointFrom(0, 0), pointFrom(10, 10), pointFrom(20, 15)],
});
expect(freedraw.strokeShape).toBe("fixed");
});
}); });
}); });
@@ -3,6 +3,7 @@ import { pointFrom } from "@excalidraw/math";
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { import {
DEFAULT_FREE_DRAW_STROKE_SHAPE,
DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE, DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE,
DEFAULT_ELEMENT_BACKGROUND_PICKS, DEFAULT_ELEMENT_BACKGROUND_PICKS,
DEFAULT_ELEMENT_STROKE_COLOR_PALETTE, DEFAULT_ELEMENT_STROKE_COLOR_PALETTE,
@@ -36,6 +37,7 @@ import {
import { LinearElementEditor } from "@excalidraw/element"; import { LinearElementEditor } from "@excalidraw/element";
import { newElementWith } from "@excalidraw/element"; import { newElementWith } from "@excalidraw/element";
import { newFreeDrawElementWithStrokeShape } from "@excalidraw/element";
import { getArrowheadForPicker } from "@excalidraw/element"; import { getArrowheadForPicker } from "@excalidraw/element";
import { import {
@@ -47,6 +49,7 @@ import {
isArrowElement, isArrowElement,
isBoundToContainer, isBoundToContainer,
isElbowArrow, isElbowArrow,
isFreeDrawElement,
isLinearElement, isLinearElement,
isLineElement, isLineElement,
isTextElement, isTextElement,
@@ -70,6 +73,7 @@ import type {
ElementsMap, ElementsMap,
ExcalidrawBindableElement, ExcalidrawBindableElement,
ExcalidrawElement, ExcalidrawElement,
ExcalidrawFreeDrawElement,
ExcalidrawLinearElement, ExcalidrawLinearElement,
ExcalidrawTextElement, ExcalidrawTextElement,
FontFamilyValues, FontFamilyValues,
@@ -105,8 +109,11 @@ import {
SloppinessArtistIcon, SloppinessArtistIcon,
SloppinessCartoonistIcon, SloppinessCartoonistIcon,
StrokeWidthBaseIcon, StrokeWidthBaseIcon,
StrokeWidthMediumIcon,
StrokeWidthBoldIcon, StrokeWidthBoldIcon,
StrokeWidthExtraBoldIcon, StrokeWidthExtraBoldIcon,
StrokeShapeFixedIcon,
StrokeShapeVariableIcon,
FontSizeSmallIcon, FontSizeSmallIcon,
FontSizeMediumIcon, FontSizeMediumIcon,
FontSizeLargeIcon, FontSizeLargeIcon,
@@ -187,6 +194,29 @@ export const changeProperty = (
}); });
}; };
const getFreeDrawStrokeShape = (item: {
strokeShape?: ExcalidrawFreeDrawElement["strokeShape"];
currentItemStrokeShape?: AppState["currentItemStrokeShape"];
}) =>
item.strokeShape ??
item.currentItemStrokeShape ??
DEFAULT_FREE_DRAW_STROKE_SHAPE;
const getAppStateWithCurrentItemStrokeShape = (
appState: AppState,
strokeShape: NonNullable<ExcalidrawFreeDrawElement["strokeShape"]>,
) => {
// if (strokeShape === DEFAULT_FREE_DRAW_STROKE_SHAPE) {
// const { currentItemStrokeShape, ...nextAppState } = appState;
// return nextAppState;
// }
return {
...appState,
currentItemStrokeShape: strokeShape,
};
};
export const getFormValue = function <T extends Primitive>( export const getFormValue = function <T extends Primitive>(
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
app: AppClassProperties, app: AppClassProperties,
@@ -574,6 +604,12 @@ export const actionChangeStrokeWidth = register<
icon: StrokeWidthBaseIcon, icon: StrokeWidthBaseIcon,
testId: "strokeWidth-thin", testId: "strokeWidth-thin",
}, },
{
value: STROKE_WIDTH.medium,
text: t("labels.medium"),
icon: StrokeWidthMediumIcon,
testId: "strokeWidth-medium",
},
{ {
value: STROKE_WIDTH.bold, value: STROKE_WIDTH.bold,
text: t("labels.bold"), text: t("labels.bold"),
@@ -602,6 +638,60 @@ export const actionChangeStrokeWidth = register<
), ),
}); });
export const actionChangeStrokeShape = register<
NonNullable<ExcalidrawFreeDrawElement["strokeShape"]>
>({
name: "changeStrokeShape",
label: "labels.strokeShape",
trackEvent: false,
perform: (elements, appState, value) => {
invariant(value, "actionChangeStrokeShape: value must be defined");
return {
elements: changeProperty(elements, appState, (el) =>
isFreeDrawElement(el)
? newFreeDrawElementWithStrokeShape(el, value)
: el,
),
appState: getAppStateWithCurrentItemStrokeShape(appState, value),
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
PanelComponent: ({ elements, appState, updateData, app }) => (
<fieldset>
<legend>{t("labels.strokeShape")}</legend>
<div className="buttonList">
<RadioSelection
group="stroke-shape"
options={[
{
value: "variable",
text: t("labels.strokeShape_variable"),
icon: StrokeShapeVariableIcon,
testId: "strokeShape-variable",
},
{
value: "fixed",
text: t("labels.strokeShape_fixed"),
icon: StrokeShapeFixedIcon,
testId: "strokeShape-fixed",
},
]}
value={getFormValue(
elements,
app,
(element) =>
getFreeDrawStrokeShape(element as ExcalidrawFreeDrawElement),
isFreeDrawElement,
(hasSelection) =>
hasSelection ? null : getFreeDrawStrokeShape(appState),
)}
onChange={(value) => updateData(value)}
/>
</div>
</fieldset>
),
});
export const actionChangeSloppiness = register<ExcalidrawElement["roughness"]>({ export const actionChangeSloppiness = register<ExcalidrawElement["roughness"]>({
name: "changeSloppiness", name: "changeSloppiness",
label: "labels.sloppiness", label: "labels.sloppiness",
@@ -1,4 +1,5 @@
import { import {
DEFAULT_FREE_DRAW_STROKE_SHAPE,
DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE,
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_TEXT_ALIGN, DEFAULT_TEXT_ALIGN,
@@ -10,6 +11,7 @@ import {
import { newElementWith } from "@excalidraw/element"; import { newElementWith } from "@excalidraw/element";
import { import {
isFreeDrawElement,
hasBoundTextElement, hasBoundTextElement,
canApplyRoundnessTypeToElement, canApplyRoundnessTypeToElement,
getDefaultRoundnessTypeForElement, getDefaultRoundnessTypeForElement,
@@ -18,6 +20,7 @@ import {
isExcalidrawElement, isExcalidrawElement,
isTextElement, isTextElement,
} from "@excalidraw/element"; } from "@excalidraw/element";
import { newFreeDrawElementWithStrokeShape } from "@excalidraw/element";
import { import {
getBoundTextElement, getBoundTextElement,
@@ -154,6 +157,17 @@ export const actionPasteStyles = register({
}); });
} }
if (
isFreeDrawElement(newElement) &&
isFreeDrawElement(elementStylesToCopyFrom)
) {
newElement = newFreeDrawElementWithStrokeShape(
newElement,
elementStylesToCopyFrom.strokeShape ??
DEFAULT_FREE_DRAW_STROKE_SHAPE,
);
}
if (isFrameLikeElement(element)) { if (isFrameLikeElement(element)) {
newElement = newElementWith(newElement, { newElement = newElementWith(newElement, {
roundness: null, roundness: null,
+2
View File
@@ -128,6 +128,7 @@ export const getDefaultAppState = (): Omit<
lockedMultiSelections: {}, lockedMultiSelections: {},
activeLockedId: null, activeLockedId: null,
bindMode: "orbit", bindMode: "orbit",
boxSelectionMode: "contain",
}; };
}; };
@@ -171,6 +172,7 @@ const APP_STATE_STORAGE_CONF = (<
currentItemStrokeColor: { browser: true, export: false, server: false }, currentItemStrokeColor: { browser: true, export: false, server: false },
currentItemStrokeStyle: { browser: true, export: false, server: false }, currentItemStrokeStyle: { browser: true, export: false, server: false },
currentItemStrokeWidth: { browser: true, export: false, server: false }, currentItemStrokeWidth: { browser: true, export: false, server: false },
currentItemStrokeShape: { browser: true, export: false, server: false },
currentItemTextAlign: { browser: true, export: false, server: false }, currentItemTextAlign: { browser: true, export: false, server: false },
currentHoveredFontFamily: { browser: false, export: false, server: false }, currentHoveredFontFamily: { browser: false, export: false, server: false },
cursorButton: { browser: true, export: false, server: false }, cursorButton: { browser: true, export: false, server: false },
@@ -394,6 +394,11 @@ const CombinedShapeProperties = ({
hasStrokeWidth(element.type), hasStrokeWidth(element.type),
)) && )) &&
renderAction("changeStrokeWidth")} renderAction("changeStrokeWidth")}
{(appState.activeTool.type === "freedraw" ||
targetElements.some(
(element) => element.type === "freedraw",
)) &&
renderAction("changeStrokeShape")}
{(hasStrokeStyle(appState.activeTool.type) || {(hasStrokeStyle(appState.activeTool.type) ||
targetElements.some((element) => targetElements.some((element) =>
hasStrokeStyle(element.type), hasStrokeStyle(element.type),
+90 -30
View File
@@ -9,6 +9,7 @@ import {
clamp, clamp,
pointFrom, pointFrom,
pointDistance, pointDistance,
round,
vector, vector,
pointRotateRads, pointRotateRads,
vectorFromPoint, vectorFromPoint,
@@ -119,6 +120,7 @@ import {
getElementAbsoluteCoords, getElementAbsoluteCoords,
bindOrUnbindBindingElements, bindOrUnbindBindingElements,
fixBindingsAfterDeletion, fixBindingsAfterDeletion,
getFixedFreeDrawPointAction,
getHoveredElementForBinding, getHoveredElementForBinding,
isBindingEnabled, isBindingEnabled,
updateBoundElements, updateBoundElements,
@@ -246,7 +248,7 @@ import {
bindOrUnbindBindingElement, bindOrUnbindBindingElement,
mutateElement, mutateElement,
getElementBounds, getElementBounds,
doNonRotatedBoundsIntersect, doBoundsIntersect,
isPointInElement, isPointInElement,
maxBindingDistance_simple, maxBindingDistance_simple,
convertToExcalidrawElements, convertToExcalidrawElements,
@@ -615,6 +617,19 @@ const gesture: Gesture = {
initialScale: null, initialScale: null,
}; };
const FREEDRAW_POINT_DECIMALS = 2;
const FREEDRAW_PRESSURE_DECIMALS = 3;
const FREEDRAW_DOT_EPSILON = 1 / 10 ** FREEDRAW_POINT_DECIMALS;
const roundFreeDrawCoordinate = (value: number) =>
round(value, FREEDRAW_POINT_DECIMALS);
const roundFreeDrawPressure = (value: number) =>
round(value, FREEDRAW_PRESSURE_DECIMALS);
const getRoundedFreeDrawPoint = (x: number, y: number) =>
pointFrom<LocalPoint>(roundFreeDrawCoordinate(x), roundFreeDrawCoordinate(y));
class App extends React.Component<AppProps, AppState> { class App extends React.Component<AppProps, AppState> {
canvas: AppClassProperties["canvas"]; canvas: AppClassProperties["canvas"];
interactiveCanvas: AppClassProperties["interactiveCanvas"] = null; interactiveCanvas: AppClassProperties["interactiveCanvas"] = null;
@@ -1154,7 +1169,7 @@ class App extends React.Component<AppProps, AppState> {
startBounds && startBounds &&
endBounds && endBounds &&
startElement.id !== endElement.id && startElement.id !== endElement.id &&
doNonRotatedBoundsIntersect(startBounds, endBounds) doBoundsIntersect(startBounds, endBounds)
); );
} }
@@ -2525,6 +2540,7 @@ class App extends React.Component<AppProps, AppState> {
const magicFrameChildren = getElementsOverlappingFrame( const magicFrameChildren = getElementsOverlappingFrame(
this.scene.getNonDeletedElements(), this.scene.getNonDeletedElements(),
magicFrame, magicFrame,
this.scene.getNonDeletedElementsMap(),
).filter((el) => !isMagicFrameElement(el)); ).filter((el) => !isMagicFrameElement(el));
if (!magicFrameChildren.length) { if (!magicFrameChildren.length) {
@@ -8079,7 +8095,7 @@ class App extends React.Component<AppProps, AppState> {
setCursor(this.interactiveCanvas, CURSOR_TYPE.GRABBING); setCursor(this.interactiveCanvas, CURSOR_TYPE.GRABBING);
let { clientX: lastX, clientY: lastY } = event; let { clientX: lastX, clientY: lastY } = event;
const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => { const onPointerMove = ((event: PointerEvent) => {
const deltaX = lastX - event.clientX; const deltaX = lastX - event.clientX;
const deltaY = lastY - event.clientY; const deltaY = lastY - event.clientY;
lastX = event.clientX; lastX = event.clientX;
@@ -8145,7 +8161,7 @@ class App extends React.Component<AppProps, AppState> {
window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove); window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
window.removeEventListener(EVENT.POINTER_UP, teardown); window.removeEventListener(EVENT.POINTER_UP, teardown);
window.removeEventListener(EVENT.BLUR, teardown); window.removeEventListener(EVENT.BLUR, teardown);
onPointerMove.flush(); // onPointerMove.flush();
}), }),
); );
window.addEventListener(EVENT.BLUR, teardown); window.addEventListener(EVENT.BLUR, teardown);
@@ -8255,14 +8271,14 @@ class App extends React.Component<AppProps, AppState> {
isDraggingScrollBar = true; isDraggingScrollBar = true;
pointerDownState.lastCoords.x = event.clientX; pointerDownState.lastCoords.x = event.clientX;
pointerDownState.lastCoords.y = event.clientY; pointerDownState.lastCoords.y = event.clientY;
const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => { const onPointerMove = (event: PointerEvent) => {
const target = event.target; const target = event.target;
if (!(target instanceof HTMLElement)) { if (!(target instanceof HTMLElement)) {
return; return;
} }
this.handlePointerMoveOverScrollbars(event, pointerDownState); this.handlePointerMoveOverScrollbars(event, pointerDownState);
}); };
const onPointerUp = withBatchedUpdates(() => { const onPointerUp = withBatchedUpdates(() => {
lastPointerUp = null; lastPointerUp = null;
isDraggingScrollBar = false; isDraggingScrollBar = false;
@@ -8273,7 +8289,7 @@ class App extends React.Component<AppProps, AppState> {
this.savePointer(event.clientX, event.clientY, "up"); this.savePointer(event.clientX, event.clientY, "up");
window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove); window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
window.removeEventListener(EVENT.POINTER_UP, onPointerUp); window.removeEventListener(EVENT.POINTER_UP, onPointerUp);
onPointerMove.flush(); // onPointerMove.flush();
}); });
lastPointerUp = onPointerUp; lastPointerUp = onPointerUp;
@@ -8832,10 +8848,13 @@ class App extends React.Component<AppProps, AppState> {
opacity: this.state.currentItemOpacity, opacity: this.state.currentItemOpacity,
roundness: null, roundness: null,
simulatePressure, simulatePressure,
strokeShape: this.state.currentItemStrokeShape,
locked: false, locked: false,
frameId: topLayerFrame ? topLayerFrame.id : null, frameId: topLayerFrame ? topLayerFrame.id : null,
points: [pointFrom<LocalPoint>(0, 0)], points: [pointFrom<LocalPoint>(0, 0)],
pressures: simulatePressure ? [] : [event.pressure], pressures: simulatePressure
? []
: [roundFreeDrawPressure(event.pressure)],
}); });
this.scene.insertElement(element); this.scene.insertElement(element);
@@ -9477,7 +9496,7 @@ class App extends React.Component<AppProps, AppState> {
private onPointerMoveFromPointerDownHandler( private onPointerMoveFromPointerDownHandler(
pointerDownState: PointerDownState, pointerDownState: PointerDownState,
) { ) {
return withBatchedUpdatesThrottled((event: PointerEvent) => { return (event: PointerEvent) => {
if (this.state.openDialog?.name === "elementLinkSelector") { if (this.state.openDialog?.name === "elementLinkSelector") {
return; return;
} }
@@ -10173,20 +10192,36 @@ class App extends React.Component<AppProps, AppState> {
const points = newElement.points; const points = newElement.points;
const dx = pointerCoords.x - newElement.x; const dx = pointerCoords.x - newElement.x;
const dy = pointerCoords.y - newElement.y; const dy = pointerCoords.y - newElement.y;
const nextPoint = getRoundedFreeDrawPoint(dx, dy);
const pressure = roundFreeDrawPressure(event.pressure);
const pointAction =
newElement.strokeShape === "fixed"
? getFixedFreeDrawPointAction({
points,
nextPoint,
strokeWidth: newElement.strokeWidth,
zoomValue: this.state.zoom.value,
})
: points.length > 0 &&
points[points.length - 1][0] === nextPoint[0] &&
points[points.length - 1][1] === nextPoint[1]
? "discard"
: "append";
const lastPoint = points.length > 0 && points[points.length - 1]; if (pointAction !== "discard") {
const discardPoint =
lastPoint && lastPoint[0] === dx && lastPoint[1] === dy;
if (!discardPoint) {
const pressures = newElement.simulatePressure const pressures = newElement.simulatePressure
? newElement.pressures ? newElement.pressures
: [...newElement.pressures, event.pressure]; : pointAction === "replace"
? [...newElement.pressures.slice(0, -1), pressure]
: [...newElement.pressures, pressure];
this.scene.mutateElement( this.scene.mutateElement(
newElement, newElement,
{ {
points: [...points, pointFrom<LocalPoint>(dx, dy)], points:
pointAction === "replace"
? [...points.slice(0, -1), nextPoint]
: [...points, nextPoint],
pressures, pressures,
}, },
{ {
@@ -10344,7 +10379,7 @@ class App extends React.Component<AppProps, AppState> {
}); });
} }
} }
}); };
} }
// Returns whether the pointer move happened over either scrollbar // Returns whether the pointer move happened over either scrollbar
@@ -10389,7 +10424,7 @@ class App extends React.Component<AppProps, AppState> {
this.removePointer(childEvent); this.removePointer(childEvent);
pointerDownState.drag.blockDragging = false; pointerDownState.drag.blockDragging = false;
if (pointerDownState.eventListeners.onMove) { if (pointerDownState.eventListeners.onMove) {
pointerDownState.eventListeners.onMove.flush(); // pointerDownState.eventListeners.onMove.flush();
} }
const { const {
newElement, newElement,
@@ -10626,23 +10661,48 @@ class App extends React.Component<AppProps, AppState> {
); );
const points = newElement.points; const points = newElement.points;
let dx = pointerCoords.x - newElement.x; const dx = pointerCoords.x - newElement.x;
let dy = pointerCoords.y - newElement.y; const dy = pointerCoords.y - newElement.y;
let nextPoint = getRoundedFreeDrawPoint(dx, dy);
// Allows dots to avoid being flagged as infinitely small // Allows dots to avoid being flagged as infinitely small
if (dx === points[0][0] && dy === points[0][1]) { if (nextPoint[0] === points[0][0] && nextPoint[1] === points[0][1]) {
dy += 0.0001; nextPoint = getRoundedFreeDrawPoint(
dx += 0.0001; dx + FREEDRAW_DOT_EPSILON,
dy + FREEDRAW_DOT_EPSILON,
);
} }
const pressures = newElement.simulatePressure const lastPoint = points[points.length - 1];
? [] const pressure = roundFreeDrawPressure(childEvent.pressure);
: [...newElement.pressures, childEvent.pressure]; const pointAction =
newElement.strokeShape === "fixed"
? getFixedFreeDrawPointAction({
points,
nextPoint,
strokeWidth: newElement.strokeWidth,
zoomValue: this.state.zoom.value,
isFinalPoint: true,
})
: !lastPoint ||
lastPoint[0] !== nextPoint[0] ||
lastPoint[1] !== nextPoint[1]
? "append"
: "discard";
this.scene.mutateElement(newElement, { if (pointAction !== "discard") {
points: [...points, pointFrom<LocalPoint>(dx, dy)], this.scene.mutateElement(newElement, {
pressures, points:
}); pointAction === "replace"
? [...points.slice(0, -1), nextPoint]
: [...points, nextPoint],
pressures: newElement.simulatePressure
? []
: pointAction === "replace"
? [...newElement.pressures.slice(0, -1), pressure]
: [...newElement.pressures, pressure],
});
}
this.actionManager.executeAction(actionFinalize); this.actionManager.executeAction(actionFinalize);
@@ -750,7 +750,7 @@ describe("frame resizing behavior", () => {
x: 0, x: 0,
y: 0, y: 0,
width: 100, width: 100,
height: 100, height: 103,
}); });
// Create a rectangle outside the frame // Create a rectangle outside the frame
+44 -2
View File
@@ -1164,7 +1164,7 @@ export const StrokeWidthBaseIcon = createIcon(
modifiedTablerIconProps, modifiedTablerIconProps,
); );
export const StrokeWidthBoldIcon = createIcon( export const StrokeWidthMediumIcon = createIcon(
<path <path
d="M5 10h10" d="M5 10h10"
stroke="currentColor" stroke="currentColor"
@@ -1175,7 +1175,7 @@ export const StrokeWidthBoldIcon = createIcon(
modifiedTablerIconProps, modifiedTablerIconProps,
); );
export const StrokeWidthExtraBoldIcon = createIcon( export const StrokeWidthBoldIcon = createIcon(
<path <path
d="M5 10h10" d="M5 10h10"
stroke="currentColor" stroke="currentColor"
@@ -1186,6 +1186,48 @@ export const StrokeWidthExtraBoldIcon = createIcon(
modifiedTablerIconProps, modifiedTablerIconProps,
); );
export const StrokeWidthExtraBoldIcon = createIcon(
<path
d="M5 10h10"
stroke="currentColor"
strokeWidth="5"
strokeLinecap="round"
strokeLinejoin="round"
/>,
modifiedTablerIconProps,
);
export const StrokeShapeVariableIcon = createIcon(
<>
<path
d="M3.5 12.5c1.8-3.5 4.1-5.2 6.8-5.2 2.4 0 4.4 1.3 6.2 3.9"
stroke="currentColor"
strokeWidth="1.25"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M7.75 10.8c1-.9 2-1.35 3.05-1.35 1.2 0 2.4.57 3.7 1.72"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</>,
modifiedTablerIconProps,
);
export const StrokeShapeFixedIcon = createIcon(
<path
d="M3.5 12h13"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
/>,
modifiedTablerIconProps,
);
export const StrokeStyleSolidIcon = React.memo(({ theme }: { theme: Theme }) => export const StrokeStyleSolidIcon = React.memo(({ theme }: { theme: Theme }) =>
createIcon( createIcon(
<path <path
@@ -437,16 +437,15 @@ const PreferencesBoxSelectionModeItem = () => {
const { t } = useI18n(); const { t } = useI18n();
const appState = useUIAppState(); const appState = useUIAppState();
const setAppState = useExcalidrawSetAppState(); const setAppState = useExcalidrawSetAppState();
const boxSelectionMode = appState.boxSelectionMode ?? "contain";
return ( return (
<DropdownMenuItemContentRadio<"contain" | "overlap"> <DropdownMenuItemContentRadio<"contain" | "overlap">
name="boxSelectionMode" name="boxSelectionMode"
icon={emptyIcon} icon={emptyIcon}
value={boxSelectionMode} value={appState.boxSelectionMode}
onChange={(value) => { onChange={(value) => {
setAppState({ setAppState({
boxSelectionMode: value === "contain" ? undefined : value, boxSelectionMode: value,
}); });
}} }}
choices={[ choices={[
+7 -1
View File
@@ -6,6 +6,7 @@ import {
MIME_TYPES, MIME_TYPES,
cloneJSON, cloneJSON,
SVG_DOCUMENT_PREAMBLE, SVG_DOCUMENT_PREAMBLE,
arrayToMap,
} from "@excalidraw/common"; } from "@excalidraw/common";
import { getNonDeletedElements } from "@excalidraw/element"; import { getNonDeletedElements } from "@excalidraw/element";
@@ -49,6 +50,7 @@ export const prepareElementsForExport = (
exportSelectionOnly: boolean, exportSelectionOnly: boolean,
) => { ) => {
elements = getNonDeletedElements(elements); elements = getNonDeletedElements(elements);
const elementsMap = arrayToMap(elements);
const isExportingSelection = const isExportingSelection =
exportSelectionOnly && exportSelectionOnly &&
@@ -71,7 +73,11 @@ export const prepareElementsForExport = (
isFrameLikeElement(exportedElements[0]) isFrameLikeElement(exportedElements[0])
) { ) {
exportingFrame = exportedElements[0]; exportingFrame = exportedElements[0];
exportedElements = getElementsOverlappingFrame(elements, exportingFrame); exportedElements = getElementsOverlappingFrame(
elements,
exportingFrame,
elementsMap,
);
} else if (exportedElements.length > 1) { } else if (exportedElements.length > 1) {
exportedElements = getSelectedElements( exportedElements = getSelectedElements(
elements, elements,
+19
View File
@@ -96,6 +96,13 @@ type RestoredAppState = Omit<
"offsetTop" | "offsetLeft" | "width" | "height" "offsetTop" | "offsetLeft" | "width" | "height"
>; >;
const normalizeFreeDrawStrokeShape = (
strokeShape: unknown,
): AppState["currentItemStrokeShape"] =>
strokeShape === "fixed" || strokeShape === "stable"
? "fixed"
: undefined;
export const AllowedExcalidrawActiveTools: Record< export const AllowedExcalidrawActiveTools: Record<
AppState["activeTool"]["type"], AppState["activeTool"]["type"],
boolean boolean
@@ -412,10 +419,12 @@ export const restoreElement = (
return element; return element;
case "freedraw": { case "freedraw": {
const strokeShape = normalizeFreeDrawStrokeShape(element.strokeShape);
return restoreElementWithProperties(element, { return restoreElementWithProperties(element, {
points: element.points, points: element.points,
simulatePressure: element.simulatePressure, simulatePressure: element.simulatePressure,
pressures: element.pressures, pressures: element.pressures,
...(strokeShape ? { strokeShape } : {}),
}); });
} }
case "image": case "image":
@@ -944,6 +953,16 @@ export const restoreAppState = (
return { return {
...nextAppState, ...nextAppState,
...(normalizeFreeDrawStrokeShape(
appState.currentItemStrokeShape ?? localAppState?.currentItemStrokeShape,
)
? {
currentItemStrokeShape: normalizeFreeDrawStrokeShape(
appState.currentItemStrokeShape ??
localAppState?.currentItemStrokeShape,
),
}
: {}),
cursorButton: localAppState?.cursorButton || "up", cursorButton: localAppState?.cursorButton || "up",
// reset on fresh restore so as to hide the UI button if penMode not active // reset on fresh restore so as to hide the UI button if penMode not active
penDetected: penDetected:
+2 -2
View File
@@ -2,7 +2,7 @@ import { arrayToMap, easeOut, THEME } from "@excalidraw/common";
import { import {
computeBoundTextPosition, computeBoundTextPosition,
doNonRotatedBoundsIntersect, doBoundsIntersect,
getBoundTextElement, getBoundTextElement,
getElementBounds, getElementBounds,
getElementLineSegments, getElementLineSegments,
@@ -219,7 +219,7 @@ const eraserTest = (
origElementBounds[3] + threshold, origElementBounds[3] + threshold,
]; ];
if (!doNonRotatedBoundsIntersect(segmentBounds, elementBounds)) { if (!doBoundsIntersect(segmentBounds, elementBounds)) {
return false; return false;
} }
+2 -2
View File
@@ -10,7 +10,7 @@ import { type Bounds } from "@excalidraw/common";
import { import {
computeBoundTextPosition, computeBoundTextPosition,
doNonRotatedBoundsIntersect, doBoundsIntersect,
getBoundTextElement, getBoundTextElement,
getElementBounds, getElementBounds,
intersectElementWithLineSegment, intersectElementWithLineSegment,
@@ -66,7 +66,7 @@ export const getLassoSelectedElementIds = (input: {
const elementBounds = getElementBounds(element, elementsMap); const elementBounds = getElementBounds(element, elementsMap);
if ( if (
doNonRotatedBoundsIntersect(lassoBounds, elementBounds) && doBoundsIntersect(lassoBounds, elementBounds) &&
!intersectedElements.has(element.id) && !intersectedElements.has(element.id) &&
!enclosedElements.has(element.id) !enclosedElements.has(element.id)
) { ) {
+3
View File
@@ -30,6 +30,9 @@
"changeBackground": "Change background color", "changeBackground": "Change background color",
"fill": "Fill", "fill": "Fill",
"strokeWidth": "Stroke width", "strokeWidth": "Stroke width",
"strokeShape": "Stroke type",
"strokeShape_variable": "Variable",
"strokeShape_fixed": "Fixed",
"strokeStyle": "Stroke style", "strokeStyle": "Stroke style",
"strokeStyle_solid": "Solid", "strokeStyle_solid": "Solid",
"strokeStyle_dashed": "Dashed", "strokeStyle_dashed": "Dashed",
+4 -4
View File
@@ -11,10 +11,10 @@ export const withBatchedUpdates = <
TFunction extends ((event: any) => void) | (() => void), TFunction extends ((event: any) => void) | (() => void),
>( >(
func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never, func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
) => ) => func;
((event) => { // ((event) => {
unstable_batchedUpdates(func as TFunction, event); // unstable_batchedUpdates(func as TFunction, event);
}) as TFunction; // }) as TFunction;
/** /**
* barches React state updates and throttles the calls to a single call per * barches React state updates and throttles the calls to a single call per
+14 -6
View File
@@ -376,6 +376,11 @@ const renderElementToSvg = (
} }
case "freedraw": { case "freedraw": {
const wrapper = svgRoot.ownerDocument.createElementNS(SVG_NS, "g"); const wrapper = svgRoot.ownerDocument.createElementNS(SVG_NS, "g");
const isFixedStroke = element.strokeShape === "fixed";
const strokeColor =
renderConfig.theme === THEME.DARK
? applyDarkModeFilter(element.strokeColor)
: element.strokeColor;
const shapes = ShapeCache.generateElementShape(element, renderConfig); const shapes = ShapeCache.generateElementShape(element, renderConfig);
// always ordered as [background, stroke] // always ordered as [background, stroke]
@@ -384,12 +389,15 @@ const renderElementToSvg = (
// stroke (SVGPathString) // stroke (SVGPathString)
const path = svgRoot.ownerDocument.createElementNS(SVG_NS, "path"); const path = svgRoot.ownerDocument.createElementNS(SVG_NS, "path");
path.setAttribute( if (isFixedStroke) {
"fill", path.setAttribute("fill", "none");
renderConfig.theme === THEME.DARK path.setAttribute("stroke", strokeColor);
? applyDarkModeFilter(element.strokeColor) path.setAttribute("stroke-width", `${element.strokeWidth}`);
: element.strokeColor, path.setAttribute("stroke-linecap", "round");
); path.setAttribute("stroke-linejoin", "round");
} else {
path.setAttribute("fill", strokeColor);
}
path.setAttribute("d", shape); path.setAttribute("d", shape);
wrapper.appendChild(path); wrapper.appendChild(path);
} else { } else {
+5 -1
View File
@@ -157,7 +157,11 @@ const prepareElementsForRender = ({
let nextElements: readonly ExcalidrawElement[]; let nextElements: readonly ExcalidrawElement[];
if (exportingFrame) { if (exportingFrame) {
nextElements = getElementsOverlappingFrame(elements, exportingFrame); nextElements = getElementsOverlappingFrame(
elements,
exportingFrame,
arrayToMap(elements),
);
} else if (frameRendering.enabled && frameRendering.name) { } else if (frameRendering.enabled && frameRendering.name) {
nextElements = addFrameLabelsAsTextElements(elements, { nextElements = addFrameLabelsAsTextElements(elements, {
exportWithDarkMode, exportWithDarkMode,
@@ -13,6 +13,7 @@ exports[`contextMenu element > right-clicking on a group should select whole gro
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": { "contextMenu": {
"items": [ "items": [
@@ -1086,6 +1087,7 @@ exports[`contextMenu element > selecting 'Add to library' in context menu adds e
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -1300,6 +1302,7 @@ exports[`contextMenu element > selecting 'Bring forward' in context menu brings
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -1631,6 +1634,7 @@ exports[`contextMenu element > selecting 'Bring to front' in context menu brings
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -1962,6 +1966,7 @@ exports[`contextMenu element > selecting 'Copy styles' in context menu copies st
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2176,6 +2181,7 @@ exports[`contextMenu element > selecting 'Delete' in context menu deletes elemen
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2417,6 +2423,7 @@ exports[`contextMenu element > selecting 'Duplicate' in context menu duplicates
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2715,6 +2722,7 @@ exports[`contextMenu element > selecting 'Group selection' in context menu group
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3087,6 +3095,7 @@ exports[`contextMenu element > selecting 'Paste styles' in context menu pastes s
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3580,6 +3589,7 @@ exports[`contextMenu element > selecting 'Send backward' in context menu sends e
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3903,6 +3913,7 @@ exports[`contextMenu element > selecting 'Send to back' in context menu sends el
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4226,6 +4237,7 @@ exports[`contextMenu element > selecting 'Ungroup selection' in context menu ung
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4637,6 +4649,7 @@ exports[`contextMenu element > shows 'Group selection' in context menu for multi
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": { "contextMenu": {
"items": [ "items": [
@@ -5854,6 +5867,7 @@ exports[`contextMenu element > shows 'Ungroup selection' in context menu for gro
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": { "contextMenu": {
"items": [ "items": [
@@ -7122,6 +7136,7 @@ exports[`contextMenu element > shows context menu for canvas > [end of test] app
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": { "contextMenu": {
"items": [ "items": [
@@ -7811,6 +7826,7 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": { "contextMenu": {
"items": [ "items": [
@@ -8802,6 +8818,7 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": { "contextMenu": {
"items": [ "items": [
@@ -13,6 +13,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -646,6 +647,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -1207,6 +1209,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -1567,6 +1570,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -1929,6 +1933,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2192,6 +2197,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2645,6 +2651,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2948,6 +2955,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3267,6 +3275,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3561,6 +3570,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3847,6 +3857,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4082,6 +4093,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4339,6 +4351,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4610,6 +4623,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4839,6 +4853,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -5068,6 +5083,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -5315,6 +5331,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -5571,6 +5588,7 @@ exports[`history > multiplayer undo/redo > conflicts in frames and their childre
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -5829,6 +5847,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -6158,6 +6177,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -6585,6 +6605,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -6959,6 +6980,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -7271,6 +7293,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -7563,6 +7586,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -7793,6 +7817,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -8145,6 +8170,7 @@ exports[`history > multiplayer undo/redo > should iterate through the history wh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -8497,6 +8523,7 @@ exports[`history > multiplayer undo/redo > should not let remote changes to inte
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -8903,6 +8930,7 @@ exports[`history > multiplayer undo/redo > should not let remote changes to inte
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9182,6 +9210,7 @@ exports[`history > multiplayer undo/redo > should not let remote changes to inte
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9446,6 +9475,7 @@ exports[`history > multiplayer undo/redo > should not override remote changes on
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9711,6 +9741,7 @@ exports[`history > multiplayer undo/redo > should not override remote changes on
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9943,6 +9974,7 @@ exports[`history > multiplayer undo/redo > should override remotely added groups
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -10240,6 +10272,7 @@ exports[`history > multiplayer undo/redo > should override remotely added points
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -10557,6 +10590,7 @@ exports[`history > multiplayer undo/redo > should redistribute deltas when eleme
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -10793,6 +10827,7 @@ exports[`history > multiplayer undo/redo > should redraw arrows on undo > [end o
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -11718,6 +11753,7 @@ exports[`history > multiplayer undo/redo > should update history entries after r
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -11978,6 +12014,7 @@ exports[`history > singleplayer undo/redo > remounting undo/redo buttons should
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -12213,6 +12250,7 @@ exports[`history > singleplayer undo/redo > should clear the redo stack on eleme
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -12450,6 +12488,7 @@ exports[`history > singleplayer undo/redo > should create entry when selecting f
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -12841,6 +12880,7 @@ exports[`history > singleplayer undo/redo > should create new history entry on e
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -13051,6 +13091,7 @@ exports[`history > singleplayer undo/redo > should create new history entry on e
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -13258,6 +13299,7 @@ exports[`history > singleplayer undo/redo > should create new history entry on i
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -13559,6 +13601,7 @@ exports[`history > singleplayer undo/redo > should create new history entry on i
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -13857,6 +13900,7 @@ exports[`history > singleplayer undo/redo > should create new history entry on s
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14102,6 +14146,7 @@ exports[`history > singleplayer undo/redo > should disable undo/redo buttons whe
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14339,6 +14384,7 @@ exports[`history > singleplayer undo/redo > should end up with no history entry
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14576,6 +14622,7 @@ exports[`history > singleplayer undo/redo > should iterate through the history w
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14823,6 +14870,7 @@ exports[`history > singleplayer undo/redo > should not clear the redo stack on s
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -15154,6 +15202,7 @@ exports[`history > singleplayer undo/redo > should not collapse when applying co
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -15324,6 +15373,7 @@ exports[`history > singleplayer undo/redo > should not end up with history entry
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -15608,6 +15658,7 @@ exports[`history > singleplayer undo/redo > should not end up with history entry
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -15871,6 +15922,7 @@ exports[`history > singleplayer undo/redo > should not modify anything on unrela
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -16024,6 +16076,7 @@ exports[`history > singleplayer undo/redo > should not override appstate changes
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -16306,6 +16359,7 @@ exports[`history > singleplayer undo/redo > should support appstate name or view
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -16468,6 +16522,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -17216,6 +17271,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -17862,6 +17918,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -18508,6 +18565,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -19257,6 +19315,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -20025,6 +20084,7 @@ exports[`history > singleplayer undo/redo > should support changes in elements'
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -20505,6 +20565,7 @@ exports[`history > singleplayer undo/redo > should support duplication of groups
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -21016,6 +21077,7 @@ exports[`history > singleplayer undo/redo > should support element creation, del
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -21475,6 +21537,7 @@ exports[`history > singleplayer undo/redo > should support linear element creati
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -13,6 +13,7 @@ exports[`given element A and group of elements B and given both are selected whe
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -439,6 +440,7 @@ exports[`given element A and group of elements B and given both are selected whe
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -855,6 +857,7 @@ exports[`regression tests > Cmd/Ctrl-click exclusively select element under poin
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -1421,6 +1424,7 @@ exports[`regression tests > Drags selected element when hitting only bounding bo
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -1628,6 +1632,7 @@ exports[`regression tests > adjusts z order when grouping > [end of test] appSta
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2012,6 +2017,7 @@ exports[`regression tests > alt-drag duplicates an element > [end of test] appSt
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2257,6 +2263,7 @@ exports[`regression tests > arrow keys > [end of test] appState 1`] = `
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2437,6 +2444,7 @@ exports[`regression tests > can drag element that covers another element, while
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -2762,6 +2770,7 @@ exports[`regression tests > change the properties of a shape > [end of test] app
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3017,6 +3026,7 @@ exports[`regression tests > click on an element and drag it > [dragged] appState
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3258,6 +3268,7 @@ exports[`regression tests > click on an element and drag it > [end of test] appS
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3494,6 +3505,7 @@ exports[`regression tests > click to select a shape > [end of test] appState 1`]
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -3752,6 +3764,7 @@ exports[`regression tests > click-drag to select a group > [end of test] appStat
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4066,6 +4079,7 @@ exports[`regression tests > deleting last but one element in editing group shoul
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4502,6 +4516,7 @@ exports[`regression tests > deselects group of selected elements on pointer down
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -4785,6 +4800,7 @@ exports[`regression tests > deselects group of selected elements on pointer up w
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -5061,6 +5077,7 @@ exports[`regression tests > deselects selected element on pointer down when poin
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -5269,6 +5286,7 @@ exports[`regression tests > deselects selected element, on pointer up, when clic
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -5469,6 +5487,7 @@ exports[`regression tests > double click to edit a group > [end of test] appStat
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -5862,6 +5881,7 @@ exports[`regression tests > drags selected elements from point inside common bou
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -6159,6 +6179,7 @@ exports[`regression tests > draw every type of shape > [end of test] appState 1`
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -6947,6 +6968,7 @@ exports[`regression tests > given a group of selected elements with an element t
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -7281,6 +7303,7 @@ exports[`regression tests > given a selected element A and a not selected elemen
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -7560,6 +7583,7 @@ exports[`regression tests > given selected element A with lower z-index than uns
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -7795,6 +7819,7 @@ exports[`regression tests > given selected element A with lower z-index than uns
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -8035,6 +8060,7 @@ exports[`regression tests > key 2 selects rectangle tool > [end of test] appStat
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -8215,6 +8241,7 @@ exports[`regression tests > key 3 selects diamond tool > [end of test] appState
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -8395,6 +8422,7 @@ exports[`regression tests > key 4 selects ellipse tool > [end of test] appState
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -8575,6 +8603,7 @@ exports[`regression tests > key 5 selects arrow tool > [end of test] appState 1`
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -8807,6 +8836,7 @@ exports[`regression tests > key 6 selects line tool > [end of test] appState 1`]
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9037,6 +9067,7 @@ exports[`regression tests > key 7 selects freedraw tool > [end of test] appState
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9229,6 +9260,7 @@ exports[`regression tests > key a selects arrow tool > [end of test] appState 1`
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9461,6 +9493,7 @@ exports[`regression tests > key d selects diamond tool > [end of test] appState
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9641,6 +9674,7 @@ exports[`regression tests > key l selects line tool > [end of test] appState 1`]
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -9871,6 +9905,7 @@ exports[`regression tests > key o selects ellipse tool > [end of test] appState
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -10051,6 +10086,7 @@ exports[`regression tests > key p selects freedraw tool > [end of test] appState
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -10243,6 +10279,7 @@ exports[`regression tests > key r selects rectangle tool > [end of test] appStat
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -10423,6 +10460,7 @@ exports[`regression tests > make a group and duplicate it > [end of test] appSta
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -10954,6 +10992,7 @@ exports[`regression tests > noop interaction after undo shouldn't create history
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -11234,6 +11273,7 @@ exports[`regression tests > pinch-to-zoom works > [end of test] appState 1`] = `
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -11357,6 +11397,7 @@ exports[`regression tests > shift click on selected element should deselect it o
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -11557,6 +11598,7 @@ exports[`regression tests > shift-click to multiselect, then drag > [end of test
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -11876,6 +11918,7 @@ exports[`regression tests > should group elements and ungroup them > [end of tes
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -12305,6 +12348,7 @@ exports[`regression tests > single-clicking on a subgroup of a selected group sh
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -12945,6 +12989,7 @@ exports[`regression tests > spacebar + drag scrolls the canvas > [end of test] a
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -13071,6 +13116,7 @@ exports[`regression tests > supports nested groups > [end of test] appState 1`]
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -13702,6 +13748,7 @@ exports[`regression tests > switches from group of selected elements to another
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14041,6 +14088,7 @@ exports[`regression tests > switches selected element on pointer down > [end of
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14305,6 +14353,7 @@ exports[`regression tests > two-finger scroll works > [end of test] appState 1`]
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14428,6 +14477,7 @@ exports[`regression tests > undo/redo drawing an element > [end of test] appStat
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14792,6 +14842,7 @@ exports[`regression tests > updates fontSize & fontFamily appState > [end of tes
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -14915,6 +14966,7 @@ exports[`regression tests > zoom hotkeys > [end of test] appState 1`] = `
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
@@ -160,6 +160,40 @@ describe("restoreElements", () => {
}); });
}); });
it("should restore fixed freedraw element correctly", () => {
const freedrawElement = API.createElement({
type: "freedraw",
id: "id-freedraw02",
strokeShape: "fixed",
points: [pointFrom(0, 0), pointFrom(10, 10)],
});
const restoredFreedraw = restore.restoreElements(
[freedrawElement],
null,
)[0] as ExcalidrawFreeDrawElement;
expect(restoredFreedraw.strokeShape).toBe("fixed");
});
it("should restore legacy stable freedraw element as fixed", () => {
const restoredFreedraw = restore.restoreElements(
[
{
...API.createElement({
type: "freedraw",
id: "id-freedraw03",
points: [pointFrom(0, 0), pointFrom(10, 10)],
}),
strokeShape: "stable",
} as any,
],
null,
)[0] as ExcalidrawFreeDrawElement;
expect(restoredFreedraw.strokeShape).toBe("fixed");
});
it("should restore line and draw elements correctly", () => { it("should restore line and draw elements correctly", () => {
const lineElement = API.createElement({ type: "line", id: "id-line01" }); const lineElement = API.createElement({ type: "line", id: "id-line01" });
@@ -641,6 +675,26 @@ describe("restoreAppState", () => {
expect(restoredAppState.name).toBe(stubImportedAppState.name); expect(restoredAppState.name).toBe(stubImportedAppState.name);
}); });
it("should restore fixed freedraw stroke type from app state", () => {
const restoredAppState = restore.restoreAppState(
{ currentItemStrokeShape: "fixed" } as ImportedDataState["appState"],
null,
);
expect(restoredAppState.currentItemStrokeShape).toBe("fixed");
});
it("should restore legacy stable freedraw stroke type from app state as fixed", () => {
const restoredAppState = restore.restoreAppState(
{
currentItemStrokeShape: "stable",
} as unknown as ImportedDataState["appState"],
null,
);
expect(restoredAppState.currentItemStrokeShape).toBe("fixed");
});
it("should return local app state when imported data state is null", () => { it("should return local app state when imported data state is null", () => {
const stubLocalAppState = getDefaultAppState(); const stubLocalAppState = getDefaultAppState();
stubLocalAppState.cursorButton = "down"; stubLocalAppState.cursorButton = "down";
@@ -0,0 +1,78 @@
import React from "react";
import { Excalidraw } from "../index";
import { API } from "./helpers/api";
import { Pointer, UI } from "./helpers/ui";
import { render } from "./test-utils";
describe("freedraw", () => {
beforeEach(async () => {
await render(<Excalidraw />);
});
it("rounds stored points and drops duplicates after rounding", () => {
const mouse = new Pointer("mouse");
UI.clickTool("freedraw");
mouse.downAt(10, 20);
mouse.moveTo(10.1234, 20.5678);
mouse.moveTo(10.1249, 20.5681);
mouse.upAt(20.9999, 30.0001);
const freedraw = window.h.elements.at(-1);
expect(freedraw).toEqual(expect.objectContaining({ type: "freedraw" }));
expect((freedraw as any).points).toEqual([
[0, 0],
[0.12, 0.57],
[11, 10],
]);
});
it("does not snap fixed strokes closed when ending near the start point", () => {
const mouse = new Pointer("mouse");
API.setAppState({ currentItemStrokeShape: "fixed" });
UI.clickTool("freedraw");
mouse.downAt(10, 10);
mouse.moveTo(40, 10);
mouse.moveTo(30, 30);
mouse.upAt(12, 12);
const freedraw = window.h.elements.at(-1) as any;
expect(freedraw.points[0]).toEqual([0, 0]);
expect(freedraw.points.at(-1)).not.toEqual([0, 0]);
});
it("coalesces nearly straight fixed freedraw points at the tip", () => {
const mouse = new Pointer("mouse");
API.setAppState({ currentItemStrokeShape: "fixed" });
UI.clickTool("freedraw");
mouse.downAt(10, 10);
[
[10.2, 10.01],
[10.4, 10.03],
[10.6, 10.02],
[10.8, 10.04],
[11, 10.03],
[11.2, 10.05],
[11.4, 10.04],
[11.6, 10.06],
[11.8, 10.05],
].forEach(([x, y]) => {
mouse.moveTo(x, y);
});
mouse.upAt(12, 10.05);
const freedraw = window.h.elements.at(-1) as any;
expect(freedraw.points.length).toBeLessThan(5);
expect(freedraw.points).toEqual([
[0, 0],
[2, 0.05],
]);
});
});
+4
View File
@@ -201,6 +201,9 @@ export class API {
? ExcalidrawTextElement["containerId"] ? ExcalidrawTextElement["containerId"]
: never; : never;
points?: T extends "arrow" | "line" | "freedraw" ? readonly LocalPoint[] : never; points?: T extends "arrow" | "line" | "freedraw" ? readonly LocalPoint[] : never;
strokeShape?: T extends "freedraw"
? ExcalidrawFreeDrawElement["strokeShape"]
: never;
locked?: boolean; locked?: boolean;
fileId?: T extends "image" ? string : never; fileId?: T extends "image" ? string : never;
scale?: T extends "image" ? ExcalidrawImageElement["scale"] : never; scale?: T extends "image" ? ExcalidrawImageElement["scale"] : never;
@@ -318,6 +321,7 @@ export class API {
type: type as "freedraw", type: type as "freedraw",
simulatePressure: true, simulatePressure: true,
points: rest.points, points: rest.points,
strokeShape: rest.strokeShape ?? appState.currentItemStrokeShape,
...base, ...base,
}); });
break; break;
+4 -1
View File
@@ -28,6 +28,7 @@ import type { GlobalPoint, LocalPoint, Radians } from "@excalidraw/math";
import type { TransformHandleType } from "@excalidraw/element"; import type { TransformHandleType } from "@excalidraw/element";
import type { import type {
ExcalidrawElement, ExcalidrawElement,
ExcalidrawFreeDrawElement,
ExcalidrawLinearElement, ExcalidrawLinearElement,
ExcalidrawTextElement, ExcalidrawTextElement,
ExcalidrawArrowElement, ExcalidrawArrowElement,
@@ -432,8 +433,10 @@ type DrawingToolName = Exclude<
"lock" | "selection" | "eraser" | "lasso" "lock" | "selection" | "eraser" | "lasso"
>; >;
type Element<T extends DrawingToolName> = T extends "line" | "freedraw" type Element<T extends DrawingToolName> = T extends "line"
? ExcalidrawLinearElement ? ExcalidrawLinearElement
: T extends "freedraw"
? ExcalidrawFreeDrawElement
: T extends "arrow" : T extends "arrow"
? ExcalidrawArrowElement ? ExcalidrawArrowElement
: T extends "text" : T extends "text"
+1 -1
View File
@@ -314,7 +314,7 @@ describe("history", () => {
expect.objectContaining({ id: rect2.id, isDeleted: true }), expect.objectContaining({ id: rect2.id, isDeleted: true }),
]); ]);
mouse.downAt(0, 0); mouse.downAt(-10, -10);
mouse.moveTo(25, 25); mouse.moveTo(25, 25);
mouse.moveTo(50, 50); mouse.moveTo(50, 50);
mouse.upAt(50, 50); mouse.upAt(50, 50);
@@ -468,7 +468,7 @@ describe("regression tests", () => {
mouse.reset(); mouse.reset();
mouse.down(); mouse.down();
mouse.move(-1000, -1000); mouse.move(-1000, -1000);
mouse.restorePosition(...end); mouse.restorePosition(end[0] + 3, end[1] + 3);
mouse.up(); mouse.up();
expect(h.elements.length).toBe(3); expect(h.elements.length).toBe(3);
@@ -519,7 +519,7 @@ describe("regression tests", () => {
mouse.reset(); mouse.reset();
mouse.down(); mouse.down();
mouse.move(-1000, -1000); mouse.move(-1000, -1000);
mouse.restorePosition(...end); mouse.restorePosition(end[0] + 3, end[1] + 3);
mouse.up(); mouse.up();
for (const element of h.elements) { for (const element of h.elements) {
@@ -537,7 +537,7 @@ describe("regression tests", () => {
mouse.moveTo(-10, -10); // the NW resizing handle is at [0, 0], so moving further mouse.moveTo(-10, -10); // the NW resizing handle is at [0, 0], so moving further
mouse.down(); mouse.down();
mouse.move(-1000, -1000); mouse.move(-1000, -1000);
mouse.restorePosition(...end); mouse.restorePosition(end[0] + 3, end[1] + 3);
mouse.up(); mouse.up();
Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => { Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => {
+4 -4
View File
@@ -348,10 +348,10 @@ describe("box-selection overlap mode", () => {
); );
const [outlineX1, outlineY1, outlineX2, outlineY2] = getOutlineBounds(rect); const [outlineX1, outlineY1, outlineX2, outlineY2] = getOutlineBounds(rect);
expect(outlineX1).toBeGreaterThan(boundsX1); expect(outlineX1).toBeGreaterThan(boundsX1 - 1);
expect(outlineY1).toBeGreaterThan(boundsY1); expect(outlineY1).toBeGreaterThan(boundsY1 - 1);
expect(outlineX2).toBeLessThan(boundsX2); expect(outlineX2).toBeLessThan(boundsX2 + 1);
expect(outlineY2).toBeLessThan(boundsY2); expect(outlineY2).toBeLessThan(boundsY2 + 1);
boxSelect( boxSelect(
outlineX1 - (outlineX1 - boundsX1) / 2, outlineX1 - (outlineX1 - boundsX1) / 2,
+4 -2
View File
@@ -33,6 +33,7 @@ import type {
ExcalidrawNonSelectionElement, ExcalidrawNonSelectionElement,
BindMode, BindMode,
ExcalidrawTextElement, ExcalidrawTextElement,
FreeDrawStrokeShape,
} from "@excalidraw/element/types"; } from "@excalidraw/element/types";
import type { import type {
@@ -310,7 +311,7 @@ export interface AppState {
*/ */
isBindingEnabled: boolean; isBindingEnabled: boolean;
/** user box selection preference; defaults to "contain" when unset */ /** user box selection preference; defaults to "contain" when unset */
boxSelectionMode?: BoxSelectionMode; boxSelectionMode: BoxSelectionMode;
/** user arrow binding preference */ /** user arrow binding preference */
bindingPreference: "enabled" | "disabled"; bindingPreference: "enabled" | "disabled";
/** user preference whether arrow snap to midpoints while binding */ /** user preference whether arrow snap to midpoints while binding */
@@ -358,6 +359,7 @@ export interface AppState {
currentItemFillStyle: ExcalidrawElement["fillStyle"]; currentItemFillStyle: ExcalidrawElement["fillStyle"];
currentItemStrokeWidth: number; currentItemStrokeWidth: number;
currentItemStrokeStyle: ExcalidrawElement["strokeStyle"]; currentItemStrokeStyle: ExcalidrawElement["strokeStyle"];
currentItemStrokeShape?: FreeDrawStrokeShape;
currentItemRoughness: number; currentItemRoughness: number;
currentItemOpacity: number; currentItemOpacity: number;
currentItemFontFamily: FontFamilyValues; currentItemFontFamily: FontFamilyValues;
@@ -888,7 +890,7 @@ export type PointerDownState = Readonly<{
// We need to have these in the state so that we can unsubscribe them // We need to have these in the state so that we can unsubscribe them
eventListeners: { eventListeners: {
// It's defined on the initial pointer down event // It's defined on the initial pointer down event
onMove: null | ReturnType<typeof throttleRAF>; onMove: null | ((event: PointerEvent) => void);
// It's defined on the initial pointer down event // It's defined on the initial pointer down event
onUp: null | ((event: PointerEvent) => void); onUp: null | ((event: PointerEvent) => void);
// It's defined on the initial pointer down event // It's defined on the initial pointer down event
+39 -5
View File
@@ -137,8 +137,17 @@ const calculate = <Point extends GlobalPoint | LocalPoint>(
[t0, s0]: [number, number], [t0, s0]: [number, number],
l: LineSegment<Point>, l: LineSegment<Point>,
c: Curve<Point>, c: Curve<Point>,
tolerance: number = 1e-2,
iterLimit: number = 4,
) => { ) => {
const solution = solveWithAnalyticalJacobian(c, l, t0, s0, 1e-2, 4); const solution = solveWithAnalyticalJacobian(
c,
l,
t0,
s0,
tolerance,
iterLimit,
);
if (!solution) { if (!solution) {
return null; return null;
@@ -158,18 +167,43 @@ const calculate = <Point extends GlobalPoint | LocalPoint>(
*/ */
export function curveIntersectLineSegment< export function curveIntersectLineSegment<
Point extends GlobalPoint | LocalPoint, Point extends GlobalPoint | LocalPoint,
>(c: Curve<Point>, l: LineSegment<Point>): Point[] { >(
let solution = calculate(initial_guesses[0], l, c); c: Curve<Point>,
l: LineSegment<Point>,
opts?: {
tolerance?: number;
iterLimit?: number;
},
): Point[] {
let solution = calculate(
initial_guesses[0],
l,
c,
opts?.tolerance,
opts?.iterLimit,
);
if (solution) { if (solution) {
return [solution]; return [solution];
} }
solution = calculate(initial_guesses[1], l, c); solution = calculate(
initial_guesses[1],
l,
c,
opts?.tolerance,
opts?.iterLimit,
);
if (solution) { if (solution) {
return [solution]; return [solution];
} }
solution = calculate(initial_guesses[2], l, c); solution = calculate(
initial_guesses[2],
l,
c,
opts?.tolerance,
opts?.iterLimit,
);
if (solution) { if (solution) {
return [solution]; return [solution];
} }
-11
View File
@@ -1,14 +1,3 @@
//
// Generic markers
//
/**
* Can be used for any type of point-likes to mark them as rotated to enlist
* the type checker to weed out subtle bugs due to rotated and non-rotated
* versions of the same data point.
*/
export type Rotated<T> = T & { _brand_rotated: "excalimath_rotated" };
// //
// Measurements // Measurements
// //
+14 -21
View File
@@ -1,9 +1,4 @@
import { import { arrayToMap, type Bounds } from "@excalidraw/common";
arrayToMap,
bounds,
type RotatedBounds,
type Bounds,
} from "@excalidraw/common";
import { getElementBounds } from "@excalidraw/element"; import { getElementBounds } from "@excalidraw/element";
import { import {
isArrowElement, isArrowElement,
@@ -95,7 +90,7 @@ const getMinMaxPoints = (points: Points) => {
return ret; return ret;
}; };
const getRotatedBBox = (element: Element): RotatedBounds => { const getRotatedBBox = (element: Element): Bounds => {
const points = getElementRelativePoints(element); const points = getElementRelativePoints(element);
const { cx, cy } = getMinMaxPoints(points); const { cx, cy } = getMinMaxPoints(points);
@@ -106,13 +101,12 @@ const getRotatedBBox = (element: Element): RotatedBounds => {
); );
const { minX, minY, maxX, maxY } = getMinMaxPoints(rotatedPoints); const { minX, minY, maxX, maxY } = getMinMaxPoints(rotatedPoints);
return bounds( return [
minX + element.x, minX + element.x,
minY + element.y, minY + element.y,
maxX + element.x, maxX + element.x,
maxY + element.y, maxY + element.y,
element.angle, ];
);
}; };
export const isElementInsideBBox = ( export const isElementInsideBBox = (
@@ -166,12 +160,12 @@ export const elementPartiallyOverlapsWithOrContainsBBox = (
export const elementsOverlappingBBox = ({ export const elementsOverlappingBBox = ({
elements, elements,
bounds: _bounds, bounds,
type, type,
errorMargin = 0, errorMargin = 0,
}: { }: {
elements: Elements; elements: Elements;
bounds: RotatedBounds | ExcalidrawElement; bounds: Bounds | ExcalidrawElement;
/** safety offset. Defaults to 0. */ /** safety offset. Defaults to 0. */
errorMargin?: number; errorMargin?: number;
/** /**
@@ -181,16 +175,15 @@ export const elementsOverlappingBBox = ({
**/ **/
type: "overlap" | "contain" | "inside"; type: "overlap" | "contain" | "inside";
}) => { }) => {
if (isExcalidrawElement(_bounds)) { if (isExcalidrawElement(bounds)) {
_bounds = getElementBounds(_bounds, arrayToMap(elements)); bounds = getElementBounds(bounds, arrayToMap(elements));
} }
const adjustedBBox = bounds( const adjustedBBox: Bounds = [
_bounds[0] - errorMargin, bounds[0] - errorMargin,
_bounds[1] - errorMargin, bounds[1] - errorMargin,
_bounds[2] + errorMargin, bounds[2] + errorMargin,
_bounds[3] + errorMargin, bounds[3] + errorMargin,
_bounds[4], ];
);
const includedElementSet = new Set<string>(); const includedElementSet = new Set<string>();
@@ -13,6 +13,7 @@ exports[`exportToSvg > with default arguments 1`] = `
}, },
"bindMode": "orbit", "bindMode": "orbit",
"bindingPreference": "enabled", "bindingPreference": "enabled",
"boxSelectionMode": "contain",
"collaborators": Map {}, "collaborators": Map {},
"contextMenu": null, "contextMenu": null,
"croppingElementId": null, "croppingElementId": null,
+7
View File
@@ -90,6 +90,13 @@ module.exports.woff2BrowserPlugin = () => {
type="font/woff2" type="font/woff2"
crossorigin="anonymous" crossorigin="anonymous"
/> />
<link
rel="preload"
href="${OSS_FONTS_CDN}fonts/Assistant/Assistant-SemiBold.woff2"
as="font"
type="font/woff2"
crossorigin="anonymous"
/>
<link <link
rel="preload" rel="preload"
href="${OSS_FONTS_CDN}fonts/ComicShanns/ComicShanns-Regular-279a7b317d12eb88de06167bd672b4b4.woff2" href="${OSS_FONTS_CDN}fonts/ComicShanns/ComicShanns-Regular-279a7b317d12eb88de06167bd672b4b4.woff2"