98b5c37e45
* feat: Word wrap inside rect and increase height when size exceeded
* fixes for auto increase in height
* fix height
* respect newlines when wrapping text
* shift text area when height increases beyond mid rect height until it reaches to the top
* select bound text if present when rect selected
* mutate y coord after text submit
* Add padding of 30px and update dimensions acordingly
* Don't allow selecting bound text element directly
* support deletion of bound text element when rect deleted
* trim text
* Support autoshrink and improve algo
* calculate approx line height instead of hardcoding
* use textContainerId instead of storing textContainer element itself
* rename boundTextElement -> boundTextElementId
* fix text properties not getting reflected after edit inside rect
* Support resizing
* remove ts ignore
* increase height of container when text height increases while resizing
* use original text when editing/resizing so it adjusts based on original text
* fix tests
* add util isRectangleElement
* use isTextElement util everywhere
* disable selecting text inside rect when selectAll
* Bind text to circle and diamond as well
* fix tests
* vertically center align the text always
* better vertical align
* Disable binding arrows for text inside shapes
* set min width for text container when text is binded to container
* update dimensions of container if its less than min width/ min height
* Allow selecting of text container for transparent containers when clicked inside
* fix test
* preserve whitespaces between long word exceeding width and next word
Use word break instead of whitespace no wrap for better readability and support safari
* Perf improvements for measuring text width and resizing
* Use canvas measureText instead of our algo. This has reduced the perf ~ 10 times
* Rewrite wrapText algo to break in words appropriately and for longer words
calculate the char width in order unless max width reached. This makes the
the number of runs linear (max text length times) which was earlier
textLength * textLength-1/2 as I was slicing the chars from end until max width reached for each run
* Add a util to calculate getApproxCharsToFitInWidth to calculate min chars to fit in a line
* use console.info so eslint doesnt warn :p
* cache char width and don't call resize unless min width exceeded
* update line height and height correctly when text properties inside container updated
* improve vertical centering when text properties updated, not yet perfect though
* when double clicked inside a conatiner take the cursor to end of text same as what happens when enter is pressed
* Add hint when container selected
* Select container when escape key is pressed after submitting text
* fix copy/paste when using copy/paste action
* fix copy when dragged with alt pressed
* fix export to svg/png
* fix add to library
* Fix copy as png/svg
* Don't allow selecting text when using selection tool and support resizing when multiple elements include ones with binded text selectec
* fix rotation jump
* moove all text utils to textElement.ts
* resize text element only after container resized so that width doesnt change when editing
* insert the remaining chars for long words once it goes beyond line
* fix typo, use string for character type
* renaming
* fix bugs in word wrap algo
* make grouping work
* set boundTextElementId only when text present else unset it
* rename textContainerId to containerId
* fix
* fix snap
* use originalText in redrawTextBoundingBox so height is calculated properly and center align works after props updated
* use boundElementIds and also support binding text in images 🎉
* fix the sw/se ends when resizing from ne/nw
* fix y coord when resizing from north
* bind when enter is pressed, double click/text tool willl edit the binded text if present else create a new text
* bind when clicked on center of container
* use pre-wrap instead of normal so it works in ff
* use container boundTextElement when container present and trying to edit text
* review fixes
* make getBoundTextElementId type safe and check for existence when using this function
* fix
* don't duplicate boundElementIds when text submitted
* only remove last trailing space if present which we have added when joining words
* set width correctly when resizing to fix alignment issues
* make duplication work using cmd/ctrl+d
* set X coord correctly during resize
* don't allow resize to negative dimensions when text is bounded to container
* fix, check last char is space
* remove logs
* make sure text editor doesn't go beyond viewport and set container dimensions in case it overflows
* add a util isTextBindableContainer to check if the container could bind text
402 lines
11 KiB
TypeScript
402 lines
11 KiB
TypeScript
import {
|
|
ExcalidrawElement,
|
|
ExcalidrawImageElement,
|
|
ExcalidrawTextElement,
|
|
ExcalidrawLinearElement,
|
|
ExcalidrawGenericElement,
|
|
NonDeleted,
|
|
TextAlign,
|
|
GroupId,
|
|
VerticalAlign,
|
|
Arrowhead,
|
|
ExcalidrawFreeDrawElement,
|
|
FontFamilyValues,
|
|
ExcalidrawRectangleElement,
|
|
} from "../element/types";
|
|
import { getFontString, getUpdatedTimestamp } from "../utils";
|
|
import { randomInteger, randomId } from "../random";
|
|
import { mutateElement, newElementWith } from "./mutateElement";
|
|
import { getNewGroupIdsForDuplication } from "../groups";
|
|
import { AppState } from "../types";
|
|
import { getElementAbsoluteCoords } from ".";
|
|
import { adjustXYWithRotation } from "../math";
|
|
import { getResizedElementAbsoluteCoords } from "./bounds";
|
|
import { measureText } from "./textElement";
|
|
import { isBoundToContainer } from "./typeChecks";
|
|
import Scene from "../scene/Scene";
|
|
import { PADDING } from "../constants";
|
|
|
|
type ElementConstructorOpts = MarkOptional<
|
|
Omit<ExcalidrawGenericElement, "id" | "type" | "isDeleted" | "updated">,
|
|
| "width"
|
|
| "height"
|
|
| "angle"
|
|
| "groupIds"
|
|
| "boundElements"
|
|
| "seed"
|
|
| "version"
|
|
| "versionNonce"
|
|
>;
|
|
|
|
const _newElementBase = <T extends ExcalidrawElement>(
|
|
type: T["type"],
|
|
{
|
|
x,
|
|
y,
|
|
strokeColor,
|
|
backgroundColor,
|
|
fillStyle,
|
|
strokeWidth,
|
|
strokeStyle,
|
|
roughness,
|
|
opacity,
|
|
width = 0,
|
|
height = 0,
|
|
angle = 0,
|
|
groupIds = [],
|
|
strokeSharpness,
|
|
boundElements = null,
|
|
...rest
|
|
}: ElementConstructorOpts & Omit<Partial<ExcalidrawGenericElement>, "type">,
|
|
) => {
|
|
const element = {
|
|
id: rest.id || randomId(),
|
|
type,
|
|
x,
|
|
y,
|
|
width,
|
|
height,
|
|
angle,
|
|
strokeColor,
|
|
backgroundColor,
|
|
fillStyle,
|
|
strokeWidth,
|
|
strokeStyle,
|
|
roughness,
|
|
opacity,
|
|
groupIds,
|
|
strokeSharpness,
|
|
seed: rest.seed ?? randomInteger(),
|
|
version: rest.version || 1,
|
|
versionNonce: rest.versionNonce ?? 0,
|
|
isDeleted: false as false,
|
|
boundElements,
|
|
updated: getUpdatedTimestamp(),
|
|
};
|
|
return element;
|
|
};
|
|
|
|
export const newElement = (
|
|
opts: {
|
|
type: ExcalidrawGenericElement["type"];
|
|
} & ElementConstructorOpts,
|
|
): NonDeleted<ExcalidrawGenericElement> =>
|
|
_newElementBase<ExcalidrawGenericElement>(opts.type, opts);
|
|
|
|
/** computes element x/y offset based on textAlign/verticalAlign */
|
|
const getTextElementPositionOffsets = (
|
|
opts: {
|
|
textAlign: ExcalidrawTextElement["textAlign"];
|
|
verticalAlign: ExcalidrawTextElement["verticalAlign"];
|
|
},
|
|
metrics: {
|
|
width: number;
|
|
height: number;
|
|
},
|
|
) => {
|
|
return {
|
|
x:
|
|
opts.textAlign === "center"
|
|
? metrics.width / 2
|
|
: opts.textAlign === "right"
|
|
? metrics.width
|
|
: 0,
|
|
y: opts.verticalAlign === "middle" ? metrics.height / 2 : 0,
|
|
};
|
|
};
|
|
|
|
export const newTextElement = (
|
|
opts: {
|
|
text: string;
|
|
fontSize: number;
|
|
fontFamily: FontFamilyValues;
|
|
textAlign: TextAlign;
|
|
verticalAlign: VerticalAlign;
|
|
containerId?: ExcalidrawRectangleElement["id"];
|
|
} & ElementConstructorOpts,
|
|
): NonDeleted<ExcalidrawTextElement> => {
|
|
const metrics = measureText(opts.text, getFontString(opts));
|
|
const offsets = getTextElementPositionOffsets(opts, metrics);
|
|
const textElement = newElementWith(
|
|
{
|
|
..._newElementBase<ExcalidrawTextElement>("text", opts),
|
|
text: opts.text,
|
|
fontSize: opts.fontSize,
|
|
fontFamily: opts.fontFamily,
|
|
textAlign: opts.textAlign,
|
|
verticalAlign: opts.verticalAlign,
|
|
x: opts.x - offsets.x,
|
|
y: opts.y - offsets.y,
|
|
width: metrics.width,
|
|
height: metrics.height,
|
|
baseline: metrics.baseline,
|
|
containerId: opts.containerId || null,
|
|
originalText: opts.text,
|
|
},
|
|
{},
|
|
);
|
|
return textElement;
|
|
};
|
|
|
|
const getAdjustedDimensions = (
|
|
element: ExcalidrawTextElement,
|
|
nextText: string,
|
|
): {
|
|
x: number;
|
|
y: number;
|
|
width: number;
|
|
height: number;
|
|
baseline: number;
|
|
} => {
|
|
const maxWidth = element.containerId ? element.width : null;
|
|
const {
|
|
width: nextWidth,
|
|
height: nextHeight,
|
|
baseline: nextBaseline,
|
|
} = measureText(nextText, getFontString(element), maxWidth);
|
|
const { textAlign, verticalAlign } = element;
|
|
let x: number;
|
|
let y: number;
|
|
if (
|
|
textAlign === "center" &&
|
|
verticalAlign === "middle" &&
|
|
!element.containerId
|
|
) {
|
|
const prevMetrics = measureText(
|
|
element.text,
|
|
getFontString(element),
|
|
maxWidth,
|
|
);
|
|
const offsets = getTextElementPositionOffsets(element, {
|
|
width: nextWidth - prevMetrics.width,
|
|
height: nextHeight - prevMetrics.height,
|
|
});
|
|
|
|
x = element.x - offsets.x;
|
|
y = element.y - offsets.y;
|
|
} else {
|
|
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
|
|
|
const [nextX1, nextY1, nextX2, nextY2] = getResizedElementAbsoluteCoords(
|
|
element,
|
|
nextWidth,
|
|
nextHeight,
|
|
);
|
|
const deltaX1 = (x1 - nextX1) / 2;
|
|
const deltaY1 = (y1 - nextY1) / 2;
|
|
const deltaX2 = (x2 - nextX2) / 2;
|
|
const deltaY2 = (y2 - nextY2) / 2;
|
|
|
|
[x, y] = adjustXYWithRotation(
|
|
{
|
|
s: true,
|
|
e: textAlign === "center" || textAlign === "left",
|
|
w: textAlign === "center" || textAlign === "right",
|
|
},
|
|
element.x,
|
|
element.y,
|
|
element.angle,
|
|
deltaX1,
|
|
deltaY1,
|
|
deltaX2,
|
|
deltaY2,
|
|
);
|
|
}
|
|
|
|
// make sure container dimensions are set properly when
|
|
// text editor overflows beyond viewport dimensions
|
|
if (isBoundToContainer(element)) {
|
|
const container = Scene.getScene(element)!.getElement(element.containerId)!;
|
|
let height = container.height;
|
|
let width = container.width;
|
|
if (nextHeight > height - PADDING * 2) {
|
|
height = nextHeight + PADDING * 2;
|
|
}
|
|
if (nextWidth > width - PADDING * 2) {
|
|
width = nextWidth + PADDING * 2;
|
|
}
|
|
if (height !== container.height || width !== container.width) {
|
|
mutateElement(container, { height, width });
|
|
}
|
|
}
|
|
return {
|
|
width: nextWidth,
|
|
height: nextHeight,
|
|
x: Number.isFinite(x) ? x : element.x,
|
|
y: Number.isFinite(y) ? y : element.y,
|
|
baseline: nextBaseline,
|
|
};
|
|
};
|
|
|
|
export const updateTextElement = (
|
|
element: ExcalidrawTextElement,
|
|
{
|
|
text,
|
|
isDeleted,
|
|
originalText,
|
|
}: { text: string; isDeleted?: boolean; originalText: string },
|
|
|
|
updateDimensions: boolean,
|
|
): ExcalidrawTextElement => {
|
|
const dimensions = updateDimensions
|
|
? getAdjustedDimensions(element, text)
|
|
: undefined;
|
|
return newElementWith(element, {
|
|
text,
|
|
originalText,
|
|
isDeleted: isDeleted ?? element.isDeleted,
|
|
...dimensions,
|
|
});
|
|
};
|
|
|
|
export const newFreeDrawElement = (
|
|
opts: {
|
|
type: "freedraw";
|
|
points?: ExcalidrawFreeDrawElement["points"];
|
|
simulatePressure: boolean;
|
|
} & ElementConstructorOpts,
|
|
): NonDeleted<ExcalidrawFreeDrawElement> => {
|
|
return {
|
|
..._newElementBase<ExcalidrawFreeDrawElement>(opts.type, opts),
|
|
points: opts.points || [],
|
|
pressures: [],
|
|
simulatePressure: opts.simulatePressure,
|
|
lastCommittedPoint: null,
|
|
};
|
|
};
|
|
|
|
export const newLinearElement = (
|
|
opts: {
|
|
type: ExcalidrawLinearElement["type"];
|
|
startArrowhead: Arrowhead | null;
|
|
endArrowhead: Arrowhead | null;
|
|
points?: ExcalidrawLinearElement["points"];
|
|
} & ElementConstructorOpts,
|
|
): NonDeleted<ExcalidrawLinearElement> => {
|
|
return {
|
|
..._newElementBase<ExcalidrawLinearElement>(opts.type, opts),
|
|
points: opts.points || [],
|
|
lastCommittedPoint: null,
|
|
startBinding: null,
|
|
endBinding: null,
|
|
startArrowhead: opts.startArrowhead,
|
|
endArrowhead: opts.endArrowhead,
|
|
};
|
|
};
|
|
|
|
export const newImageElement = (
|
|
opts: {
|
|
type: ExcalidrawImageElement["type"];
|
|
} & ElementConstructorOpts,
|
|
): NonDeleted<ExcalidrawImageElement> => {
|
|
return {
|
|
..._newElementBase<ExcalidrawImageElement>("image", opts),
|
|
// in the future we'll support changing stroke color for some SVG elements,
|
|
// and `transparent` will likely mean "use original colors of the image"
|
|
strokeColor: "transparent",
|
|
status: "pending",
|
|
fileId: null,
|
|
scale: [1, 1],
|
|
};
|
|
};
|
|
|
|
// Simplified deep clone for the purpose of cloning ExcalidrawElement only
|
|
// (doesn't clone Date, RegExp, Map, Set, Typed arrays etc.)
|
|
//
|
|
// Adapted from https://github.com/lukeed/klona
|
|
export const deepCopyElement = (val: any, depth: number = 0) => {
|
|
if (val == null || typeof val !== "object") {
|
|
return val;
|
|
}
|
|
|
|
if (Object.prototype.toString.call(val) === "[object Object]") {
|
|
const tmp =
|
|
typeof val.constructor === "function"
|
|
? Object.create(Object.getPrototypeOf(val))
|
|
: {};
|
|
for (const key in val) {
|
|
if (val.hasOwnProperty(key)) {
|
|
// don't copy top-level shape property, which we want to regenerate
|
|
if (depth === 0 && (key === "shape" || key === "canvas")) {
|
|
continue;
|
|
}
|
|
tmp[key] = deepCopyElement(val[key], depth + 1);
|
|
}
|
|
}
|
|
return tmp;
|
|
}
|
|
|
|
if (Array.isArray(val)) {
|
|
let k = val.length;
|
|
const arr = new Array(k);
|
|
while (k--) {
|
|
arr[k] = deepCopyElement(val[k], depth + 1);
|
|
}
|
|
return arr;
|
|
}
|
|
|
|
return val;
|
|
};
|
|
|
|
/**
|
|
* Duplicate an element, often used in the alt-drag operation.
|
|
* Note that this method has gotten a bit complicated since the
|
|
* introduction of gruoping/ungrouping elements.
|
|
* @param editingGroupId The current group being edited. The new
|
|
* element will inherit this group and its
|
|
* parents.
|
|
* @param groupIdMapForOperation A Map that maps old group IDs to
|
|
* duplicated ones. If you are duplicating
|
|
* multiple elements at once, share this map
|
|
* amongst all of them
|
|
* @param element Element to duplicate
|
|
* @param overrides Any element properties to override
|
|
*/
|
|
export const duplicateElement = <TElement extends Mutable<ExcalidrawElement>>(
|
|
editingGroupId: AppState["editingGroupId"],
|
|
groupIdMapForOperation: Map<GroupId, GroupId>,
|
|
element: TElement,
|
|
overrides?: Partial<TElement>,
|
|
): TElement => {
|
|
let copy: TElement = deepCopyElement(element);
|
|
if (process.env.NODE_ENV === "test") {
|
|
copy.id = `${copy.id}_copy`;
|
|
// `window.h` may not be defined in some unit tests
|
|
if (
|
|
window.h?.app
|
|
?.getSceneElementsIncludingDeleted()
|
|
.find((el) => el.id === copy.id)
|
|
) {
|
|
copy.id += "_copy";
|
|
}
|
|
} else {
|
|
copy.id = randomId();
|
|
}
|
|
copy.updated = getUpdatedTimestamp();
|
|
copy.seed = randomInteger();
|
|
copy.groupIds = getNewGroupIdsForDuplication(
|
|
copy.groupIds,
|
|
editingGroupId,
|
|
(groupId) => {
|
|
if (!groupIdMapForOperation.has(groupId)) {
|
|
groupIdMapForOperation.set(groupId, randomId());
|
|
}
|
|
return groupIdMapForOperation.get(groupId)!;
|
|
},
|
|
);
|
|
if (overrides) {
|
|
copy = Object.assign(copy, overrides);
|
|
}
|
|
return copy;
|
|
};
|