utils.ts 18 KB

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