utils.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. fn(...(lastArgs || []));
  120. };
  121. ret.cancel = () => {
  122. clearTimeout(handle);
  123. };
  124. return ret;
  125. };
  126. export const selectNode = (node: Element) => {
  127. const selection = window.getSelection();
  128. if (selection) {
  129. const range = document.createRange();
  130. range.selectNodeContents(node);
  131. selection.removeAllRanges();
  132. selection.addRange(range);
  133. }
  134. };
  135. export const removeSelection = () => {
  136. const selection = window.getSelection();
  137. if (selection) {
  138. selection.removeAllRanges();
  139. }
  140. };
  141. export const distance = (x: number, y: number) => Math.abs(x - y);
  142. export const resetCursor = (canvas: HTMLCanvasElement | null) => {
  143. if (canvas) {
  144. canvas.style.cursor = "";
  145. }
  146. };
  147. export const setCursor = (canvas: HTMLCanvasElement | null, cursor: string) => {
  148. if (canvas) {
  149. canvas.style.cursor = cursor;
  150. }
  151. };
  152. export const setCursorForShape = (
  153. canvas: HTMLCanvasElement | null,
  154. shape: string,
  155. ) => {
  156. if (!canvas) {
  157. return;
  158. }
  159. if (shape === "selection") {
  160. resetCursor(canvas);
  161. } else {
  162. canvas.style.cursor = CURSOR_TYPE.CROSSHAIR;
  163. }
  164. };
  165. export const isFullScreen = () =>
  166. document.fullscreenElement?.nodeName === "HTML";
  167. export const allowFullScreen = () =>
  168. document.documentElement.requestFullscreen();
  169. export const exitFullScreen = () => document.exitFullscreen();
  170. export const getShortcutKey = (shortcut: string): string => {
  171. shortcut = shortcut
  172. .replace(/\bAlt\b/i, "Alt")
  173. .replace(/\bShift\b/i, "Shift")
  174. .replace(/\b(Enter|Return)\b/i, "Enter")
  175. .replace(/\bDel\b/i, "Delete");
  176. if (isDarwin) {
  177. return shortcut
  178. .replace(/\bCtrlOrCmd\b/i, "Cmd")
  179. .replace(/\bAlt\b/i, "Option");
  180. }
  181. return shortcut.replace(/\bCtrlOrCmd\b/i, "Ctrl");
  182. };
  183. export const viewportCoordsToSceneCoords = (
  184. { clientX, clientY }: { clientX: number; clientY: number },
  185. {
  186. zoom,
  187. offsetLeft,
  188. offsetTop,
  189. scrollX,
  190. scrollY,
  191. }: {
  192. zoom: Zoom;
  193. offsetLeft: number;
  194. offsetTop: number;
  195. scrollX: number;
  196. scrollY: number;
  197. },
  198. ) => {
  199. const invScale = 1 / zoom.value;
  200. const x = (clientX - zoom.translation.x - offsetLeft) * invScale - scrollX;
  201. const y = (clientY - zoom.translation.y - offsetTop) * invScale - scrollY;
  202. return { x, y };
  203. };
  204. export const sceneCoordsToViewportCoords = (
  205. { sceneX, sceneY }: { sceneX: number; sceneY: number },
  206. {
  207. zoom,
  208. offsetLeft,
  209. offsetTop,
  210. scrollX,
  211. scrollY,
  212. }: {
  213. zoom: Zoom;
  214. offsetLeft: number;
  215. offsetTop: number;
  216. scrollX: number;
  217. scrollY: number;
  218. },
  219. ) => {
  220. const x = (sceneX + scrollX + offsetLeft) * zoom.value + zoom.translation.x;
  221. const y = (sceneY + scrollY + offsetTop) * zoom.value + zoom.translation.y;
  222. return { x, y };
  223. };
  224. export const getGlobalCSSVariable = (name: string) =>
  225. getComputedStyle(document.documentElement).getPropertyValue(`--${name}`);
  226. const RS_LTR_CHARS =
  227. "A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF" +
  228. "\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF";
  229. const RS_RTL_CHARS = "\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC";
  230. const RE_RTL_CHECK = new RegExp(`^[^${RS_LTR_CHARS}]*[${RS_RTL_CHARS}]`);
  231. /**
  232. * Checks whether first directional character is RTL. Meaning whether it starts
  233. * with RTL characters, or indeterminate (numbers etc.) characters followed by
  234. * RTL.
  235. * See https://github.com/excalidraw/excalidraw/pull/1722#discussion_r436340171
  236. */
  237. export const isRTL = (text: string) => RE_RTL_CHECK.test(text);
  238. export const tupleToCoors = (
  239. xyTuple: readonly [number, number],
  240. ): { x: number; y: number } => {
  241. const [x, y] = xyTuple;
  242. return { x, y };
  243. };
  244. /** use as a rejectionHandler to mute filesystem Abort errors */
  245. export const muteFSAbortError = (error?: Error) => {
  246. if (error?.name === "AbortError") {
  247. return;
  248. }
  249. throw error;
  250. };
  251. export const findIndex = <T>(
  252. array: readonly T[],
  253. cb: (element: T, index: number, array: readonly T[]) => boolean,
  254. fromIndex: number = 0,
  255. ) => {
  256. if (fromIndex < 0) {
  257. fromIndex = array.length + fromIndex;
  258. }
  259. fromIndex = Math.min(array.length, Math.max(fromIndex, 0));
  260. let index = fromIndex - 1;
  261. while (++index < array.length) {
  262. if (cb(array[index], index, array)) {
  263. return index;
  264. }
  265. }
  266. return -1;
  267. };
  268. export const findLastIndex = <T>(
  269. array: readonly T[],
  270. cb: (element: T, index: number, array: readonly T[]) => boolean,
  271. fromIndex: number = array.length - 1,
  272. ) => {
  273. if (fromIndex < 0) {
  274. fromIndex = array.length + fromIndex;
  275. }
  276. fromIndex = Math.min(array.length - 1, Math.max(fromIndex, 0));
  277. let index = fromIndex + 1;
  278. while (--index > -1) {
  279. if (cb(array[index], index, array)) {
  280. return index;
  281. }
  282. }
  283. return -1;
  284. };
  285. export const isTransparent = (color: string) => {
  286. const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0";
  287. const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00";
  288. return (
  289. isRGBTransparent ||
  290. isRRGGBBTransparent ||
  291. color === colors.elementBackground[0]
  292. );
  293. };
  294. export type ResolvablePromise<T> = Promise<T> & {
  295. resolve: [T] extends [undefined] ? (value?: T) => void : (value: T) => void;
  296. reject: (error: Error) => void;
  297. };
  298. export const resolvablePromise = <T>() => {
  299. let resolve!: any;
  300. let reject!: any;
  301. const promise = new Promise((_resolve, _reject) => {
  302. resolve = _resolve;
  303. reject = _reject;
  304. });
  305. (promise as any).resolve = resolve;
  306. (promise as any).reject = reject;
  307. return promise as ResolvablePromise<T>;
  308. };
  309. /**
  310. * @param func handler taking at most single parameter (event).
  311. */
  312. export const withBatchedUpdates = <
  313. TFunction extends ((event: any) => void) | (() => void)
  314. >(
  315. func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
  316. ) =>
  317. ((event) => {
  318. unstable_batchedUpdates(func as TFunction, event);
  319. }) as TFunction;
  320. //https://stackoverflow.com/a/9462382/8418
  321. export const nFormatter = (num: number, digits: number): string => {
  322. const si = [
  323. { value: 1, symbol: "b" },
  324. { value: 1e3, symbol: "k" },
  325. { value: 1e6, symbol: "M" },
  326. { value: 1e9, symbol: "G" },
  327. ];
  328. const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
  329. let index;
  330. for (index = si.length - 1; index > 0; index--) {
  331. if (num >= si[index].value) {
  332. break;
  333. }
  334. }
  335. return (
  336. (num / si[index].value).toFixed(digits).replace(rx, "$1") + si[index].symbol
  337. );
  338. };
  339. export const getVersion = () => {
  340. return (
  341. document.querySelector<HTMLMetaElement>('meta[name="version"]')?.content ||
  342. DEFAULT_VERSION
  343. );
  344. };
  345. // Adapted from https://github.com/Modernizr/Modernizr/blob/master/feature-detects/emoji.js
  346. export const supportsEmoji = () => {
  347. const canvas = document.createElement("canvas");
  348. const ctx = canvas.getContext("2d");
  349. if (!ctx) {
  350. return false;
  351. }
  352. const offset = 12;
  353. ctx.fillStyle = "#f00";
  354. ctx.textBaseline = "top";
  355. ctx.font = "32px Arial";
  356. // Modernizr used 🐨, but it is sort of supported on Windows 7.
  357. // Luckily 😀 isn't supported.
  358. ctx.fillText("😀", 0, 0);
  359. return ctx.getImageData(offset, offset, 1, 1).data[0] !== 0;
  360. };