clipboard.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import {
  2. ExcalidrawElement,
  3. NonDeletedExcalidrawElement,
  4. } from "./element/types";
  5. import { getSelectedElements } from "./scene";
  6. import { AppState, BinaryFiles } from "./types";
  7. import { SVG_EXPORT_TAG } from "./scene/export";
  8. import { tryParseSpreadsheet, Spreadsheet, VALID_SPREADSHEET } from "./charts";
  9. import { EXPORT_DATA_TYPES, MIME_TYPES } from "./constants";
  10. import { isInitializedImageElement } from "./element/typeChecks";
  11. type ElementsClipboard = {
  12. type: typeof EXPORT_DATA_TYPES.excalidrawClipboard;
  13. elements: ExcalidrawElement[];
  14. files: BinaryFiles | undefined;
  15. };
  16. export interface ClipboardData {
  17. spreadsheet?: Spreadsheet;
  18. elements?: readonly ExcalidrawElement[];
  19. files?: BinaryFiles;
  20. text?: string;
  21. errorMessage?: string;
  22. }
  23. let CLIPBOARD = "";
  24. let PREFER_APP_CLIPBOARD = false;
  25. export const probablySupportsClipboardReadText =
  26. "clipboard" in navigator && "readText" in navigator.clipboard;
  27. export const probablySupportsClipboardWriteText =
  28. "clipboard" in navigator && "writeText" in navigator.clipboard;
  29. export const probablySupportsClipboardBlob =
  30. "clipboard" in navigator &&
  31. "write" in navigator.clipboard &&
  32. "ClipboardItem" in window &&
  33. "toBlob" in HTMLCanvasElement.prototype;
  34. const clipboardContainsElements = (
  35. contents: any,
  36. ): contents is { elements: ExcalidrawElement[]; files?: BinaryFiles } => {
  37. if (
  38. [
  39. EXPORT_DATA_TYPES.excalidraw,
  40. EXPORT_DATA_TYPES.excalidrawClipboard,
  41. ].includes(contents?.type) &&
  42. Array.isArray(contents.elements)
  43. ) {
  44. return true;
  45. }
  46. return false;
  47. };
  48. export const copyToClipboard = async (
  49. elements: readonly NonDeletedExcalidrawElement[],
  50. appState: AppState,
  51. files: BinaryFiles,
  52. ) => {
  53. // select binded text elements when copying
  54. const selectedElements = getSelectedElements(elements, appState, true);
  55. const contents: ElementsClipboard = {
  56. type: EXPORT_DATA_TYPES.excalidrawClipboard,
  57. elements: selectedElements,
  58. files: selectedElements.reduce((acc, element) => {
  59. if (isInitializedImageElement(element) && files[element.fileId]) {
  60. acc[element.fileId] = files[element.fileId];
  61. }
  62. return acc;
  63. }, {} as BinaryFiles),
  64. };
  65. const json = JSON.stringify(contents);
  66. CLIPBOARD = json;
  67. try {
  68. PREFER_APP_CLIPBOARD = false;
  69. await copyTextToSystemClipboard(json);
  70. } catch (error: any) {
  71. PREFER_APP_CLIPBOARD = true;
  72. console.error(error);
  73. }
  74. };
  75. const getAppClipboard = (): Partial<ElementsClipboard> => {
  76. if (!CLIPBOARD) {
  77. return {};
  78. }
  79. try {
  80. return JSON.parse(CLIPBOARD);
  81. } catch (error: any) {
  82. console.error(error);
  83. return {};
  84. }
  85. };
  86. const parsePotentialSpreadsheet = (
  87. text: string,
  88. ): { spreadsheet: Spreadsheet } | { errorMessage: string } | null => {
  89. const result = tryParseSpreadsheet(text);
  90. if (result.type === VALID_SPREADSHEET) {
  91. return { spreadsheet: result.spreadsheet };
  92. }
  93. return null;
  94. };
  95. /**
  96. * Retrieves content from system clipboard (either from ClipboardEvent or
  97. * via async clipboard API if supported)
  98. */
  99. const getSystemClipboard = async (
  100. event: ClipboardEvent | null,
  101. ): Promise<string> => {
  102. try {
  103. const text = event
  104. ? event.clipboardData?.getData("text/plain").trim()
  105. : probablySupportsClipboardReadText &&
  106. (await navigator.clipboard.readText());
  107. return text || "";
  108. } catch {
  109. return "";
  110. }
  111. };
  112. /**
  113. * Attemps to parse clipboard. Prefers system clipboard.
  114. */
  115. export const parseClipboard = async (
  116. event: ClipboardEvent | null,
  117. ): Promise<ClipboardData> => {
  118. const systemClipboard = await getSystemClipboard(event);
  119. // if system clipboard empty, couldn't be resolved, or contains previously
  120. // copied excalidraw scene as SVG, fall back to previously copied excalidraw
  121. // elements
  122. if (!systemClipboard || systemClipboard.includes(SVG_EXPORT_TAG)) {
  123. return getAppClipboard();
  124. }
  125. // if system clipboard contains spreadsheet, use it even though it's
  126. // technically possible it's staler than in-app clipboard
  127. const spreadsheetResult = parsePotentialSpreadsheet(systemClipboard);
  128. if (spreadsheetResult) {
  129. return spreadsheetResult;
  130. }
  131. const appClipboardData = getAppClipboard();
  132. try {
  133. const systemClipboardData = JSON.parse(systemClipboard);
  134. if (clipboardContainsElements(systemClipboardData)) {
  135. return {
  136. elements: systemClipboardData.elements,
  137. files: systemClipboardData.files,
  138. };
  139. }
  140. return appClipboardData;
  141. } catch {
  142. // system clipboard doesn't contain excalidraw elements → return plaintext
  143. // unless we set a flag to prefer in-app clipboard because browser didn't
  144. // support storing to system clipboard on copy
  145. return PREFER_APP_CLIPBOARD && appClipboardData.elements
  146. ? appClipboardData
  147. : { text: systemClipboard };
  148. }
  149. };
  150. export const copyBlobToClipboardAsPng = async (blob: Blob) => {
  151. await navigator.clipboard.write([
  152. new window.ClipboardItem({ [MIME_TYPES.png]: blob }),
  153. ]);
  154. };
  155. export const copyTextToSystemClipboard = async (text: string | null) => {
  156. let copied = false;
  157. if (probablySupportsClipboardWriteText) {
  158. try {
  159. // NOTE: doesn't work on FF on non-HTTPS domains, or when document
  160. // not focused
  161. await navigator.clipboard.writeText(text || "");
  162. copied = true;
  163. } catch (error: any) {
  164. console.error(error);
  165. }
  166. }
  167. // Note that execCommand doesn't allow copying empty strings, so if we're
  168. // clearing clipboard using this API, we must copy at least an empty char
  169. if (!copied && !copyTextViaExecCommand(text || " ")) {
  170. throw new Error("couldn't copy");
  171. }
  172. };
  173. // adapted from https://github.com/zenorocha/clipboard.js/blob/ce79f170aa655c408b6aab33c9472e8e4fa52e19/src/clipboard-action.js#L48
  174. const copyTextViaExecCommand = (text: string) => {
  175. const isRTL = document.documentElement.getAttribute("dir") === "rtl";
  176. const textarea = document.createElement("textarea");
  177. textarea.style.border = "0";
  178. textarea.style.padding = "0";
  179. textarea.style.margin = "0";
  180. textarea.style.position = "absolute";
  181. textarea.style[isRTL ? "right" : "left"] = "-9999px";
  182. const yPosition = window.pageYOffset || document.documentElement.scrollTop;
  183. textarea.style.top = `${yPosition}px`;
  184. // Prevent zooming on iOS
  185. textarea.style.fontSize = "12pt";
  186. textarea.setAttribute("readonly", "");
  187. textarea.value = text;
  188. document.body.appendChild(textarea);
  189. let success = false;
  190. try {
  191. textarea.select();
  192. textarea.setSelectionRange(0, textarea.value.length);
  193. success = document.execCommand("copy");
  194. } catch (error: any) {
  195. console.error(error);
  196. }
  197. textarea.remove();
  198. return success;
  199. };