LayerUI.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. import clsx from "clsx";
  2. import React, {
  3. RefObject,
  4. useCallback,
  5. useEffect,
  6. useRef,
  7. useState,
  8. } from "react";
  9. import { ActionManager } from "../actions/manager";
  10. import { CLASSES } from "../constants";
  11. import { exportCanvas } from "../data";
  12. import { importLibraryFromJSON, saveLibraryAsJSON } from "../data/json";
  13. import { isTextElement, showSelectedShapeActions } from "../element";
  14. import { NonDeletedExcalidrawElement } from "../element/types";
  15. import { Language, t } from "../i18n";
  16. import { useIsMobile } from "../components/App";
  17. import { calculateScrollCenter, getSelectedElements } from "../scene";
  18. import { ExportType } from "../scene/types";
  19. import {
  20. AppProps,
  21. AppState,
  22. ExcalidrawProps,
  23. LibraryItem,
  24. LibraryItems,
  25. } from "../types";
  26. import { muteFSAbortError } from "../utils";
  27. import { SelectedShapeActions, ShapesSwitcher, ZoomActions } from "./Actions";
  28. import { BackgroundPickerAndDarkModeToggle } from "./BackgroundPickerAndDarkModeToggle";
  29. import CollabButton from "./CollabButton";
  30. import { ErrorDialog } from "./ErrorDialog";
  31. import { ExportCB, ImageExportDialog } from "./ImageExportDialog";
  32. import { FixedSideContainer } from "./FixedSideContainer";
  33. import { HintViewer } from "./HintViewer";
  34. import { exportFile, load, trash } from "./icons";
  35. import { Island } from "./Island";
  36. import "./LayerUI.scss";
  37. import { LibraryUnit } from "./LibraryUnit";
  38. import { LoadingMessage } from "./LoadingMessage";
  39. import { LockButton } from "./LockButton";
  40. import { MobileMenu } from "./MobileMenu";
  41. import { PasteChartDialog } from "./PasteChartDialog";
  42. import { Section } from "./Section";
  43. import { HelpDialog } from "./HelpDialog";
  44. import Stack from "./Stack";
  45. import { ToolButton } from "./ToolButton";
  46. import { Tooltip } from "./Tooltip";
  47. import { UserList } from "./UserList";
  48. import Library from "../data/library";
  49. import { JSONExportDialog } from "./JSONExportDialog";
  50. import { LibraryButton } from "./LibraryButton";
  51. import { isImageFileHandle } from "../data/blob";
  52. interface LayerUIProps {
  53. actionManager: ActionManager;
  54. appState: AppState;
  55. canvas: HTMLCanvasElement | null;
  56. setAppState: React.Component<any, AppState>["setState"];
  57. elements: readonly NonDeletedExcalidrawElement[];
  58. onCollabButtonClick?: () => void;
  59. onLockToggle: () => void;
  60. onInsertElements: (elements: readonly NonDeletedExcalidrawElement[]) => void;
  61. zenModeEnabled: boolean;
  62. showExitZenModeBtn: boolean;
  63. showThemeBtn: boolean;
  64. toggleZenMode: () => void;
  65. langCode: Language["code"];
  66. isCollaborating: boolean;
  67. renderTopRightUI?: (isMobile: boolean, appState: AppState) => JSX.Element;
  68. renderCustomFooter?: (isMobile: boolean, appState: AppState) => JSX.Element;
  69. viewModeEnabled: boolean;
  70. libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
  71. UIOptions: AppProps["UIOptions"];
  72. focusContainer: () => void;
  73. library: Library;
  74. id: string;
  75. }
  76. const useOnClickOutside = (
  77. ref: RefObject<HTMLElement>,
  78. cb: (event: MouseEvent) => void,
  79. ) => {
  80. useEffect(() => {
  81. const listener = (event: MouseEvent) => {
  82. if (!ref.current) {
  83. return;
  84. }
  85. if (
  86. event.target instanceof Element &&
  87. (ref.current.contains(event.target) ||
  88. !document.body.contains(event.target))
  89. ) {
  90. return;
  91. }
  92. cb(event);
  93. };
  94. document.addEventListener("pointerdown", listener, false);
  95. return () => {
  96. document.removeEventListener("pointerdown", listener);
  97. };
  98. }, [ref, cb]);
  99. };
  100. const LibraryMenuItems = ({
  101. libraryItems,
  102. onRemoveFromLibrary,
  103. onAddToLibrary,
  104. onInsertShape,
  105. pendingElements,
  106. theme,
  107. setAppState,
  108. setLibraryItems,
  109. libraryReturnUrl,
  110. focusContainer,
  111. library,
  112. id,
  113. }: {
  114. libraryItems: LibraryItems;
  115. pendingElements: LibraryItem;
  116. onRemoveFromLibrary: (index: number) => void;
  117. onInsertShape: (elements: LibraryItem) => void;
  118. onAddToLibrary: (elements: LibraryItem) => void;
  119. theme: AppState["theme"];
  120. setAppState: React.Component<any, AppState>["setState"];
  121. setLibraryItems: (library: LibraryItems) => void;
  122. libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
  123. focusContainer: () => void;
  124. library: Library;
  125. id: string;
  126. }) => {
  127. const isMobile = useIsMobile();
  128. const numCells = libraryItems.length + (pendingElements.length > 0 ? 1 : 0);
  129. const CELLS_PER_ROW = isMobile ? 4 : 6;
  130. const numRows = Math.max(1, Math.ceil(numCells / CELLS_PER_ROW));
  131. const rows = [];
  132. let addedPendingElements = false;
  133. const referrer =
  134. libraryReturnUrl || window.location.origin + window.location.pathname;
  135. rows.push(
  136. <div className="layer-ui__library-header" key="library-header">
  137. <ToolButton
  138. key="import"
  139. type="button"
  140. title={t("buttons.load")}
  141. aria-label={t("buttons.load")}
  142. icon={load}
  143. onClick={() => {
  144. importLibraryFromJSON(library)
  145. .then(() => {
  146. // Close and then open to get the libraries updated
  147. setAppState({ isLibraryOpen: false });
  148. setAppState({ isLibraryOpen: true });
  149. })
  150. .catch(muteFSAbortError)
  151. .catch((error) => {
  152. setAppState({ errorMessage: error.message });
  153. });
  154. }}
  155. />
  156. {!!libraryItems.length && (
  157. <>
  158. <ToolButton
  159. key="export"
  160. type="button"
  161. title={t("buttons.export")}
  162. aria-label={t("buttons.export")}
  163. icon={exportFile}
  164. onClick={() => {
  165. saveLibraryAsJSON(library)
  166. .catch(muteFSAbortError)
  167. .catch((error) => {
  168. setAppState({ errorMessage: error.message });
  169. });
  170. }}
  171. />
  172. <ToolButton
  173. key="reset"
  174. type="button"
  175. title={t("buttons.resetLibrary")}
  176. aria-label={t("buttons.resetLibrary")}
  177. icon={trash}
  178. onClick={() => {
  179. if (window.confirm(t("alerts.resetLibrary"))) {
  180. library.resetLibrary();
  181. setLibraryItems([]);
  182. focusContainer();
  183. }
  184. }}
  185. />
  186. </>
  187. )}
  188. <a
  189. href={`https://libraries.excalidraw.com?target=${
  190. window.name || "_blank"
  191. }&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}`}
  192. target="_excalidraw_libraries"
  193. >
  194. {t("labels.libraries")}
  195. </a>
  196. </div>,
  197. );
  198. for (let row = 0; row < numRows; row++) {
  199. const y = CELLS_PER_ROW * row;
  200. const children = [];
  201. for (let x = 0; x < CELLS_PER_ROW; x++) {
  202. const shouldAddPendingElements: boolean =
  203. pendingElements.length > 0 &&
  204. !addedPendingElements &&
  205. y + x >= libraryItems.length;
  206. addedPendingElements = addedPendingElements || shouldAddPendingElements;
  207. children.push(
  208. <Stack.Col key={x}>
  209. <LibraryUnit
  210. elements={libraryItems[y + x]}
  211. pendingElements={
  212. shouldAddPendingElements ? pendingElements : undefined
  213. }
  214. onRemoveFromLibrary={onRemoveFromLibrary.bind(null, y + x)}
  215. onClick={
  216. shouldAddPendingElements
  217. ? onAddToLibrary.bind(null, pendingElements)
  218. : onInsertShape.bind(null, libraryItems[y + x])
  219. }
  220. />
  221. </Stack.Col>,
  222. );
  223. }
  224. rows.push(
  225. <Stack.Row align="center" gap={1} key={row}>
  226. {children}
  227. </Stack.Row>,
  228. );
  229. }
  230. return (
  231. <Stack.Col align="start" gap={1} className="layer-ui__library-items">
  232. {rows}
  233. </Stack.Col>
  234. );
  235. };
  236. const LibraryMenu = ({
  237. onClickOutside,
  238. onInsertShape,
  239. pendingElements,
  240. onAddToLibrary,
  241. theme,
  242. setAppState,
  243. libraryReturnUrl,
  244. focusContainer,
  245. library,
  246. id,
  247. }: {
  248. pendingElements: LibraryItem;
  249. onClickOutside: (event: MouseEvent) => void;
  250. onInsertShape: (elements: LibraryItem) => void;
  251. onAddToLibrary: () => void;
  252. theme: AppState["theme"];
  253. setAppState: React.Component<any, AppState>["setState"];
  254. libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
  255. focusContainer: () => void;
  256. library: Library;
  257. id: string;
  258. }) => {
  259. const ref = useRef<HTMLDivElement | null>(null);
  260. useOnClickOutside(ref, (event) => {
  261. // If click on the library icon, do nothing.
  262. if ((event.target as Element).closest(".ToolIcon_type_button__library")) {
  263. return;
  264. }
  265. onClickOutside(event);
  266. });
  267. const [libraryItems, setLibraryItems] = useState<LibraryItems>([]);
  268. const [loadingState, setIsLoading] = useState<
  269. "preloading" | "loading" | "ready"
  270. >("preloading");
  271. const loadingTimerRef = useRef<NodeJS.Timeout | null>(null);
  272. useEffect(() => {
  273. Promise.race([
  274. new Promise((resolve) => {
  275. loadingTimerRef.current = setTimeout(() => {
  276. resolve("loading");
  277. }, 100);
  278. }),
  279. library.loadLibrary().then((items) => {
  280. setLibraryItems(items);
  281. setIsLoading("ready");
  282. }),
  283. ]).then((data) => {
  284. if (data === "loading") {
  285. setIsLoading("loading");
  286. }
  287. });
  288. return () => {
  289. clearTimeout(loadingTimerRef.current!);
  290. };
  291. }, [library]);
  292. const removeFromLibrary = useCallback(
  293. async (indexToRemove) => {
  294. const items = await library.loadLibrary();
  295. const nextItems = items.filter((_, index) => index !== indexToRemove);
  296. library.saveLibrary(nextItems).catch((error) => {
  297. setLibraryItems(items);
  298. setAppState({ errorMessage: t("alerts.errorRemovingFromLibrary") });
  299. });
  300. setLibraryItems(nextItems);
  301. },
  302. [library, setAppState],
  303. );
  304. const addToLibrary = useCallback(
  305. async (elements: LibraryItem) => {
  306. const items = await library.loadLibrary();
  307. const nextItems = [...items, elements];
  308. onAddToLibrary();
  309. library.saveLibrary(nextItems).catch((error) => {
  310. setLibraryItems(items);
  311. setAppState({ errorMessage: t("alerts.errorAddingToLibrary") });
  312. });
  313. setLibraryItems(nextItems);
  314. },
  315. [onAddToLibrary, library, setAppState],
  316. );
  317. return loadingState === "preloading" ? null : (
  318. <Island padding={1} ref={ref} className="layer-ui__library">
  319. {loadingState === "loading" ? (
  320. <div className="layer-ui__library-message">
  321. {t("labels.libraryLoadingMessage")}
  322. </div>
  323. ) : (
  324. <LibraryMenuItems
  325. libraryItems={libraryItems}
  326. onRemoveFromLibrary={removeFromLibrary}
  327. onAddToLibrary={addToLibrary}
  328. onInsertShape={onInsertShape}
  329. pendingElements={pendingElements}
  330. setAppState={setAppState}
  331. setLibraryItems={setLibraryItems}
  332. libraryReturnUrl={libraryReturnUrl}
  333. focusContainer={focusContainer}
  334. library={library}
  335. theme={theme}
  336. id={id}
  337. />
  338. )}
  339. </Island>
  340. );
  341. };
  342. const LayerUI = ({
  343. actionManager,
  344. appState,
  345. setAppState,
  346. canvas,
  347. elements,
  348. onCollabButtonClick,
  349. onLockToggle,
  350. onInsertElements,
  351. zenModeEnabled,
  352. showExitZenModeBtn,
  353. showThemeBtn,
  354. toggleZenMode,
  355. isCollaborating,
  356. renderTopRightUI,
  357. renderCustomFooter,
  358. viewModeEnabled,
  359. libraryReturnUrl,
  360. UIOptions,
  361. focusContainer,
  362. library,
  363. id,
  364. }: LayerUIProps) => {
  365. const isMobile = useIsMobile();
  366. const renderJSONExportDialog = () => {
  367. if (!UIOptions.canvasActions.export) {
  368. return null;
  369. }
  370. return (
  371. <JSONExportDialog
  372. elements={elements}
  373. appState={appState}
  374. actionManager={actionManager}
  375. exportOpts={UIOptions.canvasActions.export}
  376. canvas={canvas}
  377. />
  378. );
  379. };
  380. const renderImageExportDialog = () => {
  381. if (!UIOptions.canvasActions.saveAsImage) {
  382. return null;
  383. }
  384. const createExporter = (type: ExportType): ExportCB => async (
  385. exportedElements,
  386. ) => {
  387. const fileHandle = await exportCanvas(type, exportedElements, appState, {
  388. exportBackground: appState.exportBackground,
  389. name: appState.name,
  390. viewBackgroundColor: appState.viewBackgroundColor,
  391. })
  392. .catch(muteFSAbortError)
  393. .catch((error) => {
  394. console.error(error);
  395. setAppState({ errorMessage: error.message });
  396. });
  397. if (
  398. appState.exportEmbedScene &&
  399. fileHandle &&
  400. isImageFileHandle(fileHandle)
  401. ) {
  402. setAppState({ fileHandle });
  403. }
  404. };
  405. return (
  406. <ImageExportDialog
  407. elements={elements}
  408. appState={appState}
  409. actionManager={actionManager}
  410. onExportToPng={createExporter("png")}
  411. onExportToSvg={createExporter("svg")}
  412. onExportToClipboard={createExporter("clipboard")}
  413. />
  414. );
  415. };
  416. const Separator = () => {
  417. return <div style={{ width: ".625em" }} />;
  418. };
  419. const renderViewModeCanvasActions = () => {
  420. return (
  421. <Section
  422. heading="canvasActions"
  423. className={clsx("zen-mode-transition", {
  424. "transition-left": zenModeEnabled,
  425. })}
  426. >
  427. {/* the zIndex ensures this menu has higher stacking order,
  428. see https://github.com/excalidraw/excalidraw/pull/1445 */}
  429. <Island padding={2} style={{ zIndex: 1 }}>
  430. <Stack.Col gap={4}>
  431. <Stack.Row gap={1} justifyContent="space-between">
  432. {renderJSONExportDialog()}
  433. {renderImageExportDialog()}
  434. </Stack.Row>
  435. </Stack.Col>
  436. </Island>
  437. </Section>
  438. );
  439. };
  440. const renderCanvasActions = () => (
  441. <Section
  442. heading="canvasActions"
  443. className={clsx("zen-mode-transition", {
  444. "transition-left": zenModeEnabled,
  445. })}
  446. >
  447. {/* the zIndex ensures this menu has higher stacking order,
  448. see https://github.com/excalidraw/excalidraw/pull/1445 */}
  449. <Island padding={2} style={{ zIndex: 1 }}>
  450. <Stack.Col gap={4}>
  451. <Stack.Row gap={1} justifyContent="space-between">
  452. {actionManager.renderAction("clearCanvas")}
  453. <Separator />
  454. {actionManager.renderAction("loadScene")}
  455. {renderJSONExportDialog()}
  456. {renderImageExportDialog()}
  457. <Separator />
  458. {onCollabButtonClick && (
  459. <CollabButton
  460. isCollaborating={isCollaborating}
  461. collaboratorCount={appState.collaborators.size}
  462. onClick={onCollabButtonClick}
  463. />
  464. )}
  465. </Stack.Row>
  466. <BackgroundPickerAndDarkModeToggle
  467. actionManager={actionManager}
  468. appState={appState}
  469. setAppState={setAppState}
  470. showThemeBtn={showThemeBtn}
  471. />
  472. {appState.fileHandle && (
  473. <>{actionManager.renderAction("saveToActiveFile")}</>
  474. )}
  475. </Stack.Col>
  476. </Island>
  477. </Section>
  478. );
  479. const renderSelectedShapeActions = () => (
  480. <Section
  481. heading="selectedShapeActions"
  482. className={clsx("zen-mode-transition", {
  483. "transition-left": zenModeEnabled,
  484. })}
  485. >
  486. <Island
  487. className={CLASSES.SHAPE_ACTIONS_MENU}
  488. padding={2}
  489. style={{
  490. // we want to make sure this doesn't overflow so substracting 200
  491. // which is approximately height of zoom footer and top left menu items with some buffer
  492. // if active file name is displayed, subtracting 248 to account for its height
  493. maxHeight: `${appState.height - (appState.fileHandle ? 248 : 200)}px`,
  494. }}
  495. >
  496. <SelectedShapeActions
  497. appState={appState}
  498. elements={elements}
  499. renderAction={actionManager.renderAction}
  500. elementType={appState.elementType}
  501. />
  502. </Island>
  503. </Section>
  504. );
  505. const closeLibrary = useCallback(
  506. (event) => {
  507. setAppState({ isLibraryOpen: false });
  508. },
  509. [setAppState],
  510. );
  511. const deselectItems = useCallback(() => {
  512. setAppState({
  513. selectedElementIds: {},
  514. selectedGroupIds: {},
  515. });
  516. }, [setAppState]);
  517. const libraryMenu = appState.isLibraryOpen ? (
  518. <LibraryMenu
  519. pendingElements={getSelectedElements(elements, appState)}
  520. onClickOutside={closeLibrary}
  521. onInsertShape={onInsertElements}
  522. onAddToLibrary={deselectItems}
  523. setAppState={setAppState}
  524. libraryReturnUrl={libraryReturnUrl}
  525. focusContainer={focusContainer}
  526. library={library}
  527. theme={appState.theme}
  528. id={id}
  529. />
  530. ) : null;
  531. const renderFixedSideContainer = () => {
  532. const shouldRenderSelectedShapeActions = showSelectedShapeActions(
  533. appState,
  534. elements,
  535. );
  536. return (
  537. <FixedSideContainer side="top">
  538. <div className="App-menu App-menu_top">
  539. <Stack.Col
  540. gap={4}
  541. className={clsx({ "disable-pointerEvents": zenModeEnabled })}
  542. >
  543. {viewModeEnabled
  544. ? renderViewModeCanvasActions()
  545. : renderCanvasActions()}
  546. {shouldRenderSelectedShapeActions && renderSelectedShapeActions()}
  547. </Stack.Col>
  548. {!viewModeEnabled && (
  549. <Section heading="shapes">
  550. {(heading) => (
  551. <Stack.Col gap={4} align="start">
  552. <Stack.Row gap={1}>
  553. <LockButton
  554. zenModeEnabled={zenModeEnabled}
  555. checked={appState.elementLocked}
  556. onChange={onLockToggle}
  557. title={t("toolBar.lock")}
  558. />
  559. <Island
  560. padding={1}
  561. className={clsx({ "zen-mode": zenModeEnabled })}
  562. >
  563. <HintViewer appState={appState} elements={elements} />
  564. {heading}
  565. <Stack.Row gap={1}>
  566. <ShapesSwitcher
  567. canvas={canvas}
  568. elementType={appState.elementType}
  569. setAppState={setAppState}
  570. />
  571. </Stack.Row>
  572. </Island>
  573. <LibraryButton
  574. appState={appState}
  575. setAppState={setAppState}
  576. />
  577. </Stack.Row>
  578. {libraryMenu}
  579. </Stack.Col>
  580. )}
  581. </Section>
  582. )}
  583. <div
  584. className={clsx(
  585. "layer-ui__wrapper__top-right zen-mode-transition",
  586. {
  587. "transition-right": zenModeEnabled,
  588. },
  589. )}
  590. >
  591. <UserList>
  592. {appState.collaborators.size > 0 &&
  593. Array.from(appState.collaborators)
  594. // Collaborator is either not initialized or is actually the current user.
  595. .filter(([_, client]) => Object.keys(client).length !== 0)
  596. .map(([clientId, client]) => (
  597. <Tooltip
  598. label={client.username || "Unknown user"}
  599. key={clientId}
  600. >
  601. {actionManager.renderAction("goToCollaborator", {
  602. id: clientId,
  603. })}
  604. </Tooltip>
  605. ))}
  606. </UserList>
  607. {renderTopRightUI?.(isMobile, appState)}
  608. </div>
  609. </div>
  610. </FixedSideContainer>
  611. );
  612. };
  613. const renderBottomAppMenu = () => {
  614. return (
  615. <footer
  616. role="contentinfo"
  617. className="layer-ui__wrapper__footer App-menu App-menu_bottom"
  618. >
  619. <div
  620. className={clsx(
  621. "layer-ui__wrapper__footer-left zen-mode-transition",
  622. {
  623. "layer-ui__wrapper__footer-left--transition-left": zenModeEnabled,
  624. },
  625. )}
  626. >
  627. <Stack.Col gap={2}>
  628. <Section heading="canvasActions">
  629. <Island padding={1}>
  630. <ZoomActions
  631. renderAction={actionManager.renderAction}
  632. zoom={appState.zoom}
  633. />
  634. </Island>
  635. {!viewModeEnabled && (
  636. <div
  637. className={clsx("undo-redo-buttons zen-mode-transition", {
  638. "layer-ui__wrapper__footer-left--transition-bottom": zenModeEnabled,
  639. })}
  640. >
  641. {actionManager.renderAction("undo", { size: "small" })}
  642. {actionManager.renderAction("redo", { size: "small" })}
  643. </div>
  644. )}
  645. </Section>
  646. </Stack.Col>
  647. </div>
  648. <div
  649. className={clsx(
  650. "layer-ui__wrapper__footer-center zen-mode-transition",
  651. {
  652. "layer-ui__wrapper__footer-left--transition-bottom": zenModeEnabled,
  653. },
  654. )}
  655. >
  656. {renderCustomFooter?.(false, appState)}
  657. </div>
  658. <div
  659. className={clsx(
  660. "layer-ui__wrapper__footer-right zen-mode-transition",
  661. {
  662. "transition-right disable-pointerEvents": zenModeEnabled,
  663. },
  664. )}
  665. >
  666. {actionManager.renderAction("toggleShortcuts")}
  667. </div>
  668. <button
  669. className={clsx("disable-zen-mode", {
  670. "disable-zen-mode--visible": showExitZenModeBtn,
  671. })}
  672. onClick={toggleZenMode}
  673. >
  674. {t("buttons.exitZenMode")}
  675. </button>
  676. </footer>
  677. );
  678. };
  679. const dialogs = (
  680. <>
  681. {appState.isLoading && <LoadingMessage />}
  682. {appState.errorMessage && (
  683. <ErrorDialog
  684. message={appState.errorMessage}
  685. onClose={() => setAppState({ errorMessage: null })}
  686. />
  687. )}
  688. {appState.showHelpDialog && (
  689. <HelpDialog
  690. onClose={() => {
  691. setAppState({ showHelpDialog: false });
  692. }}
  693. />
  694. )}
  695. {appState.pasteDialog.shown && (
  696. <PasteChartDialog
  697. setAppState={setAppState}
  698. appState={appState}
  699. onInsertChart={onInsertElements}
  700. onClose={() =>
  701. setAppState({
  702. pasteDialog: { shown: false, data: null },
  703. })
  704. }
  705. />
  706. )}
  707. </>
  708. );
  709. return isMobile ? (
  710. <>
  711. {dialogs}
  712. <MobileMenu
  713. appState={appState}
  714. elements={elements}
  715. actionManager={actionManager}
  716. libraryMenu={libraryMenu}
  717. renderJSONExportDialog={renderJSONExportDialog}
  718. renderImageExportDialog={renderImageExportDialog}
  719. setAppState={setAppState}
  720. onCollabButtonClick={onCollabButtonClick}
  721. onLockToggle={onLockToggle}
  722. canvas={canvas}
  723. isCollaborating={isCollaborating}
  724. renderCustomFooter={renderCustomFooter}
  725. viewModeEnabled={viewModeEnabled}
  726. showThemeBtn={showThemeBtn}
  727. />
  728. </>
  729. ) : (
  730. <div
  731. className={clsx("layer-ui__wrapper", {
  732. "disable-pointerEvents":
  733. appState.draggingElement ||
  734. appState.resizingElement ||
  735. (appState.editingElement && !isTextElement(appState.editingElement)),
  736. })}
  737. >
  738. {dialogs}
  739. {renderFixedSideContainer()}
  740. {renderBottomAppMenu()}
  741. {appState.scrolledOutside && (
  742. <button
  743. className="scroll-back-to-content"
  744. onClick={() => {
  745. setAppState({
  746. ...calculateScrollCenter(elements, appState, canvas),
  747. });
  748. }}
  749. >
  750. {t("buttons.scrollBackToContent")}
  751. </button>
  752. )}
  753. </div>
  754. );
  755. };
  756. const areEqual = (prev: LayerUIProps, next: LayerUIProps) => {
  757. const getNecessaryObj = (appState: AppState): Partial<AppState> => {
  758. const {
  759. suggestedBindings,
  760. startBoundElement: boundElement,
  761. ...ret
  762. } = appState;
  763. return ret;
  764. };
  765. const prevAppState = getNecessaryObj(prev.appState);
  766. const nextAppState = getNecessaryObj(next.appState);
  767. const keys = Object.keys(prevAppState) as (keyof Partial<AppState>)[];
  768. return (
  769. prev.renderCustomFooter === next.renderCustomFooter &&
  770. prev.langCode === next.langCode &&
  771. prev.elements === next.elements &&
  772. keys.every((key) => prevAppState[key] === nextAppState[key])
  773. );
  774. };
  775. export default React.memo(LayerUI, areEqual);