
* 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
461 lines
12 KiB
TypeScript
461 lines
12 KiB
TypeScript
import colors from "./colors";
|
|
import {
|
|
CURSOR_TYPE,
|
|
DEFAULT_VERSION,
|
|
FONT_FAMILY,
|
|
WINDOWS_EMOJI_FALLBACK_FONT,
|
|
} from "./constants";
|
|
import { FontFamilyValues, FontString } from "./element/types";
|
|
import { Zoom } from "./types";
|
|
import { unstable_batchedUpdates } from "react-dom";
|
|
import { isDarwin } from "./keys";
|
|
|
|
let mockDateTime: string | null = null;
|
|
|
|
export const setDateTimeForTests = (dateTime: string) => {
|
|
mockDateTime = dateTime;
|
|
};
|
|
|
|
export const getDateTime = () => {
|
|
if (mockDateTime) {
|
|
return mockDateTime;
|
|
}
|
|
|
|
const date = new Date();
|
|
const year = date.getFullYear();
|
|
const month = `${date.getMonth() + 1}`.padStart(2, "0");
|
|
const day = `${date.getDate()}`.padStart(2, "0");
|
|
const hr = `${date.getHours()}`.padStart(2, "0");
|
|
const min = `${date.getMinutes()}`.padStart(2, "0");
|
|
|
|
return `${year}-${month}-${day}-${hr}${min}`;
|
|
};
|
|
|
|
export const capitalizeString = (str: string) =>
|
|
str.charAt(0).toUpperCase() + str.slice(1);
|
|
|
|
export const isToolIcon = (
|
|
target: Element | EventTarget | null,
|
|
): target is HTMLElement =>
|
|
target instanceof HTMLElement && target.className.includes("ToolIcon");
|
|
|
|
export const isInputLike = (
|
|
target: Element | EventTarget | null,
|
|
): target is
|
|
| HTMLInputElement
|
|
| HTMLTextAreaElement
|
|
| HTMLSelectElement
|
|
| HTMLBRElement
|
|
| HTMLDivElement =>
|
|
(target instanceof HTMLElement && target.dataset.type === "wysiwyg") ||
|
|
target instanceof HTMLBRElement || // newline in wysiwyg
|
|
target instanceof HTMLInputElement ||
|
|
target instanceof HTMLTextAreaElement ||
|
|
target instanceof HTMLSelectElement;
|
|
|
|
export const isWritableElement = (
|
|
target: Element | EventTarget | null,
|
|
): target is
|
|
| HTMLInputElement
|
|
| HTMLTextAreaElement
|
|
| HTMLBRElement
|
|
| HTMLDivElement =>
|
|
(target instanceof HTMLElement && target.dataset.type === "wysiwyg") ||
|
|
target instanceof HTMLBRElement || // newline in wysiwyg
|
|
target instanceof HTMLTextAreaElement ||
|
|
(target instanceof HTMLInputElement &&
|
|
(target.type === "text" || target.type === "number"));
|
|
|
|
export const getFontFamilyString = ({
|
|
fontFamily,
|
|
}: {
|
|
fontFamily: FontFamilyValues;
|
|
}) => {
|
|
for (const [fontFamilyString, id] of Object.entries(FONT_FAMILY)) {
|
|
if (id === fontFamily) {
|
|
return `${fontFamilyString}, ${WINDOWS_EMOJI_FALLBACK_FONT}`;
|
|
}
|
|
}
|
|
return WINDOWS_EMOJI_FALLBACK_FONT;
|
|
};
|
|
|
|
/** returns fontSize+fontFamily string for assignment to DOM elements */
|
|
export const getFontString = ({
|
|
fontSize,
|
|
fontFamily,
|
|
}: {
|
|
fontSize: number;
|
|
fontFamily: FontFamilyValues;
|
|
}) => {
|
|
return `${fontSize}px ${getFontFamilyString({ fontFamily })}` as FontString;
|
|
};
|
|
|
|
export const debounce = <T extends any[]>(
|
|
fn: (...args: T) => void,
|
|
timeout: number,
|
|
) => {
|
|
let handle = 0;
|
|
let lastArgs: T | null = null;
|
|
const ret = (...args: T) => {
|
|
lastArgs = args;
|
|
clearTimeout(handle);
|
|
handle = window.setTimeout(() => {
|
|
lastArgs = null;
|
|
fn(...args);
|
|
}, timeout);
|
|
};
|
|
ret.flush = () => {
|
|
clearTimeout(handle);
|
|
if (lastArgs) {
|
|
const _lastArgs = lastArgs;
|
|
lastArgs = null;
|
|
fn(..._lastArgs);
|
|
}
|
|
};
|
|
ret.cancel = () => {
|
|
lastArgs = null;
|
|
clearTimeout(handle);
|
|
};
|
|
return ret;
|
|
};
|
|
|
|
// https://github.com/lodash/lodash/blob/es/chunk.js
|
|
export const chunk = <T extends any>(
|
|
array: readonly T[],
|
|
size: number,
|
|
): T[][] => {
|
|
if (!array.length || size < 1) {
|
|
return [];
|
|
}
|
|
let index = 0;
|
|
let resIndex = 0;
|
|
const result = Array(Math.ceil(array.length / size));
|
|
while (index < array.length) {
|
|
result[resIndex++] = array.slice(index, (index += size));
|
|
}
|
|
return result;
|
|
};
|
|
|
|
export const selectNode = (node: Element) => {
|
|
const selection = window.getSelection();
|
|
if (selection) {
|
|
const range = document.createRange();
|
|
range.selectNodeContents(node);
|
|
selection.removeAllRanges();
|
|
selection.addRange(range);
|
|
}
|
|
};
|
|
|
|
export const removeSelection = () => {
|
|
const selection = window.getSelection();
|
|
if (selection) {
|
|
selection.removeAllRanges();
|
|
}
|
|
};
|
|
|
|
export const distance = (x: number, y: number) => Math.abs(x - y);
|
|
|
|
export const resetCursor = (canvas: HTMLCanvasElement | null) => {
|
|
if (canvas) {
|
|
canvas.style.cursor = "";
|
|
}
|
|
};
|
|
|
|
export const setCursor = (canvas: HTMLCanvasElement | null, cursor: string) => {
|
|
if (canvas) {
|
|
canvas.style.cursor = cursor;
|
|
}
|
|
};
|
|
|
|
export const setCursorForShape = (
|
|
canvas: HTMLCanvasElement | null,
|
|
shape: string,
|
|
) => {
|
|
if (!canvas) {
|
|
return;
|
|
}
|
|
if (shape === "selection") {
|
|
resetCursor(canvas);
|
|
// do nothing if image tool is selected which suggests there's
|
|
// a image-preview set as the cursor
|
|
} else if (shape !== "image") {
|
|
canvas.style.cursor = CURSOR_TYPE.CROSSHAIR;
|
|
}
|
|
};
|
|
|
|
export const isFullScreen = () =>
|
|
document.fullscreenElement?.nodeName === "HTML";
|
|
|
|
export const allowFullScreen = () =>
|
|
document.documentElement.requestFullscreen();
|
|
|
|
export const exitFullScreen = () => document.exitFullscreen();
|
|
|
|
export const getShortcutKey = (shortcut: string): string => {
|
|
shortcut = shortcut
|
|
.replace(/\bAlt\b/i, "Alt")
|
|
.replace(/\bShift\b/i, "Shift")
|
|
.replace(/\b(Enter|Return)\b/i, "Enter")
|
|
.replace(/\bDel\b/i, "Delete");
|
|
|
|
if (isDarwin) {
|
|
return shortcut
|
|
.replace(/\bCtrlOrCmd\b/i, "Cmd")
|
|
.replace(/\bAlt\b/i, "Option");
|
|
}
|
|
return shortcut.replace(/\bCtrlOrCmd\b/i, "Ctrl");
|
|
};
|
|
|
|
export const viewportCoordsToSceneCoords = (
|
|
{ clientX, clientY }: { clientX: number; clientY: number },
|
|
{
|
|
zoom,
|
|
offsetLeft,
|
|
offsetTop,
|
|
scrollX,
|
|
scrollY,
|
|
}: {
|
|
zoom: Zoom;
|
|
offsetLeft: number;
|
|
offsetTop: number;
|
|
scrollX: number;
|
|
scrollY: number;
|
|
},
|
|
) => {
|
|
const invScale = 1 / zoom.value;
|
|
const x = (clientX - zoom.translation.x - offsetLeft) * invScale - scrollX;
|
|
const y = (clientY - zoom.translation.y - offsetTop) * invScale - scrollY;
|
|
return { x, y };
|
|
};
|
|
|
|
export const sceneCoordsToViewportCoords = (
|
|
{ sceneX, sceneY }: { sceneX: number; sceneY: number },
|
|
{
|
|
zoom,
|
|
offsetLeft,
|
|
offsetTop,
|
|
scrollX,
|
|
scrollY,
|
|
}: {
|
|
zoom: Zoom;
|
|
offsetLeft: number;
|
|
offsetTop: number;
|
|
scrollX: number;
|
|
scrollY: number;
|
|
},
|
|
) => {
|
|
const x = (sceneX + scrollX + offsetLeft) * zoom.value + zoom.translation.x;
|
|
const y = (sceneY + scrollY + offsetTop) * zoom.value + zoom.translation.y;
|
|
return { x, y };
|
|
};
|
|
|
|
export const getGlobalCSSVariable = (name: string) =>
|
|
getComputedStyle(document.documentElement).getPropertyValue(`--${name}`);
|
|
|
|
const RS_LTR_CHARS =
|
|
"A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF" +
|
|
"\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF";
|
|
const RS_RTL_CHARS = "\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC";
|
|
const RE_RTL_CHECK = new RegExp(`^[^${RS_LTR_CHARS}]*[${RS_RTL_CHARS}]`);
|
|
/**
|
|
* Checks whether first directional character is RTL. Meaning whether it starts
|
|
* with RTL characters, or indeterminate (numbers etc.) characters followed by
|
|
* RTL.
|
|
* See https://github.com/excalidraw/excalidraw/pull/1722#discussion_r436340171
|
|
*/
|
|
export const isRTL = (text: string) => RE_RTL_CHECK.test(text);
|
|
|
|
export const tupleToCoors = (
|
|
xyTuple: readonly [number, number],
|
|
): { x: number; y: number } => {
|
|
const [x, y] = xyTuple;
|
|
return { x, y };
|
|
};
|
|
|
|
/** use as a rejectionHandler to mute filesystem Abort errors */
|
|
export const muteFSAbortError = (error?: Error) => {
|
|
if (error?.name === "AbortError") {
|
|
console.warn(error);
|
|
return;
|
|
}
|
|
throw error;
|
|
};
|
|
|
|
export const findIndex = <T>(
|
|
array: readonly T[],
|
|
cb: (element: T, index: number, array: readonly T[]) => boolean,
|
|
fromIndex: number = 0,
|
|
) => {
|
|
if (fromIndex < 0) {
|
|
fromIndex = array.length + fromIndex;
|
|
}
|
|
fromIndex = Math.min(array.length, Math.max(fromIndex, 0));
|
|
let index = fromIndex - 1;
|
|
while (++index < array.length) {
|
|
if (cb(array[index], index, array)) {
|
|
return index;
|
|
}
|
|
}
|
|
return -1;
|
|
};
|
|
|
|
export const findLastIndex = <T>(
|
|
array: readonly T[],
|
|
cb: (element: T, index: number, array: readonly T[]) => boolean,
|
|
fromIndex: number = array.length - 1,
|
|
) => {
|
|
if (fromIndex < 0) {
|
|
fromIndex = array.length + fromIndex;
|
|
}
|
|
fromIndex = Math.min(array.length - 1, Math.max(fromIndex, 0));
|
|
let index = fromIndex + 1;
|
|
while (--index > -1) {
|
|
if (cb(array[index], index, array)) {
|
|
return index;
|
|
}
|
|
}
|
|
return -1;
|
|
};
|
|
|
|
export const isTransparent = (color: string) => {
|
|
const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0";
|
|
const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00";
|
|
return (
|
|
isRGBTransparent ||
|
|
isRRGGBBTransparent ||
|
|
color === colors.elementBackground[0]
|
|
);
|
|
};
|
|
|
|
export type ResolvablePromise<T> = Promise<T> & {
|
|
resolve: [T] extends [undefined] ? (value?: T) => void : (value: T) => void;
|
|
reject: (error: Error) => void;
|
|
};
|
|
export const resolvablePromise = <T>() => {
|
|
let resolve!: any;
|
|
let reject!: any;
|
|
const promise = new Promise((_resolve, _reject) => {
|
|
resolve = _resolve;
|
|
reject = _reject;
|
|
});
|
|
(promise as any).resolve = resolve;
|
|
(promise as any).reject = reject;
|
|
return promise as ResolvablePromise<T>;
|
|
};
|
|
|
|
/**
|
|
* @param func handler taking at most single parameter (event).
|
|
*/
|
|
export const withBatchedUpdates = <
|
|
TFunction extends ((event: any) => void) | (() => void),
|
|
>(
|
|
func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
|
|
) =>
|
|
((event) => {
|
|
unstable_batchedUpdates(func as TFunction, event);
|
|
}) as TFunction;
|
|
|
|
//https://stackoverflow.com/a/9462382/8418
|
|
export const nFormatter = (num: number, digits: number): string => {
|
|
const si = [
|
|
{ value: 1, symbol: "b" },
|
|
{ value: 1e3, symbol: "k" },
|
|
{ value: 1e6, symbol: "M" },
|
|
{ value: 1e9, symbol: "G" },
|
|
];
|
|
const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
|
|
let index;
|
|
for (index = si.length - 1; index > 0; index--) {
|
|
if (num >= si[index].value) {
|
|
break;
|
|
}
|
|
}
|
|
return (
|
|
(num / si[index].value).toFixed(digits).replace(rx, "$1") + si[index].symbol
|
|
);
|
|
};
|
|
|
|
export const getVersion = () => {
|
|
return (
|
|
document.querySelector<HTMLMetaElement>('meta[name="version"]')?.content ||
|
|
DEFAULT_VERSION
|
|
);
|
|
};
|
|
|
|
// Adapted from https://github.com/Modernizr/Modernizr/blob/master/feature-detects/emoji.js
|
|
export const supportsEmoji = () => {
|
|
const canvas = document.createElement("canvas");
|
|
const ctx = canvas.getContext("2d");
|
|
if (!ctx) {
|
|
return false;
|
|
}
|
|
const offset = 12;
|
|
ctx.fillStyle = "#f00";
|
|
ctx.textBaseline = "top";
|
|
ctx.font = "32px Arial";
|
|
// Modernizr used 🐨, but it is sort of supported on Windows 7.
|
|
// Luckily 😀 isn't supported.
|
|
ctx.fillText("😀", 0, 0);
|
|
return ctx.getImageData(offset, offset, 1, 1).data[0] !== 0;
|
|
};
|
|
|
|
export const getNearestScrollableContainer = (
|
|
element: HTMLElement,
|
|
): HTMLElement | Document => {
|
|
let parent = element.parentElement;
|
|
while (parent) {
|
|
if (parent === document.body) {
|
|
return document;
|
|
}
|
|
const { overflowY } = window.getComputedStyle(parent);
|
|
const hasScrollableContent = parent.scrollHeight > parent.clientHeight;
|
|
if (
|
|
hasScrollableContent &&
|
|
(overflowY === "auto" || overflowY === "scroll")
|
|
) {
|
|
return parent;
|
|
}
|
|
parent = parent.parentElement;
|
|
}
|
|
return document;
|
|
};
|
|
|
|
export const focusNearestParent = (element: HTMLInputElement) => {
|
|
let parent = element.parentElement;
|
|
while (parent) {
|
|
if (parent.tabIndex > -1) {
|
|
parent.focus();
|
|
return;
|
|
}
|
|
parent = parent.parentElement;
|
|
}
|
|
};
|
|
|
|
export const preventUnload = (event: BeforeUnloadEvent) => {
|
|
event.preventDefault();
|
|
// NOTE: modern browsers no longer allow showing a custom message here
|
|
event.returnValue = "";
|
|
};
|
|
|
|
export const bytesToHexString = (bytes: Uint8Array) => {
|
|
return Array.from(bytes)
|
|
.map((byte) => `0${byte.toString(16)}`.slice(-2))
|
|
.join("");
|
|
};
|
|
|
|
export const getUpdatedTimestamp = () =>
|
|
process.env.NODE_ENV === "test" ? 1 : Date.now();
|
|
|
|
/**
|
|
* Transforms array of objects containing `id` attribute,
|
|
* or array of ids (strings), into a Map, keyd by `id`.
|
|
*/
|
|
export const arrayToMap = <T extends { id: string } | string>(
|
|
items: readonly T[],
|
|
) => {
|
|
return items.reduce((acc: Map<string, T>, element) => {
|
|
acc.set(typeof element === "string" ? element : element.id, element);
|
|
return acc;
|
|
}, new Map());
|
|
};
|