From f9bc601b61c059cdcfe541a4aab85b57fc7e79b2 Mon Sep 17 00:00:00 2001 From: Mark Tolmacs Date: Tue, 17 Nov 2026 14:42:57 +0100 Subject: [PATCH] fix: Circular deps #0 Signed-off-by: Mark Tolmacs --- CLAUDE.md | 3 +- examples/with-nextjs/package.json | 1 + excalidraw-app/package.json | 4 + excalidraw-app/vite.config.mts | 71 +-- package.json | 2 + packages/common/package.json | 20 +- packages/common/src/colors.test.ts | 2 +- packages/common/src/utils.test.ts | 11 +- packages/element/package.json | 29 +- packages/element/src/Scene.ts | 24 +- packages/element/src/bounds.ts | 4 +- packages/element/src/convertToShape.ts | 25 +- packages/element/src/delta.ts | 24 +- packages/element/src/dragElements.ts | 4 +- packages/element/src/geometricShapes.ts | 547 +++++++++++++++++ packages/element/src/linearElementEditor.ts | 4 +- packages/element/src/shape.ts | 18 +- packages/element/src/visualdebug.ts | 4 +- packages/element/tests/align.test.tsx | 2 +- packages/element/tests/collision.test.tsx | 1 - packages/element/tests/cropElement.test.tsx | 2 +- packages/element/tests/delta.test.tsx | 12 +- packages/element/tests/distribute.test.tsx | 2 +- packages/element/tests/duplicate.test.tsx | 2 +- packages/element/tests/elbowArrow.test.tsx | 6 +- packages/element/tests/flowchart.test.tsx | 2 +- .../element/tests/fractionalIndex.test.ts | 20 +- packages/element/tests/frame.test.tsx | 2 +- .../tests/geometricShapes.test.ts} | 6 +- packages/element/tests/sortElements.test.ts | 2 +- packages/element/tests/zindex.test.tsx | 2 +- .../components/Stats/MultiDimension.tsx | 2 +- .../excalidraw/components/TTDDialog/common.ts | 4 +- .../excalidraw/components/TTDDialog/types.ts | 4 +- .../components/canvases/InteractiveCanvas.tsx | 16 +- packages/excalidraw/package.json | 31 +- .../excalidraw/tests/data/restore.test.ts | 3 +- packages/excalidraw/tests/history.test.tsx | 2 - packages/excalidraw/tests/move.test.tsx | 1 - .../excalidraw/tests/queries/toolQueries.ts | 2 +- packages/fractional-indexing/package.json | 11 +- packages/laser-pointer/package.json | 11 +- packages/math/package.json | 21 +- packages/math/src/range.ts | 8 +- packages/math/tests/curve.test.ts | 2 - packages/tsconfig.base.json | 17 +- packages/utils/package.json | 21 +- packages/utils/src/shape.ts | 548 +----------------- packages/utils/src/test-utils.ts | 33 -- pnpm-lock.yaml | 57 +- pnpm-workspace.yaml | 4 + scripts/buildBase.js | 17 +- scripts/buildPackage.js | 3 - scripts/buildUtils.js | 16 +- setupTests.ts | 34 ++ tsconfig.json | 19 +- vitest.config.mts | 70 +-- 57 files changed, 902 insertions(+), 913 deletions(-) create mode 100644 packages/element/src/geometricShapes.ts rename packages/{utils/tests/geometry.test.ts => element/tests/geometricShapes.test.ts} (97%) delete mode 100644 packages/utils/src/test-utils.ts diff --git a/CLAUDE.md b/CLAUDE.md index 5c33c71fae..d295496acc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,6 +29,7 @@ pnpm fix # Auto-fix formatting and linting issues ### Package System - Uses pnpm workspaces for monorepo management -- Internal packages use path aliases (see `vitest.config.mts`) +- Internal packages depend on each other via `workspace:*` and resolve to their sources through the `excalidraw-source` export condition (enabled in tsconfig, Vite, Vitest and the esbuild scripts); `publishConfig.exports` holds the published dist exports +- A package can't import itself by name: use relative imports inside a package - Build system uses esbuild for packages, Vite for the app - TypeScript throughout with strict configuration diff --git a/examples/with-nextjs/package.json b/examples/with-nextjs/package.json index b1f5f3521e..3bc793b01a 100644 --- a/examples/with-nextjs/package.json +++ b/examples/with-nextjs/package.json @@ -12,6 +12,7 @@ "lint": "next lint" }, "dependencies": { + "@excalidraw/excalidraw": "workspace:*", "next": "14.1", "react": "19.0.0", "react-dom": "19.0.0" diff --git a/excalidraw-app/package.json b/excalidraw-app/package.json index 687520e3b4..8870e0afeb 100644 --- a/excalidraw-app/package.json +++ b/excalidraw-app/package.json @@ -26,6 +26,10 @@ "node": ">=18.0.0" }, "dependencies": { + "@excalidraw/common": "workspace:*", + "@excalidraw/element": "workspace:*", + "@excalidraw/excalidraw": "workspace:*", + "@excalidraw/math": "workspace:*", "@excalidraw/random-username": "1.1.0", "@sentry/browser": "9.0.1", "callsites": "4.2.0", diff --git a/excalidraw-app/vite.config.mts b/excalidraw-app/vite.config.mts index 0488bb1d3d..033b89aa76 100644 --- a/excalidraw-app/vite.config.mts +++ b/excalidraw-app/vite.config.mts @@ -153,74 +153,9 @@ export default defineConfig(({ mode }) => { //more located in parallel with the vite.config.ts file but in parent dir envDir: "../", resolve: { - alias: [ - { - find: /^@excalidraw\/common$/, - replacement: path.resolve( - __dirname, - "../packages/common/src/index.ts", - ), - }, - { - find: /^@excalidraw\/common\/(.*?)/, - replacement: path.resolve(__dirname, "../packages/common/src/$1"), - }, - { - find: /^@excalidraw\/element$/, - replacement: path.resolve( - __dirname, - "../packages/element/src/index.ts", - ), - }, - { - find: /^@excalidraw\/element\/(.*?)/, - replacement: path.resolve(__dirname, "../packages/element/src/$1"), - }, - { - find: /^@excalidraw\/excalidraw$/, - replacement: path.resolve( - __dirname, - "../packages/excalidraw/index.tsx", - ), - }, - { - find: /^@excalidraw\/excalidraw\/(.*?)/, - replacement: path.resolve(__dirname, "../packages/excalidraw/$1"), - }, - { - find: /^@excalidraw\/math$/, - replacement: path.resolve(__dirname, "../packages/math/src/index.ts"), - }, - { - find: /^@excalidraw\/math\/(.*?)/, - replacement: path.resolve(__dirname, "../packages/math/src/$1"), - }, - { - find: /^@excalidraw\/utils$/, - replacement: path.resolve( - __dirname, - "../packages/utils/src/index.ts", - ), - }, - { - find: /^@excalidraw\/utils\/(.*?)/, - replacement: path.resolve(__dirname, "../packages/utils/src/$1"), - }, - { - find: /^@excalidraw\/fractional-indexing$/, - replacement: path.resolve( - __dirname, - "../packages/fractional-indexing/src/index.ts", - ), - }, - { - find: /^@excalidraw\/laser-pointer$/, - replacement: path.resolve( - __dirname, - "../packages/laser-pointer/src/index.ts", - ), - }, - ], + // resolve workspace packages (linked through node_modules) to their + // sources: see the "excalidraw-source" condition in their `exports` + conditions: ["excalidraw-source"], }, build: { outDir: "build", diff --git a/package.json b/package.json index ae108cf9ee..10696b27f5 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "packageManager": "pnpm@10.34.9", "devDependencies": { "@babel/preset-env": "7.26.9", + "@excalidraw/common": "workspace:*", "@excalidraw/eslint-config": "1.0.3", "@excalidraw/prettier-config": "1.0.2", "@testing-library/dom": "10.4.0", @@ -32,6 +33,7 @@ "fonteditor-core": "2.4.0", "http-server": "14.1.1", "husky": "7.0.4", + "jest-diff": "29.7.0", "jsdom": "22.1.0", "lint-staged": "12.3.7", "pepjs": "0.5.3", diff --git a/packages/common/package.json b/packages/common/package.json index 659dca992b..94c1e99c50 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -7,12 +7,14 @@ "module": "./dist/prod/index.js", "exports": { ".": { + "excalidraw-source": "./src/index.ts", "types": "./dist/types/common/src/index.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", "default": "./dist/prod/index.js" }, "./*": { + "excalidraw-source": "./src/*.js", "types": "./dist/types/common/src/*.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", @@ -24,7 +26,21 @@ ], "description": "Excalidraw common functions, constants, etc.", "publishConfig": { - "access": "public" + "access": "public", + "exports": { + ".": { + "types": "./dist/types/common/src/index.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + }, + "./*": { + "types": "./dist/types/common/src/*.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + } + } }, "license": "MIT", "keywords": [ @@ -65,6 +81,8 @@ "tinycolor2": "1.6.0" }, "devDependencies": { + "@excalidraw/element": "workspace:*", + "@excalidraw/excalidraw": "workspace:*", "@types/tinycolor2": "1.4.6" } } diff --git a/packages/common/src/colors.test.ts b/packages/common/src/colors.test.ts index d4d9add9d0..656adee753 100644 --- a/packages/common/src/colors.test.ts +++ b/packages/common/src/colors.test.ts @@ -3,7 +3,7 @@ import { COLOR_PALETTE, removeDarkModeFilter, rgbToHex, -} from "@excalidraw/common"; +} from "./index"; describe("COLOR_PALETTE", () => { it("color palette doesn't regress", () => { diff --git a/packages/common/src/utils.test.ts b/packages/common/src/utils.test.ts index 2f148cb66f..4f5aeb88e5 100644 --- a/packages/common/src/utils.test.ts +++ b/packages/common/src/utils.test.ts @@ -1,3 +1,8 @@ +import { vi } from "vitest"; + +// Import directly to avoid the @excalidraw/common throttleRAF mock from setupTests.ts. +import { throttleRAF } from "./utils"; + import { getNearestScrollableContainer, isInputLike, @@ -7,11 +12,7 @@ import { isWritableElement, mapFind, reduceToCommonValue, -} from "@excalidraw/common"; -import { vi } from "vitest"; - -// Import directly to avoid the @excalidraw/common throttleRAF mock from setupTests.ts. -import { throttleRAF } from "./utils"; +} from "./index"; type RafCallback = FrameRequestCallback; diff --git a/packages/element/package.json b/packages/element/package.json index 45c92a0d2e..d883849e8c 100644 --- a/packages/element/package.json +++ b/packages/element/package.json @@ -7,18 +7,21 @@ "module": "./dist/prod/index.js", "exports": { ".": { + "excalidraw-source": "./src/index.ts", "types": "./dist/types/element/src/index.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", "default": "./dist/prod/index.js" }, "./*": { + "excalidraw-source": "./src/*.js", "types": "./dist/types/element/src/*.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", "default": "./dist/prod/index.js" }, "./visualdebug": { + "excalidraw-source": "./src/visualdebug.ts", "types": "./dist/types/element/src/visualdebug.d.ts", "development": "./dist/dev/visualdebug.js", "production": "./dist/prod/visualdebug.js", @@ -30,7 +33,27 @@ ], "description": "Excalidraw elements-related logic", "publishConfig": { - "access": "public" + "access": "public", + "exports": { + ".": { + "types": "./dist/types/element/src/index.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + }, + "./*": { + "types": "./dist/types/element/src/*.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + }, + "./visualdebug": { + "types": "./dist/types/element/src/visualdebug.d.ts", + "development": "./dist/dev/visualdebug.js", + "production": "./dist/prod/visualdebug.js", + "default": "./dist/prod/visualdebug.js" + } + } }, "license": "MIT", "keywords": [ @@ -64,14 +87,16 @@ }, "dependencies": { "@excalidraw/common": "workspace:*", - "@excalidraw/math": "workspace:*", "@excalidraw/fractional-indexing": "workspace:*", + "@excalidraw/math": "workspace:*", "lodash.throttle": "4.1.1", "perfect-freehand": "1.2.0", "points-on-curve": "0.2.0", "roughjs": "4.6.4" }, "devDependencies": { + "@excalidraw/excalidraw": "workspace:*", + "@excalidraw/laser-pointer": "workspace:*", "@testing-library/dom": "10.4.0", "@testing-library/react": "16.2.0", "react": "19.0.0", diff --git a/packages/element/src/Scene.ts b/packages/element/src/Scene.ts index f8d099e2e1..52d53347f9 100644 --- a/packages/element/src/Scene.ts +++ b/packages/element/src/Scene.ts @@ -9,18 +9,6 @@ import { toArray, } from "@excalidraw/common"; -import type { - ExcalidrawElement, - NonDeletedExcalidrawElement, - NonDeleted, - ExcalidrawFrameLikeElement, - ElementsMapOrArray, - SceneElementsMap, - NonDeletedSceneElementsMap, - OrderedExcalidrawElement, - Ordered, -} from "@excalidraw/element/types"; - import type { Assert, Mutable, @@ -42,6 +30,18 @@ import { mutateElement, type ElementUpdate } from "./mutateElement"; import { isNonDeletedElement } from "./index"; +import type { + ExcalidrawElement, + NonDeletedExcalidrawElement, + NonDeleted, + ExcalidrawFrameLikeElement, + ElementsMapOrArray, + SceneElementsMap, + NonDeletedSceneElementsMap, + OrderedExcalidrawElement, + Ordered, +} from "./types"; + import type { AppState } from "../../excalidraw/types"; type SceneStateCallback = () => void; diff --git a/packages/element/src/bounds.ts b/packages/element/src/bounds.ts index fbdf930a20..849e5d411d 100644 --- a/packages/element/src/bounds.ts +++ b/packages/element/src/bounds.ts @@ -17,7 +17,7 @@ import { vectorDot, vectorFromPoint, } from "@excalidraw/math"; -import { getCurvePathOps } from "@excalidraw/utils/shape"; + import { pointsOnBezierCurves } from "points-on-curve"; import type { @@ -31,6 +31,8 @@ import type { import type { AppState } from "@excalidraw/excalidraw/types"; import type { Mutable } from "@excalidraw/common/utility-types"; +import { getCurvePathOps } from "./geometricShapes"; + import { ELBOW_ARROW_CORNER_RADIUS, generateRoughOptions } from "./shape"; import { ShapeCache } from "./shape"; import { LinearElementEditor } from "./linearElementEditor"; diff --git a/packages/element/src/convertToShape.ts b/packages/element/src/convertToShape.ts index fd2fabee09..64a6f87772 100644 --- a/packages/element/src/convertToShape.ts +++ b/packages/element/src/convertToShape.ts @@ -21,6 +21,18 @@ import type { App, AppState } from "@excalidraw/excalidraw/types"; import type { LocalPoint, GlobalPoint, Radians } from "@excalidraw/math"; import type { Bounds } from "@excalidraw/common"; + +import { newArrowElement, newElement, newLinearElement } from "./newElement"; +import { getBoundsFromPoints, getElementAbsoluteCoords } from "./bounds"; + +import { getFrameLikeElements } from "./frame"; +import { + isLinearElement, + isLineElement, + isUsingAdaptiveRadius, +} from "./typeChecks"; +import { LinearElementEditor } from "./linearElementEditor"; + import type { ExcalidrawArrowElement, ExcalidrawDiamondElement, @@ -34,18 +46,7 @@ import type { NonDeletedExcalidrawElement, NonDeleted, ExcalidrawLineElement, -} from "@excalidraw/element/types"; - -import { newArrowElement, newElement, newLinearElement } from "./newElement"; -import { getBoundsFromPoints, getElementAbsoluteCoords } from "./bounds"; - -import { getFrameLikeElements } from "./frame"; -import { - isLinearElement, - isLineElement, - isUsingAdaptiveRadius, -} from "./typeChecks"; -import { LinearElementEditor } from "./linearElementEditor"; +} from "./types"; declare global { interface Window { diff --git a/packages/element/src/delta.ts b/packages/element/src/delta.ts index 4469840653..112e561bef 100644 --- a/packages/element/src/delta.ts +++ b/packages/element/src/delta.ts @@ -8,18 +8,6 @@ import { randomInteger, } from "@excalidraw/common"; -import type { - ExcalidrawElement, - ExcalidrawFreeDrawElement, - ExcalidrawLinearElement, - ExcalidrawTextElement, - NonDeleted, - NonDeletedExcalidrawElement, - Ordered, - OrderedExcalidrawElement, - SceneElementsMap, -} from "@excalidraw/element/types"; - import type { DTO, Mutable, @@ -61,6 +49,18 @@ import { StoreSnapshot } from "./store"; import { Scene } from "./Scene"; +import type { + ExcalidrawElement, + ExcalidrawFreeDrawElement, + ExcalidrawLinearElement, + ExcalidrawTextElement, + NonDeleted, + NonDeletedExcalidrawElement, + Ordered, + OrderedExcalidrawElement, + SceneElementsMap, +} from "./types"; + import type { BindableProp, BindingProp } from "./binding"; import type { ElementUpdate } from "./mutateElement"; diff --git a/packages/element/src/dragElements.ts b/packages/element/src/dragElements.ts index 60dd54f497..7316ff3d01 100644 --- a/packages/element/src/dragElements.ts +++ b/packages/element/src/dragElements.ts @@ -13,8 +13,6 @@ import type { PointerDownState, } from "@excalidraw/excalidraw/types"; -import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types"; - import { getFrameArrowIdsToReattach, getSimultaneouslyUpdatedElementIds, @@ -34,6 +32,8 @@ import { isTextElement, } from "./typeChecks"; +import type { NonDeletedExcalidrawElement } from "./types"; + import type { RenderEnvironment } from "./renderEnvironment"; import type { Scene } from "./Scene"; diff --git a/packages/element/src/geometricShapes.ts b/packages/element/src/geometricShapes.ts new file mode 100644 index 0000000000..ba0d0051f7 --- /dev/null +++ b/packages/element/src/geometricShapes.ts @@ -0,0 +1,547 @@ +/** + * this file defines pure geometric shapes + * + * for instance, a cubic bezier curve is specified by its four control points and + * an ellipse is defined by its center, angle, semi major axis and semi minor axis + * (but in semi-width and semi-height so it's more relevant to Excalidraw) + * + * the idea with pure shapes is so that we can provide collision and other geoemtric methods not depending on + * the specifics of roughjs or elements in Excalidraw; instead, we can focus on the pure shapes themselves + * + * also included in this file are methods for converting an Excalidraw element or a Drawable from roughjs + * to pure shapes + */ +import { pointsOnBezierCurves } from "points-on-curve"; + +import { invariant } from "@excalidraw/common"; +import { + curve, + lineSegment, + pointFrom, + pointDistance, + pointFromArray, + pointFromVector, + pointRotateRads, + polygon, + polygonFromPoints, + PRECISION, + segmentsIntersectAt, + vector, + vectorAdd, + vectorFromPoint, + vectorScale, + type GlobalPoint, + type LocalPoint, +} from "@excalidraw/math"; + +import type { Curve, LineSegment, Polygon, Radians } from "@excalidraw/math"; + +import { getElementAbsoluteCoords } from "./bounds"; + +import type { + ElementsMap, + ExcalidrawBindableElement, + ExcalidrawDiamondElement, + ExcalidrawElement, + ExcalidrawEllipseElement, + ExcalidrawEmbeddableElement, + ExcalidrawFrameLikeElement, + ExcalidrawFreeDrawElement, + ExcalidrawIframeElement, + ExcalidrawImageElement, + ExcalidrawLinearElement, + ExcalidrawRectangleElement, + ExcalidrawSelectionElement, + ExcalidrawStickyNoteElement, + ExcalidrawTextElement, +} from "./types"; + +import type { Drawable, Op } from "roughjs/bin/core"; + +// a polyline (made up term here) is a line consisting of other line segments +// this corresponds to a straight line element in the editor but it could also +// be used to model other elements +export type Polyline = + LineSegment[]; + +// a polycurve is a curve consisting of ther curves, this corresponds to a complex +// curve on the canvas +export type Polycurve = Curve[]; + +// an ellipse is specified by its center, angle, and its major and minor axes +// but for the sake of simplicity, we've used halfWidth and halfHeight instead +// in replace of semi major and semi minor axes +export type Ellipse = { + center: Point; + angle: Radians; + halfWidth: number; + halfHeight: number; +}; + +export type GeometricShape = + | { + type: "line"; + data: LineSegment; + } + | { + type: "polygon"; + data: Polygon; + } + | { + type: "curve"; + data: Curve; + } + | { + type: "ellipse"; + data: Ellipse; + } + | { + type: "polyline"; + data: Polyline; + } + | { + type: "polycurve"; + data: Polycurve; + }; + +type RectangularElement = + | ExcalidrawRectangleElement + | ExcalidrawStickyNoteElement + | ExcalidrawDiamondElement + | ExcalidrawFrameLikeElement + | ExcalidrawEmbeddableElement + | ExcalidrawImageElement + | ExcalidrawIframeElement + | ExcalidrawTextElement + | ExcalidrawSelectionElement; + +// polygon +export const getPolygonShape = ( + element: RectangularElement, +): GeometricShape => { + const { angle, width, height, x, y } = element; + + const cx = x + width / 2; + const cy = y + height / 2; + + const center: Point = pointFrom(cx, cy); + + let data: Polygon; + + if (element.type === "diamond") { + data = polygon( + pointRotateRads(pointFrom(cx, y), center, angle), + pointRotateRads(pointFrom(x + width, cy), center, angle), + pointRotateRads(pointFrom(cx, y + height), center, angle), + pointRotateRads(pointFrom(x, cy), center, angle), + ); + } else { + data = polygon( + pointRotateRads(pointFrom(x, y), center, angle), + pointRotateRads(pointFrom(x + width, y), center, angle), + pointRotateRads(pointFrom(x + width, y + height), center, angle), + pointRotateRads(pointFrom(x, y + height), center, angle), + ); + } + + return { + type: "polygon", + data, + }; +}; + +// return the selection box for an element, possibly rotated as well +export const getSelectionBoxShape = ( + element: ExcalidrawElement, + elementsMap: ElementsMap, + padding = 10, +) => { + let [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords( + element, + elementsMap, + true, + ); + + x1 -= padding; + x2 += padding; + y1 -= padding; + y2 += padding; + + //const angleInDegrees = angleToDegrees(element.angle); + const center = pointFrom(cx, cy); + const topLeft = pointRotateRads(pointFrom(x1, y1), center, element.angle); + const topRight = pointRotateRads(pointFrom(x2, y1), center, element.angle); + const bottomLeft = pointRotateRads(pointFrom(x1, y2), center, element.angle); + const bottomRight = pointRotateRads(pointFrom(x2, y2), center, element.angle); + + return { + type: "polygon", + data: [topLeft, topRight, bottomRight, bottomLeft], + } as GeometricShape; +}; + +// ellipse +export const getEllipseShape = ( + element: ExcalidrawEllipseElement, +): GeometricShape => { + const { width, height, angle, x, y } = element; + + return { + type: "ellipse", + data: { + center: pointFrom(x + width / 2, y + height / 2), + angle, + halfWidth: width / 2, + halfHeight: height / 2, + }, + }; +}; + +export const getCurvePathOps = (shape: Drawable): Op[] => { + // NOTE (mtolmacs): Temporary fix for extremely large elements + if (!shape) { + return []; + } + + for (const set of shape.sets) { + if (set.type === "path") { + return set.ops; + } + } + return shape.sets[0].ops; +}; + +// linear +export const getCurveShape = ( + roughShape: Drawable, + startingPoint: Point = pointFrom(0, 0), + angleInRadian: Radians, + center: Point, +): GeometricShape => { + const transform = (p: Point): Point => + pointRotateRads( + pointFrom(p[0] + startingPoint[0], p[1] + startingPoint[1]), + center, + angleInRadian, + ); + + const ops = getCurvePathOps(roughShape); + const polycurve: Polycurve = []; + let p0 = pointFrom(0, 0); + + for (const op of ops) { + if (op.op === "move") { + const p = pointFromArray(op.data); + invariant(p != null, "Ops data is not a point"); + p0 = transform(p); + } + if (op.op === "bcurveTo") { + const p1 = transform(pointFrom(op.data[0], op.data[1])); + const p2 = transform(pointFrom(op.data[2], op.data[3])); + const p3 = transform(pointFrom(op.data[4], op.data[5])); + polycurve.push(curve(p0, p1, p2, p3)); + p0 = p3; + } + } + + return { + type: "polycurve", + data: polycurve, + }; +}; + +const polylineFromPoints = ( + points: Point[], +): Polyline => { + let previousPoint: Point = points[0]; + const polyline: LineSegment[] = []; + + for (let i = 1; i < points.length; i++) { + const nextPoint = points[i]; + polyline.push(lineSegment(previousPoint, nextPoint)); + previousPoint = nextPoint; + } + + return polyline; +}; + +export const getFreedrawShape = ( + element: ExcalidrawFreeDrawElement, + center: Point, + isClosed: boolean = false, +): GeometricShape => { + const transform = (p: Point) => + pointRotateRads( + pointFromVector( + vectorAdd(vectorFromPoint(p), vector(element.x, element.y)), + ), + center, + element.angle, + ); + + const polyline = polylineFromPoints( + element.points.map((p) => transform(p as Point)), + ); + + return ( + isClosed + ? { + type: "polygon", + data: polygonFromPoints(polyline.flat()), + } + : { + type: "polyline", + data: polyline, + } + ) as GeometricShape; +}; + +export const getClosedCurveShape = ( + element: ExcalidrawLinearElement, + roughShape: Drawable, + startingPoint: Point = pointFrom(0, 0), + angleInRadian: Radians, + center: Point, +): GeometricShape => { + const transform = (p: Point) => + pointRotateRads( + pointFrom(p[0] + startingPoint[0], p[1] + startingPoint[1]), + center, + angleInRadian, + ); + + if (element.roundness === null) { + return { + type: "polygon", + data: polygonFromPoints( + element.points.map((p) => transform(p as Point)) as Point[], + ), + }; + } + + const ops = getCurvePathOps(roughShape); + + const points: Point[] = []; + let odd = false; + for (const operation of ops) { + if (operation.op === "move") { + odd = !odd; + if (odd) { + points.push(pointFrom(operation.data[0], operation.data[1])); + } + } else if (operation.op === "bcurveTo") { + if (odd) { + points.push(pointFrom(operation.data[0], operation.data[1])); + points.push(pointFrom(operation.data[2], operation.data[3])); + points.push(pointFrom(operation.data[4], operation.data[5])); + } + } else if (operation.op === "lineTo") { + if (odd) { + points.push(pointFrom(operation.data[0], operation.data[1])); + } + } + } + + const polygonPoints = pointsOnBezierCurves(points, 10, 5).map((p) => + transform(p as Point), + ) as Point[]; + + return { + type: "polygon", + data: polygonFromPoints(polygonPoints), + }; +}; + +/** + * Determine intersection of a rectangular shaped element and a + * line segment. + * + * @param element The rectangular element to test against + * @param segment The segment intersecting the element + * @param gap Optional value to inflate the shape before testing + * @returns An array of intersections + */ +// TODO: Replace with final rounded rectangle code +export const segmentIntersectRectangleElement = < + Point extends LocalPoint | GlobalPoint, +>( + element: ExcalidrawBindableElement, + segment: LineSegment, + gap: number = 0, +): Point[] => { + const bounds = [ + element.x - gap, + element.y - gap, + element.x + element.width + gap, + element.y + element.height + gap, + ]; + const center = pointFrom( + (bounds[0] + bounds[2]) / 2, + (bounds[1] + bounds[3]) / 2, + ); + + return [ + lineSegment( + pointRotateRads(pointFrom(bounds[0], bounds[1]), center, element.angle), + pointRotateRads(pointFrom(bounds[2], bounds[1]), center, element.angle), + ), + lineSegment( + pointRotateRads(pointFrom(bounds[2], bounds[1]), center, element.angle), + pointRotateRads(pointFrom(bounds[2], bounds[3]), center, element.angle), + ), + lineSegment( + pointRotateRads(pointFrom(bounds[2], bounds[3]), center, element.angle), + pointRotateRads(pointFrom(bounds[0], bounds[3]), center, element.angle), + ), + lineSegment( + pointRotateRads(pointFrom(bounds[0], bounds[3]), center, element.angle), + pointRotateRads(pointFrom(bounds[0], bounds[1]), center, element.angle), + ), + ] + .map((s) => segmentsIntersectAt(segment, s)) + .filter((i): i is Point => !!i); +}; + +const distanceToEllipse = ( + p: Point, + ellipse: Ellipse, +) => { + const { angle, halfWidth, halfHeight, center } = ellipse; + const a = halfWidth; + const b = halfHeight; + const translatedPoint = vectorAdd( + vectorFromPoint(p), + vectorScale(vectorFromPoint(center), -1), + ); + const [rotatedPointX, rotatedPointY] = pointRotateRads( + pointFromVector(translatedPoint), + pointFrom(0, 0), + -angle as Radians, + ); + + const px = Math.abs(rotatedPointX); + const py = Math.abs(rotatedPointY); + + let tx = 0.707; + let ty = 0.707; + + for (let i = 0; i < 3; i++) { + const x = a * tx; + const y = b * ty; + + const ex = ((a * a - b * b) * tx ** 3) / a; + const ey = ((b * b - a * a) * ty ** 3) / b; + + const rx = x - ex; + const ry = y - ey; + + const qx = px - ex; + const qy = py - ey; + + const r = Math.hypot(ry, rx); + const q = Math.hypot(qy, qx); + + tx = Math.min(1, Math.max(0, ((qx * r) / q + ex) / a)); + ty = Math.min(1, Math.max(0, ((qy * r) / q + ey) / b)); + const t = Math.hypot(ty, tx); + tx /= t; + ty /= t; + } + + const [minX, minY] = [ + a * tx * Math.sign(rotatedPointX), + b * ty * Math.sign(rotatedPointY), + ]; + + return pointDistance( + pointFrom(rotatedPointX, rotatedPointY), + pointFrom(minX, minY), + ); +}; + +export const pointOnEllipse = ( + point: Point, + ellipse: Ellipse, + threshold = PRECISION, +) => { + return distanceToEllipse(point, ellipse) <= threshold; +}; + +export const pointInEllipse = ( + p: Point, + ellipse: Ellipse, +) => { + const { center, angle, halfWidth, halfHeight } = ellipse; + const translatedPoint = vectorAdd( + vectorFromPoint(p), + vectorScale(vectorFromPoint(center), -1), + ); + const [rotatedPointX, rotatedPointY] = pointRotateRads( + pointFromVector(translatedPoint), + pointFrom(0, 0), + -angle as Radians, + ); + + return ( + (rotatedPointX / halfWidth) * (rotatedPointX / halfWidth) + + (rotatedPointY / halfHeight) * (rotatedPointY / halfHeight) <= + 1 + ); +}; + +export const ellipseAxes = ( + ellipse: Ellipse, +) => { + const widthGreaterThanHeight = ellipse.halfWidth > ellipse.halfHeight; + + const majorAxis = widthGreaterThanHeight + ? ellipse.halfWidth * 2 + : ellipse.halfHeight * 2; + const minorAxis = widthGreaterThanHeight + ? ellipse.halfHeight * 2 + : ellipse.halfWidth * 2; + + return { + majorAxis, + minorAxis, + }; +}; + +export const ellipseFocusToCenter = ( + ellipse: Ellipse, +) => { + const { majorAxis, minorAxis } = ellipseAxes(ellipse); + + return Math.sqrt(majorAxis ** 2 - minorAxis ** 2); +}; + +export const ellipseExtremes = ( + ellipse: Ellipse, +) => { + const { center, angle } = ellipse; + const { majorAxis, minorAxis } = ellipseAxes(ellipse); + + const cos = Math.cos(angle); + const sin = Math.sin(angle); + + const sqSum = majorAxis ** 2 + minorAxis ** 2; + const sqDiff = (majorAxis ** 2 - minorAxis ** 2) * Math.cos(2 * angle); + + const yMax = Math.sqrt((sqSum - sqDiff) / 2); + const xAtYMax = + (yMax * sqSum * sin * cos) / + (majorAxis ** 2 * sin ** 2 + minorAxis ** 2 * cos ** 2); + + const xMax = Math.sqrt((sqSum + sqDiff) / 2); + const yAtXMax = + (xMax * sqSum * sin * cos) / + (majorAxis ** 2 * cos ** 2 + minorAxis ** 2 * sin ** 2); + const centerVector = vectorFromPoint(center); + + return [ + vectorAdd(vector(xAtYMax, yMax), centerVector), + vectorAdd(vectorScale(vector(xAtYMax, yMax), -1), centerVector), + vectorAdd(vector(xMax, yAtXMax), centerVector), + vectorAdd(vector(xMax, yAtXMax), centerVector), + ]; +}; diff --git a/packages/element/src/linearElementEditor.ts b/packages/element/src/linearElementEditor.ts index 6a718633c2..445b576db7 100644 --- a/packages/element/src/linearElementEditor.ts +++ b/packages/element/src/linearElementEditor.ts @@ -18,8 +18,6 @@ import { isCurve, } from "@excalidraw/math"; -import { getCurvePathOps } from "@excalidraw/utils/shape"; - import { DRAGGING_THRESHOLD, KEYS, @@ -42,6 +40,8 @@ import type { } from "@excalidraw/excalidraw/types"; import type { Bounds } from "@excalidraw/common"; +import { getCurvePathOps } from "./geometricShapes"; + import { moveArrowAboveBindable } from "./zindex"; import { deconstructLinearOrFreeDrawElement, diff --git a/packages/element/src/shape.ts b/packages/element/src/shape.ts index b85a63d710..1265a08d77 100644 --- a/packages/element/src/shape.ts +++ b/packages/element/src/shape.ts @@ -2,15 +2,6 @@ import { pointsOnBezierCurves, simplify } from "points-on-curve"; import { getStroke, getStrokePoints } from "perfect-freehand"; import { LaserPointer } from "@excalidraw/laser-pointer"; -import { - type GeometricShape, - getClosedCurveShape, - getCurveShape, - getEllipseShape, - getFreedrawShape, - getPolygonShape, -} from "@excalidraw/utils/shape"; - import { pointFrom, pointDistance, @@ -45,6 +36,15 @@ import type { SVGPathString, } from "@excalidraw/excalidraw/scene/types"; +import { + type GeometricShape, + getClosedCurveShape, + getCurveShape, + getEllipseShape, + getFreedrawShape, + getPolygonShape, +} from "./geometricShapes"; + import { elementWithCanvasCache } from "./renderElement"; import { diff --git a/packages/element/src/visualdebug.ts b/packages/element/src/visualdebug.ts index e4e8b76c8e..140ece0afe 100644 --- a/packages/element/src/visualdebug.ts +++ b/packages/element/src/visualdebug.ts @@ -9,8 +9,6 @@ import { } from "@excalidraw/math"; import { type Bounds, isBounds } from "@excalidraw/common"; -import type { ElementsMap, ExcalidrawElement } from "@excalidraw/element/types"; - import type { Curve } from "@excalidraw/math"; import { getElementBounds } from "./bounds"; @@ -18,6 +16,8 @@ import { intersectElementWithLineSegment } from "./collision"; import { isFreeDrawElement, isLinearElement } from "./typeChecks"; import { isPathALoop } from "./utils"; +import type { ElementsMap, ExcalidrawElement } from "./types"; + // The global data holder to collect the debug operations declare global { interface Window { diff --git a/packages/element/tests/align.test.tsx b/packages/element/tests/align.test.tsx index 899b13da2b..4a44ad590b 100644 --- a/packages/element/tests/align.test.tsx +++ b/packages/element/tests/align.test.tsx @@ -8,7 +8,7 @@ import { actionAlignBottom, actionAlignLeft, actionAlignRight, -} from "@excalidraw/excalidraw/actions"; +} from "@excalidraw/excalidraw/actions/index"; import { defaultLang, setLanguage } from "@excalidraw/excalidraw/i18n"; import { Excalidraw } from "@excalidraw/excalidraw"; diff --git a/packages/element/tests/collision.test.tsx b/packages/element/tests/collision.test.tsx index 2d3a49cb20..dc74896401 100644 --- a/packages/element/tests/collision.test.tsx +++ b/packages/element/tests/collision.test.tsx @@ -14,7 +14,6 @@ import { import { Excalidraw } from "@excalidraw/excalidraw"; import { API } from "@excalidraw/excalidraw/tests/helpers/api"; import { UI } from "@excalidraw/excalidraw/tests/helpers/ui"; -import "@excalidraw/utils/test-utils"; import { render } from "@excalidraw/excalidraw/tests/test-utils"; import type { Zoom } from "@excalidraw/excalidraw/types"; diff --git a/packages/element/tests/cropElement.test.tsx b/packages/element/tests/cropElement.test.tsx index 1489e8cfa6..cf6a3ca2f8 100644 --- a/packages/element/tests/cropElement.test.tsx +++ b/packages/element/tests/cropElement.test.tsx @@ -7,7 +7,7 @@ import { Excalidraw, exportScene } from "@excalidraw/excalidraw"; import { actionFlipHorizontal, actionFlipVertical, -} from "@excalidraw/excalidraw/actions"; +} from "@excalidraw/excalidraw/actions/index"; import { API } from "@excalidraw/excalidraw/tests/helpers/api"; import { Keyboard, Pointer, UI } from "@excalidraw/excalidraw/tests/helpers/ui"; diff --git a/packages/element/tests/delta.test.tsx b/packages/element/tests/delta.test.tsx index e1fa56501f..43f6599ae6 100644 --- a/packages/element/tests/delta.test.tsx +++ b/packages/element/tests/delta.test.tsx @@ -3,15 +3,17 @@ import { arrayToMap } from "@excalidraw/common"; import { pointFrom } from "@excalidraw/math"; import type { ObservedAppState } from "@excalidraw/excalidraw/types"; -import type { LinearElementEditor } from "@excalidraw/element"; + +import { AppStateDelta, Delta, ElementsDelta } from "../src/delta"; + +import { mutateElement, newElementWith } from "../src/mutateElement"; + +import type { LinearElementEditor } from "../src/index"; import type { ExcalidrawTextElement, FractionalIndex, SceneElementsMap, -} from "@excalidraw/element/types"; - -import { AppStateDelta, Delta, ElementsDelta } from "../src/delta"; -import { mutateElement, newElementWith } from "../src/mutateElement"; +} from "../src/types"; describe("ElementsDelta", () => { describe("visible changes", () => { diff --git a/packages/element/tests/distribute.test.tsx b/packages/element/tests/distribute.test.tsx index b59567e42c..9cb5f30776 100644 --- a/packages/element/tests/distribute.test.tsx +++ b/packages/element/tests/distribute.test.tsx @@ -1,7 +1,7 @@ import { distributeHorizontally, distributeVertically, -} from "@excalidraw/excalidraw/actions"; +} from "@excalidraw/excalidraw/actions/index"; import { defaultLang, setLanguage } from "@excalidraw/excalidraw/i18n"; import { Excalidraw } from "@excalidraw/excalidraw"; diff --git a/packages/element/tests/duplicate.test.tsx b/packages/element/tests/duplicate.test.tsx index 80403fa135..63bda8e3e4 100644 --- a/packages/element/tests/duplicate.test.tsx +++ b/packages/element/tests/duplicate.test.tsx @@ -11,7 +11,7 @@ import { import { Excalidraw, mutateElement } from "@excalidraw/excalidraw"; -import { actionDuplicateSelection } from "@excalidraw/excalidraw/actions"; +import { actionDuplicateSelection } from "@excalidraw/excalidraw/actions/index"; import { API } from "@excalidraw/excalidraw/tests/helpers/api"; diff --git a/packages/element/tests/elbowArrow.test.tsx b/packages/element/tests/elbowArrow.test.tsx index 749e1b8064..db3e3b8311 100644 --- a/packages/element/tests/elbowArrow.test.tsx +++ b/packages/element/tests/elbowArrow.test.tsx @@ -1,7 +1,7 @@ import { ARROW_TYPE, DEFAULT_ZOOM } from "@excalidraw/common"; import { pointFrom } from "@excalidraw/math"; import { Excalidraw } from "@excalidraw/excalidraw"; -import { actionSelectAll } from "@excalidraw/excalidraw/actions"; +import { actionSelectAll } from "@excalidraw/excalidraw/actions/index"; import { actionChangeArrowhead } from "@excalidraw/excalidraw/actions/actionProperties"; import { actionDuplicateSelection } from "@excalidraw/excalidraw/actions/actionDuplicateSelection"; import { API } from "@excalidraw/excalidraw/tests/helpers/api"; @@ -13,11 +13,11 @@ import { queryByTestId, render, } from "@excalidraw/excalidraw/tests/test-utils"; -import "@excalidraw/utils/test-utils"; -import { bindBindingElement, validateElbowPoints } from "@excalidraw/element"; import type { LocalPoint } from "@excalidraw/math"; +import { bindBindingElement, validateElbowPoints } from "../src/index"; + import { Scene } from "../src/Scene"; import type { diff --git a/packages/element/tests/flowchart.test.tsx b/packages/element/tests/flowchart.test.tsx index 98b48ec2da..123daabc6e 100644 --- a/packages/element/tests/flowchart.test.tsx +++ b/packages/element/tests/flowchart.test.tsx @@ -12,7 +12,7 @@ import { import type { ExcalidrawElement, NonDeletedExcalidrawElement, -} from "@excalidraw/element/types"; +} from "../src/types"; unmountComponent(); diff --git a/packages/element/tests/fractionalIndex.test.ts b/packages/element/tests/fractionalIndex.test.ts index 2834a831e1..35aff5b7f8 100644 --- a/packages/element/tests/fractionalIndex.test.ts +++ b/packages/element/tests/fractionalIndex.test.ts @@ -1,15 +1,6 @@ /* eslint-disable no-lone-blocks */ import { arrayToMap } from "@excalidraw/common"; -import { - InvalidFractionalIndexError, - syncInvalidIndices, - syncMovedIndices, - validateFractionalIndices, -} from "@excalidraw/element"; - -import { deepCopyElement } from "@excalidraw/element"; - import { API } from "@excalidraw/excalidraw/tests/helpers/api"; import { @@ -17,11 +8,20 @@ import { validateOrderKey, } from "@excalidraw/fractional-indexing"; +import { + InvalidFractionalIndexError, + syncInvalidIndices, + syncMovedIndices, + validateFractionalIndices, +} from "../src/index"; + +import { deepCopyElement } from "../src/index"; + import type { ElementsMap, ExcalidrawElement, FractionalIndex, -} from "@excalidraw/element/types"; +} from "../src/types"; describe("fractional index format validation", () => { it("should reject malformed base62 order keys", () => { diff --git a/packages/element/tests/frame.test.tsx b/packages/element/tests/frame.test.tsx index 002b5bdabf..797e82f3b1 100644 --- a/packages/element/tests/frame.test.tsx +++ b/packages/element/tests/frame.test.tsx @@ -14,7 +14,7 @@ import { render, } from "@excalidraw/excalidraw/tests/test-utils"; -import { getSelectedElements } from "@excalidraw/excalidraw/scene"; +import { getSelectedElements } from "@excalidraw/excalidraw/scene/index"; import { exportScene } from "@excalidraw/excalidraw/scene/export"; import type { GlobalPoint, LocalPoint } from "@excalidraw/math"; diff --git a/packages/utils/tests/geometry.test.ts b/packages/element/tests/geometricShapes.test.ts similarity index 97% rename from packages/utils/tests/geometry.test.ts rename to packages/element/tests/geometricShapes.test.ts index 6e46de55a3..f37822b9e0 100644 --- a/packages/utils/tests/geometry.test.ts +++ b/packages/element/tests/geometricShapes.test.ts @@ -14,7 +14,11 @@ import type { Radians, } from "@excalidraw/math"; -import { pointInEllipse, pointOnEllipse, type Ellipse } from "../src/shape"; +import { + pointInEllipse, + pointOnEllipse, + type Ellipse, +} from "../src/geometricShapes"; describe("point and line", () => { // const l: Line = line(point(1, 0), point(1, 2)); diff --git a/packages/element/tests/sortElements.test.ts b/packages/element/tests/sortElements.test.ts index 0554d38e35..535c1e01c2 100644 --- a/packages/element/tests/sortElements.test.ts +++ b/packages/element/tests/sortElements.test.ts @@ -1,6 +1,6 @@ import { API } from "@excalidraw/excalidraw/tests/helpers/api"; -import { mutateElement } from "@excalidraw/element"; +import { mutateElement } from "../src/index"; import { normalizeElementOrder } from "../src/sortElements"; diff --git a/packages/element/tests/zindex.test.tsx b/packages/element/tests/zindex.test.tsx index 19614fee7d..1ce33bf2fc 100644 --- a/packages/element/tests/zindex.test.tsx +++ b/packages/element/tests/zindex.test.tsx @@ -6,7 +6,7 @@ import { actionBringToFront, actionSendToBack, actionDuplicateSelection, -} from "@excalidraw/excalidraw/actions"; +} from "@excalidraw/excalidraw/actions/index"; import { Excalidraw, getNonDeletedElements } from "@excalidraw/excalidraw"; diff --git a/packages/excalidraw/components/Stats/MultiDimension.tsx b/packages/excalidraw/components/Stats/MultiDimension.tsx index 8df541d091..fddafcd0a6 100644 --- a/packages/excalidraw/components/Stats/MultiDimension.tsx +++ b/packages/excalidraw/components/Stats/MultiDimension.tsx @@ -23,7 +23,7 @@ import { getBoundTextElement, handleBindTextResize } from "@excalidraw/element"; import { isTextElement } from "@excalidraw/element"; -import { getCommonBounds } from "@excalidraw/utils"; +import { getCommonBounds } from "@excalidraw/element"; import type { ElementsMap, diff --git a/packages/excalidraw/components/TTDDialog/common.ts b/packages/excalidraw/components/TTDDialog/common.ts index 2d07245c1e..c1d6f192d9 100644 --- a/packages/excalidraw/components/TTDDialog/common.ts +++ b/packages/excalidraw/components/TTDDialog/common.ts @@ -2,14 +2,14 @@ import { DEFAULT_EXPORT_PADDING, EDITOR_LS_KEYS } from "@excalidraw/common"; import { convertToExcalidrawElements } from "@excalidraw/element"; -import { exportScene } from "@excalidraw/utils"; - import type { RenderEnvironment } from "@excalidraw/element"; import type { NonDeletedExcalidrawElement, Theme, } from "@excalidraw/element/types"; +import { exportScene } from "../../scene/export"; + import { EditorLocalStorage } from "../../data/EditorLocalStorage"; import type { MermaidToExcalidrawLibProps } from "./types"; diff --git a/packages/excalidraw/components/TTDDialog/types.ts b/packages/excalidraw/components/TTDDialog/types.ts index 6d824d0c04..786ec6031c 100644 --- a/packages/excalidraw/components/TTDDialog/types.ts +++ b/packages/excalidraw/components/TTDDialog/types.ts @@ -1,11 +1,11 @@ -import type { RequestError } from "@excalidraw/excalidraw/errors"; - import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types"; import type { MermaidConfig } from "@excalidraw/mermaid-to-excalidraw"; import type { MermaidToExcalidrawResult } from "@excalidraw/mermaid-to-excalidraw/dist/interfaces"; +import type { RequestError } from "../../errors"; + import type { BinaryFiles } from "../../types"; export type LLMMessage = { diff --git a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx index 0d4fc23417..179ef5e070 100644 --- a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx +++ b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx @@ -6,14 +6,6 @@ import { type EditorInterface, } from "@excalidraw/common"; -import type { - InteractiveCanvasRenderConfig, - InteractiveSceneRenderAnimationState, - InteractiveSceneRenderConfig, - RenderableElementsMap, - RenderInteractiveSceneCallback, -} from "@excalidraw/excalidraw/scene/types"; - import type { NonDeletedExcalidrawElement, NonDeletedSceneElementsMap, @@ -25,6 +17,14 @@ import { renderInteractiveScene } from "../../renderer/interactiveScene"; import { AnimationController } from "../../renderer/animation"; +import type { + InteractiveCanvasRenderConfig, + InteractiveSceneRenderAnimationState, + InteractiveSceneRenderConfig, + RenderableElementsMap, + RenderInteractiveSceneCallback, +} from "../../scene/types"; + import type { AppClassProperties, AppState, diff --git a/packages/excalidraw/package.json b/packages/excalidraw/package.json index fc006b153e..a515396a16 100644 --- a/packages/excalidraw/package.json +++ b/packages/excalidraw/package.json @@ -19,6 +19,7 @@ "types": "./dist/types/utils/src/*.d.ts" }, "./*": { + "excalidraw-source": "./*.js", "types": "./dist/types/excalidraw/*.d.ts" }, "./index.css": { @@ -26,6 +27,7 @@ "production": "./dist/prod/index.css" }, ".": { + "excalidraw-source": "./index.tsx", "types": "./dist/types/excalidraw/index.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", @@ -36,7 +38,34 @@ "dist/*" ], "publishConfig": { - "access": "public" + "access": "public", + "exports": { + "./common/*": { + "types": "./dist/types/common/src/*.d.ts" + }, + "./element/*": { + "types": "./dist/types/element/src/*.d.ts" + }, + "./math/*": { + "types": "./dist/types/math/src/*.d.ts" + }, + "./utils/*": { + "types": "./dist/types/utils/src/*.d.ts" + }, + "./*": { + "types": "./dist/types/excalidraw/*.d.ts" + }, + "./index.css": { + "development": "./dist/dev/index.css", + "production": "./dist/prod/index.css" + }, + ".": { + "types": "./dist/types/excalidraw/index.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + } + } }, "description": "Excalidraw as a React component", "license": "MIT", diff --git a/packages/excalidraw/tests/data/restore.test.ts b/packages/excalidraw/tests/data/restore.test.ts index ffd52a96eb..9169fbca30 100644 --- a/packages/excalidraw/tests/data/restore.test.ts +++ b/packages/excalidraw/tests/data/restore.test.ts @@ -29,13 +29,14 @@ import type { ExcalidrawTextElement, FractionalIndex, } from "@excalidraw/element/types"; -import type { NormalizedZoomValue } from "@excalidraw/excalidraw/types"; import { API } from "../helpers/api"; import * as restore from "../../data/restore"; import { getDefaultAppState } from "../../appState"; import { serializeAsJSON } from "../../data/json"; +import type { NormalizedZoomValue } from "../../types"; + import type { ImportedDataState } from "../../data/types"; import type { LibraryItem, LibraryItem_v1, LibraryItems } from "../../types"; diff --git a/packages/excalidraw/tests/history.test.tsx b/packages/excalidraw/tests/history.test.tsx index cfcf45b15e..59cc28e4f6 100644 --- a/packages/excalidraw/tests/history.test.tsx +++ b/packages/excalidraw/tests/history.test.tsx @@ -23,8 +23,6 @@ import { randomId, } from "@excalidraw/common"; -import "@excalidraw/utils/test-utils"; - import { ElementsDelta, AppStateDelta } from "@excalidraw/element"; import { CaptureUpdateAction, StoreDelta } from "@excalidraw/element"; diff --git a/packages/excalidraw/tests/move.test.tsx b/packages/excalidraw/tests/move.test.tsx index 55ae99ca75..45ac353175 100644 --- a/packages/excalidraw/tests/move.test.tsx +++ b/packages/excalidraw/tests/move.test.tsx @@ -2,7 +2,6 @@ import React from "react"; import { vi } from "vitest"; import { KEYS, reseed, DEFAULT_ZOOM } from "@excalidraw/common"; import { bindBindingElement } from "@excalidraw/element"; -import "@excalidraw/utils/test-utils"; import type { ExcalidrawArrowElement, diff --git a/packages/excalidraw/tests/queries/toolQueries.ts b/packages/excalidraw/tests/queries/toolQueries.ts index ba73f6d531..77976f35e8 100644 --- a/packages/excalidraw/tests/queries/toolQueries.ts +++ b/packages/excalidraw/tests/queries/toolQueries.ts @@ -2,7 +2,7 @@ import { queries, buildQueries } from "@testing-library/react"; import { TOOL_TYPE } from "@excalidraw/common"; -import type { ToolType } from "@excalidraw/excalidraw/types"; +import type { ToolType } from "../../types"; const _getAllByToolName = (container: HTMLElement, tool: ToolType | "lock") => { const toolTitle = tool === "lock" ? "lock" : TOOL_TYPE[tool]; diff --git a/packages/fractional-indexing/package.json b/packages/fractional-indexing/package.json index ce31bcd8dc..3e5aeda64e 100644 --- a/packages/fractional-indexing/package.json +++ b/packages/fractional-indexing/package.json @@ -30,6 +30,7 @@ }, "exports": { ".": { + "excalidraw-source": "./src/index.ts", "types": "./dist/types/fractional-indexing/src/index.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", @@ -37,7 +38,15 @@ } }, "publishConfig": { - "access": "public" + "access": "public", + "exports": { + ".": { + "types": "./dist/types/fractional-indexing/src/index.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + } + } }, "files": [ "dist/*" diff --git a/packages/laser-pointer/package.json b/packages/laser-pointer/package.json index 9b9dad330c..b7ca7ed9c5 100644 --- a/packages/laser-pointer/package.json +++ b/packages/laser-pointer/package.json @@ -8,6 +8,7 @@ "module": "./dist/prod/index.js", "exports": { ".": { + "excalidraw-source": "./src/index.ts", "types": "./dist/types/laser-pointer/src/index.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", @@ -25,7 +26,15 @@ "repository": "https://github.com/excalidraw/excalidraw", "license": "MIT", "publishConfig": { - "access": "public" + "access": "public", + "exports": { + ".": { + "types": "./dist/types/laser-pointer/src/index.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + } + } }, "scripts": { "gen:types": "rimraf types && tsc", diff --git a/packages/math/package.json b/packages/math/package.json index 6179f41054..099050786c 100644 --- a/packages/math/package.json +++ b/packages/math/package.json @@ -7,12 +7,14 @@ "module": "./dist/prod/index.js", "exports": { ".": { + "excalidraw-source": "./src/index.ts", "types": "./dist/types/math/src/index.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", "default": "./dist/prod/index.js" }, "./*": { + "excalidraw-source": "./src/*.js", "types": "./dist/types/math/src/*.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", @@ -24,7 +26,21 @@ ], "description": "Excalidraw math functions", "publishConfig": { - "access": "public" + "access": "public", + "exports": { + ".": { + "types": "./dist/types/math/src/index.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + }, + "./*": { + "types": "./dist/types/math/src/*.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + } + } }, "license": "MIT", "keywords": [ @@ -59,8 +75,5 @@ "scripts": { "gen:types": "rimraf types && tsc", "build:esm": "rimraf dist && node ../../scripts/buildBase.js && pnpm gen:types" - }, - "dependencies": { - "@excalidraw/common": "workspace:*" } } diff --git a/packages/math/src/range.ts b/packages/math/src/range.ts index 1b292344ee..b8d3cd50c5 100644 --- a/packages/math/src/range.ts +++ b/packages/math/src/range.ts @@ -1,5 +1,3 @@ -import { toBrandedType } from "@excalidraw/common"; - import type { InclusiveRange } from "./types"; /** @@ -10,7 +8,7 @@ import type { InclusiveRange } from "./types"; * @returns */ export function rangeInclusive(start: number, end: number): InclusiveRange { - return toBrandedType([start, end]); + return [start, end] as InclusiveRange; } /** @@ -20,7 +18,7 @@ export function rangeInclusive(start: number, end: number): InclusiveRange { * @returns The new inclusive range */ export function rangeInclusiveFromPair(pair: [start: number, end: number]) { - return toBrandedType(pair); + return pair as InclusiveRange; } /** @@ -62,7 +60,7 @@ export const rangeIntersection = ( const rangeEnd = Math.min(a1, b1); if (rangeStart <= rangeEnd) { - return toBrandedType([rangeStart, rangeEnd]); + return [rangeStart, rangeEnd] as InclusiveRange; } return null; diff --git a/packages/math/tests/curve.test.ts b/packages/math/tests/curve.test.ts index 5ca0626d17..f3081d5490 100644 --- a/packages/math/tests/curve.test.ts +++ b/packages/math/tests/curve.test.ts @@ -1,5 +1,3 @@ -import "@excalidraw/utils/test-utils"; - import { bezierEquation, curve, diff --git a/packages/tsconfig.base.json b/packages/tsconfig.base.json index 59c10c0f14..60415815dc 100644 --- a/packages/tsconfig.base.json +++ b/packages/tsconfig.base.json @@ -10,21 +10,6 @@ "resolveJsonModule": true, "jsx": "react-jsx", "emitDeclarationOnly": true, - "paths": { - "@excalidraw/common": ["./common/src/index.ts"], - "@excalidraw/common/*": ["./common/src/*"], - "@excalidraw/element": ["./element/src/index.ts"], - "@excalidraw/element/*": ["./element/src/*"], - "@excalidraw/excalidraw": ["./excalidraw/index.tsx"], - "@excalidraw/excalidraw/*": ["./excalidraw/*"], - "@excalidraw/laser-pointer": ["./laser-pointer/src/index.ts"], - "@excalidraw/laser-pointer/*": ["./laser-pointer/src/*"], - "@excalidraw/math": ["./math/src/index.ts"], - "@excalidraw/math/*": ["./math/src/*"], - "@excalidraw/utils": ["./utils/src/index.ts"], - "@excalidraw/utils/*": ["./utils/src/*"], - "@excalidraw/fractional-indexing": ["./fractional-indexing/src/index.ts"], - "@excalidraw/fractional-indexing/*": ["./fractional-indexing/src/*"] - } + "customConditions": ["excalidraw-source"] } } diff --git a/packages/utils/package.json b/packages/utils/package.json index 690f10d3d1..70240e242e 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -7,12 +7,14 @@ "module": "./dist/prod/index.js", "exports": { ".": { + "excalidraw-source": "./src/index.ts", "types": "./dist/types/utils/src/index.d.ts", "development": "./dist/dev/index.js", "production": "./dist/prod/index.js", "default": "./dist/prod/index.js" }, "./*": { + "excalidraw-source": "./src/*.js", "types": "./dist/types/utils/src/*.d.ts" } }, @@ -21,7 +23,18 @@ ], "description": "Excalidraw utility functions", "publishConfig": { - "access": "public" + "access": "public", + "exports": { + ".": { + "types": "./dist/types/utils/src/index.d.ts", + "development": "./dist/dev/index.js", + "production": "./dist/prod/index.js", + "default": "./dist/prod/index.js" + }, + "./*": { + "types": "./dist/types/utils/src/*.d.ts" + } + } }, "license": "MIT", "keywords": [ @@ -56,12 +69,14 @@ "png-chunk-text": "1.0.0", "png-chunks-encode": "1.0.0", "png-chunks-extract": "1.0.0", - "points-on-curve": "0.2.0", "roughjs": "4.6.4" }, "devDependencies": { + "@excalidraw/common": "workspace:*", + "@excalidraw/element": "workspace:*", + "@excalidraw/excalidraw": "workspace:*", + "@excalidraw/math": "workspace:*", "cross-env": "7.0.3", - "jest-diff": "29.7.0", "typescript": "5.9.3", "wawoff2": "2.0.1", "which": "4.0.0" diff --git a/packages/utils/src/shape.ts b/packages/utils/src/shape.ts index 2d0e27aec7..3a49a51663 100644 --- a/packages/utils/src/shape.ts +++ b/packages/utils/src/shape.ts @@ -1,546 +1,2 @@ -/** - * this file defines pure geometric shapes - * - * for instance, a cubic bezier curve is specified by its four control points and - * an ellipse is defined by its center, angle, semi major axis and semi minor axis - * (but in semi-width and semi-height so it's more relevant to Excalidraw) - * - * the idea with pure shapes is so that we can provide collision and other geoemtric methods not depending on - * the specifics of roughjs or elements in Excalidraw; instead, we can focus on the pure shapes themselves - * - * also included in this file are methods for converting an Excalidraw element or a Drawable from roughjs - * to pure shapes - */ -import { pointsOnBezierCurves } from "points-on-curve"; - -import { invariant } from "@excalidraw/common"; -import { - curve, - lineSegment, - pointFrom, - pointDistance, - pointFromArray, - pointFromVector, - pointRotateRads, - polygon, - polygonFromPoints, - PRECISION, - segmentsIntersectAt, - vector, - vectorAdd, - vectorFromPoint, - vectorScale, - type GlobalPoint, - type LocalPoint, -} from "@excalidraw/math"; - -import { getElementAbsoluteCoords } from "@excalidraw/element"; - -import type { - ElementsMap, - ExcalidrawBindableElement, - ExcalidrawDiamondElement, - ExcalidrawElement, - ExcalidrawEllipseElement, - ExcalidrawEmbeddableElement, - ExcalidrawFrameLikeElement, - ExcalidrawFreeDrawElement, - ExcalidrawIframeElement, - ExcalidrawImageElement, - ExcalidrawLinearElement, - ExcalidrawRectangleElement, - ExcalidrawSelectionElement, - ExcalidrawStickyNoteElement, - ExcalidrawTextElement, -} from "@excalidraw/element/types"; -import type { Curve, LineSegment, Polygon, Radians } from "@excalidraw/math"; - -import type { Drawable, Op } from "roughjs/bin/core"; - -// a polyline (made up term here) is a line consisting of other line segments -// this corresponds to a straight line element in the editor but it could also -// be used to model other elements -export type Polyline = - LineSegment[]; - -// a polycurve is a curve consisting of ther curves, this corresponds to a complex -// curve on the canvas -export type Polycurve = Curve[]; - -// an ellipse is specified by its center, angle, and its major and minor axes -// but for the sake of simplicity, we've used halfWidth and halfHeight instead -// in replace of semi major and semi minor axes -export type Ellipse = { - center: Point; - angle: Radians; - halfWidth: number; - halfHeight: number; -}; - -export type GeometricShape = - | { - type: "line"; - data: LineSegment; - } - | { - type: "polygon"; - data: Polygon; - } - | { - type: "curve"; - data: Curve; - } - | { - type: "ellipse"; - data: Ellipse; - } - | { - type: "polyline"; - data: Polyline; - } - | { - type: "polycurve"; - data: Polycurve; - }; - -type RectangularElement = - | ExcalidrawRectangleElement - | ExcalidrawStickyNoteElement - | ExcalidrawDiamondElement - | ExcalidrawFrameLikeElement - | ExcalidrawEmbeddableElement - | ExcalidrawImageElement - | ExcalidrawIframeElement - | ExcalidrawTextElement - | ExcalidrawSelectionElement; - -// polygon -export const getPolygonShape = ( - element: RectangularElement, -): GeometricShape => { - const { angle, width, height, x, y } = element; - - const cx = x + width / 2; - const cy = y + height / 2; - - const center: Point = pointFrom(cx, cy); - - let data: Polygon; - - if (element.type === "diamond") { - data = polygon( - pointRotateRads(pointFrom(cx, y), center, angle), - pointRotateRads(pointFrom(x + width, cy), center, angle), - pointRotateRads(pointFrom(cx, y + height), center, angle), - pointRotateRads(pointFrom(x, cy), center, angle), - ); - } else { - data = polygon( - pointRotateRads(pointFrom(x, y), center, angle), - pointRotateRads(pointFrom(x + width, y), center, angle), - pointRotateRads(pointFrom(x + width, y + height), center, angle), - pointRotateRads(pointFrom(x, y + height), center, angle), - ); - } - - return { - type: "polygon", - data, - }; -}; - -// return the selection box for an element, possibly rotated as well -export const getSelectionBoxShape = ( - element: ExcalidrawElement, - elementsMap: ElementsMap, - padding = 10, -) => { - let [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords( - element, - elementsMap, - true, - ); - - x1 -= padding; - x2 += padding; - y1 -= padding; - y2 += padding; - - //const angleInDegrees = angleToDegrees(element.angle); - const center = pointFrom(cx, cy); - const topLeft = pointRotateRads(pointFrom(x1, y1), center, element.angle); - const topRight = pointRotateRads(pointFrom(x2, y1), center, element.angle); - const bottomLeft = pointRotateRads(pointFrom(x1, y2), center, element.angle); - const bottomRight = pointRotateRads(pointFrom(x2, y2), center, element.angle); - - return { - type: "polygon", - data: [topLeft, topRight, bottomRight, bottomLeft], - } as GeometricShape; -}; - -// ellipse -export const getEllipseShape = ( - element: ExcalidrawEllipseElement, -): GeometricShape => { - const { width, height, angle, x, y } = element; - - return { - type: "ellipse", - data: { - center: pointFrom(x + width / 2, y + height / 2), - angle, - halfWidth: width / 2, - halfHeight: height / 2, - }, - }; -}; - -export const getCurvePathOps = (shape: Drawable): Op[] => { - // NOTE (mtolmacs): Temporary fix for extremely large elements - if (!shape) { - return []; - } - - for (const set of shape.sets) { - if (set.type === "path") { - return set.ops; - } - } - return shape.sets[0].ops; -}; - -// linear -export const getCurveShape = ( - roughShape: Drawable, - startingPoint: Point = pointFrom(0, 0), - angleInRadian: Radians, - center: Point, -): GeometricShape => { - const transform = (p: Point): Point => - pointRotateRads( - pointFrom(p[0] + startingPoint[0], p[1] + startingPoint[1]), - center, - angleInRadian, - ); - - const ops = getCurvePathOps(roughShape); - const polycurve: Polycurve = []; - let p0 = pointFrom(0, 0); - - for (const op of ops) { - if (op.op === "move") { - const p = pointFromArray(op.data); - invariant(p != null, "Ops data is not a point"); - p0 = transform(p); - } - if (op.op === "bcurveTo") { - const p1 = transform(pointFrom(op.data[0], op.data[1])); - const p2 = transform(pointFrom(op.data[2], op.data[3])); - const p3 = transform(pointFrom(op.data[4], op.data[5])); - polycurve.push(curve(p0, p1, p2, p3)); - p0 = p3; - } - } - - return { - type: "polycurve", - data: polycurve, - }; -}; - -const polylineFromPoints = ( - points: Point[], -): Polyline => { - let previousPoint: Point = points[0]; - const polyline: LineSegment[] = []; - - for (let i = 1; i < points.length; i++) { - const nextPoint = points[i]; - polyline.push(lineSegment(previousPoint, nextPoint)); - previousPoint = nextPoint; - } - - return polyline; -}; - -export const getFreedrawShape = ( - element: ExcalidrawFreeDrawElement, - center: Point, - isClosed: boolean = false, -): GeometricShape => { - const transform = (p: Point) => - pointRotateRads( - pointFromVector( - vectorAdd(vectorFromPoint(p), vector(element.x, element.y)), - ), - center, - element.angle, - ); - - const polyline = polylineFromPoints( - element.points.map((p) => transform(p as Point)), - ); - - return ( - isClosed - ? { - type: "polygon", - data: polygonFromPoints(polyline.flat()), - } - : { - type: "polyline", - data: polyline, - } - ) as GeometricShape; -}; - -export const getClosedCurveShape = ( - element: ExcalidrawLinearElement, - roughShape: Drawable, - startingPoint: Point = pointFrom(0, 0), - angleInRadian: Radians, - center: Point, -): GeometricShape => { - const transform = (p: Point) => - pointRotateRads( - pointFrom(p[0] + startingPoint[0], p[1] + startingPoint[1]), - center, - angleInRadian, - ); - - if (element.roundness === null) { - return { - type: "polygon", - data: polygonFromPoints( - element.points.map((p) => transform(p as Point)) as Point[], - ), - }; - } - - const ops = getCurvePathOps(roughShape); - - const points: Point[] = []; - let odd = false; - for (const operation of ops) { - if (operation.op === "move") { - odd = !odd; - if (odd) { - points.push(pointFrom(operation.data[0], operation.data[1])); - } - } else if (operation.op === "bcurveTo") { - if (odd) { - points.push(pointFrom(operation.data[0], operation.data[1])); - points.push(pointFrom(operation.data[2], operation.data[3])); - points.push(pointFrom(operation.data[4], operation.data[5])); - } - } else if (operation.op === "lineTo") { - if (odd) { - points.push(pointFrom(operation.data[0], operation.data[1])); - } - } - } - - const polygonPoints = pointsOnBezierCurves(points, 10, 5).map((p) => - transform(p as Point), - ) as Point[]; - - return { - type: "polygon", - data: polygonFromPoints(polygonPoints), - }; -}; - -/** - * Determine intersection of a rectangular shaped element and a - * line segment. - * - * @param element The rectangular element to test against - * @param segment The segment intersecting the element - * @param gap Optional value to inflate the shape before testing - * @returns An array of intersections - */ -// TODO: Replace with final rounded rectangle code -export const segmentIntersectRectangleElement = < - Point extends LocalPoint | GlobalPoint, ->( - element: ExcalidrawBindableElement, - segment: LineSegment, - gap: number = 0, -): Point[] => { - const bounds = [ - element.x - gap, - element.y - gap, - element.x + element.width + gap, - element.y + element.height + gap, - ]; - const center = pointFrom( - (bounds[0] + bounds[2]) / 2, - (bounds[1] + bounds[3]) / 2, - ); - - return [ - lineSegment( - pointRotateRads(pointFrom(bounds[0], bounds[1]), center, element.angle), - pointRotateRads(pointFrom(bounds[2], bounds[1]), center, element.angle), - ), - lineSegment( - pointRotateRads(pointFrom(bounds[2], bounds[1]), center, element.angle), - pointRotateRads(pointFrom(bounds[2], bounds[3]), center, element.angle), - ), - lineSegment( - pointRotateRads(pointFrom(bounds[2], bounds[3]), center, element.angle), - pointRotateRads(pointFrom(bounds[0], bounds[3]), center, element.angle), - ), - lineSegment( - pointRotateRads(pointFrom(bounds[0], bounds[3]), center, element.angle), - pointRotateRads(pointFrom(bounds[0], bounds[1]), center, element.angle), - ), - ] - .map((s) => segmentsIntersectAt(segment, s)) - .filter((i): i is Point => !!i); -}; - -const distanceToEllipse = ( - p: Point, - ellipse: Ellipse, -) => { - const { angle, halfWidth, halfHeight, center } = ellipse; - const a = halfWidth; - const b = halfHeight; - const translatedPoint = vectorAdd( - vectorFromPoint(p), - vectorScale(vectorFromPoint(center), -1), - ); - const [rotatedPointX, rotatedPointY] = pointRotateRads( - pointFromVector(translatedPoint), - pointFrom(0, 0), - -angle as Radians, - ); - - const px = Math.abs(rotatedPointX); - const py = Math.abs(rotatedPointY); - - let tx = 0.707; - let ty = 0.707; - - for (let i = 0; i < 3; i++) { - const x = a * tx; - const y = b * ty; - - const ex = ((a * a - b * b) * tx ** 3) / a; - const ey = ((b * b - a * a) * ty ** 3) / b; - - const rx = x - ex; - const ry = y - ey; - - const qx = px - ex; - const qy = py - ey; - - const r = Math.hypot(ry, rx); - const q = Math.hypot(qy, qx); - - tx = Math.min(1, Math.max(0, ((qx * r) / q + ex) / a)); - ty = Math.min(1, Math.max(0, ((qy * r) / q + ey) / b)); - const t = Math.hypot(ty, tx); - tx /= t; - ty /= t; - } - - const [minX, minY] = [ - a * tx * Math.sign(rotatedPointX), - b * ty * Math.sign(rotatedPointY), - ]; - - return pointDistance( - pointFrom(rotatedPointX, rotatedPointY), - pointFrom(minX, minY), - ); -}; - -export const pointOnEllipse = ( - point: Point, - ellipse: Ellipse, - threshold = PRECISION, -) => { - return distanceToEllipse(point, ellipse) <= threshold; -}; - -export const pointInEllipse = ( - p: Point, - ellipse: Ellipse, -) => { - const { center, angle, halfWidth, halfHeight } = ellipse; - const translatedPoint = vectorAdd( - vectorFromPoint(p), - vectorScale(vectorFromPoint(center), -1), - ); - const [rotatedPointX, rotatedPointY] = pointRotateRads( - pointFromVector(translatedPoint), - pointFrom(0, 0), - -angle as Radians, - ); - - return ( - (rotatedPointX / halfWidth) * (rotatedPointX / halfWidth) + - (rotatedPointY / halfHeight) * (rotatedPointY / halfHeight) <= - 1 - ); -}; - -export const ellipseAxes = ( - ellipse: Ellipse, -) => { - const widthGreaterThanHeight = ellipse.halfWidth > ellipse.halfHeight; - - const majorAxis = widthGreaterThanHeight - ? ellipse.halfWidth * 2 - : ellipse.halfHeight * 2; - const minorAxis = widthGreaterThanHeight - ? ellipse.halfHeight * 2 - : ellipse.halfWidth * 2; - - return { - majorAxis, - minorAxis, - }; -}; - -export const ellipseFocusToCenter = ( - ellipse: Ellipse, -) => { - const { majorAxis, minorAxis } = ellipseAxes(ellipse); - - return Math.sqrt(majorAxis ** 2 - minorAxis ** 2); -}; - -export const ellipseExtremes = ( - ellipse: Ellipse, -) => { - const { center, angle } = ellipse; - const { majorAxis, minorAxis } = ellipseAxes(ellipse); - - const cos = Math.cos(angle); - const sin = Math.sin(angle); - - const sqSum = majorAxis ** 2 + minorAxis ** 2; - const sqDiff = (majorAxis ** 2 - minorAxis ** 2) * Math.cos(2 * angle); - - const yMax = Math.sqrt((sqSum - sqDiff) / 2); - const xAtYMax = - (yMax * sqSum * sin * cos) / - (majorAxis ** 2 * sin ** 2 + minorAxis ** 2 * cos ** 2); - - const xMax = Math.sqrt((sqSum + sqDiff) / 2); - const yAtXMax = - (xMax * sqSum * sin * cos) / - (majorAxis ** 2 * cos ** 2 + minorAxis ** 2 * sin ** 2); - const centerVector = vectorFromPoint(center); - - return [ - vectorAdd(vector(xAtYMax, yMax), centerVector), - vectorAdd(vectorScale(vector(xAtYMax, yMax), -1), centerVector), - vectorAdd(vector(xMax, yAtXMax), centerVector), - vectorAdd(vector(xMax, yAtXMax), centerVector), - ]; -}; +// moved to @excalidraw/element; re-exported for backwards compatibility +export * from "@excalidraw/element/geometricShapes"; diff --git a/packages/utils/src/test-utils.ts b/packages/utils/src/test-utils.ts deleted file mode 100644 index 966a589ab9..0000000000 --- a/packages/utils/src/test-utils.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { diffStringsUnified } from "jest-diff"; - -expect.extend({ - toCloselyEqualPoints(received, expected, precision) { - if (!Array.isArray(received) || !Array.isArray(expected)) { - throw new Error("expected and received are not point arrays"); - } - - const COMPARE = 1 / precision === 0 ? 1 : Math.pow(10, precision ?? 2); - const pass = expected.every( - (point, idx) => - Math.abs(received[idx][0] - point[0]) < COMPARE && - Math.abs(received[idx][1] - point[1]) < COMPARE, - ); - - if (!pass) { - return { - message: () => ` The provided array of points are not close enough. - -${diffStringsUnified( - JSON.stringify(expected, undefined, 2), - JSON.stringify(received, undefined, 2), -)}`, - pass: false, - }; - } - - return { - message: () => `expected ${received} to not be close to ${expected}`, - pass: true, - }; - }, -}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7a205cc709..6f9b475880 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@babel/preset-env': specifier: 7.26.9 version: 7.26.9(@babel/core@7.26.9) + '@excalidraw/common': + specifier: workspace:* + version: link:packages/common '@excalidraw/eslint-config': specifier: 1.0.3 version: 1.0.3(@typescript-eslint/eslint-plugin@5.62.0(@typescript-eslint/parser@5.62.0(eslint@7.32.0)(typescript@5.9.3))(eslint@7.32.0)(typescript@5.9.3))(@typescript-eslint/parser@5.62.0(eslint@7.32.0)(typescript@5.9.3))(eslint-config-prettier@8.5.0(eslint@7.32.0))(eslint-plugin-prettier@3.3.1(eslint-config-prettier@8.5.0(eslint@7.32.0))(eslint@7.32.0)(prettier@2.6.2))(eslint@7.32.0)(prettier@2.6.2) @@ -98,6 +101,9 @@ importers: husky: specifier: 7.0.4 version: 7.0.4 + jest-diff: + specifier: 29.7.0 + version: 29.7.0 jsdom: specifier: 22.1.0 version: 22.1.0 @@ -155,6 +161,9 @@ importers: examples/with-nextjs: dependencies: + '@excalidraw/excalidraw': + specifier: workspace:* + version: link:../../packages/excalidraw next: specifier: '14.1' version: 14.1.4(@babel/core@7.26.9)(react-dom@19.0.0(react@19.0.0))(react@19.0.0)(sass@1.85.1) @@ -208,6 +217,18 @@ importers: excalidraw-app: dependencies: + '@excalidraw/common': + specifier: workspace:* + version: link:../packages/common + '@excalidraw/element': + specifier: workspace:* + version: link:../packages/element + '@excalidraw/excalidraw': + specifier: workspace:* + version: link:../packages/excalidraw + '@excalidraw/math': + specifier: workspace:* + version: link:../packages/math '@excalidraw/random-username': specifier: 1.1.0 version: 1.1.0 @@ -288,6 +309,12 @@ importers: specifier: 1.6.0 version: 1.6.0 devDependencies: + '@excalidraw/element': + specifier: workspace:* + version: link:../element + '@excalidraw/excalidraw': + specifier: workspace:* + version: link:../excalidraw '@types/tinycolor2': specifier: 1.4.6 version: 1.4.6 @@ -316,6 +343,12 @@ importers: specifier: 4.6.4 version: 4.6.4 devDependencies: + '@excalidraw/excalidraw': + specifier: workspace:* + version: link:../excalidraw + '@excalidraw/laser-pointer': + specifier: workspace:* + version: link:../laser-pointer '@testing-library/dom': specifier: 10.4.0 version: 10.4.0 @@ -518,11 +551,7 @@ importers: packages/laser-pointer: {} - packages/math: - dependencies: - '@excalidraw/common': - specifier: workspace:* - version: link:../common + packages/math: {} packages/utils: dependencies: @@ -550,19 +579,25 @@ importers: png-chunks-extract: specifier: 1.0.0 version: 1.0.0 - points-on-curve: - specifier: 0.2.0 - version: 0.2.0 roughjs: specifier: 4.6.4 version: 4.6.4 devDependencies: + '@excalidraw/common': + specifier: workspace:* + version: link:../common + '@excalidraw/element': + specifier: workspace:* + version: link:../element + '@excalidraw/excalidraw': + specifier: workspace:* + version: link:../excalidraw + '@excalidraw/math': + specifier: workspace:* + version: link:../math cross-env: specifier: 7.0.3 version: 7.0.3 - jest-diff: - specifier: 29.7.0 - version: 29.7.0 typescript: specifier: 5.9.3 version: 5.9.3 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a8785fa0aa..0449f7a475 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -12,3 +12,7 @@ onlyBuiltDependencies: - core-js - esbuild - protobufjs + +# Type- and test-only edges close cycles (common/element import shared types +# from excalidraw; element tests use its test harness). Runtime deps are acyclic. +ignoreWorkspaceCycles: true diff --git a/scripts/buildBase.js b/scripts/buildBase.js index 34913d1b85..41eef313e9 100644 --- a/scripts/buildBase.js +++ b/scripts/buildBase.js @@ -1,10 +1,5 @@ -const path = require("path"); - const { build } = require("esbuild"); -// the package being built (scripts run from the package directory) -const { name: packageName } = require(path.resolve("package.json")); - // contains all dependencies bundled inside const getConfig = (outdir) => ({ outdir, @@ -13,19 +8,15 @@ const getConfig = (outdir) => ({ entryPoints: ["src/index.ts"], entryNames: "[name]", assetNames: "[dir]/[name]", - alias: { - "@excalidraw/utils": path.resolve(__dirname, "../packages/utils/src"), - // bundled sources (e.g. utils) may import the package being built by - // name: resolve those to its own sources instead of a self-import, which - // doesn't resolve from inside the package with an isolated node_modules - [packageName]: path.resolve("src"), - }, + // resolve workspace packages (linked through node_modules) to their + // sources: see the "excalidraw-source" condition in their `exports` + conditions: ["excalidraw-source"], external: [ "@excalidraw/common", "@excalidraw/element", "@excalidraw/math", "@excalidraw/fractional-indexing", - ].filter((name) => name !== packageName), + ], }); function buildDev(config) { diff --git a/scripts/buildPackage.js b/scripts/buildPackage.js index 839e135855..348fe87558 100644 --- a/scripts/buildPackage.js +++ b/scripts/buildPackage.js @@ -71,9 +71,6 @@ const getConfig = (outdir) => ({ target: "es2020", assetNames: "[dir]/[name]", chunkNames: "[dir]/[name]-[hash]", - alias: { - "@excalidraw/utils": path.resolve(__dirname, "../packages/utils/src"), - }, external: [ "@excalidraw/common", "@excalidraw/element", diff --git a/scripts/buildUtils.js b/scripts/buildUtils.js index 24d9e0a7c0..7670e7dca5 100644 --- a/scripts/buildUtils.js +++ b/scripts/buildUtils.js @@ -1,5 +1,3 @@ -const path = require("path"); - const { build } = require("esbuild"); const { sassPlugin } = require("esbuild-sass-plugin"); @@ -13,17 +11,9 @@ const getConfig = (outdir) => ({ entryPoints: ["src/index.ts"], entryNames: "[name]", assetNames: "[dir]/[name]", - alias: { - "@excalidraw/common": path.resolve(__dirname, "../packages/common/src"), - "@excalidraw/element": path.resolve(__dirname, "../packages/element/src"), - "@excalidraw/excalidraw": path.resolve(__dirname, "../packages/excalidraw"), - "@excalidraw/math": path.resolve(__dirname, "../packages/math/src"), - "@excalidraw/fractional-indexing": path.resolve( - __dirname, - "../packages/fractional-indexing/src", - ), - "@excalidraw/utils": path.resolve(__dirname, "../packages/utils/src"), - }, + // resolve workspace packages (linked through node_modules) to their + // sources: see the "excalidraw-source" condition in their `exports` + conditions: ["excalidraw-source"], }); function buildDev(config) { diff --git a/setupTests.ts b/setupTests.ts index ffd6447bbd..94363e502c 100644 --- a/setupTests.ts +++ b/setupTests.ts @@ -4,6 +4,7 @@ import fs from "fs"; import "vitest-canvas-mock"; import "@testing-library/jest-dom"; import { configure } from "@testing-library/react"; +import { diffStringsUnified } from "jest-diff"; import { vi } from "vitest"; import polyfill from "./packages/excalidraw/polyfill"; @@ -17,6 +18,39 @@ import { Object.assign(globalThis, testPolyfills); PolyfillLocalStorage(); +// typed in packages/excalidraw/global.d.ts +expect.extend({ + toCloselyEqualPoints(received, expected, precision) { + if (!Array.isArray(received) || !Array.isArray(expected)) { + throw new Error("expected and received are not point arrays"); + } + + const COMPARE = 1 / precision === 0 ? 1 : Math.pow(10, precision ?? 2); + const pass = expected.every( + (point, idx) => + Math.abs(received[idx][0] - point[0]) < COMPARE && + Math.abs(received[idx][1] - point[1]) < COMPARE, + ); + + if (!pass) { + return { + message: () => ` The provided array of points are not close enough. + +${diffStringsUnified( + JSON.stringify(expected, undefined, 2), + JSON.stringify(received, undefined, 2), +)}`, + pass: false, + }; + } + + return { + message: () => `expected ${received} to not be close to ${expected}`, + pass: true, + }; + }, +}); + // By default testing-library dumps the entire serialized DOM into the error // message whenever a `waitFor`/`getBy*` fails, which floods the test output // (often hundreds of lines of HTML per failure). Strip it out unless diff --git a/tsconfig.json b/tsconfig.json index 2d66d6be4c..21e0fe2f32 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,24 +18,7 @@ "noEmit": true, "jsx": "react-jsx", "baseUrl": ".", - "paths": { - "@excalidraw/common": ["./packages/common/src/index.ts"], - "@excalidraw/common/*": ["./packages/common/src/*"], - "@excalidraw/excalidraw": ["./packages/excalidraw/index.tsx"], - "@excalidraw/excalidraw/*": ["./packages/excalidraw/*"], - "@excalidraw/excalidraw/common/*": ["./packages/common/src/*"], - "@excalidraw/excalidraw/element/*": ["./packages/element/src/*"], - "@excalidraw/element": ["./packages/element/src/index.ts"], - "@excalidraw/element/*": ["./packages/element/src/*"], - "@excalidraw/fractional-indexing": ["./packages/fractional-indexing/src/index.ts"], - "@excalidraw/fractional-indexing/*": ["./packages/fractional-indexing/src/*"], - "@excalidraw/laser-pointer": ["./packages/laser-pointer/src/index.ts"], - "@excalidraw/laser-pointer/*": ["./packages/laser-pointer/src/*"], - "@excalidraw/math": ["./packages/math/src/index.ts"], - "@excalidraw/math/*": ["./packages/math/src/*"], - "@excalidraw/utils": ["./packages/utils/src/index.ts"], - "@excalidraw/utils/*": ["./packages/utils/src/*"] - } + "customConditions": ["excalidraw-source"] }, "include": ["packages", "excalidraw-app"], "exclude": ["examples", "dist", "types", "tests"] diff --git a/vitest.config.mts b/vitest.config.mts index 13874fbbba..1d0a5e8140 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -4,73 +4,9 @@ import { defineConfig } from "vitest/config"; export default defineConfig({ resolve: { - alias: [ - { - find: /^@excalidraw\/common$/, - replacement: path.resolve(__dirname, "./packages/common/src/index.ts"), - }, - { - find: /^@excalidraw\/common\/(.*?)/, - replacement: path.resolve(__dirname, "./packages/common/src/$1"), - }, - { - find: /^@excalidraw\/element$/, - replacement: path.resolve(__dirname, "./packages/element/src/index.ts"), - }, - { - find: /^@excalidraw\/element\/(.*?)/, - replacement: path.resolve(__dirname, "./packages/element/src/$1"), - }, - { - find: /^@excalidraw\/excalidraw$/, - replacement: path.resolve(__dirname, "./packages/excalidraw/index.tsx"), - }, - { - find: /^@excalidraw\/excalidraw\/(.*?)/, - replacement: path.resolve(__dirname, "./packages/excalidraw/$1"), - }, - { - find: /^@excalidraw\/math$/, - replacement: path.resolve(__dirname, "./packages/math/src/index.ts"), - }, - { - find: /^@excalidraw\/math\/(.*?)/, - replacement: path.resolve(__dirname, "./packages/math/src/$1"), - }, - { - find: /^@excalidraw\/utils$/, - replacement: path.resolve(__dirname, "./packages/utils/src/index.ts"), - }, - { - find: /^@excalidraw\/utils\/(.*?)/, - replacement: path.resolve(__dirname, "./packages/utils/src/$1"), - }, - { - find: /^@excalidraw\/fractional-indexing$/, - replacement: path.resolve( - __dirname, - "./packages/fractional-indexing/src/index.ts", - ), - }, - { - find: /^@excalidraw\/fractional-indexing\/(.*?)/, - replacement: path.resolve( - __dirname, - "./packages/fractional-indexing/src/$1", - ), - }, - { - find: /^@excalidraw\/laser-pointer$/, - replacement: path.resolve( - __dirname, - "./packages/laser-pointer/src/index.ts", - ), - }, - { - find: /^@excalidraw\/laser-pointer\/(.*?)/, - replacement: path.resolve(__dirname, "./packages/laser-pointer/src/$1"), - }, - ], + // resolve workspace packages (linked through node_modules) to their + // sources: see the "excalidraw-source" condition in their `exports` + conditions: ["excalidraw-source"], }, //@ts-ignore test: {