excalidraw/src/clipboard.ts

369 lines
10 KiB
TypeScript
Raw Normal View History

import {
ExcalidrawElement,
NonDeletedExcalidrawElement,
} from "./element/types";
import { BinaryFiles } from "./types";
import { SVG_EXPORT_TAG } from "./scene/export";
import { tryParseSpreadsheet, Spreadsheet, VALID_SPREADSHEET } from "./charts";
import { EXPORT_DATA_TYPES, MIME_TYPES } from "./constants";
import { isInitializedImageElement } from "./element/typeChecks";
import { deepCopyElement } from "./element/newElement";
import { mutateElement } from "./element/mutateElement";
import { getContainingFrame } from "./frame";
import { isPromiseLike, isTestEnv } from "./utils";
2020-09-04 14:58:32 +02:00
type ElementsClipboard = {
type: typeof EXPORT_DATA_TYPES.excalidrawClipboard;
elements: readonly NonDeletedExcalidrawElement[];
files: BinaryFiles | undefined;
2020-09-04 14:58:32 +02:00
};
2020-02-04 11:50:18 +01:00
export type PastedMixedContent = { type: "text" | "imageUrl"; value: string }[];
export interface ClipboardData {
spreadsheet?: Spreadsheet;
elements?: readonly ExcalidrawElement[];
files?: BinaryFiles;
text?: string;
mixedContent?: PastedMixedContent;
errorMessage?: string;
feat: support creating containers, linear elements, text containers, labelled arrows and arrow bindings programatically (#6546) * feat: support creating text containers programatically * fix * fix * fix * fix * update api to use label * fix api and support individual shapes and text element * update test case in package example * support creating arrows and line * support labelled arrows * add in package example * fix alignment * better types * fix * keep element as is unless we support prog api * fix tests * fix lint * ignore * support arrow bindings via start and end in api * fix lint * fix coords * support id as well for elements * preserve bindings if present and fix testcases * preserve bindings for labelled arrows * support ids, clean up code and move the api related stuff to transform.ts * allow multiple arrows to bind to single element * fix singular elements * fix single text element, unique id and tests * fix lint * fix * support binding arrow to text element * fix creation of regular text * use same stroke color as parent for text containers and height 0 for linear element by default * fix types * fix * remove more ts ignore * remove ts ignore * remove * Add coverage script * Add tests * fix tests * make type optional when id present * remove type when id provided in tests * Add more tests * tweak * let host call convertToExcalidrawElements when using programmatic API * remove convertToExcalidrawElements call from restore * lint * update snaps * Add new type excalidraw-api/clipboard for programmatic api * cleanup * rename tweak * tweak * make image attributes optional and better ts check * support image via programmatic API * fix lint * more types * make fileId mandatory for image and export convertToExcalidrawElements * fix * small tweaks * update snaps * fix * use Object.assign instead of mutateElement * lint * preserve z-index by pushing all elements first and then add bindings * instantiate instead of closure for storing elements * use element API to create regular text, diamond, ellipse and rectangle * fix snaps * udpdate api * ts fixes * make `convertToExcalidrawElements` more typesafe * update snaps * refactor the approach so that order of elements doesn't matter * Revert "update snaps" This reverts commit 621dfadccfea975a1f77223f506dce9d260f91fd. * review fixes * rename ExcalidrawProgrammaticElement -> ExcalidrawELementSkeleton * Add tests * give preference to first element when duplicate ids found * use console.error --------- Co-authored-by: dwelle <luzar.david@gmail.com>
2023-08-09 16:41:15 +05:30
programmaticAPI?: boolean;
}
2020-02-04 11:50:18 +01:00
let CLIPBOARD = "";
let PREFER_APP_CLIPBOARD = false;
export const probablySupportsClipboardReadText =
"clipboard" in navigator && "readText" in navigator.clipboard;
2020-02-04 11:50:18 +01:00
export const probablySupportsClipboardWriteText =
"clipboard" in navigator && "writeText" in navigator.clipboard;
export const probablySupportsClipboardBlob =
"clipboard" in navigator &&
"write" in navigator.clipboard &&
"ClipboardItem" in window &&
"toBlob" in HTMLCanvasElement.prototype;
const clipboardContainsElements = (
contents: any,
): contents is { elements: ExcalidrawElement[]; files?: BinaryFiles } => {
if (
[
EXPORT_DATA_TYPES.excalidraw,
EXPORT_DATA_TYPES.excalidrawClipboard,
feat: support creating containers, linear elements, text containers, labelled arrows and arrow bindings programatically (#6546) * feat: support creating text containers programatically * fix * fix * fix * fix * update api to use label * fix api and support individual shapes and text element * update test case in package example * support creating arrows and line * support labelled arrows * add in package example * fix alignment * better types * fix * keep element as is unless we support prog api * fix tests * fix lint * ignore * support arrow bindings via start and end in api * fix lint * fix coords * support id as well for elements * preserve bindings if present and fix testcases * preserve bindings for labelled arrows * support ids, clean up code and move the api related stuff to transform.ts * allow multiple arrows to bind to single element * fix singular elements * fix single text element, unique id and tests * fix lint * fix * support binding arrow to text element * fix creation of regular text * use same stroke color as parent for text containers and height 0 for linear element by default * fix types * fix * remove more ts ignore * remove ts ignore * remove * Add coverage script * Add tests * fix tests * make type optional when id present * remove type when id provided in tests * Add more tests * tweak * let host call convertToExcalidrawElements when using programmatic API * remove convertToExcalidrawElements call from restore * lint * update snaps * Add new type excalidraw-api/clipboard for programmatic api * cleanup * rename tweak * tweak * make image attributes optional and better ts check * support image via programmatic API * fix lint * more types * make fileId mandatory for image and export convertToExcalidrawElements * fix * small tweaks * update snaps * fix * use Object.assign instead of mutateElement * lint * preserve z-index by pushing all elements first and then add bindings * instantiate instead of closure for storing elements * use element API to create regular text, diamond, ellipse and rectangle * fix snaps * udpdate api * ts fixes * make `convertToExcalidrawElements` more typesafe * update snaps * refactor the approach so that order of elements doesn't matter * Revert "update snaps" This reverts commit 621dfadccfea975a1f77223f506dce9d260f91fd. * review fixes * rename ExcalidrawProgrammaticElement -> ExcalidrawELementSkeleton * Add tests * give preference to first element when duplicate ids found * use console.error --------- Co-authored-by: dwelle <luzar.david@gmail.com>
2023-08-09 16:41:15 +05:30
EXPORT_DATA_TYPES.excalidrawClipboardWithAPI,
].includes(contents?.type) &&
Array.isArray(contents.elements)
) {
2020-09-04 14:58:32 +02:00
return true;
}
return false;
};
export const copyToClipboard = async (
elements: readonly NonDeletedExcalidrawElement[],
files: BinaryFiles | null,
) => {
const framesToCopy = new Set(
elements.filter((element) => element.type === "frame"),
);
let foundFile = false;
const _files = elements.reduce((acc, element) => {
if (isInitializedImageElement(element)) {
foundFile = true;
if (files && files[element.fileId]) {
acc[element.fileId] = files[element.fileId];
}
}
return acc;
}, {} as BinaryFiles);
if (foundFile && !files) {
console.warn(
"copyToClipboard: attempting to file element(s) without providing associated `files` object.",
);
}
feat: bind text to shapes when pressing enter and support sticky notes 🎉 (#4343) * 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
2021-12-16 21:14:03 +05:30
// select binded text elements when copying
2020-09-04 14:58:32 +02:00
const contents: ElementsClipboard = {
type: EXPORT_DATA_TYPES.excalidrawClipboard,
elements: elements.map((element) => {
if (
getContainingFrame(element) &&
!framesToCopy.has(getContainingFrame(element)!)
) {
const copiedElement = deepCopyElement(element);
mutateElement(copiedElement, {
frameId: null,
});
return copiedElement;
}
return element;
}),
files: files ? _files : undefined,
2020-09-04 14:58:32 +02:00
};
const json = JSON.stringify(contents);
if (isTestEnv()) {
return json;
}
2020-09-04 14:58:32 +02:00
CLIPBOARD = json;
2020-02-04 11:50:18 +01:00
try {
PREFER_APP_CLIPBOARD = false;
2020-09-04 14:58:32 +02:00
await copyTextToSystemClipboard(json);
} catch (error: any) {
2020-02-04 11:50:18 +01:00
PREFER_APP_CLIPBOARD = true;
console.error(error);
2020-02-04 11:50:18 +01:00
}
};
2020-02-04 11:50:18 +01:00
2020-09-04 14:58:32 +02:00
const getAppClipboard = (): Partial<ElementsClipboard> => {
if (!CLIPBOARD) {
return {};
}
2020-02-04 11:50:18 +01:00
try {
2020-09-04 14:58:32 +02:00
return JSON.parse(CLIPBOARD);
} catch (error: any) {
console.error(error);
2020-09-04 14:58:32 +02:00
return {};
}
2020-09-04 14:58:32 +02:00
};
2020-02-04 11:50:18 +01:00
2020-09-04 14:58:32 +02:00
const parsePotentialSpreadsheet = (
text: string,
): { spreadsheet: Spreadsheet } | { errorMessage: string } | null => {
const result = tryParseSpreadsheet(text);
if (result.type === VALID_SPREADSHEET) {
return { spreadsheet: result.spreadsheet };
}
return null;
};
2020-02-04 11:50:18 +01:00
/** internal, specific to parsing paste events. Do not reuse. */
function parseHTMLTree(el: ChildNode) {
let result: PastedMixedContent = [];
for (const node of el.childNodes) {
if (node.nodeType === 3) {
const text = node.textContent?.trim();
if (text) {
result.push({ type: "text", value: text });
}
} else if (node instanceof HTMLImageElement) {
const url = node.getAttribute("src");
if (url && url.startsWith("http")) {
result.push({ type: "imageUrl", value: url });
}
} else {
result = result.concat(parseHTMLTree(node));
}
}
return result;
}
const maybeParseHTMLPaste = (event: ClipboardEvent) => {
const html = event.clipboardData?.getData("text/html");
if (!html) {
return null;
}
try {
const doc = new DOMParser().parseFromString(html, "text/html");
const content = parseHTMLTree(doc.body);
if (content.length) {
return content;
}
} catch (error: any) {
console.error(`error in parseHTMLFromPaste: ${error.message}`);
}
return null;
};
2020-09-04 14:58:32 +02:00
/**
* Retrieves content from system clipboard (either from ClipboardEvent or
* via async clipboard API if supported)
*/
const getSystemClipboard = async (
event: ClipboardEvent | null,
isPlainPaste = false,
): Promise<
| { type: "text"; value: string }
| { type: "mixedContent"; value: PastedMixedContent }
> => {
2020-02-04 11:50:18 +01:00
try {
const mixedContent = !isPlainPaste && event && maybeParseHTMLPaste(event);
if (mixedContent) {
return { type: "mixedContent", value: mixedContent };
}
const text = event
? event.clipboardData?.getData("text/plain")
: probablySupportsClipboardReadText &&
(await navigator.clipboard.readText());
return { type: "text", value: (text || "").trim() };
2020-09-04 14:58:32 +02:00
} catch {
return { type: "text", value: "" };
}
2020-09-04 14:58:32 +02:00
};
2020-02-04 11:50:18 +01:00
2020-09-04 14:58:32 +02:00
/**
* Attempts to parse clipboard. Prefers system clipboard.
2020-09-04 14:58:32 +02:00
*/
export const parseClipboard = async (
event: ClipboardEvent | null,
isPlainPaste = false,
): Promise<ClipboardData> => {
const systemClipboard = await getSystemClipboard(event, isPlainPaste);
if (systemClipboard.type === "mixedContent") {
return {
mixedContent: systemClipboard.value,
};
}
2020-09-04 14:58:32 +02:00
// if system clipboard empty, couldn't be resolved, or contains previously
// copied excalidraw scene as SVG, fall back to previously copied excalidraw
// elements
if (
!systemClipboard ||
(!isPlainPaste && systemClipboard.value.includes(SVG_EXPORT_TAG))
) {
2020-09-04 14:58:32 +02:00
return getAppClipboard();
}
// if system clipboard contains spreadsheet, use it even though it's
// technically possible it's staler than in-app clipboard
const spreadsheetResult =
!isPlainPaste && parsePotentialSpreadsheet(systemClipboard.value);
2020-09-04 14:58:32 +02:00
if (spreadsheetResult) {
return spreadsheetResult;
}
const appClipboardData = getAppClipboard();
try {
const systemClipboardData = JSON.parse(systemClipboard.value);
feat: support creating containers, linear elements, text containers, labelled arrows and arrow bindings programatically (#6546) * feat: support creating text containers programatically * fix * fix * fix * fix * update api to use label * fix api and support individual shapes and text element * update test case in package example * support creating arrows and line * support labelled arrows * add in package example * fix alignment * better types * fix * keep element as is unless we support prog api * fix tests * fix lint * ignore * support arrow bindings via start and end in api * fix lint * fix coords * support id as well for elements * preserve bindings if present and fix testcases * preserve bindings for labelled arrows * support ids, clean up code and move the api related stuff to transform.ts * allow multiple arrows to bind to single element * fix singular elements * fix single text element, unique id and tests * fix lint * fix * support binding arrow to text element * fix creation of regular text * use same stroke color as parent for text containers and height 0 for linear element by default * fix types * fix * remove more ts ignore * remove ts ignore * remove * Add coverage script * Add tests * fix tests * make type optional when id present * remove type when id provided in tests * Add more tests * tweak * let host call convertToExcalidrawElements when using programmatic API * remove convertToExcalidrawElements call from restore * lint * update snaps * Add new type excalidraw-api/clipboard for programmatic api * cleanup * rename tweak * tweak * make image attributes optional and better ts check * support image via programmatic API * fix lint * more types * make fileId mandatory for image and export convertToExcalidrawElements * fix * small tweaks * update snaps * fix * use Object.assign instead of mutateElement * lint * preserve z-index by pushing all elements first and then add bindings * instantiate instead of closure for storing elements * use element API to create regular text, diamond, ellipse and rectangle * fix snaps * udpdate api * ts fixes * make `convertToExcalidrawElements` more typesafe * update snaps * refactor the approach so that order of elements doesn't matter * Revert "update snaps" This reverts commit 621dfadccfea975a1f77223f506dce9d260f91fd. * review fixes * rename ExcalidrawProgrammaticElement -> ExcalidrawELementSkeleton * Add tests * give preference to first element when duplicate ids found * use console.error --------- Co-authored-by: dwelle <luzar.david@gmail.com>
2023-08-09 16:41:15 +05:30
const programmaticAPI =
systemClipboardData.type === EXPORT_DATA_TYPES.excalidrawClipboardWithAPI;
if (clipboardContainsElements(systemClipboardData)) {
return {
elements: systemClipboardData.elements,
files: systemClipboardData.files,
text: isPlainPaste
? JSON.stringify(systemClipboardData.elements, null, 2)
: undefined,
feat: support creating containers, linear elements, text containers, labelled arrows and arrow bindings programatically (#6546) * feat: support creating text containers programatically * fix * fix * fix * fix * update api to use label * fix api and support individual shapes and text element * update test case in package example * support creating arrows and line * support labelled arrows * add in package example * fix alignment * better types * fix * keep element as is unless we support prog api * fix tests * fix lint * ignore * support arrow bindings via start and end in api * fix lint * fix coords * support id as well for elements * preserve bindings if present and fix testcases * preserve bindings for labelled arrows * support ids, clean up code and move the api related stuff to transform.ts * allow multiple arrows to bind to single element * fix singular elements * fix single text element, unique id and tests * fix lint * fix * support binding arrow to text element * fix creation of regular text * use same stroke color as parent for text containers and height 0 for linear element by default * fix types * fix * remove more ts ignore * remove ts ignore * remove * Add coverage script * Add tests * fix tests * make type optional when id present * remove type when id provided in tests * Add more tests * tweak * let host call convertToExcalidrawElements when using programmatic API * remove convertToExcalidrawElements call from restore * lint * update snaps * Add new type excalidraw-api/clipboard for programmatic api * cleanup * rename tweak * tweak * make image attributes optional and better ts check * support image via programmatic API * fix lint * more types * make fileId mandatory for image and export convertToExcalidrawElements * fix * small tweaks * update snaps * fix * use Object.assign instead of mutateElement * lint * preserve z-index by pushing all elements first and then add bindings * instantiate instead of closure for storing elements * use element API to create regular text, diamond, ellipse and rectangle * fix snaps * udpdate api * ts fixes * make `convertToExcalidrawElements` more typesafe * update snaps * refactor the approach so that order of elements doesn't matter * Revert "update snaps" This reverts commit 621dfadccfea975a1f77223f506dce9d260f91fd. * review fixes * rename ExcalidrawProgrammaticElement -> ExcalidrawELementSkeleton * Add tests * give preference to first element when duplicate ids found * use console.error --------- Co-authored-by: dwelle <luzar.david@gmail.com>
2023-08-09 16:41:15 +05:30
programmaticAPI,
};
2020-09-04 14:58:32 +02:00
}
} catch (e) {}
// system clipboard doesn't contain excalidraw elements → return plaintext
// unless we set a flag to prefer in-app clipboard because browser didn't
// support storing to system clipboard on copy
return PREFER_APP_CLIPBOARD && appClipboardData.elements
? {
...appClipboardData,
text: isPlainPaste
? JSON.stringify(appClipboardData.elements, null, 2)
: undefined,
}
: { text: systemClipboard.value };
};
2020-02-04 11:50:18 +01:00
export const copyBlobToClipboardAsPng = async (blob: Blob | Promise<Blob>) => {
try {
// in Safari so far we need to construct the ClipboardItem synchronously
// (i.e. in the same tick) otherwise browser will complain for lack of
// user intent. Using a Promise ClipboardItem constructor solves this.
// https://bugs.webkit.org/show_bug.cgi?id=222262
//
// Note that Firefox (and potentially others) seems to support Promise
// ClipboardItem constructor, but throws on an unrelated MIME type error.
// So we need to await this and fallback to awaiting the blob if applicable.
await navigator.clipboard.write([
new window.ClipboardItem({
[MIME_TYPES.png]: blob,
}),
]);
} catch (error: any) {
// if we're using a Promise ClipboardItem, let's try constructing
// with resolution value instead
if (isPromiseLike(blob)) {
await navigator.clipboard.write([
new window.ClipboardItem({
[MIME_TYPES.png]: await blob,
}),
]);
} else {
throw error;
}
}
};
2020-02-04 11:50:18 +01:00
export const copyTextToSystemClipboard = async (text: string | null) => {
2020-02-04 11:50:18 +01:00
let copied = false;
if (probablySupportsClipboardWriteText) {
try {
// NOTE: doesn't work on FF on non-HTTPS domains, or when document
// not focused
2020-02-04 11:50:18 +01:00
await navigator.clipboard.writeText(text || "");
copied = true;
} catch (error: any) {
console.error(error);
}
2020-02-04 11:50:18 +01:00
}
// Note that execCommand doesn't allow copying empty strings, so if we're
// clearing clipboard using this API, we must copy at least an empty char
2020-02-04 11:50:18 +01:00
if (!copied && !copyTextViaExecCommand(text || " ")) {
throw new Error("couldn't copy");
}
};
2020-02-04 11:50:18 +01:00
// adapted from https://github.com/zenorocha/clipboard.js/blob/ce79f170aa655c408b6aab33c9472e8e4fa52e19/src/clipboard-action.js#L48
const copyTextViaExecCommand = (text: string) => {
2020-02-04 11:50:18 +01:00
const isRTL = document.documentElement.getAttribute("dir") === "rtl";
const textarea = document.createElement("textarea");
textarea.style.border = "0";
textarea.style.padding = "0";
textarea.style.margin = "0";
textarea.style.position = "absolute";
textarea.style[isRTL ? "right" : "left"] = "-9999px";
const yPosition = window.pageYOffset || document.documentElement.scrollTop;
textarea.style.top = `${yPosition}px`;
// Prevent zooming on iOS
textarea.style.fontSize = "12pt";
textarea.setAttribute("readonly", "");
textarea.value = text;
document.body.appendChild(textarea);
let success = false;
try {
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
success = document.execCommand("copy");
} catch (error: any) {
console.error(error);
}
2020-02-04 11:50:18 +01:00
textarea.remove();
return success;
};