clipboard.ts 6.0 KB

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