utils.ts 14 KB

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