Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

clipboard.ts 6.5KB

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