library.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. import { loadLibraryFromBlob } from "./blob";
  2. import {
  3. LibraryItems,
  4. LibraryItem,
  5. ExcalidrawImperativeAPI,
  6. LibraryItemsSource,
  7. } from "../types";
  8. import { restoreLibraryItems } from "./restore";
  9. import type App from "../components/App";
  10. import { atom } from "jotai";
  11. import { jotaiStore } from "../jotai";
  12. import { ExcalidrawElement } from "../element/types";
  13. import { getCommonBoundingBox } from "../element/bounds";
  14. import { AbortError } from "../errors";
  15. import { t } from "../i18n";
  16. import { useEffect, useRef } from "react";
  17. import { URL_HASH_KEYS, URL_QUERY_KEYS, APP_NAME, EVENT } from "../constants";
  18. export const libraryItemsAtom = atom<{
  19. status: "loading" | "loaded";
  20. isInitialized: boolean;
  21. libraryItems: LibraryItems;
  22. }>({ status: "loaded", isInitialized: true, libraryItems: [] });
  23. const cloneLibraryItems = (libraryItems: LibraryItems): LibraryItems =>
  24. JSON.parse(JSON.stringify(libraryItems));
  25. /**
  26. * checks if library item does not exist already in current library
  27. */
  28. const isUniqueItem = (
  29. existingLibraryItems: LibraryItems,
  30. targetLibraryItem: LibraryItem,
  31. ) => {
  32. return !existingLibraryItems.find((libraryItem) => {
  33. if (libraryItem.elements.length !== targetLibraryItem.elements.length) {
  34. return false;
  35. }
  36. // detect z-index difference by checking the excalidraw elements
  37. // are in order
  38. return libraryItem.elements.every((libItemExcalidrawItem, idx) => {
  39. return (
  40. libItemExcalidrawItem.id === targetLibraryItem.elements[idx].id &&
  41. libItemExcalidrawItem.versionNonce ===
  42. targetLibraryItem.elements[idx].versionNonce
  43. );
  44. });
  45. });
  46. };
  47. /** Merges otherItems into localItems. Unique items in otherItems array are
  48. sorted first. */
  49. export const mergeLibraryItems = (
  50. localItems: LibraryItems,
  51. otherItems: LibraryItems,
  52. ): LibraryItems => {
  53. const newItems = [];
  54. for (const item of otherItems) {
  55. if (isUniqueItem(localItems, item)) {
  56. newItems.push(item);
  57. }
  58. }
  59. return [...newItems, ...localItems];
  60. };
  61. class Library {
  62. /** latest libraryItems */
  63. private lastLibraryItems: LibraryItems = [];
  64. /** indicates whether library is initialized with library items (has gone
  65. * though at least one update) */
  66. private isInitialized = false;
  67. private app: App;
  68. constructor(app: App) {
  69. this.app = app;
  70. }
  71. private updateQueue: Promise<LibraryItems>[] = [];
  72. private getLastUpdateTask = (): Promise<LibraryItems> | undefined => {
  73. return this.updateQueue[this.updateQueue.length - 1];
  74. };
  75. private notifyListeners = () => {
  76. if (this.updateQueue.length > 0) {
  77. jotaiStore.set(libraryItemsAtom, {
  78. status: "loading",
  79. libraryItems: this.lastLibraryItems,
  80. isInitialized: this.isInitialized,
  81. });
  82. } else {
  83. this.isInitialized = true;
  84. jotaiStore.set(libraryItemsAtom, {
  85. status: "loaded",
  86. libraryItems: this.lastLibraryItems,
  87. isInitialized: this.isInitialized,
  88. });
  89. try {
  90. this.app.props.onLibraryChange?.(
  91. cloneLibraryItems(this.lastLibraryItems),
  92. );
  93. } catch (error) {
  94. console.error(error);
  95. }
  96. }
  97. };
  98. resetLibrary = () => {
  99. return this.setLibrary([]);
  100. };
  101. /**
  102. * @returns latest cloned libraryItems. Awaits all in-progress updates first.
  103. */
  104. getLatestLibrary = (): Promise<LibraryItems> => {
  105. return new Promise(async (resolve) => {
  106. try {
  107. const libraryItems = await (this.getLastUpdateTask() ||
  108. this.lastLibraryItems);
  109. if (this.updateQueue.length > 0) {
  110. resolve(this.getLatestLibrary());
  111. } else {
  112. resolve(cloneLibraryItems(libraryItems));
  113. }
  114. } catch (error) {
  115. return resolve(this.lastLibraryItems);
  116. }
  117. });
  118. };
  119. // NOTE this is a high-level public API (exposed on ExcalidrawAPI) with
  120. // a slight overhead (always restoring library items). For internal use
  121. // where merging isn't needed, use `library.setLibrary()` directly.
  122. updateLibrary = async ({
  123. libraryItems,
  124. prompt = false,
  125. merge = false,
  126. openLibraryMenu = false,
  127. defaultStatus = "unpublished",
  128. }: {
  129. libraryItems: LibraryItemsSource;
  130. merge?: boolean;
  131. prompt?: boolean;
  132. openLibraryMenu?: boolean;
  133. defaultStatus?: "unpublished" | "published";
  134. }): Promise<LibraryItems> => {
  135. if (openLibraryMenu) {
  136. this.app.setState({ isLibraryOpen: true });
  137. }
  138. return this.setLibrary(() => {
  139. return new Promise<LibraryItems>(async (resolve, reject) => {
  140. try {
  141. const source = await (typeof libraryItems === "function"
  142. ? libraryItems(this.lastLibraryItems)
  143. : libraryItems);
  144. let nextItems;
  145. if (source instanceof Blob) {
  146. nextItems = await loadLibraryFromBlob(source, defaultStatus);
  147. } else {
  148. nextItems = restoreLibraryItems(source, defaultStatus);
  149. }
  150. if (
  151. !prompt ||
  152. window.confirm(
  153. t("alerts.confirmAddLibrary", {
  154. numShapes: nextItems.length,
  155. }),
  156. )
  157. ) {
  158. if (merge) {
  159. resolve(mergeLibraryItems(this.lastLibraryItems, nextItems));
  160. } else {
  161. resolve(nextItems);
  162. }
  163. } else {
  164. reject(new AbortError());
  165. }
  166. } catch (error: any) {
  167. reject(error);
  168. }
  169. });
  170. }).finally(() => {
  171. this.app.focusContainer();
  172. });
  173. };
  174. setLibrary = (
  175. /**
  176. * LibraryItems that will replace current items. Can be a function which
  177. * will be invoked after all previous tasks are resolved
  178. * (this is the prefered way to update the library to avoid race conditions,
  179. * but you'll want to manually merge the library items in the callback
  180. * - which is what we're doing in Library.importLibrary()).
  181. *
  182. * If supplied promise is rejected with AbortError, we swallow it and
  183. * do not update the library.
  184. */
  185. libraryItems:
  186. | LibraryItems
  187. | Promise<LibraryItems>
  188. | ((
  189. latestLibraryItems: LibraryItems,
  190. ) => LibraryItems | Promise<LibraryItems>),
  191. ): Promise<LibraryItems> => {
  192. const task = new Promise<LibraryItems>(async (resolve, reject) => {
  193. try {
  194. await this.getLastUpdateTask();
  195. if (typeof libraryItems === "function") {
  196. libraryItems = libraryItems(this.lastLibraryItems);
  197. }
  198. this.lastLibraryItems = cloneLibraryItems(await libraryItems);
  199. resolve(this.lastLibraryItems);
  200. } catch (error: any) {
  201. reject(error);
  202. }
  203. })
  204. .catch((error) => {
  205. if (error.name === "AbortError") {
  206. console.warn("Library update aborted by user");
  207. return this.lastLibraryItems;
  208. }
  209. throw error;
  210. })
  211. .finally(() => {
  212. this.updateQueue = this.updateQueue.filter((_task) => _task !== task);
  213. this.notifyListeners();
  214. });
  215. this.updateQueue.push(task);
  216. this.notifyListeners();
  217. return task;
  218. };
  219. }
  220. export default Library;
  221. export const distributeLibraryItemsOnSquareGrid = (
  222. libraryItems: LibraryItems,
  223. ) => {
  224. const PADDING = 50;
  225. const ITEMS_PER_ROW = Math.ceil(Math.sqrt(libraryItems.length));
  226. const resElements: ExcalidrawElement[] = [];
  227. const getMaxHeightPerRow = (row: number) => {
  228. const maxHeight = libraryItems
  229. .slice(row * ITEMS_PER_ROW, row * ITEMS_PER_ROW + ITEMS_PER_ROW)
  230. .reduce((acc, item) => {
  231. const { height } = getCommonBoundingBox(item.elements);
  232. return Math.max(acc, height);
  233. }, 0);
  234. return maxHeight;
  235. };
  236. const getMaxWidthPerCol = (targetCol: number) => {
  237. let index = 0;
  238. let currCol = 0;
  239. let maxWidth = 0;
  240. for (const item of libraryItems) {
  241. if (index % ITEMS_PER_ROW === 0) {
  242. currCol = 0;
  243. }
  244. if (currCol === targetCol) {
  245. const { width } = getCommonBoundingBox(item.elements);
  246. maxWidth = Math.max(maxWidth, width);
  247. }
  248. index++;
  249. currCol++;
  250. }
  251. return maxWidth;
  252. };
  253. let colOffsetX = 0;
  254. let rowOffsetY = 0;
  255. let maxHeightCurrRow = 0;
  256. let maxWidthCurrCol = 0;
  257. let index = 0;
  258. let col = 0;
  259. let row = 0;
  260. for (const item of libraryItems) {
  261. if (index && index % ITEMS_PER_ROW === 0) {
  262. rowOffsetY += maxHeightCurrRow + PADDING;
  263. colOffsetX = 0;
  264. col = 0;
  265. row++;
  266. }
  267. if (col === 0) {
  268. maxHeightCurrRow = getMaxHeightPerRow(row);
  269. }
  270. maxWidthCurrCol = getMaxWidthPerCol(col);
  271. const { minX, minY, width, height } = getCommonBoundingBox(item.elements);
  272. const offsetCenterX = (maxWidthCurrCol - width) / 2;
  273. const offsetCenterY = (maxHeightCurrRow - height) / 2;
  274. resElements.push(
  275. // eslint-disable-next-line no-loop-func
  276. ...item.elements.map((element) => ({
  277. ...element,
  278. x:
  279. element.x +
  280. // offset for column
  281. colOffsetX +
  282. // offset to center in given square grid
  283. offsetCenterX -
  284. // subtract minX so that given item starts at 0 coord
  285. minX,
  286. y:
  287. element.y +
  288. // offset for row
  289. rowOffsetY +
  290. // offset to center in given square grid
  291. offsetCenterY -
  292. // subtract minY so that given item starts at 0 coord
  293. minY,
  294. })),
  295. );
  296. colOffsetX += maxWidthCurrCol + PADDING;
  297. index++;
  298. col++;
  299. }
  300. return resElements;
  301. };
  302. export const parseLibraryTokensFromUrl = () => {
  303. const libraryUrl =
  304. // current
  305. new URLSearchParams(window.location.hash.slice(1)).get(
  306. URL_HASH_KEYS.addLibrary,
  307. ) ||
  308. // legacy, kept for compat reasons
  309. new URLSearchParams(window.location.search).get(URL_QUERY_KEYS.addLibrary);
  310. const idToken = libraryUrl
  311. ? new URLSearchParams(window.location.hash.slice(1)).get("token")
  312. : null;
  313. return libraryUrl ? { libraryUrl, idToken } : null;
  314. };
  315. export const useHandleLibrary = ({
  316. excalidrawAPI,
  317. getInitialLibraryItems,
  318. }: {
  319. excalidrawAPI: ExcalidrawImperativeAPI | null;
  320. getInitialLibraryItems?: () => LibraryItemsSource;
  321. }) => {
  322. const getInitialLibraryRef = useRef(getInitialLibraryItems);
  323. useEffect(() => {
  324. if (!excalidrawAPI) {
  325. return;
  326. }
  327. const importLibraryFromURL = async ({
  328. libraryUrl,
  329. idToken,
  330. }: {
  331. libraryUrl: string;
  332. idToken: string | null;
  333. }) => {
  334. const libraryPromise = new Promise<Blob>(async (resolve, reject) => {
  335. try {
  336. const request = await fetch(decodeURIComponent(libraryUrl));
  337. const blob = await request.blob();
  338. resolve(blob);
  339. } catch (error: any) {
  340. reject(error);
  341. }
  342. });
  343. const shouldPrompt = idToken !== excalidrawAPI.id;
  344. // wait for the tab to be focused before continuing in case we'll prompt
  345. // for confirmation
  346. await (shouldPrompt && document.hidden
  347. ? new Promise<void>((resolve) => {
  348. window.addEventListener("focus", () => resolve(), {
  349. once: true,
  350. });
  351. })
  352. : null);
  353. try {
  354. await excalidrawAPI.updateLibrary({
  355. libraryItems: libraryPromise,
  356. prompt: shouldPrompt,
  357. merge: true,
  358. defaultStatus: "published",
  359. openLibraryMenu: true,
  360. });
  361. } catch (error) {
  362. throw error;
  363. } finally {
  364. if (window.location.hash.includes(URL_HASH_KEYS.addLibrary)) {
  365. const hash = new URLSearchParams(window.location.hash.slice(1));
  366. hash.delete(URL_HASH_KEYS.addLibrary);
  367. window.history.replaceState({}, APP_NAME, `#${hash.toString()}`);
  368. } else if (window.location.search.includes(URL_QUERY_KEYS.addLibrary)) {
  369. const query = new URLSearchParams(window.location.search);
  370. query.delete(URL_QUERY_KEYS.addLibrary);
  371. window.history.replaceState({}, APP_NAME, `?${query.toString()}`);
  372. }
  373. }
  374. };
  375. const onHashChange = (event: HashChangeEvent) => {
  376. event.preventDefault();
  377. const libraryUrlTokens = parseLibraryTokensFromUrl();
  378. if (libraryUrlTokens) {
  379. event.stopImmediatePropagation();
  380. // If hash changed and it contains library url, import it and replace
  381. // the url to its previous state (important in case of collaboration
  382. // and similar).
  383. // Using history API won't trigger another hashchange.
  384. window.history.replaceState({}, "", event.oldURL);
  385. importLibraryFromURL(libraryUrlTokens);
  386. }
  387. };
  388. // -------------------------------------------------------------------------
  389. // ------ init load --------------------------------------------------------
  390. if (getInitialLibraryRef.current) {
  391. excalidrawAPI.updateLibrary({
  392. libraryItems: getInitialLibraryRef.current(),
  393. });
  394. }
  395. const libraryUrlTokens = parseLibraryTokensFromUrl();
  396. if (libraryUrlTokens) {
  397. importLibraryFromURL(libraryUrlTokens);
  398. }
  399. // --------------------------------------------------------- init load -----
  400. window.addEventListener(EVENT.HASHCHANGE, onHashChange);
  401. return () => {
  402. window.removeEventListener(EVENT.HASHCHANGE, onHashChange);
  403. };
  404. }, [excalidrawAPI]);
  405. };