123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543 |
- import {
- ExcalidrawElement,
- ExcalidrawLinearElement,
- Arrowhead,
- ExcalidrawFreeDrawElement,
- NonDeleted,
- } from "./types";
- import { distance2d, rotate } from "../math";
- import rough from "roughjs/bin/rough";
- import { Drawable, Op } from "roughjs/bin/core";
- import { Point } from "../types";
- import {
- getShapeForElement,
- generateRoughOptions,
- } from "../renderer/renderElement";
- import { isFreeDrawElement, isLinearElement } from "./typeChecks";
- import { rescalePoints } from "../points";
- // x and y position of top left corner, x and y position of bottom right corner
- export type Bounds = readonly [number, number, number, number];
- // If the element is created from right to left, the width is going to be negative
- // This set of functions retrieves the absolute position of the 4 points.
- export const getElementAbsoluteCoords = (
- element: ExcalidrawElement,
- ): Bounds => {
- if (isFreeDrawElement(element)) {
- return getFreeDrawElementAbsoluteCoords(element);
- } else if (isLinearElement(element)) {
- return getLinearElementAbsoluteCoords(element);
- }
- return [
- element.x,
- element.y,
- element.x + element.width,
- element.y + element.height,
- ];
- };
- export const pointRelativeTo = (
- element: ExcalidrawElement,
- absoluteCoords: Point,
- ): Point => {
- return [absoluteCoords[0] - element.x, absoluteCoords[1] - element.y];
- };
- export const getDiamondPoints = (element: ExcalidrawElement) => {
- // Here we add +1 to avoid these numbers to be 0
- // otherwise rough.js will throw an error complaining about it
- const topX = Math.floor(element.width / 2) + 1;
- const topY = 0;
- const rightX = element.width;
- const rightY = Math.floor(element.height / 2) + 1;
- const bottomX = topX;
- const bottomY = element.height;
- const leftX = 0;
- const leftY = rightY;
- return [topX, topY, rightX, rightY, bottomX, bottomY, leftX, leftY];
- };
- export const getCurvePathOps = (shape: Drawable): Op[] => {
- for (const set of shape.sets) {
- if (set.type === "path") {
- return set.ops;
- }
- }
- return shape.sets[0].ops;
- };
- const getMinMaxXYFromCurvePathOps = (
- ops: Op[],
- transformXY?: (x: number, y: number) => [number, number],
- ): [number, number, number, number] => {
- let currentP: Point = [0, 0];
- const { minX, minY, maxX, maxY } = ops.reduce(
- (limits, { op, data }) => {
- // There are only four operation types:
- // move, bcurveTo, lineTo, and curveTo
- if (op === "move") {
- // change starting point
- currentP = data as unknown as Point;
- // move operation does not draw anything; so, it always
- // returns false
- } else if (op === "bcurveTo") {
- // create points from bezier curve
- // bezier curve stores data as a flattened array of three positions
- // [x1, y1, x2, y2, x3, y3]
- const p1 = [data[0], data[1]] as Point;
- const p2 = [data[2], data[3]] as Point;
- const p3 = [data[4], data[5]] as Point;
- const p0 = currentP;
- currentP = p3;
- const equation = (t: number, idx: number) =>
- Math.pow(1 - t, 3) * p3[idx] +
- 3 * t * Math.pow(1 - t, 2) * p2[idx] +
- 3 * Math.pow(t, 2) * (1 - t) * p1[idx] +
- p0[idx] * Math.pow(t, 3);
- let t = 0;
- while (t <= 1.0) {
- let x = equation(t, 0);
- let y = equation(t, 1);
- if (transformXY) {
- [x, y] = transformXY(x, y);
- }
- limits.minY = Math.min(limits.minY, y);
- limits.minX = Math.min(limits.minX, x);
- limits.maxX = Math.max(limits.maxX, x);
- limits.maxY = Math.max(limits.maxY, y);
- t += 0.1;
- }
- } else if (op === "lineTo") {
- // TODO: Implement this
- } else if (op === "qcurveTo") {
- // TODO: Implement this
- }
- return limits;
- },
- { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity },
- );
- return [minX, minY, maxX, maxY];
- };
- const getBoundsFromPoints = (
- points: ExcalidrawFreeDrawElement["points"],
- ): [number, number, number, number] => {
- let minX = Infinity;
- let minY = Infinity;
- let maxX = -Infinity;
- let maxY = -Infinity;
- for (const [x, y] of points) {
- minX = Math.min(minX, x);
- minY = Math.min(minY, y);
- maxX = Math.max(maxX, x);
- maxY = Math.max(maxY, y);
- }
- return [minX, minY, maxX, maxY];
- };
- const getFreeDrawElementAbsoluteCoords = (
- element: ExcalidrawFreeDrawElement,
- ): [number, number, number, number] => {
- const [minX, minY, maxX, maxY] = getBoundsFromPoints(element.points);
- return [
- minX + element.x,
- minY + element.y,
- maxX + element.x,
- maxY + element.y,
- ];
- };
- const getLinearElementAbsoluteCoords = (
- element: ExcalidrawLinearElement,
- ): [number, number, number, number] => {
- let coords: [number, number, number, number];
- if (element.points.length < 2 || !getShapeForElement(element)) {
- // XXX this is just a poor estimate and not very useful
- const { minX, minY, maxX, maxY } = element.points.reduce(
- (limits, [x, y]) => {
- limits.minY = Math.min(limits.minY, y);
- limits.minX = Math.min(limits.minX, x);
- limits.maxX = Math.max(limits.maxX, x);
- limits.maxY = Math.max(limits.maxY, y);
- return limits;
- },
- { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity },
- );
- coords = [
- minX + element.x,
- minY + element.y,
- maxX + element.x,
- maxY + element.y,
- ];
- } else {
- const shape = getShapeForElement(element) as Drawable[];
- // first element is always the curve
- const ops = getCurvePathOps(shape[0]);
- const [minX, minY, maxX, maxY] = getMinMaxXYFromCurvePathOps(ops);
- coords = [
- minX + element.x,
- minY + element.y,
- maxX + element.x,
- maxY + element.y,
- ];
- }
- return coords;
- };
- export const getArrowheadPoints = (
- element: ExcalidrawLinearElement,
- shape: Drawable[],
- position: "start" | "end",
- arrowhead: Arrowhead,
- ) => {
- const ops = getCurvePathOps(shape[0]);
- if (ops.length < 1) {
- return null;
- }
- // The index of the bCurve operation to examine.
- const index = position === "start" ? 1 : ops.length - 1;
- const data = ops[index].data;
- const p3 = [data[4], data[5]] as Point;
- const p2 = [data[2], data[3]] as Point;
- const p1 = [data[0], data[1]] as Point;
- // We need to find p0 of the bezier curve.
- // It is typically the last point of the previous
- // curve; it can also be the position of moveTo operation.
- const prevOp = ops[index - 1];
- let p0: Point = [0, 0];
- if (prevOp.op === "move") {
- p0 = prevOp.data as unknown as Point;
- } else if (prevOp.op === "bcurveTo") {
- p0 = [prevOp.data[4], prevOp.data[5]];
- }
- // B(t) = p0 * (1-t)^3 + 3p1 * t * (1-t)^2 + 3p2 * t^2 * (1-t) + p3 * t^3
- const equation = (t: number, idx: number) =>
- Math.pow(1 - t, 3) * p3[idx] +
- 3 * t * Math.pow(1 - t, 2) * p2[idx] +
- 3 * Math.pow(t, 2) * (1 - t) * p1[idx] +
- p0[idx] * Math.pow(t, 3);
- // Ee know the last point of the arrow (or the first, if start arrowhead).
- const [x2, y2] = position === "start" ? p0 : p3;
- // By using cubic bezier equation (B(t)) and the given parameters,
- // we calculate a point that is closer to the last point.
- // The value 0.3 is chosen arbitrarily and it works best for all
- // the tested cases.
- const [x1, y1] = [equation(0.3, 0), equation(0.3, 1)];
- // Find the normalized direction vector based on the
- // previously calculated points.
- const distance = Math.hypot(x2 - x1, y2 - y1);
- const nx = (x2 - x1) / distance;
- const ny = (y2 - y1) / distance;
- const size = {
- arrow: 30,
- bar: 15,
- dot: 15,
- triangle: 15,
- }[arrowhead]; // pixels (will differ for each arrowhead)
- let length = 0;
- if (arrowhead === "arrow") {
- // Length for -> arrows is based on the length of the last section
- const [cx, cy] = element.points[element.points.length - 1];
- const [px, py] =
- element.points.length > 1
- ? element.points[element.points.length - 2]
- : [0, 0];
- length = Math.hypot(cx - px, cy - py);
- } else {
- // Length for other arrowhead types is based on the total length of the line
- for (let i = 0; i < element.points.length; i++) {
- const [px, py] = element.points[i - 1] || [0, 0];
- const [cx, cy] = element.points[i];
- length += Math.hypot(cx - px, cy - py);
- }
- }
- // Scale down the arrowhead until we hit a certain size so that it doesn't look weird.
- // This value is selected by minimizing a minimum size with the last segment of the arrowhead
- const minSize = Math.min(size, length / 2);
- const xs = x2 - nx * minSize;
- const ys = y2 - ny * minSize;
- if (arrowhead === "dot") {
- const r = Math.hypot(ys - y2, xs - x2) + element.strokeWidth;
- return [x2, y2, r];
- }
- const angle = {
- arrow: 20,
- bar: 90,
- triangle: 25,
- }[arrowhead]; // degrees
- // Return points
- const [x3, y3] = rotate(xs, ys, x2, y2, (-angle * Math.PI) / 180);
- const [x4, y4] = rotate(xs, ys, x2, y2, (angle * Math.PI) / 180);
- return [x2, y2, x3, y3, x4, y4];
- };
- const getLinearElementRotatedBounds = (
- element: ExcalidrawLinearElement,
- cx: number,
- cy: number,
- ): [number, number, number, number] => {
- if (element.points.length < 2 || !getShapeForElement(element)) {
- // XXX this is just a poor estimate and not very useful
- const { minX, minY, maxX, maxY } = element.points.reduce(
- (limits, [x, y]) => {
- [x, y] = rotate(element.x + x, element.y + y, cx, cy, element.angle);
- limits.minY = Math.min(limits.minY, y);
- limits.minX = Math.min(limits.minX, x);
- limits.maxX = Math.max(limits.maxX, x);
- limits.maxY = Math.max(limits.maxY, y);
- return limits;
- },
- { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity },
- );
- return [minX, minY, maxX, maxY];
- }
- const shape = getShapeForElement(element) as Drawable[];
- // first element is always the curve
- const ops = getCurvePathOps(shape[0]);
- const transformXY = (x: number, y: number) =>
- rotate(element.x + x, element.y + y, cx, cy, element.angle);
- return getMinMaxXYFromCurvePathOps(ops, transformXY);
- };
- // We could cache this stuff
- export const getElementBounds = (
- element: ExcalidrawElement,
- ): [number, number, number, number] => {
- let bounds: [number, number, number, number];
- const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
- const cx = (x1 + x2) / 2;
- const cy = (y1 + y2) / 2;
- if (isFreeDrawElement(element)) {
- const [minX, minY, maxX, maxY] = getBoundsFromPoints(
- element.points.map(([x, y]) =>
- rotate(x, y, cx - element.x, cy - element.y, element.angle),
- ),
- );
- return [
- minX + element.x,
- minY + element.y,
- maxX + element.x,
- maxY + element.y,
- ];
- } else if (isLinearElement(element)) {
- bounds = getLinearElementRotatedBounds(element, cx, cy);
- } else if (element.type === "diamond") {
- const [x11, y11] = rotate(cx, y1, cx, cy, element.angle);
- const [x12, y12] = rotate(cx, y2, cx, cy, element.angle);
- const [x22, y22] = rotate(x1, cy, cx, cy, element.angle);
- const [x21, y21] = rotate(x2, cy, cx, cy, element.angle);
- const minX = Math.min(x11, x12, x22, x21);
- const minY = Math.min(y11, y12, y22, y21);
- const maxX = Math.max(x11, x12, x22, x21);
- const maxY = Math.max(y11, y12, y22, y21);
- bounds = [minX, minY, maxX, maxY];
- } else if (element.type === "ellipse") {
- const w = (x2 - x1) / 2;
- const h = (y2 - y1) / 2;
- const cos = Math.cos(element.angle);
- const sin = Math.sin(element.angle);
- const ww = Math.hypot(w * cos, h * sin);
- const hh = Math.hypot(h * cos, w * sin);
- bounds = [cx - ww, cy - hh, cx + ww, cy + hh];
- } else {
- const [x11, y11] = rotate(x1, y1, cx, cy, element.angle);
- const [x12, y12] = rotate(x1, y2, cx, cy, element.angle);
- const [x22, y22] = rotate(x2, y2, cx, cy, element.angle);
- const [x21, y21] = rotate(x2, y1, cx, cy, element.angle);
- const minX = Math.min(x11, x12, x22, x21);
- const minY = Math.min(y11, y12, y22, y21);
- const maxX = Math.max(x11, x12, x22, x21);
- const maxY = Math.max(y11, y12, y22, y21);
- bounds = [minX, minY, maxX, maxY];
- }
- return bounds;
- };
- export const getCommonBounds = (
- elements: readonly ExcalidrawElement[],
- ): [number, number, number, number] => {
- if (!elements.length) {
- return [0, 0, 0, 0];
- }
- let minX = Infinity;
- let maxX = -Infinity;
- let minY = Infinity;
- let maxY = -Infinity;
- elements.forEach((element) => {
- const [x1, y1, x2, y2] = getElementBounds(element);
- minX = Math.min(minX, x1);
- minY = Math.min(minY, y1);
- maxX = Math.max(maxX, x2);
- maxY = Math.max(maxY, y2);
- });
- return [minX, minY, maxX, maxY];
- };
- export const getResizedElementAbsoluteCoords = (
- element: ExcalidrawElement,
- nextWidth: number,
- nextHeight: number,
- ): [number, number, number, number] => {
- if (!(isLinearElement(element) || isFreeDrawElement(element))) {
- return [
- element.x,
- element.y,
- element.x + nextWidth,
- element.y + nextHeight,
- ];
- }
- const points = rescalePoints(
- 0,
- nextWidth,
- rescalePoints(1, nextHeight, element.points),
- );
- let bounds: [number, number, number, number];
- if (isFreeDrawElement(element)) {
- // Free Draw
- bounds = getBoundsFromPoints(points);
- } else {
- // Line
- const gen = rough.generator();
- const curve =
- element.strokeSharpness === "sharp"
- ? gen.linearPath(
- points as [number, number][],
- generateRoughOptions(element),
- )
- : gen.curve(
- points as [number, number][],
- generateRoughOptions(element),
- );
- const ops = getCurvePathOps(curve);
- bounds = getMinMaxXYFromCurvePathOps(ops);
- }
- const [minX, minY, maxX, maxY] = bounds;
- return [
- minX + element.x,
- minY + element.y,
- maxX + element.x,
- maxY + element.y,
- ];
- };
- export const getElementPointsCoords = (
- element: ExcalidrawLinearElement,
- points: readonly (readonly [number, number])[],
- sharpness: ExcalidrawElement["strokeSharpness"],
- ): [number, number, number, number] => {
- // This might be computationally heavey
- const gen = rough.generator();
- const curve =
- sharpness === "sharp"
- ? gen.linearPath(
- points as [number, number][],
- generateRoughOptions(element),
- )
- : gen.curve(points as [number, number][], generateRoughOptions(element));
- const ops = getCurvePathOps(curve);
- const [minX, minY, maxX, maxY] = getMinMaxXYFromCurvePathOps(ops);
- return [
- minX + element.x,
- minY + element.y,
- maxX + element.x,
- maxY + element.y,
- ];
- };
- export const getClosestElementBounds = (
- elements: readonly ExcalidrawElement[],
- from: { x: number; y: number },
- ): [number, number, number, number] => {
- if (!elements.length) {
- return [0, 0, 0, 0];
- }
- let minDistance = Infinity;
- let closestElement = elements[0];
- elements.forEach((element) => {
- const [x1, y1, x2, y2] = getElementBounds(element);
- const distance = distance2d((x1 + x2) / 2, (y1 + y2) / 2, from.x, from.y);
- if (distance < minDistance) {
- minDistance = distance;
- closestElement = element;
- }
- });
- return getElementBounds(closestElement);
- };
- export interface Box {
- minX: number;
- minY: number;
- maxX: number;
- maxY: number;
- midX: number;
- midY: number;
- width: number;
- height: number;
- }
- export const getCommonBoundingBox = (
- elements: ExcalidrawElement[] | readonly NonDeleted<ExcalidrawElement>[],
- ): Box => {
- const [minX, minY, maxX, maxY] = getCommonBounds(elements);
- return {
- minX,
- minY,
- maxX,
- maxY,
- width: maxX - minX,
- height: maxY - minY,
- midX: (minX + maxX) / 2,
- midY: (minY + maxY) / 2,
- };
- };
|