utils.ts 17 KB

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