utils.ts 12 KB

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