utils.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 { FontFamily, FontString } from "./element/types";
  9. import { Zoom } from "./types";
  10. import { unstable_batchedUpdates } from "react-dom";
  11. import { isDarwin } from "./keys";
  12. export const SVG_NS = "http://www.w3.org/2000/svg";
  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: FontFamily;
  64. }) => {
  65. return `${FONT_FAMILY[fontFamily]}, ${WINDOWS_EMOJI_FALLBACK_FONT}`;
  66. };
  67. /** returns fontSize+fontFamily string for assignment to DOM elements */
  68. export const getFontString = ({
  69. fontSize,
  70. fontFamily,
  71. }: {
  72. fontSize: number;
  73. fontFamily: FontFamily;
  74. }) => {
  75. return `${fontSize}px ${getFontFamilyString({ fontFamily })}` as FontString;
  76. };
  77. // https://github.com/grassator/canvas-text-editor/blob/master/lib/FontMetrics.js
  78. export const measureText = (text: string, font: FontString) => {
  79. const line = document.createElement("div");
  80. const body = document.body;
  81. line.style.position = "absolute";
  82. line.style.whiteSpace = "pre";
  83. line.style.font = font;
  84. body.appendChild(line);
  85. line.innerText = text
  86. .split("\n")
  87. // replace empty lines with single space because leading/trailing empty
  88. // lines would be stripped from computation
  89. .map((x) => x || " ")
  90. .join("\n");
  91. const width = line.offsetWidth;
  92. const height = line.offsetHeight;
  93. // Now creating 1px sized item that will be aligned to baseline
  94. // to calculate baseline shift
  95. const span = document.createElement("span");
  96. span.style.display = "inline-block";
  97. span.style.overflow = "hidden";
  98. span.style.width = "1px";
  99. span.style.height = "1px";
  100. line.appendChild(span);
  101. // Baseline is important for positioning text on canvas
  102. const baseline = span.offsetTop + span.offsetHeight;
  103. document.body.removeChild(line);
  104. return { width, height, baseline };
  105. };
  106. export const debounce = <T extends any[]>(
  107. fn: (...args: T) => void,
  108. timeout: number,
  109. ) => {
  110. let handle = 0;
  111. let lastArgs: T;
  112. const ret = (...args: T) => {
  113. lastArgs = args;
  114. clearTimeout(handle);
  115. handle = window.setTimeout(() => fn(...args), timeout);
  116. };
  117. ret.flush = () => {
  118. clearTimeout(handle);
  119. if (lastArgs) {
  120. fn(...lastArgs);
  121. }
  122. };
  123. ret.cancel = () => {
  124. clearTimeout(handle);
  125. };
  126. return ret;
  127. };
  128. export const selectNode = (node: Element) => {
  129. const selection = window.getSelection();
  130. if (selection) {
  131. const range = document.createRange();
  132. range.selectNodeContents(node);
  133. selection.removeAllRanges();
  134. selection.addRange(range);
  135. }
  136. };
  137. export const removeSelection = () => {
  138. const selection = window.getSelection();
  139. if (selection) {
  140. selection.removeAllRanges();
  141. }
  142. };
  143. export const distance = (x: number, y: number) => Math.abs(x - y);
  144. export const resetCursor = () => {
  145. document.documentElement.style.cursor = "";
  146. };
  147. export const setCursorForShape = (shape: string) => {
  148. if (shape === "selection") {
  149. resetCursor();
  150. } else {
  151. document.documentElement.style.cursor = CURSOR_TYPE.CROSSHAIR;
  152. }
  153. };
  154. export const isFullScreen = () =>
  155. document.fullscreenElement?.nodeName === "HTML";
  156. export const allowFullScreen = () =>
  157. document.documentElement.requestFullscreen();
  158. export const exitFullScreen = () => document.exitFullscreen();
  159. export const getShortcutKey = (shortcut: string): string => {
  160. shortcut = shortcut
  161. .replace(/\bAlt\b/i, "Alt")
  162. .replace(/\bShift\b/i, "Shift")
  163. .replace(/\b(Enter|Return)\b/i, "Enter")
  164. .replace(/\bDel\b/i, "Delete");
  165. if (isDarwin) {
  166. return shortcut
  167. .replace(/\bCtrlOrCmd\b/i, "Cmd")
  168. .replace(/\bAlt\b/i, "Option");
  169. }
  170. return shortcut.replace(/\bCtrlOrCmd\b/i, "Ctrl");
  171. };
  172. export const viewportCoordsToSceneCoords = (
  173. { clientX, clientY }: { clientX: number; clientY: number },
  174. {
  175. zoom,
  176. offsetLeft,
  177. offsetTop,
  178. scrollX,
  179. scrollY,
  180. }: {
  181. zoom: Zoom;
  182. offsetLeft: number;
  183. offsetTop: number;
  184. scrollX: number;
  185. scrollY: number;
  186. },
  187. ) => {
  188. const invScale = 1 / zoom.value;
  189. const x = (clientX - zoom.translation.x - offsetLeft) * invScale - scrollX;
  190. const y = (clientY - zoom.translation.y - offsetTop) * invScale - scrollY;
  191. return { x, y };
  192. };
  193. export const sceneCoordsToViewportCoords = (
  194. { sceneX, sceneY }: { sceneX: number; sceneY: number },
  195. {
  196. zoom,
  197. offsetLeft,
  198. offsetTop,
  199. scrollX,
  200. scrollY,
  201. }: {
  202. zoom: Zoom;
  203. offsetLeft: number;
  204. offsetTop: number;
  205. scrollX: number;
  206. scrollY: number;
  207. },
  208. ) => {
  209. const x = (sceneX + scrollX + offsetLeft) * zoom.value + zoom.translation.x;
  210. const y = (sceneY + scrollY + offsetTop) * zoom.value + zoom.translation.y;
  211. return { x, y };
  212. };
  213. export const getGlobalCSSVariable = (name: string) =>
  214. getComputedStyle(document.documentElement).getPropertyValue(`--${name}`);
  215. const RS_LTR_CHARS =
  216. "A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF" +
  217. "\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF";
  218. const RS_RTL_CHARS = "\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC";
  219. const RE_RTL_CHECK = new RegExp(`^[^${RS_LTR_CHARS}]*[${RS_RTL_CHARS}]`);
  220. /**
  221. * Checks whether first directional character is RTL. Meaning whether it starts
  222. * with RTL characters, or indeterminate (numbers etc.) characters followed by
  223. * RTL.
  224. * See https://github.com/excalidraw/excalidraw/pull/1722#discussion_r436340171
  225. */
  226. export const isRTL = (text: string) => RE_RTL_CHECK.test(text);
  227. export const tupleToCoors = (
  228. xyTuple: readonly [number, number],
  229. ): { x: number; y: number } => {
  230. const [x, y] = xyTuple;
  231. return { x, y };
  232. };
  233. /** use as a rejectionHandler to mute filesystem Abort errors */
  234. export const muteFSAbortError = (error?: Error) => {
  235. if (error?.name === "AbortError") {
  236. return;
  237. }
  238. throw error;
  239. };
  240. export const findIndex = <T>(
  241. array: readonly T[],
  242. cb: (element: T, index: number, array: readonly T[]) => boolean,
  243. fromIndex: number = 0,
  244. ) => {
  245. if (fromIndex < 0) {
  246. fromIndex = array.length + fromIndex;
  247. }
  248. fromIndex = Math.min(array.length, Math.max(fromIndex, 0));
  249. let index = fromIndex - 1;
  250. while (++index < array.length) {
  251. if (cb(array[index], index, array)) {
  252. return index;
  253. }
  254. }
  255. return -1;
  256. };
  257. export const findLastIndex = <T>(
  258. array: readonly T[],
  259. cb: (element: T, index: number, array: readonly T[]) => boolean,
  260. fromIndex: number = array.length - 1,
  261. ) => {
  262. if (fromIndex < 0) {
  263. fromIndex = array.length + fromIndex;
  264. }
  265. fromIndex = Math.min(array.length - 1, Math.max(fromIndex, 0));
  266. let index = fromIndex + 1;
  267. while (--index > -1) {
  268. if (cb(array[index], index, array)) {
  269. return index;
  270. }
  271. }
  272. return -1;
  273. };
  274. export const isTransparent = (color: string) => {
  275. const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0";
  276. const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00";
  277. return (
  278. isRGBTransparent ||
  279. isRRGGBBTransparent ||
  280. color === colors.elementBackground[0]
  281. );
  282. };
  283. export type ResolvablePromise<T> = Promise<T> & {
  284. resolve: [T] extends [undefined] ? (value?: T) => void : (value: T) => void;
  285. reject: (error: Error) => void;
  286. };
  287. export const resolvablePromise = <T>() => {
  288. let resolve!: any;
  289. let reject!: any;
  290. const promise = new Promise((_resolve, _reject) => {
  291. resolve = _resolve;
  292. reject = _reject;
  293. });
  294. (promise as any).resolve = resolve;
  295. (promise as any).reject = reject;
  296. return promise as ResolvablePromise<T>;
  297. };
  298. /**
  299. * @param func handler taking at most single parameter (event).
  300. */
  301. export const withBatchedUpdates = <
  302. TFunction extends ((event: any) => void) | (() => void)
  303. >(
  304. func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
  305. ) =>
  306. ((event) => {
  307. unstable_batchedUpdates(func as TFunction, event);
  308. }) as TFunction;
  309. //https://stackoverflow.com/a/9462382/8418
  310. export const nFormatter = (num: number, digits: number): string => {
  311. const si = [
  312. { value: 1, symbol: "b" },
  313. { value: 1e3, symbol: "k" },
  314. { value: 1e6, symbol: "M" },
  315. { value: 1e9, symbol: "G" },
  316. ];
  317. const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
  318. let index;
  319. for (index = si.length - 1; index > 0; index--) {
  320. if (num >= si[index].value) {
  321. break;
  322. }
  323. }
  324. return (
  325. (num / si[index].value).toFixed(digits).replace(rx, "$1") + si[index].symbol
  326. );
  327. };
  328. export const getVersion = () => {
  329. return (
  330. document.querySelector<HTMLMetaElement>('meta[name="version"]')?.content ||
  331. DEFAULT_VERSION
  332. );
  333. };
  334. // Adapted from https://github.com/Modernizr/Modernizr/blob/master/feature-detects/emoji.js
  335. export const supportsEmoji = () => {
  336. const canvas = document.createElement("canvas");
  337. const ctx = canvas.getContext("2d");
  338. if (!ctx) {
  339. return false;
  340. }
  341. const offset = 12;
  342. ctx.fillStyle = "#f00";
  343. ctx.textBaseline = "top";
  344. ctx.font = "32px Arial";
  345. // Modernizr used 🐨, but it is sort of supported on Windows 7.
  346. // Luckily 😀 isn't supported.
  347. ctx.fillText("😀", 0, 0);
  348. return ctx.getImageData(offset, offset, 1, 1).data[0] !== 0;
  349. };