utils.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import oc from "open-color";
  2. import colors from "./colors";
  3. import {
  4. CURSOR_TYPE,
  5. DEFAULT_VERSION,
  6. EVENT,
  7. FONT_FAMILY,
  8. MIME_TYPES,
  9. THEME,
  10. WINDOWS_EMOJI_FALLBACK_FONT,
  11. } from "./constants";
  12. import { FontFamilyValues, FontString } from "./element/types";
  13. import { AppState, DataURL, Zoom } from "./types";
  14. import { unstable_batchedUpdates } from "react-dom";
  15. import { isDarwin } from "./keys";
  16. let mockDateTime: string | null = null;
  17. export const setDateTimeForTests = (dateTime: string) => {
  18. mockDateTime = dateTime;
  19. };
  20. export const getDateTime = () => {
  21. if (mockDateTime) {
  22. return mockDateTime;
  23. }
  24. const date = new Date();
  25. const year = date.getFullYear();
  26. const month = `${date.getMonth() + 1}`.padStart(2, "0");
  27. const day = `${date.getDate()}`.padStart(2, "0");
  28. const hr = `${date.getHours()}`.padStart(2, "0");
  29. const min = `${date.getMinutes()}`.padStart(2, "0");
  30. return `${year}-${month}-${day}-${hr}${min}`;
  31. };
  32. export const capitalizeString = (str: string) =>
  33. str.charAt(0).toUpperCase() + str.slice(1);
  34. export const isToolIcon = (
  35. target: Element | EventTarget | null,
  36. ): target is HTMLElement =>
  37. target instanceof HTMLElement && target.className.includes("ToolIcon");
  38. export const isInputLike = (
  39. target: Element | EventTarget | null,
  40. ): target is
  41. | HTMLInputElement
  42. | HTMLTextAreaElement
  43. | HTMLSelectElement
  44. | HTMLBRElement
  45. | HTMLDivElement =>
  46. (target instanceof HTMLElement && target.dataset.type === "wysiwyg") ||
  47. target instanceof HTMLBRElement || // newline in wysiwyg
  48. target instanceof HTMLInputElement ||
  49. target instanceof HTMLTextAreaElement ||
  50. target instanceof HTMLSelectElement;
  51. export const isWritableElement = (
  52. target: Element | EventTarget | null,
  53. ): target is
  54. | HTMLInputElement
  55. | HTMLTextAreaElement
  56. | HTMLBRElement
  57. | HTMLDivElement =>
  58. (target instanceof HTMLElement && target.dataset.type === "wysiwyg") ||
  59. target instanceof HTMLBRElement || // newline in wysiwyg
  60. target instanceof HTMLTextAreaElement ||
  61. (target instanceof HTMLInputElement &&
  62. (target.type === "text" || target.type === "number"));
  63. export const getFontFamilyString = ({
  64. fontFamily,
  65. }: {
  66. fontFamily: FontFamilyValues;
  67. }) => {
  68. for (const [fontFamilyString, id] of Object.entries(FONT_FAMILY)) {
  69. if (id === fontFamily) {
  70. return `${fontFamilyString}, ${WINDOWS_EMOJI_FALLBACK_FONT}`;
  71. }
  72. }
  73. return WINDOWS_EMOJI_FALLBACK_FONT;
  74. };
  75. /** returns fontSize+fontFamily string for assignment to DOM elements */
  76. export const getFontString = ({
  77. fontSize,
  78. fontFamily,
  79. }: {
  80. fontSize: number;
  81. fontFamily: FontFamilyValues;
  82. }) => {
  83. return `${fontSize}px ${getFontFamilyString({ fontFamily })}` as FontString;
  84. };
  85. export const debounce = <T extends any[]>(
  86. fn: (...args: T) => void,
  87. timeout: number,
  88. ) => {
  89. let handle = 0;
  90. let lastArgs: T | null = null;
  91. const ret = (...args: T) => {
  92. lastArgs = args;
  93. clearTimeout(handle);
  94. handle = window.setTimeout(() => {
  95. lastArgs = null;
  96. fn(...args);
  97. }, timeout);
  98. };
  99. ret.flush = () => {
  100. clearTimeout(handle);
  101. if (lastArgs) {
  102. const _lastArgs = lastArgs;
  103. lastArgs = null;
  104. fn(..._lastArgs);
  105. }
  106. };
  107. ret.cancel = () => {
  108. lastArgs = null;
  109. clearTimeout(handle);
  110. };
  111. return ret;
  112. };
  113. // throttle callback to execute once per animation frame
  114. export const throttleRAF = <T extends any[]>(fn: (...args: T) => void) => {
  115. let handle: number | null = null;
  116. let lastArgs: T | null = null;
  117. let callback: ((...args: T) => void) | null = null;
  118. const ret = (...args: T) => {
  119. if (process.env.NODE_ENV === "test") {
  120. fn(...args);
  121. return;
  122. }
  123. lastArgs = args;
  124. callback = fn;
  125. if (handle === null) {
  126. handle = window.requestAnimationFrame(() => {
  127. handle = null;
  128. lastArgs = null;
  129. callback = null;
  130. fn(...args);
  131. });
  132. }
  133. };
  134. ret.flush = () => {
  135. if (handle !== null) {
  136. cancelAnimationFrame(handle);
  137. handle = null;
  138. }
  139. if (lastArgs) {
  140. const _lastArgs = lastArgs;
  141. const _callback = callback;
  142. lastArgs = null;
  143. callback = null;
  144. if (_callback !== null) {
  145. _callback(..._lastArgs);
  146. }
  147. }
  148. };
  149. ret.cancel = () => {
  150. lastArgs = null;
  151. callback = null;
  152. if (handle !== null) {
  153. cancelAnimationFrame(handle);
  154. handle = null;
  155. }
  156. };
  157. return ret;
  158. };
  159. // https://github.com/lodash/lodash/blob/es/chunk.js
  160. export const chunk = <T extends any>(
  161. array: readonly T[],
  162. size: number,
  163. ): T[][] => {
  164. if (!array.length || size < 1) {
  165. return [];
  166. }
  167. let index = 0;
  168. let resIndex = 0;
  169. const result = Array(Math.ceil(array.length / size));
  170. while (index < array.length) {
  171. result[resIndex++] = array.slice(index, (index += size));
  172. }
  173. return result;
  174. };
  175. export const selectNode = (node: Element) => {
  176. const selection = window.getSelection();
  177. if (selection) {
  178. const range = document.createRange();
  179. range.selectNodeContents(node);
  180. selection.removeAllRanges();
  181. selection.addRange(range);
  182. }
  183. };
  184. export const removeSelection = () => {
  185. const selection = window.getSelection();
  186. if (selection) {
  187. selection.removeAllRanges();
  188. }
  189. };
  190. export const distance = (x: number, y: number) => Math.abs(x - y);
  191. export const resetCursor = (canvas: HTMLCanvasElement | null) => {
  192. if (canvas) {
  193. canvas.style.cursor = "";
  194. }
  195. };
  196. export const setCursor = (canvas: HTMLCanvasElement | null, cursor: string) => {
  197. if (canvas) {
  198. canvas.style.cursor = cursor;
  199. }
  200. };
  201. let eraserCanvasCache: any;
  202. let previewDataURL: string;
  203. export const setEraserCursor = (
  204. canvas: HTMLCanvasElement | null,
  205. theme: AppState["theme"],
  206. ) => {
  207. const cursorImageSizePx = 20;
  208. const drawCanvas = () => {
  209. const isDarkTheme = theme === THEME.DARK;
  210. eraserCanvasCache = document.createElement("canvas");
  211. eraserCanvasCache.theme = theme;
  212. eraserCanvasCache.height = cursorImageSizePx;
  213. eraserCanvasCache.width = cursorImageSizePx;
  214. const context = eraserCanvasCache.getContext("2d")!;
  215. context.lineWidth = 1;
  216. context.beginPath();
  217. context.arc(
  218. eraserCanvasCache.width / 2,
  219. eraserCanvasCache.height / 2,
  220. 5,
  221. 0,
  222. 2 * Math.PI,
  223. );
  224. context.fillStyle = isDarkTheme ? oc.black : oc.white;
  225. context.fill();
  226. context.strokeStyle = isDarkTheme ? oc.white : oc.black;
  227. context.stroke();
  228. previewDataURL = eraserCanvasCache.toDataURL(MIME_TYPES.svg) as DataURL;
  229. };
  230. if (!eraserCanvasCache || eraserCanvasCache.theme !== theme) {
  231. drawCanvas();
  232. }
  233. setCursor(
  234. canvas,
  235. `url(${previewDataURL}) ${cursorImageSizePx / 2} ${
  236. cursorImageSizePx / 2
  237. }, auto`,
  238. );
  239. };
  240. export const setCursorForShape = (
  241. canvas: HTMLCanvasElement | null,
  242. appState: AppState,
  243. ) => {
  244. if (!canvas) {
  245. return;
  246. }
  247. if (appState.activeTool.type === "selection") {
  248. resetCursor(canvas);
  249. } else if (appState.activeTool.type === "eraser") {
  250. setEraserCursor(canvas, appState.theme);
  251. // do nothing if image tool is selected which suggests there's
  252. // a image-preview set as the cursor
  253. } else if (appState.activeTool.type !== "image") {
  254. canvas.style.cursor = CURSOR_TYPE.CROSSHAIR;
  255. }
  256. };
  257. export const isFullScreen = () =>
  258. document.fullscreenElement?.nodeName === "HTML";
  259. export const allowFullScreen = () =>
  260. document.documentElement.requestFullscreen();
  261. export const exitFullScreen = () => document.exitFullscreen();
  262. export const getShortcutKey = (shortcut: string): string => {
  263. shortcut = shortcut
  264. .replace(/\bAlt\b/i, "Alt")
  265. .replace(/\bShift\b/i, "Shift")
  266. .replace(/\b(Enter|Return)\b/i, "Enter")
  267. .replace(/\bDel\b/i, "Delete");
  268. if (isDarwin) {
  269. return shortcut
  270. .replace(/\bCtrlOrCmd\b/i, "Cmd")
  271. .replace(/\bAlt\b/i, "Option");
  272. }
  273. return shortcut.replace(/\bCtrlOrCmd\b/i, "Ctrl");
  274. };
  275. export const viewportCoordsToSceneCoords = (
  276. { clientX, clientY }: { clientX: number; clientY: number },
  277. {
  278. zoom,
  279. offsetLeft,
  280. offsetTop,
  281. scrollX,
  282. scrollY,
  283. }: {
  284. zoom: Zoom;
  285. offsetLeft: number;
  286. offsetTop: number;
  287. scrollX: number;
  288. scrollY: number;
  289. },
  290. ) => {
  291. const invScale = 1 / zoom.value;
  292. const x = (clientX - offsetLeft) * invScale - scrollX;
  293. const y = (clientY - offsetTop) * invScale - scrollY;
  294. return { x, y };
  295. };
  296. export const sceneCoordsToViewportCoords = (
  297. { sceneX, sceneY }: { sceneX: number; sceneY: number },
  298. {
  299. zoom,
  300. offsetLeft,
  301. offsetTop,
  302. scrollX,
  303. scrollY,
  304. }: {
  305. zoom: Zoom;
  306. offsetLeft: number;
  307. offsetTop: number;
  308. scrollX: number;
  309. scrollY: number;
  310. },
  311. ) => {
  312. const x = (sceneX + scrollX) * zoom.value + offsetLeft;
  313. const y = (sceneY + scrollY) * zoom.value + offsetTop;
  314. return { x, y };
  315. };
  316. export const getGlobalCSSVariable = (name: string) =>
  317. getComputedStyle(document.documentElement).getPropertyValue(`--${name}`);
  318. const RS_LTR_CHARS =
  319. "A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF" +
  320. "\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF";
  321. const RS_RTL_CHARS = "\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC";
  322. const RE_RTL_CHECK = new RegExp(`^[^${RS_LTR_CHARS}]*[${RS_RTL_CHARS}]`);
  323. /**
  324. * Checks whether first directional character is RTL. Meaning whether it starts
  325. * with RTL characters, or indeterminate (numbers etc.) characters followed by
  326. * RTL.
  327. * See https://github.com/excalidraw/excalidraw/pull/1722#discussion_r436340171
  328. */
  329. export const isRTL = (text: string) => RE_RTL_CHECK.test(text);
  330. export const tupleToCoors = (
  331. xyTuple: readonly [number, number],
  332. ): { x: number; y: number } => {
  333. const [x, y] = xyTuple;
  334. return { x, y };
  335. };
  336. /** use as a rejectionHandler to mute filesystem Abort errors */
  337. export const muteFSAbortError = (error?: Error) => {
  338. if (error?.name === "AbortError") {
  339. console.warn(error);
  340. return;
  341. }
  342. throw error;
  343. };
  344. export const findIndex = <T>(
  345. array: readonly T[],
  346. cb: (element: T, index: number, array: readonly T[]) => boolean,
  347. fromIndex: number = 0,
  348. ) => {
  349. if (fromIndex < 0) {
  350. fromIndex = array.length + fromIndex;
  351. }
  352. fromIndex = Math.min(array.length, Math.max(fromIndex, 0));
  353. let index = fromIndex - 1;
  354. while (++index < array.length) {
  355. if (cb(array[index], index, array)) {
  356. return index;
  357. }
  358. }
  359. return -1;
  360. };
  361. export const findLastIndex = <T>(
  362. array: readonly T[],
  363. cb: (element: T, index: number, array: readonly T[]) => boolean,
  364. fromIndex: number = array.length - 1,
  365. ) => {
  366. if (fromIndex < 0) {
  367. fromIndex = array.length + fromIndex;
  368. }
  369. fromIndex = Math.min(array.length - 1, Math.max(fromIndex, 0));
  370. let index = fromIndex + 1;
  371. while (--index > -1) {
  372. if (cb(array[index], index, array)) {
  373. return index;
  374. }
  375. }
  376. return -1;
  377. };
  378. export const isTransparent = (color: string) => {
  379. const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0";
  380. const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00";
  381. return (
  382. isRGBTransparent ||
  383. isRRGGBBTransparent ||
  384. color === colors.elementBackground[0]
  385. );
  386. };
  387. export type ResolvablePromise<T> = Promise<T> & {
  388. resolve: [T] extends [undefined] ? (value?: T) => void : (value: T) => void;
  389. reject: (error: Error) => void;
  390. };
  391. export const resolvablePromise = <T>() => {
  392. let resolve!: any;
  393. let reject!: any;
  394. const promise = new Promise((_resolve, _reject) => {
  395. resolve = _resolve;
  396. reject = _reject;
  397. });
  398. (promise as any).resolve = resolve;
  399. (promise as any).reject = reject;
  400. return promise as ResolvablePromise<T>;
  401. };
  402. /**
  403. * @param func handler taking at most single parameter (event).
  404. */
  405. export const withBatchedUpdates = <
  406. TFunction extends ((event: any) => void) | (() => void),
  407. >(
  408. func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
  409. ) =>
  410. ((event) => {
  411. unstable_batchedUpdates(func as TFunction, event);
  412. }) as TFunction;
  413. /**
  414. * barches React state updates and throttles the calls to a single call per
  415. * animation frame
  416. */
  417. export const withBatchedUpdatesThrottled = <
  418. TFunction extends ((event: any) => void) | (() => void),
  419. >(
  420. func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
  421. ) => {
  422. // @ts-ignore
  423. return throttleRAF<Parameters<TFunction>>(((event) => {
  424. unstable_batchedUpdates(func, event);
  425. }) as TFunction);
  426. };
  427. //https://stackoverflow.com/a/9462382/8418
  428. export const nFormatter = (num: number, digits: number): string => {
  429. const si = [
  430. { value: 1, symbol: "b" },
  431. { value: 1e3, symbol: "k" },
  432. { value: 1e6, symbol: "M" },
  433. { value: 1e9, symbol: "G" },
  434. ];
  435. const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
  436. let index;
  437. for (index = si.length - 1; index > 0; index--) {
  438. if (num >= si[index].value) {
  439. break;
  440. }
  441. }
  442. return (
  443. (num / si[index].value).toFixed(digits).replace(rx, "$1") + si[index].symbol
  444. );
  445. };
  446. export const getVersion = () => {
  447. return (
  448. document.querySelector<HTMLMetaElement>('meta[name="version"]')?.content ||
  449. DEFAULT_VERSION
  450. );
  451. };
  452. // Adapted from https://github.com/Modernizr/Modernizr/blob/master/feature-detects/emoji.js
  453. export const supportsEmoji = () => {
  454. const canvas = document.createElement("canvas");
  455. const ctx = canvas.getContext("2d");
  456. if (!ctx) {
  457. return false;
  458. }
  459. const offset = 12;
  460. ctx.fillStyle = "#f00";
  461. ctx.textBaseline = "top";
  462. ctx.font = "32px Arial";
  463. // Modernizr used 🐨, but it is sort of supported on Windows 7.
  464. // Luckily 😀 isn't supported.
  465. ctx.fillText("😀", 0, 0);
  466. return ctx.getImageData(offset, offset, 1, 1).data[0] !== 0;
  467. };
  468. export const getNearestScrollableContainer = (
  469. element: HTMLElement,
  470. ): HTMLElement | Document => {
  471. let parent = element.parentElement;
  472. while (parent) {
  473. if (parent === document.body) {
  474. return document;
  475. }
  476. const { overflowY } = window.getComputedStyle(parent);
  477. const hasScrollableContent = parent.scrollHeight > parent.clientHeight;
  478. if (
  479. hasScrollableContent &&
  480. (overflowY === "auto" ||
  481. overflowY === "scroll" ||
  482. overflowY === "overlay")
  483. ) {
  484. return parent;
  485. }
  486. parent = parent.parentElement;
  487. }
  488. return document;
  489. };
  490. export const focusNearestParent = (element: HTMLInputElement) => {
  491. let parent = element.parentElement;
  492. while (parent) {
  493. if (parent.tabIndex > -1) {
  494. parent.focus();
  495. return;
  496. }
  497. parent = parent.parentElement;
  498. }
  499. };
  500. export const preventUnload = (event: BeforeUnloadEvent) => {
  501. event.preventDefault();
  502. // NOTE: modern browsers no longer allow showing a custom message here
  503. event.returnValue = "";
  504. };
  505. export const bytesToHexString = (bytes: Uint8Array) => {
  506. return Array.from(bytes)
  507. .map((byte) => `0${byte.toString(16)}`.slice(-2))
  508. .join("");
  509. };
  510. export const getUpdatedTimestamp = () => (isTestEnv() ? 1 : Date.now());
  511. /**
  512. * Transforms array of objects containing `id` attribute,
  513. * or array of ids (strings), into a Map, keyd by `id`.
  514. */
  515. export const arrayToMap = <T extends { id: string } | string>(
  516. items: readonly T[],
  517. ) => {
  518. return items.reduce((acc: Map<string, T>, element) => {
  519. acc.set(typeof element === "string" ? element : element.id, element);
  520. return acc;
  521. }, new Map());
  522. };
  523. export const isTestEnv = () =>
  524. typeof process !== "undefined" && process.env?.NODE_ENV === "test";
  525. export const wrapEvent = <T extends Event>(name: EVENT, nativeEvent: T) => {
  526. return new CustomEvent(name, {
  527. detail: {
  528. nativeEvent,
  529. },
  530. cancelable: true,
  531. });
  532. };
  533. export const updateObject = <T extends Record<string, any>>(
  534. obj: T,
  535. updates: Partial<T>,
  536. ): T => {
  537. let didChange = false;
  538. for (const key in updates) {
  539. const value = (updates as any)[key];
  540. if (typeof value !== "undefined") {
  541. if (
  542. (obj as any)[key] === value &&
  543. // if object, always update because its attrs could have changed
  544. (typeof value !== "object" || value === null)
  545. ) {
  546. continue;
  547. }
  548. didChange = true;
  549. }
  550. }
  551. if (!didChange) {
  552. return obj;
  553. }
  554. return {
  555. ...obj,
  556. ...updates,
  557. };
  558. };
  559. export const isPrimitive = (val: any) => {
  560. const type = typeof val;
  561. return val == null || (type !== "object" && type !== "function");
  562. };
  563. export const getFrame = () => {
  564. try {
  565. return window.self === window.top ? "top" : "iframe";
  566. } catch (error) {
  567. return "iframe";
  568. }
  569. };
  570. export const isPromiseLike = (
  571. value: any,
  572. ): value is Promise<ResolutionType<typeof value>> => {
  573. return (
  574. !!value &&
  575. typeof value === "object" &&
  576. "then" in value &&
  577. "catch" in value &&
  578. "finally" in value
  579. );
  580. };