utils.ts 11 KB

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