aboutsummaryrefslogtreecommitdiffstats
path: root/packages/excalidraw/components
diff options
context:
space:
mode:
authorkj_sh6042026-03-15 16:19:35 -0400
committerkj_sh6042026-03-15 16:19:35 -0400
commit6ec259a0e71174651bae95d4628138bf6fd68742 (patch)
tree5e33c6a5ec091ecabfcb257fdc7b6a88ed8754ac /packages/excalidraw/components
parent16c8578b15c727f22921f8a80a56ee4d4e7f2272 (diff)
refactor: packages/
Diffstat (limited to 'packages/excalidraw/components')
-rw-r--r--packages/excalidraw/components/Actions.scss93
-rw-r--r--packages/excalidraw/components/Actions.tsx478
-rw-r--r--packages/excalidraw/components/ActiveConfirmDialog.tsx35
-rw-r--r--packages/excalidraw/components/App.tsx11180
-rw-r--r--packages/excalidraw/components/Avatar.scss7
-rw-r--r--packages/excalidraw/components/Avatar.tsx41
-rw-r--r--packages/excalidraw/components/BraveMeasureTextError.tsx43
-rw-r--r--packages/excalidraw/components/Button.scss7
-rw-r--r--packages/excalidraw/components/Button.tsx44
-rw-r--r--packages/excalidraw/components/ButtonIcon.scss12
-rw-r--r--packages/excalidraw/components/ButtonIcon.tsx37
-rw-r--r--packages/excalidraw/components/ButtonIconCycle.tsx29
-rw-r--r--packages/excalidraw/components/ButtonIconSelect.tsx58
-rw-r--r--packages/excalidraw/components/ButtonSelect.tsx30
-rw-r--r--packages/excalidraw/components/ButtonSeparator.tsx10
-rw-r--r--packages/excalidraw/components/Card.scss57
-rw-r--r--packages/excalidraw/components/Card.tsx28
-rw-r--r--packages/excalidraw/components/CheckboxItem.scss91
-rw-r--r--packages/excalidraw/components/CheckboxItem.tsx36
-rw-r--r--packages/excalidraw/components/ColorPicker/ColorInput.tsx130
-rw-r--r--packages/excalidraw/components/ColorPicker/ColorPicker.scss441
-rw-r--r--packages/excalidraw/components/ColorPicker/ColorPicker.tsx246
-rw-r--r--packages/excalidraw/components/ColorPicker/CustomColorList.tsx63
-rw-r--r--packages/excalidraw/components/ColorPicker/HotkeyLabel.tsx29
-rw-r--r--packages/excalidraw/components/ColorPicker/Picker.tsx178
-rw-r--r--packages/excalidraw/components/ColorPicker/PickerColorList.tsx91
-rw-r--r--packages/excalidraw/components/ColorPicker/PickerHeading.tsx7
-rw-r--r--packages/excalidraw/components/ColorPicker/ShadeList.tsx105
-rw-r--r--packages/excalidraw/components/ColorPicker/TopPicks.tsx65
-rw-r--r--packages/excalidraw/components/ColorPicker/colorPickerUtils.ts133
-rw-r--r--packages/excalidraw/components/ColorPicker/keyboardNavHandlers.ts286
-rw-r--r--packages/excalidraw/components/CommandPalette/CommandPalette.scss137
-rw-r--r--packages/excalidraw/components/CommandPalette/CommandPalette.tsx956
-rw-r--r--packages/excalidraw/components/CommandPalette/defaultCommandPaletteItems.ts11
-rw-r--r--packages/excalidraw/components/CommandPalette/types.ts26
-rw-r--r--packages/excalidraw/components/ConfirmDialog.scss11
-rw-r--r--packages/excalidraw/components/ConfirmDialog.tsx78
-rw-r--r--packages/excalidraw/components/ContextMenu.scss98
-rw-r--r--packages/excalidraw/components/ContextMenu.tsx128
-rw-r--r--packages/excalidraw/components/DarkModeToggle.tsx52
-rw-r--r--packages/excalidraw/components/DefaultSidebar.test.tsx144
-rw-r--r--packages/excalidraw/components/DefaultSidebar.tsx121
-rw-r--r--packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodePlugin.tsx17
-rw-r--r--packages/excalidraw/components/Dialog.scss54
-rw-r--r--packages/excalidraw/components/Dialog.tsx134
-rw-r--r--packages/excalidraw/components/DialogActionButton.scss47
-rw-r--r--packages/excalidraw/components/DialogActionButton.tsx46
-rw-r--r--packages/excalidraw/components/ElementLinkDialog.scss87
-rw-r--r--packages/excalidraw/components/ElementLinkDialog.tsx174
-rw-r--r--packages/excalidraw/components/ErrorDialog.tsx40
-rw-r--r--packages/excalidraw/components/ExcalidrawLogo.scss73
-rw-r--r--packages/excalidraw/components/ExcalidrawLogo.tsx69
-rw-r--r--packages/excalidraw/components/ExportDialog.scss129
-rw-r--r--packages/excalidraw/components/EyeDropper.scss48
-rw-r--r--packages/excalidraw/components/EyeDropper.tsx235
-rw-r--r--packages/excalidraw/components/FilledButton.scss317
-rw-r--r--packages/excalidraw/components/FilledButton.tsx114
-rw-r--r--packages/excalidraw/components/FixedSideContainer.scss39
-rw-r--r--packages/excalidraw/components/FixedSideContainer.tsx26
-rw-r--r--packages/excalidraw/components/FollowMode/FollowMode.scss59
-rw-r--r--packages/excalidraw/components/FollowMode/FollowMode.tsx42
-rw-r--r--packages/excalidraw/components/FontPicker/FontPicker.scss15
-rw-r--r--packages/excalidraw/components/FontPicker/FontPicker.tsx110
-rw-r--r--packages/excalidraw/components/FontPicker/FontPickerList.tsx272
-rw-r--r--packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx38
-rw-r--r--packages/excalidraw/components/FontPicker/keyboardNavHandlers.ts66
-rw-r--r--packages/excalidraw/components/HandButton.tsx32
-rw-r--r--packages/excalidraw/components/HelpButton.tsx20
-rw-r--r--packages/excalidraw/components/HelpDialog.scss130
-rw-r--r--packages/excalidraw/components/HelpDialog.tsx503
-rw-r--r--packages/excalidraw/components/HintViewer.scss38
-rw-r--r--packages/excalidraw/components/HintViewer.tsx194
-rw-r--r--packages/excalidraw/components/IconPicker.scss109
-rw-r--r--packages/excalidraw/components/IconPicker.tsx239
-rw-r--r--packages/excalidraw/components/ImageExportDialog.scss175
-rw-r--r--packages/excalidraw/components/ImageExportDialog.tsx407
-rw-r--r--packages/excalidraw/components/InitializeApp.tsx28
-rw-r--r--packages/excalidraw/components/InlineIcon.tsx15
-rw-r--r--packages/excalidraw/components/Island.scss16
-rw-r--r--packages/excalidraw/components/Island.tsx23
-rw-r--r--packages/excalidraw/components/JSONExportDialog.tsx136
-rw-r--r--packages/excalidraw/components/LaserPointerButton.tsx41
-rw-r--r--packages/excalidraw/components/LayerUI.scss119
-rw-r--r--packages/excalidraw/components/LayerUI.tsx607
-rw-r--r--packages/excalidraw/components/LibraryMenu.scss150
-rw-r--r--packages/excalidraw/components/LibraryMenu.tsx290
-rw-r--r--packages/excalidraw/components/LibraryMenuBrowseButton.tsx31
-rw-r--r--packages/excalidraw/components/LibraryMenuControlButtons.tsx33
-rw-r--r--packages/excalidraw/components/LibraryMenuHeaderContent.tsx321
-rw-r--r--packages/excalidraw/components/LibraryMenuItems.scss99
-rw-r--r--packages/excalidraw/components/LibraryMenuItems.tsx342
-rw-r--r--packages/excalidraw/components/LibraryMenuSection.tsx78
-rw-r--r--packages/excalidraw/components/LibraryUnit.scss185
-rw-r--r--packages/excalidraw/components/LibraryUnit.tsx108
-rw-r--r--packages/excalidraw/components/LoadingMessage.tsx40
-rw-r--r--packages/excalidraw/components/LockButton.tsx48
-rw-r--r--packages/excalidraw/components/MagicButton.tsx39
-rw-r--r--packages/excalidraw/components/MobileMenu.tsx211
-rw-r--r--packages/excalidraw/components/Modal.scss136
-rw-r--r--packages/excalidraw/components/Modal.tsx65
-rw-r--r--packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm.scss126
-rw-r--r--packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm.tsx74
-rw-r--r--packages/excalidraw/components/OverwriteConfirm/OverwriteConfirmActions.tsx85
-rw-r--r--packages/excalidraw/components/OverwriteConfirm/OverwriteConfirmState.ts45
-rw-r--r--packages/excalidraw/components/Paragraph.tsx10
-rw-r--r--packages/excalidraw/components/PasteChartDialog.scss46
-rw-r--r--packages/excalidraw/components/PasteChartDialog.tsx136
-rw-r--r--packages/excalidraw/components/PenModeButton.tsx46
-rw-r--r--packages/excalidraw/components/Popover.scss8
-rw-r--r--packages/excalidraw/components/Popover.tsx152
-rw-r--r--packages/excalidraw/components/ProjectName.scss25
-rw-r--r--packages/excalidraw/components/ProjectName.tsx57
-rw-r--r--packages/excalidraw/components/PropertiesPopover.tsx96
-rw-r--r--packages/excalidraw/components/PublishLibrary.scss172
-rw-r--r--packages/excalidraw/components/PublishLibrary.tsx540
-rw-r--r--packages/excalidraw/components/QuickSearch.scss48
-rw-r--r--packages/excalidraw/components/QuickSearch.tsx28
-rw-r--r--packages/excalidraw/components/RadioGroup.scss91
-rw-r--r--packages/excalidraw/components/RadioGroup.tsx45
-rw-r--r--packages/excalidraw/components/Range.scss56
-rw-r--r--packages/excalidraw/components/Range.tsx65
-rw-r--r--packages/excalidraw/components/SVGLayer.scss24
-rw-r--r--packages/excalidraw/components/SVGLayer.tsx33
-rw-r--r--packages/excalidraw/components/ScrollableList.scss21
-rw-r--r--packages/excalidraw/components/ScrollableList.tsx24
-rw-r--r--packages/excalidraw/components/SearchMenu.scss110
-rw-r--r--packages/excalidraw/components/SearchMenu.tsx713
-rw-r--r--packages/excalidraw/components/Section.tsx28
-rw-r--r--packages/excalidraw/components/ShareableLinkDialog.scss91
-rw-r--r--packages/excalidraw/components/ShareableLinkDialog.tsx80
-rw-r--r--packages/excalidraw/components/Sidebar/Sidebar.scss176
-rw-r--r--packages/excalidraw/components/Sidebar/Sidebar.test.tsx393
-rw-r--r--packages/excalidraw/components/Sidebar/Sidebar.tsx213
-rw-r--r--packages/excalidraw/components/Sidebar/SidebarHeader.tsx57
-rw-r--r--packages/excalidraw/components/Sidebar/SidebarTab.tsx18
-rw-r--r--packages/excalidraw/components/Sidebar/SidebarTabTrigger.tsx26
-rw-r--r--packages/excalidraw/components/Sidebar/SidebarTabTriggers.tsx16
-rw-r--r--packages/excalidraw/components/Sidebar/SidebarTabs.tsx36
-rw-r--r--packages/excalidraw/components/Sidebar/SidebarTrigger.scss38
-rw-r--r--packages/excalidraw/components/Sidebar/SidebarTrigger.tsx45
-rw-r--r--packages/excalidraw/components/Sidebar/common.ts42
-rw-r--r--packages/excalidraw/components/Sidebar/siderbar.test.helpers.tsx42
-rw-r--r--packages/excalidraw/components/Spinner.scss49
-rw-r--r--packages/excalidraw/components/Spinner.tsx43
-rw-r--r--packages/excalidraw/components/Stack.scss19
-rw-r--r--packages/excalidraw/components/Stack.tsx62
-rw-r--r--packages/excalidraw/components/Stats/Angle.tsx95
-rw-r--r--packages/excalidraw/components/Stats/CanvasGrid.tsx67
-rw-r--r--packages/excalidraw/components/Stats/Collapsible.tsx46
-rw-r--r--packages/excalidraw/components/Stats/Dimension.tsx272
-rw-r--r--packages/excalidraw/components/Stats/DragInput.scss76
-rw-r--r--packages/excalidraw/components/Stats/DragInput.tsx355
-rw-r--r--packages/excalidraw/components/Stats/FontSize.tsx99
-rw-r--r--packages/excalidraw/components/Stats/MultiAngle.tsx136
-rw-r--r--packages/excalidraw/components/Stats/MultiDimension.tsx401
-rw-r--r--packages/excalidraw/components/Stats/MultiFontSize.tsx164
-rw-r--r--packages/excalidraw/components/Stats/MultiPosition.tsx270
-rw-r--r--packages/excalidraw/components/Stats/Position.tsx214
-rw-r--r--packages/excalidraw/components/Stats/Stats.scss72
-rw-r--r--packages/excalidraw/components/Stats/index.tsx434
-rw-r--r--packages/excalidraw/components/Stats/stats.test.tsx724
-rw-r--r--packages/excalidraw/components/Stats/utils.ts219
-rw-r--r--packages/excalidraw/components/Switch.scss118
-rw-r--r--packages/excalidraw/components/Switch.tsx38
-rw-r--r--packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.scss10
-rw-r--r--packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx132
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialog.scss315
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialog.tsx394
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogInput.tsx53
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogOutput.tsx39
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogPanel.tsx63
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogPanels.tsx5
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogSubmitShortcut.tsx14
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogTab.tsx17
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogTabTrigger.tsx21
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogTabTriggers.tsx13
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogTabs.tsx55
-rw-r--r--packages/excalidraw/components/TTDDialog/TTDDialogTrigger.tsx35
-rw-r--r--packages/excalidraw/components/TTDDialog/common.ts161
-rw-r--r--packages/excalidraw/components/TextField.scss123
-rw-r--r--packages/excalidraw/components/TextField.tsx112
-rw-r--r--packages/excalidraw/components/TextInput.scss7
-rw-r--r--packages/excalidraw/components/Toast.scss49
-rw-r--r--packages/excalidraw/components/Toast.tsx63
-rw-r--r--packages/excalidraw/components/ToolButton.tsx206
-rw-r--r--packages/excalidraw/components/ToolIcon.scss199
-rw-r--r--packages/excalidraw/components/Toolbar.scss50
-rw-r--r--packages/excalidraw/components/Tooltip.scss47
-rw-r--r--packages/excalidraw/components/Tooltip.tsx119
-rw-r--r--packages/excalidraw/components/Trans.test.tsx72
-rw-r--r--packages/excalidraw/components/Trans.tsx170
-rw-r--r--packages/excalidraw/components/UserList.scss160
-rw-r--r--packages/excalidraw/components/UserList.tsx293
-rw-r--r--packages/excalidraw/components/__snapshots__/App.test.tsx.snap50
-rw-r--r--packages/excalidraw/components/canvases/InteractiveCanvas.tsx240
-rw-r--r--packages/excalidraw/components/canvases/NewElementCanvas.tsx56
-rw-r--r--packages/excalidraw/components/canvases/StaticCanvas.tsx141
-rw-r--r--packages/excalidraw/components/canvases/index.tsx4
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenu.scss218
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenu.test.tsx26
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenu.tsx43
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx88
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuGroup.tsx23
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuItem.tsx123
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuItemContent.tsx28
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuItemContentRadio.tsx51
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuItemCustom.tsx25
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuItemLink.tsx49
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuSeparator.tsx14
-rw-r--r--packages/excalidraw/components/dropdownMenu/DropdownMenuTrigger.tsx40
-rw-r--r--packages/excalidraw/components/dropdownMenu/common.ts38
-rw-r--r--packages/excalidraw/components/dropdownMenu/dropdownMenuUtils.ts35
-rw-r--r--packages/excalidraw/components/footer/Footer.tsx95
-rw-r--r--packages/excalidraw/components/footer/FooterCenter.scss11
-rw-r--r--packages/excalidraw/components/footer/FooterCenter.tsx24
-rw-r--r--packages/excalidraw/components/hoc/withInternalFallback.test.tsx101
-rw-r--r--packages/excalidraw/components/hoc/withInternalFallback.tsx75
-rw-r--r--packages/excalidraw/components/hyperlink/Hyperlink.scss70
-rw-r--r--packages/excalidraw/components/hyperlink/Hyperlink.tsx480
-rw-r--r--packages/excalidraw/components/hyperlink/helpers.ts99
-rw-r--r--packages/excalidraw/components/icons.tsx2222
-rw-r--r--packages/excalidraw/components/live-collaboration/LiveCollaborationTrigger.scss66
-rw-r--r--packages/excalidraw/components/live-collaboration/LiveCollaborationTrigger.tsx42
-rw-r--r--packages/excalidraw/components/main-menu/DefaultItems.scss21
-rw-r--r--packages/excalidraw/components/main-menu/DefaultItems.tsx391
-rw-r--r--packages/excalidraw/components/main-menu/MainMenu.tsx84
-rw-r--r--packages/excalidraw/components/welcome-screen/WelcomeScreen.Center.tsx195
-rw-r--r--packages/excalidraw/components/welcome-screen/WelcomeScreen.Hints.tsx52
-rw-r--r--packages/excalidraw/components/welcome-screen/WelcomeScreen.scss272
-rw-r--r--packages/excalidraw/components/welcome-screen/WelcomeScreen.tsx26
230 files changed, 39876 insertions, 0 deletions
diff --git a/packages/excalidraw/components/Actions.scss b/packages/excalidraw/components/Actions.scss
new file mode 100644
index 0000000..5826628
--- /dev/null
+++ b/packages/excalidraw/components/Actions.scss
@@ -0,0 +1,93 @@
+.zoom-actions,
+.undo-redo-buttons {
+ background-color: var(--island-bg-color);
+ border-radius: var(--border-radius-lg);
+ box-shadow: 0 0 0 1px var(--color-surface-lowest);
+}
+
+.zoom-button,
+.undo-redo-buttons button {
+ border-radius: 0 !important;
+ background-color: var(--color-surface-low) !important;
+ font-size: 0.875rem !important;
+ width: var(--lg-button-size);
+ height: var(--lg-button-size);
+
+ svg {
+ width: var(--lg-icon-size) !important;
+ height: var(--lg-icon-size) !important;
+ }
+
+ .ToolIcon__icon {
+ width: 100%;
+ height: 100%;
+ }
+}
+
+.reset-zoom-button {
+ border-left: 0 !important;
+ border-right: 0 !important;
+ padding: 0 0.625rem !important;
+ width: 3.75rem !important;
+ justify-content: center;
+ color: var(--text-primary-color);
+}
+
+.zoom-out-button {
+ border-top-left-radius: var(--border-radius-lg) !important;
+ border-bottom-left-radius: var(--border-radius-lg) !important;
+
+ :root[dir="rtl"] & {
+ transform: scaleX(-1);
+ }
+
+ .ToolIcon__icon {
+ border-top-right-radius: 0 !important;
+ border-bottom-right-radius: 0 !important;
+ }
+}
+
+.zoom-in-button {
+ border-top-right-radius: var(--border-radius-lg) !important;
+ border-bottom-right-radius: var(--border-radius-lg) !important;
+
+ :root[dir="rtl"] & {
+ transform: scaleX(-1);
+ }
+
+ .ToolIcon__icon {
+ border-top-left-radius: 0 !important;
+ border-bottom-left-radius: 0 !important;
+ }
+}
+
+.undo-redo-buttons {
+ .undo-button-container button {
+ border-top-left-radius: var(--border-radius-lg) !important;
+ border-bottom-left-radius: var(--border-radius-lg) !important;
+ border-right: 0 !important;
+
+ :root[dir="rtl"] & {
+ transform: scaleX(-1);
+ }
+
+ .ToolIcon__icon {
+ border-top-right-radius: 0 !important;
+ border-bottom-right-radius: 0 !important;
+ }
+ }
+
+ .redo-button-container button {
+ border-top-right-radius: var(--border-radius-lg) !important;
+ border-bottom-right-radius: var(--border-radius-lg) !important;
+
+ :root[dir="rtl"] & {
+ transform: scaleX(-1);
+ }
+
+ .ToolIcon__icon {
+ border-top-left-radius: 0 !important;
+ border-bottom-left-radius: 0 !important;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Actions.tsx b/packages/excalidraw/components/Actions.tsx
new file mode 100644
index 0000000..cd9120f
--- /dev/null
+++ b/packages/excalidraw/components/Actions.tsx
@@ -0,0 +1,478 @@
+import { useState } from "react";
+import type { ActionManager } from "../actions/manager";
+import type {
+ ExcalidrawElement,
+ ExcalidrawElementType,
+ NonDeletedElementsMap,
+ NonDeletedSceneElementsMap,
+} from "../element/types";
+import { t } from "../i18n";
+import { useDevice } from "./App";
+import {
+ canChangeRoundness,
+ canHaveArrowheads,
+ getTargetElements,
+ hasBackground,
+ hasStrokeStyle,
+ hasStrokeWidth,
+} from "../scene";
+import { SHAPES } from "../shapes";
+import type { AppClassProperties, AppProps, UIAppState, Zoom } from "../types";
+import { capitalizeString, isTransparent } from "../utils";
+import Stack from "./Stack";
+import { ToolButton } from "./ToolButton";
+import { hasStrokeColor, toolIsArrow } from "../scene/comparisons";
+import { trackEvent } from "../analytics";
+import {
+ hasBoundTextElement,
+ isElbowArrow,
+ isImageElement,
+ isLinearElement,
+ isTextElement,
+} from "../element/typeChecks";
+import clsx from "clsx";
+import { actionToggleZenMode } from "../actions";
+import { Tooltip } from "./Tooltip";
+import {
+ shouldAllowVerticalAlign,
+ suppportsHorizontalAlign,
+} from "../element/textElement";
+
+import "./Actions.scss";
+import DropdownMenu from "./dropdownMenu/DropdownMenu";
+import {
+ EmbedIcon,
+ extraToolsIcon,
+ frameToolIcon,
+ mermaidLogoIcon,
+ laserPointerToolIcon,
+ MagicIcon,
+} from "./icons";
+import { KEYS } from "../keys";
+import { useTunnels } from "../context/tunnels";
+import { CLASSES } from "../constants";
+import { alignActionsPredicate } from "../actions/actionAlign";
+
+export const canChangeStrokeColor = (
+ appState: UIAppState,
+ targetElements: ExcalidrawElement[],
+) => {
+ let commonSelectedType: ExcalidrawElementType | null =
+ targetElements[0]?.type || null;
+
+ for (const element of targetElements) {
+ if (element.type !== commonSelectedType) {
+ commonSelectedType = null;
+ break;
+ }
+ }
+
+ return (
+ (hasStrokeColor(appState.activeTool.type) &&
+ appState.activeTool.type !== "image" &&
+ commonSelectedType !== "image" &&
+ commonSelectedType !== "frame" &&
+ commonSelectedType !== "magicframe") ||
+ targetElements.some((element) => hasStrokeColor(element.type))
+ );
+};
+
+export const canChangeBackgroundColor = (
+ appState: UIAppState,
+ targetElements: ExcalidrawElement[],
+) => {
+ return (
+ hasBackground(appState.activeTool.type) ||
+ targetElements.some((element) => hasBackground(element.type))
+ );
+};
+
+export const SelectedShapeActions = ({
+ appState,
+ elementsMap,
+ renderAction,
+ app,
+}: {
+ appState: UIAppState;
+ elementsMap: NonDeletedElementsMap | NonDeletedSceneElementsMap;
+ renderAction: ActionManager["renderAction"];
+ app: AppClassProperties;
+}) => {
+ const targetElements = getTargetElements(elementsMap, appState);
+
+ let isSingleElementBoundContainer = false;
+ if (
+ targetElements.length === 2 &&
+ (hasBoundTextElement(targetElements[0]) ||
+ hasBoundTextElement(targetElements[1]))
+ ) {
+ isSingleElementBoundContainer = true;
+ }
+ const isEditingTextOrNewElement = Boolean(
+ appState.editingTextElement || appState.newElement,
+ );
+ const device = useDevice();
+ const isRTL = document.documentElement.getAttribute("dir") === "rtl";
+
+ const showFillIcons =
+ (hasBackground(appState.activeTool.type) &&
+ !isTransparent(appState.currentItemBackgroundColor)) ||
+ targetElements.some(
+ (element) =>
+ hasBackground(element.type) && !isTransparent(element.backgroundColor),
+ );
+
+ const showLinkIcon =
+ targetElements.length === 1 || isSingleElementBoundContainer;
+
+ const showLineEditorAction =
+ !appState.editingLinearElement &&
+ targetElements.length === 1 &&
+ isLinearElement(targetElements[0]) &&
+ !isElbowArrow(targetElements[0]);
+
+ const showCropEditorAction =
+ !appState.croppingElementId &&
+ targetElements.length === 1 &&
+ isImageElement(targetElements[0]);
+
+ const showAlignActions =
+ !isSingleElementBoundContainer && alignActionsPredicate(appState, app);
+
+ return (
+ <div className="panelColumn">
+ <div>
+ {canChangeStrokeColor(appState, targetElements) &&
+ renderAction("changeStrokeColor")}
+ </div>
+ {canChangeBackgroundColor(appState, targetElements) && (
+ <div>{renderAction("changeBackgroundColor")}</div>
+ )}
+ {showFillIcons && renderAction("changeFillStyle")}
+
+ {(hasStrokeWidth(appState.activeTool.type) ||
+ targetElements.some((element) => hasStrokeWidth(element.type))) &&
+ renderAction("changeStrokeWidth")}
+
+ {(appState.activeTool.type === "freedraw" ||
+ targetElements.some((element) => element.type === "freedraw")) &&
+ renderAction("changeStrokeShape")}
+
+ {(hasStrokeStyle(appState.activeTool.type) ||
+ targetElements.some((element) => hasStrokeStyle(element.type))) && (
+ <>
+ {renderAction("changeStrokeStyle")}
+ {renderAction("changeSloppiness")}
+ </>
+ )}
+
+ {(canChangeRoundness(appState.activeTool.type) ||
+ targetElements.some((element) => canChangeRoundness(element.type))) && (
+ <>{renderAction("changeRoundness")}</>
+ )}
+
+ {(toolIsArrow(appState.activeTool.type) ||
+ targetElements.some((element) => toolIsArrow(element.type))) && (
+ <>{renderAction("changeArrowType")}</>
+ )}
+
+ {(appState.activeTool.type === "text" ||
+ targetElements.some(isTextElement)) && (
+ <>
+ {renderAction("changeFontFamily")}
+ {renderAction("changeFontSize")}
+ {(appState.activeTool.type === "text" ||
+ suppportsHorizontalAlign(targetElements, elementsMap)) &&
+ renderAction("changeTextAlign")}
+ </>
+ )}
+
+ {shouldAllowVerticalAlign(targetElements, elementsMap) &&
+ renderAction("changeVerticalAlign")}
+ {(canHaveArrowheads(appState.activeTool.type) ||
+ targetElements.some((element) => canHaveArrowheads(element.type))) && (
+ <>{renderAction("changeArrowhead")}</>
+ )}
+
+ {renderAction("changeOpacity")}
+
+ <fieldset>
+ <legend>{t("labels.layers")}</legend>
+ <div className="buttonList">
+ {renderAction("sendToBack")}
+ {renderAction("sendBackward")}
+ {renderAction("bringForward")}
+ {renderAction("bringToFront")}
+ </div>
+ </fieldset>
+
+ {showAlignActions && !isSingleElementBoundContainer && (
+ <fieldset>
+ <legend>{t("labels.align")}</legend>
+ <div className="buttonList">
+ {
+ // swap this order for RTL so the button positions always match their action
+ // (i.e. the leftmost button aligns left)
+ }
+ {isRTL ? (
+ <>
+ {renderAction("alignRight")}
+ {renderAction("alignHorizontallyCentered")}
+ {renderAction("alignLeft")}
+ </>
+ ) : (
+ <>
+ {renderAction("alignLeft")}
+ {renderAction("alignHorizontallyCentered")}
+ {renderAction("alignRight")}
+ </>
+ )}
+ {targetElements.length > 2 &&
+ renderAction("distributeHorizontally")}
+ {/* breaks the row ˇˇ */}
+ <div style={{ flexBasis: "100%", height: 0 }} />
+ <div
+ style={{
+ display: "flex",
+ flexWrap: "wrap",
+ gap: ".5rem",
+ marginTop: "-0.5rem",
+ }}
+ >
+ {renderAction("alignTop")}
+ {renderAction("alignVerticallyCentered")}
+ {renderAction("alignBottom")}
+ {targetElements.length > 2 &&
+ renderAction("distributeVertically")}
+ </div>
+ </div>
+ </fieldset>
+ )}
+ {!isEditingTextOrNewElement && targetElements.length > 0 && (
+ <fieldset>
+ <legend>{t("labels.actions")}</legend>
+ <div className="buttonList">
+ {!device.editor.isMobile && renderAction("duplicateSelection")}
+ {!device.editor.isMobile && renderAction("deleteSelectedElements")}
+ {renderAction("group")}
+ {renderAction("ungroup")}
+ {showLinkIcon && renderAction("hyperlink")}
+ {showCropEditorAction && renderAction("cropEditor")}
+ {showLineEditorAction && renderAction("toggleLinearEditor")}
+ </div>
+ </fieldset>
+ )}
+ </div>
+ );
+};
+
+export const ShapesSwitcher = ({
+ activeTool,
+ appState,
+ app,
+ UIOptions,
+}: {
+ activeTool: UIAppState["activeTool"];
+ appState: UIAppState;
+ app: AppClassProperties;
+ UIOptions: AppProps["UIOptions"];
+}) => {
+ const [isExtraToolsMenuOpen, setIsExtraToolsMenuOpen] = useState(false);
+
+ const frameToolSelected = activeTool.type === "frame";
+ const laserToolSelected = activeTool.type === "laser";
+ const embeddableToolSelected = activeTool.type === "embeddable";
+
+ const { TTDDialogTriggerTunnel } = useTunnels();
+
+ return (
+ <>
+ {SHAPES.map(({ value, icon, key, numericKey, fillable }, index) => {
+ if (
+ UIOptions.tools?.[
+ value as Extract<typeof value, keyof AppProps["UIOptions"]["tools"]>
+ ] === false
+ ) {
+ return null;
+ }
+
+ const label = t(`toolBar.${value}`);
+ const letter =
+ key && capitalizeString(typeof key === "string" ? key : key[0]);
+ const shortcut = letter
+ ? `${letter} ${t("helpDialog.or")} ${numericKey}`
+ : `${numericKey}`;
+ return (
+ <ToolButton
+ className={clsx("Shape", { fillable })}
+ key={value}
+ type="radio"
+ icon={icon}
+ checked={activeTool.type === value}
+ name="editor-current-shape"
+ title={`${capitalizeString(label)} — ${shortcut}`}
+ keyBindingLabel={numericKey || letter}
+ aria-label={capitalizeString(label)}
+ aria-keyshortcuts={shortcut}
+ data-testid={`toolbar-${value}`}
+ onPointerDown={({ pointerType }) => {
+ if (!appState.penDetected && pointerType === "pen") {
+ app.togglePenMode(true);
+ }
+ }}
+ onChange={({ pointerType }) => {
+ if (appState.activeTool.type !== value) {
+ trackEvent("toolbar", value, "ui");
+ }
+ if (value === "image") {
+ app.setActiveTool({
+ type: value,
+ insertOnCanvasDirectly: pointerType !== "mouse",
+ });
+ } else {
+ app.setActiveTool({ type: value });
+ }
+ }}
+ />
+ );
+ })}
+ <div className="App-toolbar__divider" />
+
+ <DropdownMenu open={isExtraToolsMenuOpen}>
+ <DropdownMenu.Trigger
+ className={clsx("App-toolbar__extra-tools-trigger", {
+ "App-toolbar__extra-tools-trigger--selected":
+ frameToolSelected ||
+ embeddableToolSelected ||
+ // in collab we're already highlighting the laser button
+ // outside toolbar, so let's not highlight extra-tools button
+ // on top of it
+ (laserToolSelected && !app.props.isCollaborating),
+ })}
+ onToggle={() => setIsExtraToolsMenuOpen(!isExtraToolsMenuOpen)}
+ title={t("toolBar.extraTools")}
+ >
+ {extraToolsIcon}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content
+ onClickOutside={() => setIsExtraToolsMenuOpen(false)}
+ onSelect={() => setIsExtraToolsMenuOpen(false)}
+ className="App-toolbar__extra-tools-dropdown"
+ >
+ <DropdownMenu.Item
+ onSelect={() => app.setActiveTool({ type: "frame" })}
+ icon={frameToolIcon}
+ shortcut={KEYS.F.toLocaleUpperCase()}
+ data-testid="toolbar-frame"
+ selected={frameToolSelected}
+ >
+ {t("toolBar.frame")}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ onSelect={() => app.setActiveTool({ type: "embeddable" })}
+ icon={EmbedIcon}
+ data-testid="toolbar-embeddable"
+ selected={embeddableToolSelected}
+ >
+ {t("toolBar.embeddable")}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ onSelect={() => app.setActiveTool({ type: "laser" })}
+ icon={laserPointerToolIcon}
+ data-testid="toolbar-laser"
+ selected={laserToolSelected}
+ shortcut={KEYS.K.toLocaleUpperCase()}
+ >
+ {t("toolBar.laser")}
+ </DropdownMenu.Item>
+ <div style={{ margin: "6px 0", fontSize: 14, fontWeight: 600 }}>
+ Generate
+ </div>
+ {app.props.aiEnabled !== false && <TTDDialogTriggerTunnel.Out />}
+ <DropdownMenu.Item
+ onSelect={() => app.setOpenDialog({ name: "ttd", tab: "mermaid" })}
+ icon={mermaidLogoIcon}
+ data-testid="toolbar-embeddable"
+ >
+ {t("toolBar.mermaidToExcalidraw")}
+ </DropdownMenu.Item>
+ {app.props.aiEnabled !== false && app.plugins.diagramToCode && (
+ <>
+ <DropdownMenu.Item
+ onSelect={() => app.onMagicframeToolSelect()}
+ icon={MagicIcon}
+ data-testid="toolbar-magicframe"
+ >
+ {t("toolBar.magicframe")}
+ <DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>
+ </DropdownMenu.Item>
+ </>
+ )}
+ </DropdownMenu.Content>
+ </DropdownMenu>
+ </>
+ );
+};
+
+export const ZoomActions = ({
+ renderAction,
+ zoom,
+}: {
+ renderAction: ActionManager["renderAction"];
+ zoom: Zoom;
+}) => (
+ <Stack.Col gap={1} className={CLASSES.ZOOM_ACTIONS}>
+ <Stack.Row align="center">
+ {renderAction("zoomOut")}
+ {renderAction("resetZoom")}
+ {renderAction("zoomIn")}
+ </Stack.Row>
+ </Stack.Col>
+);
+
+export const UndoRedoActions = ({
+ renderAction,
+ className,
+}: {
+ renderAction: ActionManager["renderAction"];
+ className?: string;
+}) => (
+ <div className={`undo-redo-buttons ${className}`}>
+ <div className="undo-button-container">
+ <Tooltip label={t("buttons.undo")}>{renderAction("undo")}</Tooltip>
+ </div>
+ <div className="redo-button-container">
+ <Tooltip label={t("buttons.redo")}> {renderAction("redo")}</Tooltip>
+ </div>
+ </div>
+);
+
+export const ExitZenModeAction = ({
+ actionManager,
+ showExitZenModeBtn,
+}: {
+ actionManager: ActionManager;
+ showExitZenModeBtn: boolean;
+}) => (
+ <button
+ type="button"
+ className={clsx("disable-zen-mode", {
+ "disable-zen-mode--visible": showExitZenModeBtn,
+ })}
+ onClick={() => actionManager.executeAction(actionToggleZenMode)}
+ >
+ {t("buttons.exitZenMode")}
+ </button>
+);
+
+export const FinalizeAction = ({
+ renderAction,
+ className,
+}: {
+ renderAction: ActionManager["renderAction"];
+ className?: string;
+}) => (
+ <div className={`finalize-button ${className}`}>
+ {renderAction("finalize", { size: "small" })}
+ </div>
+);
diff --git a/packages/excalidraw/components/ActiveConfirmDialog.tsx b/packages/excalidraw/components/ActiveConfirmDialog.tsx
new file mode 100644
index 0000000..699fbc6
--- /dev/null
+++ b/packages/excalidraw/components/ActiveConfirmDialog.tsx
@@ -0,0 +1,35 @@
+import { actionClearCanvas } from "../actions";
+import { t } from "../i18n";
+import { atom, useAtom } from "../editor-jotai";
+import { useExcalidrawActionManager } from "./App";
+import ConfirmDialog from "./ConfirmDialog";
+
+export const activeConfirmDialogAtom = atom<"clearCanvas" | null>(null);
+
+export const ActiveConfirmDialog = () => {
+ const [activeConfirmDialog, setActiveConfirmDialog] = useAtom(
+ activeConfirmDialogAtom,
+ );
+ const actionManager = useExcalidrawActionManager();
+
+ if (!activeConfirmDialog) {
+ return null;
+ }
+
+ if (activeConfirmDialog === "clearCanvas") {
+ return (
+ <ConfirmDialog
+ onConfirm={() => {
+ actionManager.executeAction(actionClearCanvas);
+ setActiveConfirmDialog(null);
+ }}
+ onCancel={() => setActiveConfirmDialog(null)}
+ title={t("clearCanvasDialog.title")}
+ >
+ <p className="clear-canvas__content"> {t("alerts.clearReset")}</p>
+ </ConfirmDialog>
+ );
+ }
+
+ return null;
+};
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
new file mode 100644
index 0000000..dc6d287
--- /dev/null
+++ b/packages/excalidraw/components/App.tsx
@@ -0,0 +1,11180 @@
+import React, { useContext } from "react";
+import { flushSync } from "react-dom";
+
+import type { RoughCanvas } from "roughjs/bin/canvas";
+import rough from "roughjs/bin/rough";
+import clsx from "clsx";
+import { nanoid } from "nanoid";
+import {
+ actionAddToLibrary,
+ actionBringForward,
+ actionBringToFront,
+ actionCopy,
+ actionCopyAsPng,
+ actionCopyAsSvg,
+ copyText,
+ actionCopyStyles,
+ actionCut,
+ actionDeleteSelected,
+ actionDuplicateSelection,
+ actionFinalize,
+ actionFlipHorizontal,
+ actionFlipVertical,
+ actionGroup,
+ actionPasteStyles,
+ actionSelectAll,
+ actionSendBackward,
+ actionSendToBack,
+ actionToggleGridMode,
+ actionToggleStats,
+ actionToggleZenMode,
+ actionUnbindText,
+ actionBindText,
+ actionUngroup,
+ actionLink,
+ actionToggleElementLock,
+ actionToggleLinearEditor,
+ actionToggleObjectsSnapMode,
+ actionToggleCropEditor,
+} from "../actions";
+import { createRedoAction, createUndoAction } from "../actions/actionHistory";
+import { ActionManager } from "../actions/manager";
+import { actions } from "../actions/register";
+import type { Action, ActionResult } from "../actions/types";
+import { trackEvent } from "../analytics";
+import {
+ getDefaultAppState,
+ isEraserActive,
+ isHandToolActive,
+} from "../appState";
+import type { PastedMixedContent } from "../clipboard";
+import { copyTextToSystemClipboard, parseClipboard } from "../clipboard";
+import {
+ APP_NAME,
+ CURSOR_TYPE,
+ DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
+ DEFAULT_VERTICAL_ALIGN,
+ DRAGGING_THRESHOLD,
+ ELEMENT_SHIFT_TRANSLATE_AMOUNT,
+ ELEMENT_TRANSLATE_AMOUNT,
+ ENV,
+ EVENT,
+ FRAME_STYLE,
+ IMAGE_MIME_TYPES,
+ IMAGE_RENDER_TIMEOUT,
+ isBrave,
+ LINE_CONFIRM_THRESHOLD,
+ MAX_ALLOWED_FILE_BYTES,
+ MIME_TYPES,
+ MQ_MAX_HEIGHT_LANDSCAPE,
+ MQ_MAX_WIDTH_LANDSCAPE,
+ MQ_MAX_WIDTH_PORTRAIT,
+ MQ_RIGHT_SIDEBAR_MIN_WIDTH,
+ POINTER_BUTTON,
+ ROUNDNESS,
+ SCROLL_TIMEOUT,
+ TAP_TWICE_TIMEOUT,
+ TEXT_TO_CENTER_SNAP_THRESHOLD,
+ THEME,
+ THEME_FILTER,
+ TOUCH_CTX_MENU_TIMEOUT,
+ VERTICAL_ALIGN,
+ YOUTUBE_STATES,
+ ZOOM_STEP,
+ POINTER_EVENTS,
+ TOOL_TYPE,
+ isIOS,
+ supportsResizeObserver,
+ DEFAULT_COLLISION_THRESHOLD,
+ DEFAULT_TEXT_ALIGN,
+ ARROW_TYPE,
+ DEFAULT_REDUCED_GLOBAL_ALPHA,
+ isSafari,
+ type EXPORT_IMAGE_TYPES,
+} from "../constants";
+import type { ExportedElements } from "../data";
+import { exportCanvas, loadFromBlob } from "../data";
+import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
+import { restore, restoreElements } from "../data/restore";
+import {
+ dragNewElement,
+ dragSelectedElements,
+ duplicateElement,
+ getCommonBounds,
+ getCursorForResizingElement,
+ getDragOffsetXY,
+ getElementWithTransformHandleType,
+ getNormalizedDimensions,
+ getResizeArrowDirection,
+ getResizeOffsetXY,
+ getLockedLinearCursorAlignSize,
+ getTransformHandleTypeFromCoords,
+ isInvisiblySmallElement,
+ isNonDeletedElement,
+ isTextElement,
+ newElement,
+ newLinearElement,
+ newTextElement,
+ newImageElement,
+ transformElements,
+ refreshTextDimensions,
+ redrawTextBoundingBox,
+ getElementAbsoluteCoords,
+} from "../element";
+import {
+ bindOrUnbindLinearElement,
+ bindOrUnbindLinearElements,
+ fixBindingsAfterDeletion,
+ fixBindingsAfterDuplication,
+ getHoveredElementForBinding,
+ isBindingEnabled,
+ isLinearElementSimpleAndAlreadyBound,
+ maybeBindLinearElement,
+ shouldEnableBindingForPointerEvent,
+ updateBoundElements,
+ getSuggestedBindingsForArrows,
+} from "../element/binding";
+import { LinearElementEditor } from "../element/linearElementEditor";
+import { mutateElement, newElementWith } from "../element/mutateElement";
+import {
+ deepCopyElement,
+ duplicateElements,
+ newFrameElement,
+ newFreeDrawElement,
+ newEmbeddableElement,
+ newMagicFrameElement,
+ newIframeElement,
+ newArrowElement,
+} from "../element/newElement";
+import {
+ hasBoundTextElement,
+ isArrowElement,
+ isBindingElement,
+ isBindingElementType,
+ isBoundToContainer,
+ isFrameLikeElement,
+ isImageElement,
+ isEmbeddableElement,
+ isInitializedImageElement,
+ isLinearElement,
+ isLinearElementType,
+ isUsingAdaptiveRadius,
+ isIframeElement,
+ isIframeLikeElement,
+ isMagicFrameElement,
+ isTextBindableContainer,
+ isElbowArrow,
+ isFlowchartNodeElement,
+ isBindableElement,
+} from "../element/typeChecks";
+import type {
+ ExcalidrawBindableElement,
+ ExcalidrawElement,
+ ExcalidrawFreeDrawElement,
+ ExcalidrawGenericElement,
+ ExcalidrawLinearElement,
+ ExcalidrawTextElement,
+ NonDeleted,
+ InitializedExcalidrawImageElement,
+ ExcalidrawImageElement,
+ FileId,
+ NonDeletedExcalidrawElement,
+ ExcalidrawTextContainer,
+ ExcalidrawFrameLikeElement,
+ ExcalidrawMagicFrameElement,
+ ExcalidrawIframeLikeElement,
+ IframeData,
+ ExcalidrawIframeElement,
+ ExcalidrawEmbeddableElement,
+ Ordered,
+ MagicGenerationData,
+ ExcalidrawNonSelectionElement,
+ ExcalidrawArrowElement,
+} from "../element/types";
+import { getCenter, getDistance } from "../gesture";
+import {
+ editGroupForSelectedElement,
+ getElementsInGroup,
+ getSelectedGroupIdForElement,
+ getSelectedGroupIds,
+ isElementInGroup,
+ isSelectedViaGroup,
+ selectGroupsForSelectedElements,
+} from "../groups";
+import { History } from "../history";
+import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
+import {
+ CODES,
+ shouldResizeFromCenter,
+ shouldMaintainAspectRatio,
+ shouldRotateWithDiscreteAngle,
+ isArrowKey,
+ KEYS,
+} from "../keys";
+import {
+ isElementCompletelyInViewport,
+ isElementInViewport,
+} from "../element/sizeHelpers";
+import {
+ calculateScrollCenter,
+ getElementsWithinSelection,
+ getNormalizedZoom,
+ getSelectedElements,
+ hasBackground,
+ isSomeElementSelected,
+} from "../scene";
+import Scene from "../scene/Scene";
+import type {
+ RenderInteractiveSceneCallback,
+ ScrollBars,
+} from "../scene/types";
+import { getStateForZoom } from "../scene/zoom";
+import {
+ findShapeByKey,
+ getBoundTextShape,
+ getCornerRadius,
+ getElementShape,
+ isPathALoop,
+} from "../shapes";
+import { getSelectionBoxShape } from "@excalidraw/utils/geometry/shape";
+import { isPointInShape } from "@excalidraw/utils/collision";
+import type {
+ AppClassProperties,
+ AppProps,
+ AppState,
+ BinaryFileData,
+ DataURL,
+ ExcalidrawImperativeAPI,
+ BinaryFiles,
+ Gesture,
+ GestureEvent,
+ LibraryItems,
+ PointerDownState,
+ SceneData,
+ Device,
+ FrameNameBoundsCache,
+ SidebarName,
+ SidebarTabName,
+ KeyboardModifiersObject,
+ CollaboratorPointer,
+ ToolType,
+ OnUserFollowedPayload,
+ UnsubscribeCallback,
+ EmbedsValidationStatus,
+ ElementsPendingErasure,
+ GenerateDiagramToCode,
+ NullableGridSize,
+ Offsets,
+} from "../types";
+import {
+ debounce,
+ distance,
+ getFontString,
+ getNearestScrollableContainer,
+ isInputLike,
+ isToolIcon,
+ isWritableElement,
+ sceneCoordsToViewportCoords,
+ tupleToCoors,
+ viewportCoordsToSceneCoords,
+ wrapEvent,
+ updateObject,
+ updateActiveTool,
+ getShortcutKey,
+ isTransparent,
+ easeToValuesRAF,
+ muteFSAbortError,
+ isTestEnv,
+ easeOut,
+ updateStable,
+ addEventListener,
+ normalizeEOL,
+ getDateTime,
+ isShallowEqual,
+ arrayToMap,
+} from "../utils";
+import {
+ createSrcDoc,
+ embeddableURLValidator,
+ maybeParseEmbedSrc,
+ getEmbedLink,
+} from "../element/embeddable";
+import type { ContextMenuItems } from "./ContextMenu";
+import { ContextMenu, CONTEXT_MENU_SEPARATOR } from "./ContextMenu";
+import LayerUI from "./LayerUI";
+import { Toast } from "./Toast";
+import { actionToggleViewMode } from "../actions/actionToggleViewMode";
+import {
+ dataURLToFile,
+ dataURLToString,
+ generateIdFromFile,
+ getDataURL,
+ getDataURL_sync,
+ getFileFromEvent,
+ ImageURLToFile,
+ isImageFileHandle,
+ isSupportedImageFile,
+ loadSceneOrLibraryFromBlob,
+ normalizeFile,
+ parseLibraryJSON,
+ resizeImageFile,
+ SVGStringToFile,
+} from "../data/blob";
+import {
+ getInitializedImageElements,
+ loadHTMLImageElement,
+ normalizeSVG,
+ updateImageCache as _updateImageCache,
+} from "../element/image";
+import throttle from "lodash.throttle";
+import type { FileSystemHandle } from "../data/filesystem";
+import { fileOpen } from "../data/filesystem";
+import {
+ bindTextToShapeAfterDuplication,
+ getBoundTextElement,
+ getContainerCenter,
+ getContainerElement,
+ isValidTextContainer,
+} from "../element/textElement";
+import {
+ showHyperlinkTooltip,
+ hideHyperlinkToolip,
+ Hyperlink,
+} from "../components/hyperlink/Hyperlink";
+import { isLocalLink, normalizeLink, toValidURL } from "../data/url";
+import { shouldShowBoundingBox } from "../element/transformHandles";
+import { actionUnlockAllElements } from "../actions/actionElementLock";
+import { Fonts, getLineHeight } from "../fonts";
+import {
+ getFrameChildren,
+ isCursorInFrame,
+ bindElementsToFramesAfterDuplication,
+ addElementsToFrame,
+ replaceAllElementsInFrame,
+ removeElementsFromFrame,
+ getElementsInResizingFrame,
+ getElementsInNewFrame,
+ getContainingFrame,
+ elementOverlapsWithFrame,
+ updateFrameMembershipOfSelectedElements,
+ isElementInFrame,
+ getFrameLikeTitle,
+ getElementsOverlappingFrame,
+ filterElementsEligibleAsFrameChildren,
+} from "../frame";
+import {
+ excludeElementsInFramesFromSelection,
+ makeNextSelectedElementIds,
+} from "../scene/selection";
+import { actionPaste } from "../actions/actionClipboard";
+import {
+ actionRemoveAllElementsFromFrame,
+ actionSelectAllElementsInFrame,
+ actionWrapSelectionInFrame,
+} from "../actions/actionFrame";
+import { actionToggleHandTool, zoomToFit } from "../actions/actionCanvas";
+import { editorJotaiStore } from "../editor-jotai";
+import { activeConfirmDialogAtom } from "./ActiveConfirmDialog";
+import { ImageSceneDataError } from "../errors";
+import {
+ getSnapLinesAtPointer,
+ snapDraggedElements,
+ isActiveToolNonLinearSnappable,
+ snapNewElement,
+ snapResizingElements,
+ isSnappingEnabled,
+ getVisibleGaps,
+ getReferenceSnapPoints,
+ SnapCache,
+ isGridModeEnabled,
+ getGridPoint,
+} from "../snapping";
+import { actionWrapTextInContainer } from "../actions/actionBoundText";
+import BraveMeasureTextError from "./BraveMeasureTextError";
+import { activeEyeDropperAtom } from "./EyeDropper";
+import type { ExcalidrawElementSkeleton } from "../data/transform";
+import { convertToExcalidrawElements } from "../data/transform";
+import type { ValueOf } from "../utility-types";
+import { isSidebarDockedAtom } from "./Sidebar/Sidebar";
+import { StaticCanvas, InteractiveCanvas } from "./canvases";
+import { Renderer } from "../scene/Renderer";
+import { ShapeCache } from "../scene/ShapeCache";
+import { SVGLayer } from "./SVGLayer";
+import {
+ setEraserCursor,
+ setCursor,
+ resetCursor,
+ setCursorForShape,
+} from "../cursor";
+import { Emitter } from "../emitter";
+import { ElementCanvasButtons } from "../element/ElementCanvasButtons";
+import { COLOR_PALETTE } from "../colors";
+import { ElementCanvasButton } from "./MagicButton";
+import { MagicIcon, copyIcon, fullscreenIcon } from "./icons";
+import FollowMode from "./FollowMode/FollowMode";
+import { Store, CaptureUpdateAction } from "../store";
+import { AnimationFrameHandler } from "../animation-frame-handler";
+import { AnimatedTrail } from "../animated-trail";
+import { LaserTrails } from "../laser-trails";
+import { withBatchedUpdates, withBatchedUpdatesThrottled } from "../reactUtils";
+import { getRenderOpacity } from "../renderer/renderElement";
+import {
+ hitElementBoundText,
+ hitElementBoundingBoxOnly,
+ hitElementItself,
+} from "../element/collision";
+import { textWysiwyg } from "../element/textWysiwyg";
+import { isOverScrollBars } from "../scene/scrollbars";
+import { syncInvalidIndices, syncMovedIndices } from "../fractionalIndex";
+import {
+ isPointHittingLink,
+ isPointHittingLinkIcon,
+} from "./hyperlink/helpers";
+import { getShortcutFromShortcutName } from "../actions/shortcuts";
+import { actionTextAutoResize } from "../actions/actionTextAutoResize";
+import { getVisibleSceneBounds } from "../element/bounds";
+import { isMaybeMermaidDefinition } from "../mermaid";
+import NewElementCanvas from "./canvases/NewElementCanvas";
+import {
+ FlowChartCreator,
+ FlowChartNavigator,
+ getLinkDirectionFromKey,
+} from "../element/flowchart";
+import { searchItemInFocusAtom } from "./SearchMenu";
+import type { LocalPoint, Radians } from "@excalidraw/math";
+import {
+ clamp,
+ pointFrom,
+ pointDistance,
+ vector,
+ pointRotateRads,
+ vectorScale,
+ vectorFromPoint,
+ vectorSubtract,
+ vectorDot,
+ vectorNormalize,
+} from "@excalidraw/math";
+import { cropElement } from "../element/cropElement";
+import { wrapText } from "../element/textWrapping";
+import { actionCopyElementLink } from "../actions/actionElementLink";
+import { isElementLink, parseElementLinkFromURL } from "../element/elementLink";
+import {
+ isMeasureTextSupported,
+ normalizeText,
+ measureText,
+ getLineHeightInPx,
+ getApproxMinLineWidth,
+ getApproxMinLineHeight,
+ getMinTextElementWidth,
+} from "../element/textMeasurements";
+
+const AppContext = React.createContext<AppClassProperties>(null!);
+const AppPropsContext = React.createContext<AppProps>(null!);
+
+const deviceContextInitialValue = {
+ viewport: {
+ isMobile: false,
+ isLandscape: false,
+ },
+ editor: {
+ isMobile: false,
+ canFitSidebar: false,
+ },
+ isTouchScreen: false,
+};
+const DeviceContext = React.createContext<Device>(deviceContextInitialValue);
+DeviceContext.displayName = "DeviceContext";
+
+export const ExcalidrawContainerContext = React.createContext<{
+ container: HTMLDivElement | null;
+ id: string | null;
+}>({ container: null, id: null });
+ExcalidrawContainerContext.displayName = "ExcalidrawContainerContext";
+
+const ExcalidrawElementsContext = React.createContext<
+ readonly NonDeletedExcalidrawElement[]
+>([]);
+ExcalidrawElementsContext.displayName = "ExcalidrawElementsContext";
+
+const ExcalidrawAppStateContext = React.createContext<AppState>({
+ ...getDefaultAppState(),
+ width: 0,
+ height: 0,
+ offsetLeft: 0,
+ offsetTop: 0,
+});
+ExcalidrawAppStateContext.displayName = "ExcalidrawAppStateContext";
+
+const ExcalidrawSetAppStateContext = React.createContext<
+ React.Component<any, AppState>["setState"]
+>(() => {
+ console.warn("Uninitialized ExcalidrawSetAppStateContext context!");
+});
+ExcalidrawSetAppStateContext.displayName = "ExcalidrawSetAppStateContext";
+
+const ExcalidrawActionManagerContext = React.createContext<ActionManager>(
+ null!,
+);
+ExcalidrawActionManagerContext.displayName = "ExcalidrawActionManagerContext";
+
+export const useApp = () => useContext(AppContext);
+export const useAppProps = () => useContext(AppPropsContext);
+export const useDevice = () => useContext<Device>(DeviceContext);
+export const useExcalidrawContainer = () =>
+ useContext(ExcalidrawContainerContext);
+export const useExcalidrawElements = () =>
+ useContext(ExcalidrawElementsContext);
+export const useExcalidrawAppState = () =>
+ useContext(ExcalidrawAppStateContext);
+export const useExcalidrawSetAppState = () =>
+ useContext(ExcalidrawSetAppStateContext);
+export const useExcalidrawActionManager = () =>
+ useContext(ExcalidrawActionManagerContext);
+
+let didTapTwice: boolean = false;
+let tappedTwiceTimer = 0;
+let isHoldingSpace: boolean = false;
+let isPanning: boolean = false;
+let isDraggingScrollBar: boolean = false;
+let currentScrollBars: ScrollBars = { horizontal: null, vertical: null };
+let touchTimeout = 0;
+let invalidateContextMenu = false;
+
+/**
+ * Map of youtube embed video states
+ */
+const YOUTUBE_VIDEO_STATES = new Map<
+ ExcalidrawElement["id"],
+ ValueOf<typeof YOUTUBE_STATES>
+>();
+
+let IS_PLAIN_PASTE = false;
+let IS_PLAIN_PASTE_TIMER = 0;
+let PLAIN_PASTE_TOAST_SHOWN = false;
+
+let lastPointerUp: (() => void) | null = null;
+const gesture: Gesture = {
+ pointers: new Map(),
+ lastCenter: null,
+ initialDistance: null,
+ initialScale: null,
+};
+
+class App extends React.Component<AppProps, AppState> {
+ canvas: AppClassProperties["canvas"];
+ interactiveCanvas: AppClassProperties["interactiveCanvas"] = null;
+ rc: RoughCanvas;
+ unmounted: boolean = false;
+ actionManager: ActionManager;
+ device: Device = deviceContextInitialValue;
+
+ private excalidrawContainerRef = React.createRef<HTMLDivElement>();
+
+ public scene: Scene;
+ public fonts: Fonts;
+ public renderer: Renderer;
+ public visibleElements: readonly NonDeletedExcalidrawElement[];
+ private resizeObserver: ResizeObserver | undefined;
+ private nearestScrollableContainer: HTMLElement | Document | undefined;
+ public library: AppClassProperties["library"];
+ public libraryItemsFromStorage: LibraryItems | undefined;
+ public id: string;
+ private store: Store;
+ private history: History;
+ public excalidrawContainerValue: {
+ container: HTMLDivElement | null;
+ id: string;
+ };
+
+ public files: BinaryFiles = {};
+ public imageCache: AppClassProperties["imageCache"] = new Map();
+ private iFrameRefs = new Map<ExcalidrawElement["id"], HTMLIFrameElement>();
+ /**
+ * Indicates whether the embeddable's url has been validated for rendering.
+ * If value not set, indicates that the validation is pending.
+ * Initially or on url change the flag is not reset so that we can guarantee
+ * the validation came from a trusted source (the editor).
+ **/
+ private embedsValidationStatus: EmbedsValidationStatus = new Map();
+ /** embeds that have been inserted to DOM (as a perf optim, we don't want to
+ * insert to DOM before user initially scrolls to them) */
+ private initializedEmbeds = new Set<ExcalidrawIframeLikeElement["id"]>();
+
+ private elementsPendingErasure: ElementsPendingErasure = new Set();
+
+ public flowChartCreator: FlowChartCreator = new FlowChartCreator();
+ private flowChartNavigator: FlowChartNavigator = new FlowChartNavigator();
+
+ hitLinkElement?: NonDeletedExcalidrawElement;
+ lastPointerDownEvent: React.PointerEvent<HTMLElement> | null = null;
+ lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null =
+ null;
+ lastPointerMoveEvent: PointerEvent | null = null;
+ lastPointerMoveCoords: { x: number; y: number } | null = null;
+ lastViewportPosition = { x: 0, y: 0 };
+
+ animationFrameHandler = new AnimationFrameHandler();
+
+ laserTrails = new LaserTrails(this.animationFrameHandler, this);
+ eraserTrail = new AnimatedTrail(this.animationFrameHandler, this, {
+ streamline: 0.2,
+ size: 5,
+ keepHead: true,
+ sizeMapping: (c) => {
+ const DECAY_TIME = 200;
+ const DECAY_LENGTH = 10;
+ const t = Math.max(0, 1 - (performance.now() - c.pressure) / DECAY_TIME);
+ const l =
+ (DECAY_LENGTH -
+ Math.min(DECAY_LENGTH, c.totalLength - c.currentIndex)) /
+ DECAY_LENGTH;
+
+ return Math.min(easeOut(l), easeOut(t));
+ },
+ fill: () =>
+ this.state.theme === THEME.LIGHT
+ ? "rgba(0, 0, 0, 0.2)"
+ : "rgba(255, 255, 255, 0.2)",
+ });
+
+ onChangeEmitter = new Emitter<
+ [
+ elements: readonly ExcalidrawElement[],
+ appState: AppState,
+ files: BinaryFiles,
+ ]
+ >();
+
+ onPointerDownEmitter = new Emitter<
+ [
+ activeTool: AppState["activeTool"],
+ pointerDownState: PointerDownState,
+ event: React.PointerEvent<HTMLElement>,
+ ]
+ >();
+
+ onPointerUpEmitter = new Emitter<
+ [
+ activeTool: AppState["activeTool"],
+ pointerDownState: PointerDownState,
+ event: PointerEvent,
+ ]
+ >();
+ onUserFollowEmitter = new Emitter<[payload: OnUserFollowedPayload]>();
+ onScrollChangeEmitter = new Emitter<
+ [scrollX: number, scrollY: number, zoom: AppState["zoom"]]
+ >();
+
+ missingPointerEventCleanupEmitter = new Emitter<
+ [event: PointerEvent | null]
+ >();
+ onRemoveEventListenersEmitter = new Emitter<[]>();
+
+ constructor(props: AppProps) {
+ super(props);
+ const defaultAppState = getDefaultAppState();
+ const {
+ excalidrawAPI,
+ viewModeEnabled = false,
+ zenModeEnabled = false,
+ gridModeEnabled = false,
+ objectsSnapModeEnabled = false,
+ theme = defaultAppState.theme,
+ name = `${t("labels.untitled")}-${getDateTime()}`,
+ } = props;
+ this.state = {
+ ...defaultAppState,
+ theme,
+ isLoading: true,
+ ...this.getCanvasOffsets(),
+ viewModeEnabled,
+ zenModeEnabled,
+ objectsSnapModeEnabled,
+ gridModeEnabled: gridModeEnabled ?? defaultAppState.gridModeEnabled,
+ name,
+ width: window.innerWidth,
+ height: window.innerHeight,
+ };
+
+ this.id = nanoid();
+ this.library = new Library(this);
+ this.actionManager = new ActionManager(
+ this.syncActionResult,
+ () => this.state,
+ () => this.scene.getElementsIncludingDeleted(),
+ this,
+ );
+ this.scene = new Scene();
+
+ this.canvas = document.createElement("canvas");
+ this.rc = rough.canvas(this.canvas);
+ this.renderer = new Renderer(this.scene);
+ this.visibleElements = [];
+
+ this.store = new Store();
+ this.history = new History();
+
+ if (excalidrawAPI) {
+ const api: ExcalidrawImperativeAPI = {
+ updateScene: this.updateScene,
+ updateLibrary: this.library.updateLibrary,
+ addFiles: this.addFiles,
+ resetScene: this.resetScene,
+ getSceneElementsIncludingDeleted: this.getSceneElementsIncludingDeleted,
+ history: {
+ clear: this.resetHistory,
+ },
+ scrollToContent: this.scrollToContent,
+ getSceneElements: this.getSceneElements,
+ getAppState: () => this.state,
+ getFiles: () => this.files,
+ getName: this.getName,
+ registerAction: (action: Action) => {
+ this.actionManager.registerAction(action);
+ },
+ refresh: this.refresh,
+ setToast: this.setToast,
+ id: this.id,
+ setActiveTool: this.setActiveTool,
+ setCursor: this.setCursor,
+ resetCursor: this.resetCursor,
+ updateFrameRendering: this.updateFrameRendering,
+ toggleSidebar: this.toggleSidebar,
+ onChange: (cb) => this.onChangeEmitter.on(cb),
+ onPointerDown: (cb) => this.onPointerDownEmitter.on(cb),
+ onPointerUp: (cb) => this.onPointerUpEmitter.on(cb),
+ onScrollChange: (cb) => this.onScrollChangeEmitter.on(cb),
+ onUserFollow: (cb) => this.onUserFollowEmitter.on(cb),
+ } as const;
+ if (typeof excalidrawAPI === "function") {
+ excalidrawAPI(api);
+ } else {
+ console.error("excalidrawAPI should be a function!");
+ }
+ }
+
+ this.excalidrawContainerValue = {
+ container: this.excalidrawContainerRef.current,
+ id: this.id,
+ };
+
+ this.fonts = new Fonts(this.scene);
+ this.history = new History();
+
+ this.actionManager.registerAll(actions);
+ this.actionManager.registerAction(
+ createUndoAction(this.history, this.store),
+ );
+ this.actionManager.registerAction(
+ createRedoAction(this.history, this.store),
+ );
+ }
+
+ private onWindowMessage(event: MessageEvent) {
+ if (
+ event.origin !== "https://player.vimeo.com" &&
+ event.origin !== "https://www.youtube.com"
+ ) {
+ return;
+ }
+
+ let data = null;
+ try {
+ data = JSON.parse(event.data);
+ } catch (e) {}
+ if (!data) {
+ return;
+ }
+
+ switch (event.origin) {
+ case "https://player.vimeo.com":
+ //Allowing for multiple instances of Excalidraw running in the window
+ if (data.method === "paused") {
+ let source: Window | null = null;
+ const iframes = document.body.querySelectorAll(
+ "iframe.excalidraw__embeddable",
+ );
+ if (!iframes) {
+ break;
+ }
+ for (const iframe of iframes as NodeListOf<HTMLIFrameElement>) {
+ if (iframe.contentWindow === event.source) {
+ source = iframe.contentWindow;
+ }
+ }
+ source?.postMessage(
+ JSON.stringify({
+ method: data.value ? "play" : "pause",
+ value: true,
+ }),
+ "*",
+ );
+ }
+ break;
+ case "https://www.youtube.com":
+ if (
+ data.event === "infoDelivery" &&
+ data.info &&
+ data.id &&
+ typeof data.info.playerState === "number"
+ ) {
+ const id = data.id;
+ const playerState = data.info.playerState as number;
+ if (
+ (Object.values(YOUTUBE_STATES) as number[]).includes(playerState)
+ ) {
+ YOUTUBE_VIDEO_STATES.set(
+ id,
+ playerState as ValueOf<typeof YOUTUBE_STATES>,
+ );
+ }
+ }
+ break;
+ }
+ }
+
+ private cacheEmbeddableRef(
+ element: ExcalidrawIframeLikeElement,
+ ref: HTMLIFrameElement | null,
+ ) {
+ if (ref) {
+ this.iFrameRefs.set(element.id, ref);
+ }
+ }
+
+ /**
+ * Returns gridSize taking into account `gridModeEnabled`.
+ * If disabled, returns null.
+ */
+ public getEffectiveGridSize = () => {
+ return (
+ isGridModeEnabled(this) ? this.state.gridSize : null
+ ) as NullableGridSize;
+ };
+
+ private getHTMLIFrameElement(
+ element: ExcalidrawIframeLikeElement,
+ ): HTMLIFrameElement | undefined {
+ return this.iFrameRefs.get(element.id);
+ }
+
+ private handleEmbeddableCenterClick(element: ExcalidrawIframeLikeElement) {
+ if (
+ this.state.activeEmbeddable?.element === element &&
+ this.state.activeEmbeddable?.state === "active"
+ ) {
+ return;
+ }
+
+ // The delay serves two purposes
+ // 1. To prevent first click propagating to iframe on mobile,
+ // else the click will immediately start and stop the video
+ // 2. If the user double clicks the frame center to activate it
+ // without the delay youtube will immediately open the video
+ // in fullscreen mode
+ setTimeout(() => {
+ this.setState({
+ activeEmbeddable: { element, state: "active" },
+ selectedElementIds: { [element.id]: true },
+ newElement: null,
+ selectionElement: null,
+ });
+ }, 100);
+
+ if (isIframeElement(element)) {
+ return;
+ }
+
+ const iframe = this.getHTMLIFrameElement(element);
+
+ if (!iframe?.contentWindow) {
+ return;
+ }
+
+ if (iframe.src.includes("youtube")) {
+ const state = YOUTUBE_VIDEO_STATES.get(element.id);
+ if (!state) {
+ YOUTUBE_VIDEO_STATES.set(element.id, YOUTUBE_STATES.UNSTARTED);
+ iframe.contentWindow.postMessage(
+ JSON.stringify({
+ event: "listening",
+ id: element.id,
+ }),
+ "*",
+ );
+ }
+ switch (state) {
+ case YOUTUBE_STATES.PLAYING:
+ case YOUTUBE_STATES.BUFFERING:
+ iframe.contentWindow?.postMessage(
+ JSON.stringify({
+ event: "command",
+ func: "pauseVideo",
+ args: "",
+ }),
+ "*",
+ );
+ break;
+ default:
+ iframe.contentWindow?.postMessage(
+ JSON.stringify({
+ event: "command",
+ func: "playVideo",
+ args: "",
+ }),
+ "*",
+ );
+ }
+ }
+
+ if (iframe.src.includes("player.vimeo.com")) {
+ iframe.contentWindow.postMessage(
+ JSON.stringify({
+ method: "paused", //video play/pause in onWindowMessage handler
+ }),
+ "*",
+ );
+ }
+ }
+
+ private isIframeLikeElementCenter(
+ el: ExcalidrawIframeLikeElement | null,
+ event: React.PointerEvent<HTMLElement> | PointerEvent,
+ sceneX: number,
+ sceneY: number,
+ ) {
+ return (
+ el &&
+ !event.altKey &&
+ !event.shiftKey &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ (this.state.activeEmbeddable?.element !== el ||
+ this.state.activeEmbeddable?.state === "hover" ||
+ !this.state.activeEmbeddable) &&
+ sceneX >= el.x + el.width / 3 &&
+ sceneX <= el.x + (2 * el.width) / 3 &&
+ sceneY >= el.y + el.height / 3 &&
+ sceneY <= el.y + (2 * el.height) / 3
+ );
+ }
+
+ private updateEmbedValidationStatus = (
+ element: ExcalidrawEmbeddableElement,
+ status: boolean,
+ ) => {
+ this.embedsValidationStatus.set(element.id, status);
+ ShapeCache.delete(element);
+ };
+
+ private updateEmbeddables = () => {
+ const iframeLikes = new Set<ExcalidrawIframeLikeElement["id"]>();
+
+ let updated = false;
+ this.scene.getNonDeletedElements().filter((element) => {
+ if (isEmbeddableElement(element)) {
+ iframeLikes.add(element.id);
+ if (!this.embedsValidationStatus.has(element.id)) {
+ updated = true;
+
+ const validated = embeddableURLValidator(
+ element.link,
+ this.props.validateEmbeddable,
+ );
+
+ this.updateEmbedValidationStatus(element, validated);
+ }
+ } else if (isIframeElement(element)) {
+ iframeLikes.add(element.id);
+ }
+ return false;
+ });
+
+ if (updated) {
+ this.scene.triggerUpdate();
+ }
+
+ // GC
+ this.iFrameRefs.forEach((ref, id) => {
+ if (!iframeLikes.has(id)) {
+ this.iFrameRefs.delete(id);
+ }
+ });
+ };
+
+ private renderEmbeddables() {
+ const scale = this.state.zoom.value;
+ const normalizedWidth = this.state.width;
+ const normalizedHeight = this.state.height;
+
+ const embeddableElements = this.scene
+ .getNonDeletedElements()
+ .filter(
+ (el): el is Ordered<NonDeleted<ExcalidrawIframeLikeElement>> =>
+ (isEmbeddableElement(el) &&
+ this.embedsValidationStatus.get(el.id) === true) ||
+ isIframeElement(el),
+ );
+
+ return (
+ <>
+ {embeddableElements.map((el) => {
+ const { x, y } = sceneCoordsToViewportCoords(
+ { sceneX: el.x, sceneY: el.y },
+ this.state,
+ );
+
+ const isVisible = isElementInViewport(
+ el,
+ normalizedWidth,
+ normalizedHeight,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ const hasBeenInitialized = this.initializedEmbeds.has(el.id);
+
+ if (isVisible && !hasBeenInitialized) {
+ this.initializedEmbeds.add(el.id);
+ }
+ const shouldRender = isVisible || hasBeenInitialized;
+
+ if (!shouldRender) {
+ return null;
+ }
+
+ let src: IframeData | null;
+
+ if (isIframeElement(el)) {
+ src = null;
+
+ const data: MagicGenerationData = (el.customData?.generationData ??
+ this.magicGenerations.get(el.id)) || {
+ status: "error",
+ message: "No generation data",
+ code: "ERR_NO_GENERATION_DATA",
+ };
+
+ if (data.status === "done") {
+ const html = data.html;
+ src = {
+ intrinsicSize: { w: el.width, h: el.height },
+ type: "document",
+ srcdoc: () => {
+ return html;
+ },
+ } as const;
+ } else if (data.status === "pending") {
+ src = {
+ intrinsicSize: { w: el.width, h: el.height },
+ type: "document",
+ srcdoc: () => {
+ return createSrcDoc(`
+ <style>
+ html, body {
+ width: 100%;
+ height: 100%;
+ color: ${
+ this.state.theme === THEME.DARK ? "white" : "black"
+ };
+ }
+ body {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-direction: column;
+ gap: 1rem;
+ }
+
+ .Spinner {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ margin-left: auto;
+ margin-right: auto;
+ }
+
+ .Spinner svg {
+ animation: rotate 1.6s linear infinite;
+ transform-origin: center center;
+ width: 40px;
+ height: 40px;
+ }
+
+ .Spinner circle {
+ stroke: currentColor;
+ animation: dash 1.6s linear 0s infinite;
+ stroke-linecap: round;
+ }
+
+ @keyframes rotate {
+ 100% {
+ transform: rotate(360deg);
+ }
+ }
+
+ @keyframes dash {
+ 0% {
+ stroke-dasharray: 1, 300;
+ stroke-dashoffset: 0;
+ }
+ 50% {
+ stroke-dasharray: 150, 300;
+ stroke-dashoffset: -200;
+ }
+ 100% {
+ stroke-dasharray: 1, 300;
+ stroke-dashoffset: -280;
+ }
+ }
+ </style>
+ <div class="Spinner">
+ <svg
+ viewBox="0 0 100 100"
+ >
+ <circle
+ cx="50"
+ cy="50"
+ r="46"
+ stroke-width="8"
+ fill="none"
+ stroke-miter-limit="10"
+ />
+ </svg>
+ </div>
+ <div>Generating...</div>
+ `);
+ },
+ } as const;
+ } else {
+ let message: string;
+ if (data.code === "ERR_GENERATION_INTERRUPTED") {
+ message = "Generation was interrupted...";
+ } else {
+ message = data.message || "Generation failed";
+ }
+ src = {
+ intrinsicSize: { w: el.width, h: el.height },
+ type: "document",
+ srcdoc: () => {
+ return createSrcDoc(`
+ <style>
+ html, body {
+ height: 100%;
+ }
+ body {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ color: ${COLOR_PALETTE.red[3]};
+ }
+ h1, h3 {
+ margin-top: 0;
+ margin-bottom: 0.5rem;
+ }
+ </style>
+ <h1>Error!</h1>
+ <h3>${message}</h3>
+ `);
+ },
+ } as const;
+ }
+ } else {
+ src = getEmbedLink(toValidURL(el.link || ""));
+ }
+
+ const isActive =
+ this.state.activeEmbeddable?.element === el &&
+ this.state.activeEmbeddable?.state === "active";
+ const isHovered =
+ this.state.activeEmbeddable?.element === el &&
+ this.state.activeEmbeddable?.state === "hover";
+
+ return (
+ <div
+ key={el.id}
+ className={clsx("excalidraw__embeddable-container", {
+ "is-hovered": isHovered,
+ })}
+ style={{
+ transform: isVisible
+ ? `translate(${x - this.state.offsetLeft}px, ${
+ y - this.state.offsetTop
+ }px) scale(${scale})`
+ : "none",
+ display: isVisible ? "block" : "none",
+ opacity: getRenderOpacity(
+ el,
+ getContainingFrame(el, this.scene.getNonDeletedElementsMap()),
+ this.elementsPendingErasure,
+ null,
+ this.state.openDialog?.name === "elementLinkSelector"
+ ? DEFAULT_REDUCED_GLOBAL_ALPHA
+ : 1,
+ ),
+ ["--embeddable-radius" as string]: `${getCornerRadius(
+ Math.min(el.width, el.height),
+ el,
+ )}px`,
+ }}
+ >
+ <div
+ //this is a hack that addresses isse with embedded excalidraw.com embeddable
+ //https://github.com/excalidraw/excalidraw/pull/6691#issuecomment-1607383938
+ /*ref={(ref) => {
+ if (!this.excalidrawContainerRef.current) {
+ return;
+ }
+ const container = this.excalidrawContainerRef.current;
+ const sh = container.scrollHeight;
+ const ch = container.clientHeight;
+ if (sh !== ch) {
+ container.style.height = `${sh}px`;
+ setTimeout(() => {
+ container.style.height = `100%`;
+ });
+ }
+ }}*/
+ className="excalidraw__embeddable-container__inner"
+ style={{
+ width: isVisible ? `${el.width}px` : 0,
+ height: isVisible ? `${el.height}px` : 0,
+ transform: isVisible ? `rotate(${el.angle}rad)` : "none",
+ pointerEvents: isActive
+ ? POINTER_EVENTS.enabled
+ : POINTER_EVENTS.disabled,
+ }}
+ >
+ {isHovered && (
+ <div className="excalidraw__embeddable-hint">
+ {t("buttons.embeddableInteractionButton")}
+ </div>
+ )}
+ <div
+ className="excalidraw__embeddable__outer"
+ style={{
+ padding: `${el.strokeWidth}px`,
+ }}
+ >
+ {(isEmbeddableElement(el)
+ ? this.props.renderEmbeddable?.(el, this.state)
+ : null) ?? (
+ <iframe
+ ref={(ref) => this.cacheEmbeddableRef(el, ref)}
+ className="excalidraw__embeddable"
+ srcDoc={
+ src?.type === "document"
+ ? src.srcdoc(this.state.theme)
+ : undefined
+ }
+ src={
+ src?.type !== "document" ? src?.link ?? "" : undefined
+ }
+ // https://stackoverflow.com/q/18470015
+ scrolling="no"
+ referrerPolicy="no-referrer-when-downgrade"
+ title="Excalidraw Embedded Content"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowFullScreen={true}
+ sandbox={`${
+ src?.sandbox?.allowSameOrigin ? "allow-same-origin" : ""
+ } allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation allow-downloads`}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </>
+ );
+ }
+
+ private getFrameNameDOMId = (frameElement: ExcalidrawElement) => {
+ return `${this.id}-frame-name-${frameElement.id}`;
+ };
+
+ frameNameBoundsCache: FrameNameBoundsCache = {
+ get: (frameElement) => {
+ let bounds = this.frameNameBoundsCache._cache.get(frameElement.id);
+ if (
+ !bounds ||
+ bounds.zoom !== this.state.zoom.value ||
+ bounds.versionNonce !== frameElement.versionNonce
+ ) {
+ const frameNameDiv = document.getElementById(
+ this.getFrameNameDOMId(frameElement),
+ );
+
+ if (frameNameDiv) {
+ const box = frameNameDiv.getBoundingClientRect();
+ const boxSceneTopLeft = viewportCoordsToSceneCoords(
+ { clientX: box.x, clientY: box.y },
+ this.state,
+ );
+ const boxSceneBottomRight = viewportCoordsToSceneCoords(
+ { clientX: box.right, clientY: box.bottom },
+ this.state,
+ );
+
+ bounds = {
+ x: boxSceneTopLeft.x,
+ y: boxSceneTopLeft.y,
+ width: boxSceneBottomRight.x - boxSceneTopLeft.x,
+ height: boxSceneBottomRight.y - boxSceneTopLeft.y,
+ angle: 0,
+ zoom: this.state.zoom.value,
+ versionNonce: frameElement.versionNonce,
+ };
+
+ this.frameNameBoundsCache._cache.set(frameElement.id, bounds);
+
+ return bounds;
+ }
+ return null;
+ }
+
+ return bounds;
+ },
+ /**
+ * @private
+ */
+ _cache: new Map(),
+ };
+
+ private resetEditingFrame = (frame: ExcalidrawFrameLikeElement | null) => {
+ if (frame) {
+ mutateElement(frame, { name: frame.name?.trim() || null });
+ }
+ this.setState({ editingFrame: null });
+ };
+
+ private renderFrameNames = () => {
+ if (!this.state.frameRendering.enabled || !this.state.frameRendering.name) {
+ if (this.state.editingFrame) {
+ this.resetEditingFrame(null);
+ }
+ return null;
+ }
+
+ const isDarkTheme = this.state.theme === THEME.DARK;
+
+ return this.scene.getNonDeletedFramesLikes().map((f) => {
+ if (
+ !isElementInViewport(
+ f,
+ this.canvas.width / window.devicePixelRatio,
+ this.canvas.height / window.devicePixelRatio,
+ {
+ offsetLeft: this.state.offsetLeft,
+ offsetTop: this.state.offsetTop,
+ scrollX: this.state.scrollX,
+ scrollY: this.state.scrollY,
+ zoom: this.state.zoom,
+ },
+ this.scene.getNonDeletedElementsMap(),
+ )
+ ) {
+ if (this.state.editingFrame === f.id) {
+ this.resetEditingFrame(f);
+ }
+ // if frame not visible, don't render its name
+ return null;
+ }
+
+ const { x: x1, y: y1 } = sceneCoordsToViewportCoords(
+ { sceneX: f.x, sceneY: f.y },
+ this.state,
+ );
+
+ const FRAME_NAME_EDIT_PADDING = 6;
+
+ let frameNameJSX;
+
+ const frameName = getFrameLikeTitle(f);
+
+ if (f.id === this.state.editingFrame) {
+ const frameNameInEdit = frameName;
+
+ frameNameJSX = (
+ <input
+ autoFocus
+ value={frameNameInEdit}
+ onChange={(e) => {
+ mutateElement(f, {
+ name: e.target.value,
+ });
+ }}
+ onFocus={(e) => e.target.select()}
+ onBlur={() => this.resetEditingFrame(f)}
+ onKeyDown={(event) => {
+ // for some inexplicable reason, `onBlur` triggered on ESC
+ // does not reset `state.editingFrame` despite being called,
+ // and we need to reset it here as well
+ if (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) {
+ this.resetEditingFrame(f);
+ }
+ }}
+ style={{
+ background: this.state.viewBackgroundColor,
+ filter: isDarkTheme ? THEME_FILTER : "none",
+ zIndex: 2,
+ border: "none",
+ display: "block",
+ padding: `${FRAME_NAME_EDIT_PADDING}px`,
+ borderRadius: 4,
+ boxShadow: "inset 0 0 0 1px var(--color-primary)",
+ fontFamily: "Assistant",
+ fontSize: "14px",
+ transform: `translate(-${FRAME_NAME_EDIT_PADDING}px, ${FRAME_NAME_EDIT_PADDING}px)`,
+ color: "var(--color-gray-80)",
+ overflow: "hidden",
+ maxWidth: `${
+ document.body.clientWidth - x1 - FRAME_NAME_EDIT_PADDING
+ }px`,
+ }}
+ size={frameNameInEdit.length + 1 || 1}
+ dir="auto"
+ autoComplete="off"
+ autoCapitalize="off"
+ autoCorrect="off"
+ />
+ );
+ } else {
+ frameNameJSX = frameName;
+ }
+
+ return (
+ <div
+ id={this.getFrameNameDOMId(f)}
+ key={f.id}
+ style={{
+ position: "absolute",
+ // Positioning from bottom so that we don't to either
+ // calculate text height or adjust using transform (which)
+ // messes up input position when editing the frame name.
+ // This makes the positioning deterministic and we can calculate
+ // the same position when rendering to canvas / svg.
+ bottom: `${
+ this.state.height +
+ FRAME_STYLE.nameOffsetY -
+ y1 +
+ this.state.offsetTop
+ }px`,
+ left: `${x1 - this.state.offsetLeft}px`,
+ zIndex: 2,
+ fontSize: FRAME_STYLE.nameFontSize,
+ color: isDarkTheme
+ ? FRAME_STYLE.nameColorDarkTheme
+ : FRAME_STYLE.nameColorLightTheme,
+ lineHeight: FRAME_STYLE.nameLineHeight,
+ width: "max-content",
+ maxWidth: `${f.width}px`,
+ overflow: f.id === this.state.editingFrame ? "visible" : "hidden",
+ whiteSpace: "nowrap",
+ textOverflow: "ellipsis",
+ cursor: CURSOR_TYPE.MOVE,
+ pointerEvents: this.state.viewModeEnabled
+ ? POINTER_EVENTS.disabled
+ : POINTER_EVENTS.enabled,
+ }}
+ onPointerDown={(event) => this.handleCanvasPointerDown(event)}
+ onWheel={(event) => this.handleWheel(event)}
+ onContextMenu={this.handleCanvasContextMenu}
+ onDoubleClick={() => {
+ this.setState({
+ editingFrame: f.id,
+ });
+ }}
+ >
+ {frameNameJSX}
+ </div>
+ );
+ });
+ };
+
+ private toggleOverscrollBehavior(event: React.PointerEvent) {
+ // when pointer inside editor, disable overscroll behavior to prevent
+ // panning to trigger history back/forward on MacOS Chrome
+ document.documentElement.style.overscrollBehaviorX =
+ event.type === "pointerenter" ? "none" : "auto";
+ }
+
+ public render() {
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ const { renderTopRightUI, renderCustomStats } = this.props;
+
+ const sceneNonce = this.scene.getSceneNonce();
+ const { elementsMap, visibleElements } =
+ this.renderer.getRenderableElements({
+ sceneNonce,
+ zoom: this.state.zoom,
+ offsetLeft: this.state.offsetLeft,
+ offsetTop: this.state.offsetTop,
+ scrollX: this.state.scrollX,
+ scrollY: this.state.scrollY,
+ height: this.state.height,
+ width: this.state.width,
+ editingTextElement: this.state.editingTextElement,
+ newElementId: this.state.newElement?.id,
+ pendingImageElementId: this.state.pendingImageElementId,
+ });
+ this.visibleElements = visibleElements;
+
+ const allElementsMap = this.scene.getNonDeletedElementsMap();
+
+ const shouldBlockPointerEvents =
+ // default back to `--ui-pointerEvents` flow if setPointerCapture
+ // not supported
+ "setPointerCapture" in HTMLElement.prototype
+ ? false
+ : this.state.selectionElement ||
+ this.state.newElement ||
+ this.state.selectedElementsAreBeingDragged ||
+ this.state.resizingElement ||
+ (this.state.activeTool.type === "laser" &&
+ // technically we can just test on this once we make it more safe
+ this.state.cursorButton === "down");
+
+ const firstSelectedElement = selectedElements[0];
+
+ return (
+ <div
+ className={clsx("excalidraw excalidraw-container", {
+ "excalidraw--view-mode":
+ this.state.viewModeEnabled ||
+ this.state.openDialog?.name === "elementLinkSelector",
+ "excalidraw--mobile": this.device.editor.isMobile,
+ })}
+ style={{
+ ["--ui-pointerEvents" as any]: shouldBlockPointerEvents
+ ? POINTER_EVENTS.disabled
+ : POINTER_EVENTS.enabled,
+ ["--right-sidebar-width" as any]: "302px",
+ }}
+ ref={this.excalidrawContainerRef}
+ onDrop={this.handleAppOnDrop}
+ tabIndex={0}
+ onKeyDown={
+ this.props.handleKeyboardGlobally ? undefined : this.onKeyDown
+ }
+ onPointerEnter={this.toggleOverscrollBehavior}
+ onPointerLeave={this.toggleOverscrollBehavior}
+ >
+ <AppContext.Provider value={this}>
+ <AppPropsContext.Provider value={this.props}>
+ <ExcalidrawContainerContext.Provider
+ value={this.excalidrawContainerValue}
+ >
+ <DeviceContext.Provider value={this.device}>
+ <ExcalidrawSetAppStateContext.Provider value={this.setAppState}>
+ <ExcalidrawAppStateContext.Provider value={this.state}>
+ <ExcalidrawElementsContext.Provider
+ value={this.scene.getNonDeletedElements()}
+ >
+ <ExcalidrawActionManagerContext.Provider
+ value={this.actionManager}
+ >
+ <LayerUI
+ canvas={this.canvas}
+ appState={this.state}
+ files={this.files}
+ setAppState={this.setAppState}
+ actionManager={this.actionManager}
+ elements={this.scene.getNonDeletedElements()}
+ onLockToggle={this.toggleLock}
+ onPenModeToggle={this.togglePenMode}
+ onHandToolToggle={this.onHandToolToggle}
+ langCode={getLanguage().code}
+ renderTopRightUI={renderTopRightUI}
+ renderCustomStats={renderCustomStats}
+ showExitZenModeBtn={
+ typeof this.props?.zenModeEnabled === "undefined" &&
+ this.state.zenModeEnabled
+ }
+ UIOptions={this.props.UIOptions}
+ onExportImage={this.onExportImage}
+ renderWelcomeScreen={
+ !this.state.isLoading &&
+ this.state.showWelcomeScreen &&
+ this.state.activeTool.type === "selection" &&
+ !this.state.zenModeEnabled &&
+ !this.scene.getElementsIncludingDeleted().length
+ }
+ app={this}
+ isCollaborating={this.props.isCollaborating}
+ generateLinkForSelection={
+ this.props.generateLinkForSelection
+ }
+ >
+ {this.props.children}
+ </LayerUI>
+
+ <div className="excalidraw-textEditorContainer" />
+ <div className="excalidraw-contextMenuContainer" />
+ <div className="excalidraw-eye-dropper-container" />
+ <SVGLayer
+ trails={[this.laserTrails, this.eraserTrail]}
+ />
+ {selectedElements.length === 1 &&
+ this.state.openDialog?.name !==
+ "elementLinkSelector" &&
+ this.state.showHyperlinkPopup && (
+ <Hyperlink
+ key={firstSelectedElement.id}
+ element={firstSelectedElement}
+ elementsMap={allElementsMap}
+ setAppState={this.setAppState}
+ onLinkOpen={this.props.onLinkOpen}
+ setToast={this.setToast}
+ updateEmbedValidationStatus={
+ this.updateEmbedValidationStatus
+ }
+ />
+ )}
+ {this.props.aiEnabled !== false &&
+ selectedElements.length === 1 &&
+ isMagicFrameElement(firstSelectedElement) && (
+ <ElementCanvasButtons
+ element={firstSelectedElement}
+ elementsMap={elementsMap}
+ >
+ <ElementCanvasButton
+ title={t("labels.convertToCode")}
+ icon={MagicIcon}
+ checked={false}
+ onChange={() =>
+ this.onMagicFrameGenerate(
+ firstSelectedElement,
+ "button",
+ )
+ }
+ />
+ </ElementCanvasButtons>
+ )}
+ {selectedElements.length === 1 &&
+ isIframeElement(firstSelectedElement) &&
+ firstSelectedElement.customData?.generationData
+ ?.status === "done" && (
+ <ElementCanvasButtons
+ element={firstSelectedElement}
+ elementsMap={elementsMap}
+ >
+ <ElementCanvasButton
+ title={t("labels.copySource")}
+ icon={copyIcon}
+ checked={false}
+ onChange={() =>
+ this.onIframeSrcCopy(firstSelectedElement)
+ }
+ />
+ <ElementCanvasButton
+ title="Enter fullscreen"
+ icon={fullscreenIcon}
+ checked={false}
+ onChange={() => {
+ const iframe =
+ this.getHTMLIFrameElement(
+ firstSelectedElement,
+ );
+ if (iframe) {
+ try {
+ iframe.requestFullscreen();
+ this.setState({
+ activeEmbeddable: {
+ element: firstSelectedElement,
+ state: "active",
+ },
+ selectedElementIds: {
+ [firstSelectedElement.id]: true,
+ },
+ newElement: null,
+ selectionElement: null,
+ });
+ } catch (err: any) {
+ console.warn(err);
+ this.setState({
+ errorMessage:
+ "Couldn't enter fullscreen",
+ });
+ }
+ }
+ }}
+ />
+ </ElementCanvasButtons>
+ )}
+ {this.state.toast !== null && (
+ <Toast
+ message={this.state.toast.message}
+ onClose={() => this.setToast(null)}
+ duration={this.state.toast.duration}
+ closable={this.state.toast.closable}
+ />
+ )}
+ {this.state.contextMenu && (
+ <ContextMenu
+ items={this.state.contextMenu.items}
+ top={this.state.contextMenu.top}
+ left={this.state.contextMenu.left}
+ actionManager={this.actionManager}
+ onClose={(callback) => {
+ this.setState({ contextMenu: null }, () => {
+ this.focusContainer();
+ callback?.();
+ });
+ }}
+ />
+ )}
+ <StaticCanvas
+ canvas={this.canvas}
+ rc={this.rc}
+ elementsMap={elementsMap}
+ allElementsMap={allElementsMap}
+ visibleElements={visibleElements}
+ sceneNonce={sceneNonce}
+ selectionNonce={
+ this.state.selectionElement?.versionNonce
+ }
+ scale={window.devicePixelRatio}
+ appState={this.state}
+ renderConfig={{
+ imageCache: this.imageCache,
+ isExporting: false,
+ renderGrid: isGridModeEnabled(this),
+ canvasBackgroundColor:
+ this.state.viewBackgroundColor,
+ embedsValidationStatus: this.embedsValidationStatus,
+ elementsPendingErasure: this.elementsPendingErasure,
+ pendingFlowchartNodes:
+ this.flowChartCreator.pendingNodes,
+ }}
+ />
+ {this.state.newElement && (
+ <NewElementCanvas
+ appState={this.state}
+ scale={window.devicePixelRatio}
+ rc={this.rc}
+ elementsMap={elementsMap}
+ allElementsMap={allElementsMap}
+ renderConfig={{
+ imageCache: this.imageCache,
+ isExporting: false,
+ renderGrid: false,
+ canvasBackgroundColor:
+ this.state.viewBackgroundColor,
+ embedsValidationStatus:
+ this.embedsValidationStatus,
+ elementsPendingErasure:
+ this.elementsPendingErasure,
+ pendingFlowchartNodes: null,
+ }}
+ />
+ )}
+ <InteractiveCanvas
+ containerRef={this.excalidrawContainerRef}
+ canvas={this.interactiveCanvas}
+ elementsMap={elementsMap}
+ visibleElements={visibleElements}
+ allElementsMap={allElementsMap}
+ selectedElements={selectedElements}
+ sceneNonce={sceneNonce}
+ selectionNonce={
+ this.state.selectionElement?.versionNonce
+ }
+ scale={window.devicePixelRatio}
+ appState={this.state}
+ device={this.device}
+ renderInteractiveSceneCallback={
+ this.renderInteractiveSceneCallback
+ }
+ handleCanvasRef={this.handleInteractiveCanvasRef}
+ onContextMenu={this.handleCanvasContextMenu}
+ onPointerMove={this.handleCanvasPointerMove}
+ onPointerUp={this.handleCanvasPointerUp}
+ onPointerCancel={this.removePointer}
+ onTouchMove={this.handleTouchMove}
+ onPointerDown={this.handleCanvasPointerDown}
+ onDoubleClick={this.handleCanvasDoubleClick}
+ />
+ {this.state.userToFollow && (
+ <FollowMode
+ width={this.state.width}
+ height={this.state.height}
+ userToFollow={this.state.userToFollow}
+ onDisconnect={this.maybeUnfollowRemoteUser}
+ />
+ )}
+ {this.renderFrameNames()}
+ </ExcalidrawActionManagerContext.Provider>
+ {this.renderEmbeddables()}
+ </ExcalidrawElementsContext.Provider>
+ </ExcalidrawAppStateContext.Provider>
+ </ExcalidrawSetAppStateContext.Provider>
+ </DeviceContext.Provider>
+ </ExcalidrawContainerContext.Provider>
+ </AppPropsContext.Provider>
+ </AppContext.Provider>
+ </div>
+ );
+ }
+
+ public focusContainer: AppClassProperties["focusContainer"] = () => {
+ this.excalidrawContainerRef.current?.focus();
+ };
+
+ public getSceneElementsIncludingDeleted = () => {
+ return this.scene.getElementsIncludingDeleted();
+ };
+
+ public getSceneElements = () => {
+ return this.scene.getNonDeletedElements();
+ };
+
+ public onInsertElements = (elements: readonly ExcalidrawElement[]) => {
+ this.addElementsFromPasteOrLibrary({
+ elements,
+ position: "center",
+ files: null,
+ });
+ };
+
+ public onExportImage = async (
+ type: keyof typeof EXPORT_IMAGE_TYPES,
+ elements: ExportedElements,
+ opts: { exportingFrame: ExcalidrawFrameLikeElement | null },
+ ) => {
+ trackEvent("export", type, "ui");
+ const fileHandle = await exportCanvas(
+ type,
+ elements,
+ this.state,
+ this.files,
+ {
+ exportBackground: this.state.exportBackground,
+ name: this.getName(),
+ viewBackgroundColor: this.state.viewBackgroundColor,
+ exportingFrame: opts.exportingFrame,
+ },
+ )
+ .catch(muteFSAbortError)
+ .catch((error) => {
+ console.error(error);
+ this.setState({ errorMessage: error.message });
+ });
+
+ if (
+ this.state.exportEmbedScene &&
+ fileHandle &&
+ isImageFileHandle(fileHandle)
+ ) {
+ this.setState({ fileHandle });
+ }
+ };
+
+ private magicGenerations = new Map<
+ ExcalidrawIframeElement["id"],
+ MagicGenerationData
+ >();
+
+ private updateMagicGeneration = ({
+ frameElement,
+ data,
+ }: {
+ frameElement: ExcalidrawIframeElement;
+ data: MagicGenerationData;
+ }) => {
+ if (data.status === "pending") {
+ // We don't wanna persist pending state to storage. It should be in-app
+ // state only.
+ // Thus reset so that we prefer local cache (if there was some
+ // generationData set previously)
+ mutateElement(
+ frameElement,
+ { customData: { generationData: undefined } },
+ false,
+ );
+ } else {
+ mutateElement(
+ frameElement,
+ { customData: { generationData: data } },
+ false,
+ );
+ }
+ this.magicGenerations.set(frameElement.id, data);
+ this.triggerRender();
+ };
+
+ public plugins: {
+ diagramToCode?: {
+ generate: GenerateDiagramToCode;
+ };
+ } = {};
+
+ public setPlugins(plugins: Partial<App["plugins"]>) {
+ Object.assign(this.plugins, plugins);
+ }
+
+ private async onMagicFrameGenerate(
+ magicFrame: ExcalidrawMagicFrameElement,
+ source: "button" | "upstream",
+ ) {
+ const generateDiagramToCode = this.plugins.diagramToCode?.generate;
+
+ if (!generateDiagramToCode) {
+ this.setState({
+ errorMessage: "No diagram to code plugin found",
+ });
+ return;
+ }
+
+ const magicFrameChildren = getElementsOverlappingFrame(
+ this.scene.getNonDeletedElements(),
+ magicFrame,
+ ).filter((el) => !isMagicFrameElement(el));
+
+ if (!magicFrameChildren.length) {
+ if (source === "button") {
+ this.setState({ errorMessage: "Cannot generate from an empty frame" });
+ trackEvent("ai", "generate (no-children)", "d2c");
+ } else {
+ this.setActiveTool({ type: "magicframe" });
+ }
+ return;
+ }
+
+ const frameElement = this.insertIframeElement({
+ sceneX: magicFrame.x + magicFrame.width + 30,
+ sceneY: magicFrame.y,
+ width: magicFrame.width,
+ height: magicFrame.height,
+ });
+
+ if (!frameElement) {
+ return;
+ }
+
+ this.updateMagicGeneration({
+ frameElement,
+ data: { status: "pending" },
+ });
+
+ this.setState({
+ selectedElementIds: { [frameElement.id]: true },
+ });
+
+ trackEvent("ai", "generate (start)", "d2c");
+ try {
+ const { html } = await generateDiagramToCode({
+ frame: magicFrame,
+ children: magicFrameChildren,
+ });
+
+ trackEvent("ai", "generate (success)", "d2c");
+
+ if (!html.trim()) {
+ this.updateMagicGeneration({
+ frameElement,
+ data: {
+ status: "error",
+ code: "ERR_OAI",
+ message: "Nothing genereated :(",
+ },
+ });
+ return;
+ }
+
+ const parsedHtml =
+ html.includes("<!DOCTYPE html>") && html.includes("</html>")
+ ? html.slice(
+ html.indexOf("<!DOCTYPE html>"),
+ html.indexOf("</html>") + "</html>".length,
+ )
+ : html;
+
+ this.updateMagicGeneration({
+ frameElement,
+ data: { status: "done", html: parsedHtml },
+ });
+ } catch (error: any) {
+ trackEvent("ai", "generate (failed)", "d2c");
+ this.updateMagicGeneration({
+ frameElement,
+ data: {
+ status: "error",
+ code: "ERR_OAI",
+ message: error.message || "Unknown error during generation",
+ },
+ });
+ }
+ }
+
+ private onIframeSrcCopy(element: ExcalidrawIframeElement) {
+ if (element.customData?.generationData?.status === "done") {
+ copyTextToSystemClipboard(element.customData.generationData.html);
+ this.setToast({
+ message: "copied to clipboard",
+ closable: false,
+ duration: 1500,
+ });
+ }
+ }
+
+ public onMagicframeToolSelect = () => {
+ const selectedElements = this.scene.getSelectedElements({
+ selectedElementIds: this.state.selectedElementIds,
+ });
+
+ if (selectedElements.length === 0) {
+ this.setActiveTool({ type: TOOL_TYPE.magicframe });
+ trackEvent("ai", "tool-select (empty-selection)", "d2c");
+ } else {
+ const selectedMagicFrame: ExcalidrawMagicFrameElement | false =
+ selectedElements.length === 1 &&
+ isMagicFrameElement(selectedElements[0]) &&
+ selectedElements[0];
+
+ // case: user selected elements containing frame-like(s) or are frame
+ // members, we don't want to wrap into another magicframe
+ // (unless the only selected element is a magic frame which we reuse)
+ if (
+ !selectedMagicFrame &&
+ selectedElements.some((el) => isFrameLikeElement(el) || el.frameId)
+ ) {
+ this.setActiveTool({ type: TOOL_TYPE.magicframe });
+ return;
+ }
+
+ trackEvent("ai", "tool-select (existing selection)", "d2c");
+
+ let frame: ExcalidrawMagicFrameElement;
+ if (selectedMagicFrame) {
+ // a single magicframe already selected -> use it
+ frame = selectedMagicFrame;
+ } else {
+ // selected elements aren't wrapped in magic frame yet -> wrap now
+
+ const [minX, minY, maxX, maxY] = getCommonBounds(selectedElements);
+ const padding = 50;
+
+ frame = newMagicFrameElement({
+ ...FRAME_STYLE,
+ x: minX - padding,
+ y: minY - padding,
+ width: maxX - minX + padding * 2,
+ height: maxY - minY + padding * 2,
+ opacity: 100,
+ locked: false,
+ });
+
+ this.scene.insertElement(frame);
+
+ for (const child of selectedElements) {
+ mutateElement(child, { frameId: frame.id });
+ }
+
+ this.setState({
+ selectedElementIds: { [frame.id]: true },
+ });
+ }
+
+ this.onMagicFrameGenerate(frame, "upstream");
+ }
+ };
+
+ private openEyeDropper = ({ type }: { type: "stroke" | "background" }) => {
+ editorJotaiStore.set(activeEyeDropperAtom, {
+ swapPreviewOnAlt: true,
+ colorPickerType:
+ type === "stroke" ? "elementStroke" : "elementBackground",
+ onSelect: (color, event) => {
+ const shouldUpdateStrokeColor =
+ (type === "background" && event.altKey) ||
+ (type === "stroke" && !event.altKey);
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ if (
+ !selectedElements.length ||
+ this.state.activeTool.type !== "selection"
+ ) {
+ if (shouldUpdateStrokeColor) {
+ this.syncActionResult({
+ appState: { ...this.state, currentItemStrokeColor: color },
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+ } else {
+ this.syncActionResult({
+ appState: { ...this.state, currentItemBackgroundColor: color },
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+ }
+ } else {
+ this.updateScene({
+ elements: this.scene.getElementsIncludingDeleted().map((el) => {
+ if (this.state.selectedElementIds[el.id]) {
+ return newElementWith(el, {
+ [shouldUpdateStrokeColor ? "strokeColor" : "backgroundColor"]:
+ color,
+ });
+ }
+ return el;
+ }),
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+ }
+ },
+ keepOpenOnAlt: false,
+ });
+ };
+
+ public dismissLinearEditor = () => {
+ setTimeout(() => {
+ this.setState({
+ editingLinearElement: null,
+ });
+ });
+ };
+
+ public syncActionResult = withBatchedUpdates((actionResult: ActionResult) => {
+ if (this.unmounted || actionResult === false) {
+ return;
+ }
+
+ if (actionResult.captureUpdate === CaptureUpdateAction.NEVER) {
+ this.store.shouldUpdateSnapshot();
+ } else if (actionResult.captureUpdate === CaptureUpdateAction.IMMEDIATELY) {
+ this.store.shouldCaptureIncrement();
+ }
+
+ let didUpdate = false;
+
+ let editingTextElement: AppState["editingTextElement"] | null = null;
+ if (actionResult.elements) {
+ this.scene.replaceAllElements(actionResult.elements);
+ didUpdate = true;
+ }
+
+ if (actionResult.files) {
+ this.addMissingFiles(actionResult.files, actionResult.replaceFiles);
+ this.addNewImagesToImageCache();
+ }
+
+ if (actionResult.appState || editingTextElement || this.state.contextMenu) {
+ let viewModeEnabled = actionResult?.appState?.viewModeEnabled || false;
+ let zenModeEnabled = actionResult?.appState?.zenModeEnabled || false;
+ const theme =
+ actionResult?.appState?.theme || this.props.theme || THEME.LIGHT;
+ const name = actionResult?.appState?.name ?? this.state.name;
+ const errorMessage =
+ actionResult?.appState?.errorMessage ?? this.state.errorMessage;
+ if (typeof this.props.viewModeEnabled !== "undefined") {
+ viewModeEnabled = this.props.viewModeEnabled;
+ }
+
+ if (typeof this.props.zenModeEnabled !== "undefined") {
+ zenModeEnabled = this.props.zenModeEnabled;
+ }
+
+ editingTextElement = actionResult.appState?.editingTextElement || null;
+
+ // make sure editingTextElement points to latest element reference
+ if (actionResult.elements && editingTextElement) {
+ actionResult.elements.forEach((element) => {
+ if (
+ editingTextElement?.id === element.id &&
+ editingTextElement !== element &&
+ isNonDeletedElement(element) &&
+ isTextElement(element)
+ ) {
+ editingTextElement = element;
+ }
+ });
+ }
+
+ if (editingTextElement?.isDeleted) {
+ editingTextElement = null;
+ }
+
+ this.setState((prevAppState) => {
+ const actionAppState = actionResult.appState || {};
+
+ return {
+ ...prevAppState,
+ ...actionAppState,
+ // NOTE this will prevent opening context menu using an action
+ // or programmatically from the host, so it will need to be
+ // rewritten later
+ contextMenu: null,
+ editingTextElement,
+ viewModeEnabled,
+ zenModeEnabled,
+ theme,
+ name,
+ errorMessage,
+ };
+ });
+
+ didUpdate = true;
+ }
+
+ if (
+ !didUpdate &&
+ actionResult.captureUpdate !== CaptureUpdateAction.EVENTUALLY
+ ) {
+ this.scene.triggerUpdate();
+ }
+ });
+
+ // Lifecycle
+
+ private onBlur = withBatchedUpdates(() => {
+ isHoldingSpace = false;
+ this.setState({ isBindingEnabled: true });
+ });
+
+ private onUnload = () => {
+ this.onBlur();
+ };
+
+ private disableEvent: EventListener = (event) => {
+ event.preventDefault();
+ };
+
+ private resetHistory = () => {
+ this.history.clear();
+ };
+
+ private resetStore = () => {
+ this.store.clear();
+ };
+
+ /**
+ * Resets scene & history.
+ * ! Do not use to clear scene user action !
+ */
+ private resetScene = withBatchedUpdates(
+ (opts?: { resetLoadingState: boolean }) => {
+ this.scene.replaceAllElements([]);
+ this.setState((state) => ({
+ ...getDefaultAppState(),
+ isLoading: opts?.resetLoadingState ? false : state.isLoading,
+ theme: this.state.theme,
+ }));
+ this.resetStore();
+ this.resetHistory();
+ },
+ );
+
+ private initializeScene = async () => {
+ if ("launchQueue" in window && "LaunchParams" in window) {
+ (window as any).launchQueue.setConsumer(
+ async (launchParams: { files: any[] }) => {
+ if (!launchParams.files.length) {
+ return;
+ }
+ const fileHandle = launchParams.files[0];
+ const blob: Blob = await fileHandle.getFile();
+ this.loadFileToCanvas(
+ new File([blob], blob.name || "", { type: blob.type }),
+ fileHandle,
+ );
+ },
+ );
+ }
+
+ if (this.props.theme) {
+ this.setState({ theme: this.props.theme });
+ }
+ if (!this.state.isLoading) {
+ this.setState({ isLoading: true });
+ }
+ let initialData = null;
+ try {
+ if (typeof this.props.initialData === "function") {
+ initialData = (await this.props.initialData()) || null;
+ } else {
+ initialData = (await this.props.initialData) || null;
+ }
+ if (initialData?.libraryItems) {
+ this.library
+ .updateLibrary({
+ libraryItems: initialData.libraryItems,
+ merge: true,
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ }
+ } catch (error: any) {
+ console.error(error);
+ initialData = {
+ appState: {
+ errorMessage:
+ error.message ||
+ "Encountered an error during importing or restoring scene data",
+ },
+ };
+ }
+ const scene = restore(initialData, null, null, { repairBindings: true });
+ scene.appState = {
+ ...scene.appState,
+ theme: this.props.theme || scene.appState.theme,
+ // we're falling back to current (pre-init) state when deciding
+ // whether to open the library, to handle a case where we
+ // update the state outside of initialData (e.g. when loading the app
+ // with a library install link, which should auto-open the library)
+ openSidebar: scene.appState?.openSidebar || this.state.openSidebar,
+ activeTool:
+ scene.appState.activeTool.type === "image"
+ ? { ...scene.appState.activeTool, type: "selection" }
+ : scene.appState.activeTool,
+ isLoading: false,
+ toast: this.state.toast,
+ };
+ if (initialData?.scrollToContent) {
+ scene.appState = {
+ ...scene.appState,
+ ...calculateScrollCenter(scene.elements, {
+ ...scene.appState,
+ width: this.state.width,
+ height: this.state.height,
+ offsetTop: this.state.offsetTop,
+ offsetLeft: this.state.offsetLeft,
+ }),
+ };
+ }
+
+ this.resetStore();
+ this.resetHistory();
+ this.syncActionResult({
+ ...scene,
+ captureUpdate: CaptureUpdateAction.NEVER,
+ });
+
+ // clear the shape and image cache so that any images in initialData
+ // can be loaded fresh
+ this.clearImageShapeCache();
+
+ // manually loading the font faces seems faster even in browsers that do fire the loadingdone event
+ this.fonts.loadSceneFonts().then((fontFaces) => {
+ this.fonts.onLoaded(fontFaces);
+ });
+
+ if (isElementLink(window.location.href)) {
+ this.scrollToContent(window.location.href, { animate: false });
+ }
+ };
+
+ private isMobileBreakpoint = (width: number, height: number) => {
+ return (
+ width < MQ_MAX_WIDTH_PORTRAIT ||
+ (height < MQ_MAX_HEIGHT_LANDSCAPE && width < MQ_MAX_WIDTH_LANDSCAPE)
+ );
+ };
+
+ private refreshViewportBreakpoints = () => {
+ const container = this.excalidrawContainerRef.current;
+ if (!container) {
+ return;
+ }
+
+ const { clientWidth: viewportWidth, clientHeight: viewportHeight } =
+ document.body;
+
+ const prevViewportState = this.device.viewport;
+
+ const nextViewportState = updateObject(prevViewportState, {
+ isLandscape: viewportWidth > viewportHeight,
+ isMobile: this.isMobileBreakpoint(viewportWidth, viewportHeight),
+ });
+
+ if (prevViewportState !== nextViewportState) {
+ this.device = { ...this.device, viewport: nextViewportState };
+ return true;
+ }
+ return false;
+ };
+
+ private refreshEditorBreakpoints = () => {
+ const container = this.excalidrawContainerRef.current;
+ if (!container) {
+ return;
+ }
+
+ const { width: editorWidth, height: editorHeight } =
+ container.getBoundingClientRect();
+
+ const sidebarBreakpoint =
+ this.props.UIOptions.dockedSidebarBreakpoint != null
+ ? this.props.UIOptions.dockedSidebarBreakpoint
+ : MQ_RIGHT_SIDEBAR_MIN_WIDTH;
+
+ const prevEditorState = this.device.editor;
+
+ const nextEditorState = updateObject(prevEditorState, {
+ isMobile: this.isMobileBreakpoint(editorWidth, editorHeight),
+ canFitSidebar: editorWidth > sidebarBreakpoint,
+ });
+
+ if (prevEditorState !== nextEditorState) {
+ this.device = { ...this.device, editor: nextEditorState };
+ return true;
+ }
+ return false;
+ };
+
+ private clearImageShapeCache(filesMap?: BinaryFiles) {
+ const files = filesMap ?? this.files;
+ this.scene.getNonDeletedElements().forEach((element) => {
+ if (isInitializedImageElement(element) && files[element.fileId]) {
+ this.imageCache.delete(element.fileId);
+ ShapeCache.delete(element);
+ }
+ });
+ }
+
+ public async componentDidMount() {
+ this.unmounted = false;
+ this.excalidrawContainerValue.container =
+ this.excalidrawContainerRef.current;
+
+ if (import.meta.env.MODE === ENV.TEST || import.meta.env.DEV) {
+ const setState = this.setState.bind(this);
+ Object.defineProperties(window.h, {
+ state: {
+ configurable: true,
+ get: () => {
+ return this.state;
+ },
+ },
+ setState: {
+ configurable: true,
+ value: (...args: Parameters<typeof setState>) => {
+ return this.setState(...args);
+ },
+ },
+ app: {
+ configurable: true,
+ value: this,
+ },
+ history: {
+ configurable: true,
+ value: this.history,
+ },
+ store: {
+ configurable: true,
+ value: this.store,
+ },
+ fonts: {
+ configurable: true,
+ value: this.fonts,
+ },
+ });
+ }
+
+ this.store.onStoreIncrementEmitter.on((increment) => {
+ this.history.record(increment.elementsChange, increment.appStateChange);
+ });
+
+ this.scene.onUpdate(this.triggerRender);
+ this.addEventListeners();
+
+ if (this.props.autoFocus && this.excalidrawContainerRef.current) {
+ this.focusContainer();
+ }
+
+ if (
+ // bounding rects don't work in tests so updating
+ // the state on init would result in making the test enviro run
+ // in mobile breakpoint (0 width/height), making everything fail
+ !isTestEnv()
+ ) {
+ this.refreshViewportBreakpoints();
+ this.refreshEditorBreakpoints();
+ }
+
+ if (supportsResizeObserver && this.excalidrawContainerRef.current) {
+ this.resizeObserver = new ResizeObserver(() => {
+ this.refreshEditorBreakpoints();
+ this.updateDOMRect();
+ });
+ this.resizeObserver?.observe(this.excalidrawContainerRef.current);
+ }
+
+ const searchParams = new URLSearchParams(window.location.search.slice(1));
+
+ if (searchParams.has("web-share-target")) {
+ // Obtain a file that was shared via the Web Share Target API.
+ this.restoreFileFromShare();
+ } else {
+ this.updateDOMRect(this.initializeScene);
+ }
+
+ // note that this check seems to always pass in localhost
+ if (isBrave() && !isMeasureTextSupported()) {
+ this.setState({
+ errorMessage: <BraveMeasureTextError />,
+ });
+ }
+ }
+
+ public componentWillUnmount() {
+ (window as any).launchQueue?.setConsumer(() => {});
+ this.renderer.destroy();
+ this.scene.destroy();
+ this.scene = new Scene();
+ this.fonts = new Fonts(this.scene);
+ this.renderer = new Renderer(this.scene);
+ this.files = {};
+ this.imageCache.clear();
+ this.resizeObserver?.disconnect();
+ this.unmounted = true;
+ this.removeEventListeners();
+ this.library.destroy();
+ this.laserTrails.stop();
+ this.eraserTrail.stop();
+ this.onChangeEmitter.clear();
+ this.store.onStoreIncrementEmitter.clear();
+ ShapeCache.destroy();
+ SnapCache.destroy();
+ clearTimeout(touchTimeout);
+ isSomeElementSelected.clearCache();
+ selectGroupsForSelectedElements.clearCache();
+ touchTimeout = 0;
+ document.documentElement.style.overscrollBehaviorX = "";
+ }
+
+ private onResize = withBatchedUpdates(() => {
+ this.scene
+ .getElementsIncludingDeleted()
+ .forEach((element) => ShapeCache.delete(element));
+ this.refreshViewportBreakpoints();
+ this.updateDOMRect();
+ if (!supportsResizeObserver) {
+ this.refreshEditorBreakpoints();
+ }
+ this.setState({});
+ });
+
+ /** generally invoked only if fullscreen was invoked programmatically */
+ private onFullscreenChange = () => {
+ if (
+ // points to the iframe element we fullscreened
+ !document.fullscreenElement &&
+ this.state.activeEmbeddable?.state === "active"
+ ) {
+ this.setState({
+ activeEmbeddable: null,
+ });
+ }
+ };
+
+ private removeEventListeners() {
+ this.onRemoveEventListenersEmitter.trigger();
+ }
+
+ private addEventListeners() {
+ // remove first as we can add event listeners multiple times
+ this.removeEventListeners();
+
+ // -------------------------------------------------------------------------
+ // view+edit mode listeners
+ // -------------------------------------------------------------------------
+
+ if (this.props.handleKeyboardGlobally) {
+ this.onRemoveEventListenersEmitter.once(
+ addEventListener(document, EVENT.KEYDOWN, this.onKeyDown, false),
+ );
+ }
+
+ this.onRemoveEventListenersEmitter.once(
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.WHEEL,
+ this.handleWheel,
+ { passive: false },
+ ),
+ addEventListener(window, EVENT.MESSAGE, this.onWindowMessage, false),
+ addEventListener(document, EVENT.POINTER_UP, this.removePointer, {
+ passive: false,
+ }), // #3553
+ addEventListener(document, EVENT.COPY, this.onCopy, { passive: false }),
+ addEventListener(document, EVENT.KEYUP, this.onKeyUp, { passive: true }),
+ addEventListener(
+ document,
+ EVENT.POINTER_MOVE,
+ this.updateCurrentCursorPosition,
+ { passive: false },
+ ),
+ // rerender text elements on font load to fix #637 && #1553
+ addEventListener(
+ document.fonts,
+ "loadingdone",
+ (event) => {
+ const fontFaces = (event as FontFaceSetLoadEvent).fontfaces;
+ this.fonts.onLoaded(fontFaces);
+ },
+ { passive: false },
+ ),
+ // Safari-only desktop pinch zoom
+ addEventListener(
+ document,
+ EVENT.GESTURE_START,
+ this.onGestureStart as any,
+ false,
+ ),
+ addEventListener(
+ document,
+ EVENT.GESTURE_CHANGE,
+ this.onGestureChange as any,
+ false,
+ ),
+ addEventListener(
+ document,
+ EVENT.GESTURE_END,
+ this.onGestureEnd as any,
+ false,
+ ),
+ addEventListener(
+ window,
+ EVENT.FOCUS,
+ () => {
+ this.maybeCleanupAfterMissingPointerUp(null);
+ // browsers (chrome?) tend to free up memory a lot, which results
+ // in canvas context being cleared. Thus re-render on focus.
+ this.triggerRender(true);
+ },
+ { passive: false },
+ ),
+ );
+
+ if (this.state.viewModeEnabled) {
+ return;
+ }
+
+ // -------------------------------------------------------------------------
+ // edit-mode listeners only
+ // -------------------------------------------------------------------------
+
+ this.onRemoveEventListenersEmitter.once(
+ addEventListener(
+ document,
+ EVENT.FULLSCREENCHANGE,
+ this.onFullscreenChange,
+ { passive: false },
+ ),
+ addEventListener(document, EVENT.PASTE, this.pasteFromClipboard, {
+ passive: false,
+ }),
+ addEventListener(document, EVENT.CUT, this.onCut, { passive: false }),
+ addEventListener(window, EVENT.RESIZE, this.onResize, false),
+ addEventListener(window, EVENT.UNLOAD, this.onUnload, false),
+ addEventListener(window, EVENT.BLUR, this.onBlur, false),
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.WHEEL,
+ this.handleWheel,
+ { passive: false },
+ ),
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.DRAG_OVER,
+ this.disableEvent,
+ false,
+ ),
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.DROP,
+ this.disableEvent,
+ false,
+ ),
+ );
+
+ if (this.props.detectScroll) {
+ this.onRemoveEventListenersEmitter.once(
+ addEventListener(
+ getNearestScrollableContainer(this.excalidrawContainerRef.current!),
+ EVENT.SCROLL,
+ this.onScroll,
+ { passive: false },
+ ),
+ );
+ }
+ }
+
+ componentDidUpdate(prevProps: AppProps, prevState: AppState) {
+ this.updateEmbeddables();
+ const elements = this.scene.getElementsIncludingDeleted();
+ const elementsMap = this.scene.getElementsMapIncludingDeleted();
+ const nonDeletedElementsMap = this.scene.getNonDeletedElementsMap();
+
+ if (!this.state.showWelcomeScreen && !elements.length) {
+ this.setState({ showWelcomeScreen: true });
+ }
+
+ if (
+ prevProps.UIOptions.dockedSidebarBreakpoint !==
+ this.props.UIOptions.dockedSidebarBreakpoint
+ ) {
+ this.refreshEditorBreakpoints();
+ }
+
+ const hasFollowedPersonLeft =
+ prevState.userToFollow &&
+ !this.state.collaborators.has(prevState.userToFollow.socketId);
+
+ if (hasFollowedPersonLeft) {
+ this.maybeUnfollowRemoteUser();
+ }
+
+ if (
+ prevState.zoom.value !== this.state.zoom.value ||
+ prevState.scrollX !== this.state.scrollX ||
+ prevState.scrollY !== this.state.scrollY
+ ) {
+ this.props?.onScrollChange?.(
+ this.state.scrollX,
+ this.state.scrollY,
+ this.state.zoom,
+ );
+ this.onScrollChangeEmitter.trigger(
+ this.state.scrollX,
+ this.state.scrollY,
+ this.state.zoom,
+ );
+ }
+
+ if (prevState.userToFollow !== this.state.userToFollow) {
+ if (prevState.userToFollow) {
+ this.onUserFollowEmitter.trigger({
+ userToFollow: prevState.userToFollow,
+ action: "UNFOLLOW",
+ });
+ }
+
+ if (this.state.userToFollow) {
+ this.onUserFollowEmitter.trigger({
+ userToFollow: this.state.userToFollow,
+ action: "FOLLOW",
+ });
+ }
+ }
+
+ if (
+ Object.keys(this.state.selectedElementIds).length &&
+ isEraserActive(this.state)
+ ) {
+ this.setState({
+ activeTool: updateActiveTool(this.state, { type: "selection" }),
+ });
+ }
+ if (
+ this.state.activeTool.type === "eraser" &&
+ prevState.theme !== this.state.theme
+ ) {
+ setEraserCursor(this.interactiveCanvas, this.state.theme);
+ }
+ // Hide hyperlink popup if shown when element type is not selection
+ if (
+ prevState.activeTool.type === "selection" &&
+ this.state.activeTool.type !== "selection" &&
+ this.state.showHyperlinkPopup
+ ) {
+ this.setState({ showHyperlinkPopup: false });
+ }
+ if (prevProps.langCode !== this.props.langCode) {
+ this.updateLanguage();
+ }
+
+ if (isEraserActive(prevState) && !isEraserActive(this.state)) {
+ this.eraserTrail.endPath();
+ }
+
+ if (prevProps.viewModeEnabled !== this.props.viewModeEnabled) {
+ this.setState({ viewModeEnabled: !!this.props.viewModeEnabled });
+ }
+
+ if (prevState.viewModeEnabled !== this.state.viewModeEnabled) {
+ this.addEventListeners();
+ this.deselectElements();
+ }
+
+ // cleanup
+ if (
+ (prevState.openDialog?.name === "elementLinkSelector" ||
+ this.state.openDialog?.name === "elementLinkSelector") &&
+ prevState.openDialog?.name !== this.state.openDialog?.name
+ ) {
+ this.deselectElements();
+ this.setState({
+ hoveredElementIds: {},
+ });
+ }
+
+ if (prevProps.zenModeEnabled !== this.props.zenModeEnabled) {
+ this.setState({ zenModeEnabled: !!this.props.zenModeEnabled });
+ }
+
+ if (prevProps.theme !== this.props.theme && this.props.theme) {
+ this.setState({ theme: this.props.theme });
+ }
+
+ this.excalidrawContainerRef.current?.classList.toggle(
+ "theme--dark",
+ this.state.theme === THEME.DARK,
+ );
+
+ if (
+ this.state.editingLinearElement &&
+ !this.state.selectedElementIds[this.state.editingLinearElement.elementId]
+ ) {
+ // defer so that the shouldCaptureIncrement flag isn't reset via current update
+ setTimeout(() => {
+ // execute only if the condition still holds when the deferred callback
+ // executes (it can be scheduled multiple times depending on how
+ // many times the component renders)
+ this.state.editingLinearElement &&
+ this.actionManager.executeAction(actionFinalize);
+ });
+ }
+
+ // failsafe in case the state is being updated in incorrect order resulting
+ // in the editingTextElement being now a deleted element
+ if (this.state.editingTextElement?.isDeleted) {
+ this.setState({ editingTextElement: null });
+ }
+
+ if (
+ this.state.selectedLinearElement &&
+ !this.state.selectedElementIds[this.state.selectedLinearElement.elementId]
+ ) {
+ // To make sure `selectedLinearElement` is in sync with `selectedElementIds`, however this shouldn't be needed once
+ // we have a single API to update `selectedElementIds`
+ this.setState({ selectedLinearElement: null });
+ }
+
+ const { multiElement } = prevState;
+ if (
+ prevState.activeTool !== this.state.activeTool &&
+ multiElement != null &&
+ isBindingEnabled(this.state) &&
+ isBindingElement(multiElement, false)
+ ) {
+ maybeBindLinearElement(
+ multiElement,
+ this.state,
+ tupleToCoors(
+ LinearElementEditor.getPointAtIndexGlobalCoordinates(
+ multiElement,
+ -1,
+ nonDeletedElementsMap,
+ ),
+ ),
+ this.scene.getNonDeletedElementsMap(),
+ this.scene.getNonDeletedElements(),
+ );
+ }
+
+ this.store.commit(elementsMap, this.state);
+
+ // Do not notify consumers if we're still loading the scene. Among other
+ // potential issues, this fixes a case where the tab isn't focused during
+ // init, which would trigger onChange with empty elements, which would then
+ // override whatever is in localStorage currently.
+ if (!this.state.isLoading) {
+ this.props.onChange?.(elements, this.state, this.files);
+ this.onChangeEmitter.trigger(elements, this.state, this.files);
+ }
+ }
+
+ private renderInteractiveSceneCallback = ({
+ atLeastOneVisibleElement,
+ scrollBars,
+ elementsMap,
+ }: RenderInteractiveSceneCallback) => {
+ if (scrollBars) {
+ currentScrollBars = scrollBars;
+ }
+ const scrolledOutside =
+ // hide when editing text
+ this.state.editingTextElement
+ ? false
+ : !atLeastOneVisibleElement && elementsMap.size > 0;
+ if (this.state.scrolledOutside !== scrolledOutside) {
+ this.setState({ scrolledOutside });
+ }
+
+ this.scheduleImageRefresh();
+ };
+
+ private onScroll = debounce(() => {
+ const { offsetTop, offsetLeft } = this.getCanvasOffsets();
+ this.setState((state) => {
+ if (state.offsetLeft === offsetLeft && state.offsetTop === offsetTop) {
+ return null;
+ }
+ return { offsetTop, offsetLeft };
+ });
+ }, SCROLL_TIMEOUT);
+
+ // Copy/paste
+
+ private onCut = withBatchedUpdates((event: ClipboardEvent) => {
+ const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
+ document.activeElement,
+ );
+ if (!isExcalidrawActive || isWritableElement(event.target)) {
+ return;
+ }
+ this.actionManager.executeAction(actionCut, "keyboard", event);
+ event.preventDefault();
+ event.stopPropagation();
+ });
+
+ private onCopy = withBatchedUpdates((event: ClipboardEvent) => {
+ const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
+ document.activeElement,
+ );
+ if (!isExcalidrawActive || isWritableElement(event.target)) {
+ return;
+ }
+ this.actionManager.executeAction(actionCopy, "keyboard", event);
+ event.preventDefault();
+ event.stopPropagation();
+ });
+
+ private static resetTapTwice() {
+ didTapTwice = false;
+ }
+
+ private onTouchStart = (event: TouchEvent) => {
+ // fix for Apple Pencil Scribble (do not prevent for other devices)
+ if (isIOS) {
+ event.preventDefault();
+ }
+
+ if (!didTapTwice) {
+ didTapTwice = true;
+ clearTimeout(tappedTwiceTimer);
+ tappedTwiceTimer = window.setTimeout(
+ App.resetTapTwice,
+ TAP_TWICE_TIMEOUT,
+ );
+ return;
+ }
+ // insert text only if we tapped twice with a single finger
+ // event.touches.length === 1 will also prevent inserting text when user's zooming
+ if (didTapTwice && event.touches.length === 1) {
+ const touch = event.touches[0];
+ // @ts-ignore
+ this.handleCanvasDoubleClick({
+ clientX: touch.clientX,
+ clientY: touch.clientY,
+ });
+ didTapTwice = false;
+ clearTimeout(tappedTwiceTimer);
+ }
+
+ if (event.touches.length === 2) {
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.state),
+ activeEmbeddable: null,
+ });
+ }
+ };
+
+ private onTouchEnd = (event: TouchEvent) => {
+ this.resetContextMenuTimer();
+ if (event.touches.length > 0) {
+ this.setState({
+ previousSelectedElementIds: {},
+ selectedElementIds: makeNextSelectedElementIds(
+ this.state.previousSelectedElementIds,
+ this.state,
+ ),
+ });
+ } else {
+ gesture.pointers.clear();
+ }
+ };
+
+ public pasteFromClipboard = withBatchedUpdates(
+ async (event: ClipboardEvent) => {
+ const isPlainPaste = !!IS_PLAIN_PASTE;
+
+ // #686
+ const target = document.activeElement;
+ const isExcalidrawActive =
+ this.excalidrawContainerRef.current?.contains(target);
+ if (event && !isExcalidrawActive) {
+ return;
+ }
+
+ const elementUnderCursor = document.elementFromPoint(
+ this.lastViewportPosition.x,
+ this.lastViewportPosition.y,
+ );
+ if (
+ event &&
+ (!(elementUnderCursor instanceof HTMLCanvasElement) ||
+ isWritableElement(target))
+ ) {
+ return;
+ }
+
+ const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
+ {
+ clientX: this.lastViewportPosition.x,
+ clientY: this.lastViewportPosition.y,
+ },
+ this.state,
+ );
+
+ // must be called in the same frame (thus before any awaits) as the paste
+ // event else some browsers (FF...) will clear the clipboardData
+ // (something something security)
+ let file = event?.clipboardData?.files[0];
+ const data = await parseClipboard(event, isPlainPaste);
+ if (!file && !isPlainPaste) {
+ if (data.mixedContent) {
+ return this.addElementsFromMixedContentPaste(data.mixedContent, {
+ isPlainPaste,
+ sceneX,
+ sceneY,
+ });
+ } else if (data.text) {
+ const string = data.text.trim();
+ if (string.startsWith("<svg") && string.endsWith("</svg>")) {
+ // ignore SVG validation/normalization which will be done during image
+ // initialization
+ file = SVGStringToFile(string);
+ }
+ }
+ }
+
+ // prefer spreadsheet data over image file (MS Office/Libre Office)
+ if (isSupportedImageFile(file) && !data.spreadsheet) {
+ if (!this.isToolSupported("image")) {
+ this.setState({ errorMessage: t("errors.imageToolNotSupported") });
+ return;
+ }
+
+ const imageElement = this.createImageElement({ sceneX, sceneY });
+ this.insertImageElement(imageElement, file);
+ this.initializeImageDimensions(imageElement);
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ [imageElement.id]: true,
+ },
+ this.state,
+ ),
+ });
+
+ return;
+ }
+
+ if (this.props.onPaste) {
+ try {
+ if ((await this.props.onPaste(data, event)) === false) {
+ return;
+ }
+ } catch (error: any) {
+ console.error(error);
+ }
+ }
+
+ if (data.errorMessage) {
+ this.setState({ errorMessage: data.errorMessage });
+ } else if (data.spreadsheet && !isPlainPaste) {
+ this.setState({
+ pasteDialog: {
+ data: data.spreadsheet,
+ shown: true,
+ },
+ });
+ } else if (data.elements) {
+ const elements = (
+ data.programmaticAPI
+ ? convertToExcalidrawElements(
+ data.elements as ExcalidrawElementSkeleton[],
+ )
+ : data.elements
+ ) as readonly ExcalidrawElement[];
+ // TODO remove formatting from elements if isPlainPaste
+ this.addElementsFromPasteOrLibrary({
+ elements,
+ files: data.files || null,
+ position: "cursor",
+ retainSeed: isPlainPaste,
+ });
+ } else if (data.text) {
+ if (data.text && isMaybeMermaidDefinition(data.text)) {
+ const api = await import("@excalidraw/mermaid-to-excalidraw");
+
+ try {
+ const { elements: skeletonElements, files } =
+ await api.parseMermaidToExcalidraw(data.text);
+
+ const elements = convertToExcalidrawElements(skeletonElements, {
+ regenerateIds: true,
+ });
+
+ this.addElementsFromPasteOrLibrary({
+ elements,
+ files,
+ position: "cursor",
+ });
+
+ return;
+ } catch (err: any) {
+ console.warn(
+ `parsing pasted text as mermaid definition failed: ${err.message}`,
+ );
+ }
+ }
+
+ const nonEmptyLines = normalizeEOL(data.text)
+ .split(/\n+/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+
+ const embbeddableUrls = nonEmptyLines
+ .map((str) => maybeParseEmbedSrc(str))
+ .filter((string) => {
+ return (
+ embeddableURLValidator(string, this.props.validateEmbeddable) &&
+ (/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(string) ||
+ getEmbedLink(string)?.type === "video")
+ );
+ });
+
+ if (
+ !IS_PLAIN_PASTE &&
+ embbeddableUrls.length > 0 &&
+ // if there were non-embeddable text (lines) mixed in with embeddable
+ // urls, ignore and paste as text
+ embbeddableUrls.length === nonEmptyLines.length
+ ) {
+ const embeddables: NonDeleted<ExcalidrawEmbeddableElement>[] = [];
+ for (const url of embbeddableUrls) {
+ const prevEmbeddable: ExcalidrawEmbeddableElement | undefined =
+ embeddables[embeddables.length - 1];
+ const embeddable = this.insertEmbeddableElement({
+ sceneX: prevEmbeddable
+ ? prevEmbeddable.x + prevEmbeddable.width + 20
+ : sceneX,
+ sceneY,
+ link: normalizeLink(url),
+ });
+ if (embeddable) {
+ embeddables.push(embeddable);
+ }
+ }
+ if (embeddables.length) {
+ this.setState({
+ selectedElementIds: Object.fromEntries(
+ embeddables.map((embeddable) => [embeddable.id, true]),
+ ),
+ });
+ }
+ return;
+ }
+ this.addTextFromPaste(data.text, isPlainPaste);
+ }
+ this.setActiveTool({ type: "selection" });
+ event?.preventDefault();
+ },
+ );
+
+ addElementsFromPasteOrLibrary = (opts: {
+ elements: readonly ExcalidrawElement[];
+ files: BinaryFiles | null;
+ position: { clientX: number; clientY: number } | "cursor" | "center";
+ retainSeed?: boolean;
+ fitToContent?: boolean;
+ }) => {
+ const elements = restoreElements(opts.elements, null, undefined);
+ const [minX, minY, maxX, maxY] = getCommonBounds(elements);
+
+ const elementsCenterX = distance(minX, maxX) / 2;
+ const elementsCenterY = distance(minY, maxY) / 2;
+
+ const clientX =
+ typeof opts.position === "object"
+ ? opts.position.clientX
+ : opts.position === "cursor"
+ ? this.lastViewportPosition.x
+ : this.state.width / 2 + this.state.offsetLeft;
+ const clientY =
+ typeof opts.position === "object"
+ ? opts.position.clientY
+ : opts.position === "cursor"
+ ? this.lastViewportPosition.y
+ : this.state.height / 2 + this.state.offsetTop;
+
+ const { x, y } = viewportCoordsToSceneCoords(
+ { clientX, clientY },
+ this.state,
+ );
+
+ const dx = x - elementsCenterX;
+ const dy = y - elementsCenterY;
+
+ const [gridX, gridY] = getGridPoint(dx, dy, this.getEffectiveGridSize());
+
+ const newElements = duplicateElements(
+ elements.map((element) => {
+ return newElementWith(element, {
+ x: element.x + gridX - minX,
+ y: element.y + gridY - minY,
+ });
+ }),
+ {
+ randomizeSeed: !opts.retainSeed,
+ },
+ );
+
+ const prevElements = this.scene.getElementsIncludingDeleted();
+ let nextElements = [...prevElements, ...newElements];
+
+ const mappedNewSceneElements = this.props.onDuplicate?.(
+ nextElements,
+ prevElements,
+ );
+
+ nextElements = mappedNewSceneElements || nextElements;
+
+ syncMovedIndices(nextElements, arrayToMap(newElements));
+
+ const topLayerFrame = this.getTopLayerFrameAtSceneCoords({ x, y });
+
+ if (topLayerFrame) {
+ const eligibleElements = filterElementsEligibleAsFrameChildren(
+ newElements,
+ topLayerFrame,
+ );
+ addElementsToFrame(
+ nextElements,
+ eligibleElements,
+ topLayerFrame,
+ this.state,
+ );
+ }
+
+ this.scene.replaceAllElements(nextElements);
+
+ newElements.forEach((newElement) => {
+ if (isTextElement(newElement) && isBoundToContainer(newElement)) {
+ const container = getContainerElement(
+ newElement,
+ this.scene.getElementsMapIncludingDeleted(),
+ );
+ redrawTextBoundingBox(
+ newElement,
+ container,
+ this.scene.getElementsMapIncludingDeleted(),
+ );
+ }
+ });
+
+ // paste event may not fire FontFace loadingdone event in Safari, hence loading font faces manually
+ if (isSafari) {
+ Fonts.loadElementsFonts(newElements).then((fontFaces) => {
+ this.fonts.onLoaded(fontFaces);
+ });
+ }
+
+ if (opts.files) {
+ this.addMissingFiles(opts.files);
+ }
+
+ this.store.shouldCaptureIncrement();
+
+ const nextElementsToSelect =
+ excludeElementsInFramesFromSelection(newElements);
+
+ this.setState(
+ {
+ ...this.state,
+ // keep sidebar (presumably the library) open if it's docked and
+ // can fit.
+ //
+ // Note, we should close the sidebar only if we're dropping items
+ // from library, not when pasting from clipboard. Alas.
+ openSidebar:
+ this.state.openSidebar &&
+ this.device.editor.canFitSidebar &&
+ editorJotaiStore.get(isSidebarDockedAtom)
+ ? this.state.openSidebar
+ : null,
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: null,
+ selectedElementIds: nextElementsToSelect.reduce(
+ (acc: Record<ExcalidrawElement["id"], true>, element) => {
+ if (!isBoundToContainer(element)) {
+ acc[element.id] = true;
+ }
+ return acc;
+ },
+ {},
+ ),
+ },
+ this.scene.getNonDeletedElements(),
+ this.state,
+ this,
+ ),
+ },
+ () => {
+ if (opts.files) {
+ this.addNewImagesToImageCache();
+ }
+ },
+ );
+ this.setActiveTool({ type: "selection" });
+
+ if (opts.fitToContent) {
+ this.scrollToContent(newElements, {
+ fitToContent: true,
+ canvasOffsets: this.getEditorUIOffsets(),
+ });
+ }
+ };
+
+ // TODO rewrite this to paste both text & images at the same time if
+ // pasted data contains both
+ private async addElementsFromMixedContentPaste(
+ mixedContent: PastedMixedContent,
+ {
+ isPlainPaste,
+ sceneX,
+ sceneY,
+ }: { isPlainPaste: boolean; sceneX: number; sceneY: number },
+ ) {
+ if (
+ !isPlainPaste &&
+ mixedContent.some((node) => node.type === "imageUrl") &&
+ this.isToolSupported("image")
+ ) {
+ const imageURLs = mixedContent
+ .filter((node) => node.type === "imageUrl")
+ .map((node) => node.value);
+ const responses = await Promise.all(
+ imageURLs.map(async (url) => {
+ try {
+ return { file: await ImageURLToFile(url) };
+ } catch (error: any) {
+ let errorMessage = error.message;
+ if (error.cause === "FETCH_ERROR") {
+ errorMessage = t("errors.failedToFetchImage");
+ } else if (error.cause === "UNSUPPORTED") {
+ errorMessage = t("errors.unsupportedFileType");
+ }
+ return { errorMessage };
+ }
+ }),
+ );
+ let y = sceneY;
+ let firstImageYOffsetDone = false;
+ const nextSelectedIds: Record<ExcalidrawElement["id"], true> = {};
+ for (const response of responses) {
+ if (response.file) {
+ const imageElement = this.createImageElement({
+ sceneX,
+ sceneY: y,
+ });
+
+ const initializedImageElement = await this.insertImageElement(
+ imageElement,
+ response.file,
+ );
+ if (initializedImageElement) {
+ // vertically center first image in the batch
+ if (!firstImageYOffsetDone) {
+ firstImageYOffsetDone = true;
+ y -= initializedImageElement.height / 2;
+ }
+ // hack to reset the `y` coord because we vertically center during
+ // insertImageElement
+ mutateElement(initializedImageElement, { y }, false);
+
+ y = imageElement.y + imageElement.height + 25;
+
+ nextSelectedIds[imageElement.id] = true;
+ }
+ }
+ }
+
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds(
+ nextSelectedIds,
+ this.state,
+ ),
+ });
+
+ const error = responses.find((response) => !!response.errorMessage);
+ if (error && error.errorMessage) {
+ this.setState({ errorMessage: error.errorMessage });
+ }
+ } else {
+ const textNodes = mixedContent.filter((node) => node.type === "text");
+ if (textNodes.length) {
+ this.addTextFromPaste(
+ textNodes.map((node) => node.value).join("\n\n"),
+ isPlainPaste,
+ );
+ }
+ }
+ }
+
+ private addTextFromPaste(text: string, isPlainPaste = false) {
+ const { x, y } = viewportCoordsToSceneCoords(
+ {
+ clientX: this.lastViewportPosition.x,
+ clientY: this.lastViewportPosition.y,
+ },
+ this.state,
+ );
+
+ const textElementProps = {
+ x,
+ y,
+ strokeColor: this.state.currentItemStrokeColor,
+ backgroundColor: this.state.currentItemBackgroundColor,
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roundness: null,
+ roughness: this.state.currentItemRoughness,
+ opacity: this.state.currentItemOpacity,
+ text,
+ fontSize: this.state.currentItemFontSize,
+ fontFamily: this.state.currentItemFontFamily,
+ textAlign: DEFAULT_TEXT_ALIGN,
+ verticalAlign: DEFAULT_VERTICAL_ALIGN,
+ locked: false,
+ };
+ const fontString = getFontString({
+ fontSize: textElementProps.fontSize,
+ fontFamily: textElementProps.fontFamily,
+ });
+ const lineHeight = getLineHeight(textElementProps.fontFamily);
+ const [x1, , x2] = getVisibleSceneBounds(this.state);
+ // long texts should not go beyond 800 pixels in width nor should it go below 200 px
+ const maxTextWidth = Math.max(Math.min((x2 - x1) * 0.5, 800), 200);
+ const LINE_GAP = 10;
+ let currentY = y;
+
+ const lines = isPlainPaste ? [text] : text.split("\n");
+ const textElements = lines.reduce(
+ (acc: ExcalidrawTextElement[], line, idx) => {
+ const originalText = normalizeText(line).trim();
+ if (originalText.length) {
+ const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
+ x,
+ y: currentY,
+ });
+
+ let metrics = measureText(originalText, fontString, lineHeight);
+ const isTextUnwrapped = metrics.width > maxTextWidth;
+
+ const text = isTextUnwrapped
+ ? wrapText(originalText, fontString, maxTextWidth)
+ : originalText;
+
+ metrics = isTextUnwrapped
+ ? measureText(text, fontString, lineHeight)
+ : metrics;
+
+ const startX = x - metrics.width / 2;
+ const startY = currentY - metrics.height / 2;
+
+ const element = newTextElement({
+ ...textElementProps,
+ x: startX,
+ y: startY,
+ text,
+ originalText,
+ lineHeight,
+ autoResize: !isTextUnwrapped,
+ frameId: topLayerFrame ? topLayerFrame.id : null,
+ });
+ acc.push(element);
+ currentY += element.height + LINE_GAP;
+ } else {
+ const prevLine = lines[idx - 1]?.trim();
+ // add paragraph only if previous line was not empty, IOW don't add
+ // more than one empty line
+ if (prevLine) {
+ currentY +=
+ getLineHeightInPx(textElementProps.fontSize, lineHeight) +
+ LINE_GAP;
+ }
+ }
+
+ return acc;
+ },
+ [],
+ );
+
+ if (textElements.length === 0) {
+ return;
+ }
+
+ this.scene.insertElements(textElements);
+
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds(
+ Object.fromEntries(textElements.map((el) => [el.id, true])),
+ this.state,
+ ),
+ });
+
+ if (
+ !isPlainPaste &&
+ textElements.length > 1 &&
+ PLAIN_PASTE_TOAST_SHOWN === false &&
+ !this.device.editor.isMobile
+ ) {
+ this.setToast({
+ message: t("toast.pasteAsSingleElement", {
+ shortcut: getShortcutKey("CtrlOrCmd+Shift+V"),
+ }),
+ duration: 5000,
+ });
+ PLAIN_PASTE_TOAST_SHOWN = true;
+ }
+
+ this.store.shouldCaptureIncrement();
+ }
+
+ setAppState: React.Component<any, AppState>["setState"] = (
+ state,
+ callback,
+ ) => {
+ this.setState(state, callback);
+ };
+
+ removePointer = (event: React.PointerEvent<HTMLElement> | PointerEvent) => {
+ if (touchTimeout) {
+ this.resetContextMenuTimer();
+ }
+
+ gesture.pointers.delete(event.pointerId);
+ };
+
+ toggleLock = (source: "keyboard" | "ui" = "ui") => {
+ if (!this.state.activeTool.locked) {
+ trackEvent(
+ "toolbar",
+ "toggleLock",
+ `${source} (${this.device.editor.isMobile ? "mobile" : "desktop"})`,
+ );
+ }
+ this.setState((prevState) => {
+ return {
+ activeTool: {
+ ...prevState.activeTool,
+ ...updateActiveTool(
+ this.state,
+ prevState.activeTool.locked
+ ? { type: "selection" }
+ : prevState.activeTool,
+ ),
+ locked: !prevState.activeTool.locked,
+ },
+ };
+ });
+ };
+
+ updateFrameRendering = (
+ opts:
+ | Partial<AppState["frameRendering"]>
+ | ((
+ prevState: AppState["frameRendering"],
+ ) => Partial<AppState["frameRendering"]>),
+ ) => {
+ this.setState((prevState) => {
+ const next =
+ typeof opts === "function" ? opts(prevState.frameRendering) : opts;
+ return {
+ frameRendering: {
+ enabled: next?.enabled ?? prevState.frameRendering.enabled,
+ clip: next?.clip ?? prevState.frameRendering.clip,
+ name: next?.name ?? prevState.frameRendering.name,
+ outline: next?.outline ?? prevState.frameRendering.outline,
+ },
+ };
+ });
+ };
+
+ togglePenMode = (force: boolean | null) => {
+ this.setState((prevState) => {
+ return {
+ penMode: force ?? !prevState.penMode,
+ penDetected: true,
+ };
+ });
+ };
+
+ onHandToolToggle = () => {
+ this.actionManager.executeAction(actionToggleHandTool);
+ };
+
+ /**
+ * Zooms on canvas viewport center
+ */
+ zoomCanvas = (
+ /**
+ * Decimal fraction, auto-clamped between MIN_ZOOM and MAX_ZOOM.
+ * 1 = 100% zoom, 2 = 200% zoom, 0.5 = 50% zoom
+ */
+ value: number,
+ ) => {
+ this.setState({
+ ...getStateForZoom(
+ {
+ viewportX: this.state.width / 2 + this.state.offsetLeft,
+ viewportY: this.state.height / 2 + this.state.offsetTop,
+ nextZoom: getNormalizedZoom(value),
+ },
+ this.state,
+ ),
+ });
+ };
+
+ private cancelInProgressAnimation: (() => void) | null = null;
+
+ scrollToContent = (
+ /**
+ * target to scroll to
+ *
+ * - string - id of element or group, or url containing elementLink
+ * - ExcalidrawElement | ExcalidrawElement[] - element(s) objects
+ */
+ target:
+ | string
+ | ExcalidrawElement
+ | readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(),
+ opts?: (
+ | {
+ fitToContent?: boolean;
+ fitToViewport?: never;
+ viewportZoomFactor?: number;
+ animate?: boolean;
+ duration?: number;
+ }
+ | {
+ fitToContent?: never;
+ fitToViewport?: boolean;
+ /** when fitToViewport=true, how much screen should the content cover,
+ * between 0.1 (10%) and 1 (100%)
+ */
+ viewportZoomFactor?: number;
+ animate?: boolean;
+ duration?: number;
+ }
+ ) & {
+ minZoom?: number;
+ maxZoom?: number;
+ canvasOffsets?: Offsets;
+ },
+ ) => {
+ if (typeof target === "string") {
+ let id: string | null;
+ if (isElementLink(target)) {
+ id = parseElementLinkFromURL(target);
+ } else {
+ id = target;
+ }
+ if (id) {
+ const elements = this.scene.getElementsFromId(id);
+
+ if (elements?.length) {
+ this.scrollToContent(elements, {
+ fitToContent: opts?.fitToContent ?? true,
+ animate: opts?.animate ?? true,
+ });
+ } else if (isElementLink(target)) {
+ this.setState({
+ toast: {
+ message: t("elementLink.notFound"),
+ duration: 3000,
+ closable: true,
+ },
+ });
+ }
+ }
+ return;
+ }
+
+ this.cancelInProgressAnimation?.();
+
+ // convert provided target into ExcalidrawElement[] if necessary
+ const targetElements = Array.isArray(target) ? target : [target];
+
+ let zoom = this.state.zoom;
+ let scrollX = this.state.scrollX;
+ let scrollY = this.state.scrollY;
+
+ if (opts?.fitToContent || opts?.fitToViewport) {
+ const { appState } = zoomToFit({
+ canvasOffsets: opts.canvasOffsets,
+ targetElements,
+ appState: this.state,
+ fitToViewport: !!opts?.fitToViewport,
+ viewportZoomFactor: opts?.viewportZoomFactor,
+ minZoom: opts?.minZoom,
+ maxZoom: opts?.maxZoom,
+ });
+ zoom = appState.zoom;
+ scrollX = appState.scrollX;
+ scrollY = appState.scrollY;
+ } else {
+ // compute only the viewport location, without any zoom adjustment
+ const scroll = calculateScrollCenter(targetElements, this.state);
+ scrollX = scroll.scrollX;
+ scrollY = scroll.scrollY;
+ }
+
+ // when animating, we use RequestAnimationFrame to prevent the animation
+ // from slowing down other processes
+ if (opts?.animate) {
+ const origScrollX = this.state.scrollX;
+ const origScrollY = this.state.scrollY;
+ const origZoom = this.state.zoom.value;
+
+ const cancel = easeToValuesRAF({
+ fromValues: {
+ scrollX: origScrollX,
+ scrollY: origScrollY,
+ zoom: origZoom,
+ },
+ toValues: { scrollX, scrollY, zoom: zoom.value },
+ interpolateValue: (from, to, progress, key) => {
+ // for zoom, use different easing
+ if (key === "zoom") {
+ return from * Math.pow(to / from, easeOut(progress));
+ }
+ // handle using default
+ return undefined;
+ },
+ onStep: ({ scrollX, scrollY, zoom }) => {
+ this.setState({
+ scrollX,
+ scrollY,
+ zoom: { value: zoom },
+ });
+ },
+ onStart: () => {
+ this.setState({ shouldCacheIgnoreZoom: true });
+ },
+ onEnd: () => {
+ this.setState({ shouldCacheIgnoreZoom: false });
+ },
+ onCancel: () => {
+ this.setState({ shouldCacheIgnoreZoom: false });
+ },
+ duration: opts?.duration ?? 500,
+ });
+
+ this.cancelInProgressAnimation = () => {
+ cancel();
+ this.cancelInProgressAnimation = null;
+ };
+ } else {
+ this.setState({ scrollX, scrollY, zoom });
+ }
+ };
+
+ private maybeUnfollowRemoteUser = () => {
+ if (this.state.userToFollow) {
+ this.setState({ userToFollow: null });
+ }
+ };
+
+ /** use when changing scrollX/scrollY/zoom based on user interaction */
+ private translateCanvas: React.Component<any, AppState>["setState"] = (
+ state,
+ ) => {
+ this.cancelInProgressAnimation?.();
+ this.maybeUnfollowRemoteUser();
+ this.setState(state);
+ };
+
+ setToast = (
+ toast: {
+ message: string;
+ closable?: boolean;
+ duration?: number;
+ } | null,
+ ) => {
+ this.setState({ toast });
+ };
+
+ restoreFileFromShare = async () => {
+ try {
+ const webShareTargetCache = await caches.open("web-share-target");
+
+ const response = await webShareTargetCache.match("shared-file");
+ if (response) {
+ const blob = await response.blob();
+ const file = new File([blob], blob.name || "", { type: blob.type });
+ this.loadFileToCanvas(file, null);
+ await webShareTargetCache.delete("shared-file");
+ window.history.replaceState(null, APP_NAME, window.location.pathname);
+ }
+ } catch (error: any) {
+ this.setState({ errorMessage: error.message });
+ }
+ };
+
+ /**
+ * adds supplied files to existing files in the appState.
+ * NOTE if file already exists in editor state, the file data is not updated
+ * */
+ public addFiles: ExcalidrawImperativeAPI["addFiles"] = withBatchedUpdates(
+ (files) => {
+ const { addedFiles } = this.addMissingFiles(files);
+
+ this.clearImageShapeCache(addedFiles);
+ this.scene.triggerUpdate();
+
+ this.addNewImagesToImageCache();
+ },
+ );
+
+ private addMissingFiles = (
+ files: BinaryFiles | BinaryFileData[],
+ replace = false,
+ ) => {
+ const nextFiles = replace ? {} : { ...this.files };
+ const addedFiles: BinaryFiles = {};
+
+ const _files = Array.isArray(files) ? files : Object.values(files);
+
+ for (const fileData of _files) {
+ if (nextFiles[fileData.id]) {
+ continue;
+ }
+
+ addedFiles[fileData.id] = fileData;
+ nextFiles[fileData.id] = fileData;
+
+ if (fileData.mimeType === MIME_TYPES.svg) {
+ try {
+ const restoredDataURL = getDataURL_sync(
+ normalizeSVG(dataURLToString(fileData.dataURL)),
+ MIME_TYPES.svg,
+ );
+ if (fileData.dataURL !== restoredDataURL) {
+ // bump version so persistence layer can update the store
+ fileData.version = (fileData.version ?? 1) + 1;
+ fileData.dataURL = restoredDataURL;
+ }
+ } catch (error) {
+ console.error(error);
+ }
+ }
+ }
+
+ this.files = nextFiles;
+
+ return { addedFiles };
+ };
+
+ public updateScene = withBatchedUpdates(
+ <K extends keyof AppState>(sceneData: {
+ elements?: SceneData["elements"];
+ appState?: Pick<AppState, K> | null;
+ collaborators?: SceneData["collaborators"];
+ /**
+ * Controls which updates should be captured by the `Store`. Captured updates are emmitted and listened to by other components, such as `History` for undo / redo purposes.
+ *
+ * - `CaptureUpdateAction.IMMEDIATELY`: Updates are immediately undoable. Use for most local updates.
+ * - `CaptureUpdateAction.NEVER`: Updates never make it to undo/redo stack. Use for remote updates or scene initialization.
+ * - `CaptureUpdateAction.EVENTUALLY`: Updates will be eventually be captured as part of a future increment.
+ *
+ * Check [API docs](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/props/excalidraw-api#captureUpdate) for more details.
+ *
+ * @default CaptureUpdateAction.EVENTUALLY
+ */
+ captureUpdate?: SceneData["captureUpdate"];
+ }) => {
+ const nextElements = syncInvalidIndices(sceneData.elements ?? []);
+
+ if (
+ sceneData.captureUpdate &&
+ sceneData.captureUpdate !== CaptureUpdateAction.EVENTUALLY
+ ) {
+ const prevCommittedAppState = this.store.snapshot.appState;
+ const prevCommittedElements = this.store.snapshot.elements;
+
+ const nextCommittedAppState = sceneData.appState
+ ? Object.assign({}, prevCommittedAppState, sceneData.appState) // new instance, with partial appstate applied to previously captured one, including hidden prop inside `prevCommittedAppState`
+ : prevCommittedAppState;
+
+ const nextCommittedElements = sceneData.elements
+ ? this.store.filterUncomittedElements(
+ this.scene.getElementsMapIncludingDeleted(), // Only used to detect uncomitted local elements
+ arrayToMap(nextElements), // We expect all (already reconciled) elements
+ )
+ : prevCommittedElements;
+
+ // WARN: store action always performs deep clone of changed elements, for ephemeral remote updates (i.e. remote dragging, resizing, drawing) we might consider doing something smarter
+ // do NOT schedule store actions (execute after re-render), as it might cause unexpected concurrency issues if not handled well
+ if (sceneData.captureUpdate === CaptureUpdateAction.IMMEDIATELY) {
+ this.store.captureIncrement(
+ nextCommittedElements,
+ nextCommittedAppState,
+ );
+ } else if (sceneData.captureUpdate === CaptureUpdateAction.NEVER) {
+ this.store.updateSnapshot(
+ nextCommittedElements,
+ nextCommittedAppState,
+ );
+ }
+ }
+
+ if (sceneData.appState) {
+ this.setState(sceneData.appState);
+ }
+
+ if (sceneData.elements) {
+ this.scene.replaceAllElements(nextElements);
+ }
+
+ if (sceneData.collaborators) {
+ this.setState({ collaborators: sceneData.collaborators });
+ }
+ },
+ );
+
+ private triggerRender = (
+ /** force always re-renders canvas even if no change */
+ force?: boolean,
+ ) => {
+ if (force === true) {
+ this.scene.triggerUpdate();
+ } else {
+ this.setState({});
+ }
+ };
+
+ /**
+ * @returns whether the menu was toggled on or off
+ */
+ public toggleSidebar = ({
+ name,
+ tab,
+ force,
+ }: {
+ name: SidebarName | null;
+ tab?: SidebarTabName;
+ force?: boolean;
+ }): boolean => {
+ let nextName;
+ if (force === undefined) {
+ nextName =
+ this.state.openSidebar?.name === name &&
+ this.state.openSidebar?.tab === tab
+ ? null
+ : name;
+ } else {
+ nextName = force ? name : null;
+ }
+
+ const nextState: AppState["openSidebar"] = nextName
+ ? { name: nextName }
+ : null;
+ if (nextState && tab) {
+ nextState.tab = tab;
+ }
+
+ this.setState({ openSidebar: nextState });
+
+ return !!nextName;
+ };
+
+ private updateCurrentCursorPosition = withBatchedUpdates(
+ (event: MouseEvent) => {
+ this.lastViewportPosition.x = event.clientX;
+ this.lastViewportPosition.y = event.clientY;
+ },
+ );
+
+ public getEditorUIOffsets = (): Offsets => {
+ const toolbarBottom =
+ this.excalidrawContainerRef?.current
+ ?.querySelector(".App-toolbar")
+ ?.getBoundingClientRect()?.bottom ?? 0;
+ const sidebarRect = this.excalidrawContainerRef?.current
+ ?.querySelector(".sidebar")
+ ?.getBoundingClientRect();
+ const propertiesPanelRect = this.excalidrawContainerRef?.current
+ ?.querySelector(".App-menu__left")
+ ?.getBoundingClientRect();
+
+ const PADDING = 16;
+
+ return getLanguage().rtl
+ ? {
+ top: toolbarBottom + PADDING,
+ right:
+ Math.max(
+ this.state.width -
+ (propertiesPanelRect?.left ?? this.state.width),
+ 0,
+ ) + PADDING,
+ bottom: PADDING,
+ left: Math.max(sidebarRect?.right ?? 0, 0) + PADDING,
+ }
+ : {
+ top: toolbarBottom + PADDING,
+ right: Math.max(
+ this.state.width -
+ (sidebarRect?.left ?? this.state.width) +
+ PADDING,
+ 0,
+ ),
+ bottom: PADDING,
+ left: Math.max(propertiesPanelRect?.right ?? 0, 0) + PADDING,
+ };
+ };
+
+ // Input handling
+ private onKeyDown = withBatchedUpdates(
+ (event: React.KeyboardEvent | KeyboardEvent) => {
+ // normalize `event.key` when CapsLock is pressed #2372
+
+ if (
+ "Proxy" in window &&
+ ((!event.shiftKey && /^[A-Z]$/.test(event.key)) ||
+ (event.shiftKey && /^[a-z]$/.test(event.key)))
+ ) {
+ event = new Proxy(event, {
+ get(ev: any, prop) {
+ const value = ev[prop];
+ if (typeof value === "function") {
+ // fix for Proxies hijacking `this`
+ return value.bind(ev);
+ }
+ return prop === "key"
+ ? // CapsLock inverts capitalization based on ShiftKey, so invert
+ // it back
+ event.shiftKey
+ ? ev.key.toUpperCase()
+ : ev.key.toLowerCase()
+ : value;
+ },
+ });
+ }
+
+ if (!isInputLike(event.target)) {
+ if (
+ (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) &&
+ this.state.croppingElementId
+ ) {
+ this.finishImageCropping();
+ return;
+ }
+
+ const selectedElements = getSelectedElements(
+ this.scene.getNonDeletedElementsMap(),
+ this.state,
+ );
+
+ if (
+ selectedElements.length === 1 &&
+ isImageElement(selectedElements[0]) &&
+ event.key === KEYS.ENTER
+ ) {
+ this.startImageCropping(selectedElements[0]);
+ return;
+ }
+
+ if (
+ event.key === KEYS.ESCAPE &&
+ this.flowChartCreator.isCreatingChart
+ ) {
+ this.flowChartCreator.clear();
+ this.triggerRender(true);
+ return;
+ }
+
+ const arrowKeyPressed = isArrowKey(event.key);
+
+ if (event[KEYS.CTRL_OR_CMD] && arrowKeyPressed && !event.shiftKey) {
+ event.preventDefault();
+
+ const selectedElements = getSelectedElements(
+ this.scene.getNonDeletedElementsMap(),
+ this.state,
+ );
+
+ if (
+ selectedElements.length === 1 &&
+ isFlowchartNodeElement(selectedElements[0])
+ ) {
+ this.flowChartCreator.createNodes(
+ selectedElements[0],
+ this.scene.getNonDeletedElementsMap(),
+ this.state,
+ getLinkDirectionFromKey(event.key),
+ );
+ }
+
+ if (
+ this.flowChartCreator.pendingNodes?.length &&
+ !isElementCompletelyInViewport(
+ this.flowChartCreator.pendingNodes,
+ this.canvas.width / window.devicePixelRatio,
+ this.canvas.height / window.devicePixelRatio,
+ {
+ offsetLeft: this.state.offsetLeft,
+ offsetTop: this.state.offsetTop,
+ scrollX: this.state.scrollX,
+ scrollY: this.state.scrollY,
+ zoom: this.state.zoom,
+ },
+ this.scene.getNonDeletedElementsMap(),
+ this.getEditorUIOffsets(),
+ )
+ ) {
+ this.scrollToContent(this.flowChartCreator.pendingNodes, {
+ animate: true,
+ duration: 300,
+ fitToContent: true,
+ canvasOffsets: this.getEditorUIOffsets(),
+ });
+ }
+
+ return;
+ }
+
+ if (event.altKey) {
+ const selectedElements = getSelectedElements(
+ this.scene.getNonDeletedElementsMap(),
+ this.state,
+ );
+
+ if (selectedElements.length === 1 && arrowKeyPressed) {
+ event.preventDefault();
+
+ const nextId = this.flowChartNavigator.exploreByDirection(
+ selectedElements[0],
+ this.scene.getNonDeletedElementsMap(),
+ getLinkDirectionFromKey(event.key),
+ );
+
+ if (nextId) {
+ this.setState((prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ [nextId]: true,
+ },
+ prevState,
+ ),
+ }));
+
+ const nextNode = this.scene
+ .getNonDeletedElementsMap()
+ .get(nextId);
+
+ if (
+ nextNode &&
+ !isElementCompletelyInViewport(
+ [nextNode],
+ this.canvas.width / window.devicePixelRatio,
+ this.canvas.height / window.devicePixelRatio,
+ {
+ offsetLeft: this.state.offsetLeft,
+ offsetTop: this.state.offsetTop,
+ scrollX: this.state.scrollX,
+ scrollY: this.state.scrollY,
+ zoom: this.state.zoom,
+ },
+ this.scene.getNonDeletedElementsMap(),
+ this.getEditorUIOffsets(),
+ )
+ ) {
+ this.scrollToContent(nextNode, {
+ animate: true,
+ duration: 300,
+ canvasOffsets: this.getEditorUIOffsets(),
+ });
+ }
+ }
+ return;
+ }
+ }
+ }
+
+ if (
+ event[KEYS.CTRL_OR_CMD] &&
+ event.key === KEYS.P &&
+ !event.shiftKey &&
+ !event.altKey
+ ) {
+ this.setToast({
+ message: t("commandPalette.shortcutHint", {
+ shortcut: getShortcutFromShortcutName("commandPalette"),
+ }),
+ });
+ event.preventDefault();
+ return;
+ }
+
+ if (event[KEYS.CTRL_OR_CMD] && event.key.toLowerCase() === KEYS.V) {
+ IS_PLAIN_PASTE = event.shiftKey;
+ clearTimeout(IS_PLAIN_PASTE_TIMER);
+ // reset (100ms to be safe that we it runs after the ensuing
+ // paste event). Though, technically unnecessary to reset since we
+ // (re)set the flag before each paste event.
+ IS_PLAIN_PASTE_TIMER = window.setTimeout(() => {
+ IS_PLAIN_PASTE = false;
+ }, 100);
+ }
+
+ // prevent browser zoom in input fields
+ if (event[KEYS.CTRL_OR_CMD] && isWritableElement(event.target)) {
+ if (event.code === CODES.MINUS || event.code === CODES.EQUAL) {
+ event.preventDefault();
+ return;
+ }
+ }
+
+ // bail if
+ if (
+ // inside an input
+ (isWritableElement(event.target) &&
+ // unless pressing escape (finalize action)
+ event.key !== KEYS.ESCAPE) ||
+ // or unless using arrows (to move between buttons)
+ (isArrowKey(event.key) && isInputLike(event.target))
+ ) {
+ return;
+ }
+
+ if (event.key === KEYS.QUESTION_MARK) {
+ this.setState({
+ openDialog: { name: "help" },
+ });
+ return;
+ } else if (
+ event.key.toLowerCase() === KEYS.E &&
+ event.shiftKey &&
+ event[KEYS.CTRL_OR_CMD]
+ ) {
+ event.preventDefault();
+ this.setState({ openDialog: { name: "imageExport" } });
+ return;
+ }
+
+ if (event.key === KEYS.PAGE_UP || event.key === KEYS.PAGE_DOWN) {
+ let offset =
+ (event.shiftKey ? this.state.width : this.state.height) /
+ this.state.zoom.value;
+ if (event.key === KEYS.PAGE_DOWN) {
+ offset = -offset;
+ }
+ if (event.shiftKey) {
+ this.translateCanvas((state) => ({
+ scrollX: state.scrollX + offset,
+ }));
+ } else {
+ this.translateCanvas((state) => ({
+ scrollY: state.scrollY + offset,
+ }));
+ }
+ }
+
+ if (this.state.openDialog?.name === "elementLinkSelector") {
+ return;
+ }
+
+ if (this.actionManager.handleKeyDown(event)) {
+ return;
+ }
+
+ if (this.state.viewModeEnabled) {
+ return;
+ }
+
+ if (event[KEYS.CTRL_OR_CMD] && this.state.isBindingEnabled) {
+ this.setState({ isBindingEnabled: false });
+ }
+
+ if (isArrowKey(event.key)) {
+ let selectedElements = this.scene.getSelectedElements({
+ selectedElementIds: this.state.selectedElementIds,
+ includeBoundTextElement: true,
+ includeElementsInFrames: true,
+ });
+
+ const elbowArrow = selectedElements.find(isElbowArrow) as
+ | ExcalidrawArrowElement
+ | undefined;
+
+ const arrowIdsToRemove = new Set<string>();
+
+ selectedElements
+ .filter(isElbowArrow)
+ .filter((arrow) => {
+ const startElementNotInSelection =
+ arrow.startBinding &&
+ !selectedElements.some(
+ (el) => el.id === arrow.startBinding?.elementId,
+ );
+ const endElementNotInSelection =
+ arrow.endBinding &&
+ !selectedElements.some(
+ (el) => el.id === arrow.endBinding?.elementId,
+ );
+ return startElementNotInSelection || endElementNotInSelection;
+ })
+ .forEach((arrow) => arrowIdsToRemove.add(arrow.id));
+
+ selectedElements = selectedElements.filter(
+ (el) => !arrowIdsToRemove.has(el.id),
+ );
+
+ const step =
+ (this.getEffectiveGridSize() &&
+ (event.shiftKey
+ ? ELEMENT_TRANSLATE_AMOUNT
+ : this.getEffectiveGridSize())) ||
+ (event.shiftKey
+ ? ELEMENT_SHIFT_TRANSLATE_AMOUNT
+ : ELEMENT_TRANSLATE_AMOUNT);
+
+ let offsetX = 0;
+ let offsetY = 0;
+
+ if (event.key === KEYS.ARROW_LEFT) {
+ offsetX = -step;
+ } else if (event.key === KEYS.ARROW_RIGHT) {
+ offsetX = step;
+ } else if (event.key === KEYS.ARROW_UP) {
+ offsetY = -step;
+ } else if (event.key === KEYS.ARROW_DOWN) {
+ offsetY = step;
+ }
+
+ selectedElements.forEach((element) => {
+ mutateElement(
+ element,
+ {
+ x: element.x + offsetX,
+ y: element.y + offsetY,
+ },
+ false,
+ );
+
+ updateBoundElements(element, this.scene.getNonDeletedElementsMap(), {
+ simultaneouslyUpdated: selectedElements,
+ });
+ });
+
+ this.setState({
+ suggestedBindings: getSuggestedBindingsForArrows(
+ selectedElements.filter(
+ (element) => element.id !== elbowArrow?.id || step !== 0,
+ ),
+ this.scene.getNonDeletedElementsMap(),
+ this.state.zoom,
+ ),
+ });
+
+ this.scene.triggerUpdate();
+
+ event.preventDefault();
+ } else if (event.key === KEYS.ENTER) {
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ if (selectedElements.length === 1) {
+ const selectedElement = selectedElements[0];
+ if (event[KEYS.CTRL_OR_CMD]) {
+ if (isLinearElement(selectedElement)) {
+ if (
+ !this.state.editingLinearElement ||
+ this.state.editingLinearElement.elementId !==
+ selectedElements[0].id
+ ) {
+ this.store.shouldCaptureIncrement();
+ if (!isElbowArrow(selectedElement)) {
+ this.setState({
+ editingLinearElement: new LinearElementEditor(
+ selectedElement,
+ ),
+ });
+ }
+ }
+ }
+ } else if (
+ isTextElement(selectedElement) ||
+ isValidTextContainer(selectedElement)
+ ) {
+ let container;
+ if (!isTextElement(selectedElement)) {
+ container = selectedElement as ExcalidrawTextContainer;
+ }
+ const midPoint = getContainerCenter(
+ selectedElement,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ const sceneX = midPoint.x;
+ const sceneY = midPoint.y;
+ this.startTextEditing({
+ sceneX,
+ sceneY,
+ container,
+ });
+ event.preventDefault();
+ return;
+ } else if (isFrameLikeElement(selectedElement)) {
+ this.setState({
+ editingFrame: selectedElement.id,
+ });
+ }
+ }
+ } else if (
+ !event.ctrlKey &&
+ !event.altKey &&
+ !event.metaKey &&
+ !this.state.newElement &&
+ !this.state.selectionElement &&
+ !this.state.selectedElementsAreBeingDragged
+ ) {
+ const shape = findShapeByKey(event.key);
+ if (shape) {
+ if (this.state.activeTool.type !== shape) {
+ trackEvent(
+ "toolbar",
+ shape,
+ `keyboard (${
+ this.device.editor.isMobile ? "mobile" : "desktop"
+ })`,
+ );
+ }
+ if (shape === "arrow" && this.state.activeTool.type === "arrow") {
+ this.setState((prevState) => ({
+ currentItemArrowType:
+ prevState.currentItemArrowType === ARROW_TYPE.sharp
+ ? ARROW_TYPE.round
+ : prevState.currentItemArrowType === ARROW_TYPE.round
+ ? ARROW_TYPE.elbow
+ : ARROW_TYPE.sharp,
+ }));
+ }
+ this.setActiveTool({ type: shape });
+ event.stopPropagation();
+ } else if (event.key === KEYS.Q) {
+ this.toggleLock("keyboard");
+ event.stopPropagation();
+ }
+ }
+ if (event.key === KEYS.SPACE && gesture.pointers.size === 0) {
+ isHoldingSpace = true;
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
+ event.preventDefault();
+ }
+
+ if (
+ (event.key === KEYS.G || event.key === KEYS.S) &&
+ !event.altKey &&
+ !event[KEYS.CTRL_OR_CMD]
+ ) {
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ if (
+ this.state.activeTool.type === "selection" &&
+ !selectedElements.length
+ ) {
+ return;
+ }
+
+ if (
+ event.key === KEYS.G &&
+ (hasBackground(this.state.activeTool.type) ||
+ selectedElements.some((element) => hasBackground(element.type)))
+ ) {
+ this.setState({ openPopup: "elementBackground" });
+ event.stopPropagation();
+ }
+ if (event.key === KEYS.S) {
+ this.setState({ openPopup: "elementStroke" });
+ event.stopPropagation();
+ }
+ }
+
+ if (
+ !event[KEYS.CTRL_OR_CMD] &&
+ event.shiftKey &&
+ event.key.toLowerCase() === KEYS.F
+ ) {
+ const selectedElements = this.scene.getSelectedElements(this.state);
+
+ if (
+ this.state.activeTool.type === "selection" &&
+ !selectedElements.length
+ ) {
+ return;
+ }
+
+ if (
+ this.state.activeTool.type === "text" ||
+ selectedElements.find(
+ (element) =>
+ isTextElement(element) ||
+ getBoundTextElement(
+ element,
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ )
+ ) {
+ event.preventDefault();
+ this.setState({ openPopup: "fontFamily" });
+ }
+ }
+
+ if (event.key === KEYS.K && !event.altKey && !event[KEYS.CTRL_OR_CMD]) {
+ if (this.state.activeTool.type === "laser") {
+ this.setActiveTool({ type: "selection" });
+ } else {
+ this.setActiveTool({ type: "laser" });
+ }
+ return;
+ }
+
+ if (
+ event[KEYS.CTRL_OR_CMD] &&
+ (event.key === KEYS.BACKSPACE || event.key === KEYS.DELETE)
+ ) {
+ editorJotaiStore.set(activeConfirmDialogAtom, "clearCanvas");
+ }
+
+ // eye dropper
+ // -----------------------------------------------------------------------
+ const lowerCased = event.key.toLocaleLowerCase();
+ const isPickingStroke = lowerCased === KEYS.S && event.shiftKey;
+ const isPickingBackground =
+ event.key === KEYS.I || (lowerCased === KEYS.G && event.shiftKey);
+
+ if (isPickingStroke || isPickingBackground) {
+ this.openEyeDropper({
+ type: isPickingStroke ? "stroke" : "background",
+ });
+ }
+ // -----------------------------------------------------------------------
+ },
+ );
+
+ private onKeyUp = withBatchedUpdates((event: KeyboardEvent) => {
+ if (event.key === KEYS.SPACE) {
+ if (
+ this.state.viewModeEnabled ||
+ this.state.openDialog?.name === "elementLinkSelector"
+ ) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
+ } else if (this.state.activeTool.type === "selection") {
+ resetCursor(this.interactiveCanvas);
+ } else {
+ setCursorForShape(this.interactiveCanvas, this.state);
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.state),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ });
+ }
+ isHoldingSpace = false;
+ }
+ if (!event[KEYS.CTRL_OR_CMD] && !this.state.isBindingEnabled) {
+ this.setState({ isBindingEnabled: true });
+ }
+ if (isArrowKey(event.key)) {
+ bindOrUnbindLinearElements(
+ this.scene.getSelectedElements(this.state).filter(isLinearElement),
+ this.scene.getNonDeletedElementsMap(),
+ this.scene.getNonDeletedElements(),
+ this.scene,
+ isBindingEnabled(this.state),
+ this.state.selectedLinearElement?.selectedPointsIndices ?? [],
+ this.state.zoom,
+ );
+ this.setState({ suggestedBindings: [] });
+ }
+
+ if (!event.altKey) {
+ if (this.flowChartNavigator.isExploring) {
+ this.flowChartNavigator.clear();
+ this.syncActionResult({
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+ }
+ }
+
+ if (!event[KEYS.CTRL_OR_CMD]) {
+ if (this.flowChartCreator.isCreatingChart) {
+ if (this.flowChartCreator.pendingNodes?.length) {
+ this.scene.insertElements(this.flowChartCreator.pendingNodes);
+ }
+
+ const firstNode = this.flowChartCreator.pendingNodes?.[0];
+
+ if (firstNode) {
+ this.setState((prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ [firstNode.id]: true,
+ },
+ prevState,
+ ),
+ }));
+
+ if (
+ !isElementCompletelyInViewport(
+ [firstNode],
+ this.canvas.width / window.devicePixelRatio,
+ this.canvas.height / window.devicePixelRatio,
+ {
+ offsetLeft: this.state.offsetLeft,
+ offsetTop: this.state.offsetTop,
+ scrollX: this.state.scrollX,
+ scrollY: this.state.scrollY,
+ zoom: this.state.zoom,
+ },
+ this.scene.getNonDeletedElementsMap(),
+ this.getEditorUIOffsets(),
+ )
+ ) {
+ this.scrollToContent(firstNode, {
+ animate: true,
+ duration: 300,
+ canvasOffsets: this.getEditorUIOffsets(),
+ });
+ }
+ }
+
+ this.flowChartCreator.clear();
+ this.syncActionResult({
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+ }
+ }
+ });
+
+ // We purposely widen the `tool` type so this helper can be called with
+ // any tool without having to type check it
+ private isToolSupported = <T extends ToolType | "custom">(tool: T) => {
+ return (
+ this.props.UIOptions.tools?.[
+ tool as Extract<T, keyof AppProps["UIOptions"]["tools"]>
+ ] !== false
+ );
+ };
+
+ setActiveTool = (
+ tool: (
+ | (
+ | { type: Exclude<ToolType, "image"> }
+ | {
+ type: Extract<ToolType, "image">;
+ insertOnCanvasDirectly?: boolean;
+ }
+ )
+ | { type: "custom"; customType: string }
+ ) & { locked?: boolean },
+ ) => {
+ if (!this.isToolSupported(tool.type)) {
+ console.warn(
+ `"${tool.type}" tool is disabled via "UIOptions.canvasActions.tools.${tool.type}"`,
+ );
+ return;
+ }
+
+ const nextActiveTool = updateActiveTool(this.state, tool);
+ if (nextActiveTool.type === "hand") {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
+ } else if (!isHoldingSpace) {
+ setCursorForShape(this.interactiveCanvas, {
+ ...this.state,
+ activeTool: nextActiveTool,
+ });
+ }
+ if (isToolIcon(document.activeElement)) {
+ this.focusContainer();
+ }
+ if (!isLinearElementType(nextActiveTool.type)) {
+ this.setState({ suggestedBindings: [] });
+ }
+ if (nextActiveTool.type === "image") {
+ this.onImageAction({
+ insertOnCanvasDirectly:
+ (tool.type === "image" && tool.insertOnCanvasDirectly) ?? false,
+ });
+ }
+
+ this.setState((prevState) => {
+ const commonResets = {
+ snapLines: prevState.snapLines.length ? [] : prevState.snapLines,
+ originSnapOffset: null,
+ activeEmbeddable: null,
+ } as const;
+
+ if (nextActiveTool.type === "freedraw") {
+ this.store.shouldCaptureIncrement();
+ }
+
+ if (nextActiveTool.type !== "selection") {
+ return {
+ ...prevState,
+ activeTool: nextActiveTool,
+ selectedElementIds: makeNextSelectedElementIds({}, prevState),
+ selectedGroupIds: makeNextSelectedElementIds({}, prevState),
+ editingGroupId: null,
+ multiElement: null,
+ ...commonResets,
+ };
+ }
+ return {
+ ...prevState,
+ activeTool: nextActiveTool,
+ ...commonResets,
+ };
+ });
+ };
+
+ setOpenDialog = (dialogType: AppState["openDialog"]) => {
+ this.setState({ openDialog: dialogType });
+ };
+
+ private setCursor = (cursor: string) => {
+ setCursor(this.interactiveCanvas, cursor);
+ };
+
+ private resetCursor = () => {
+ resetCursor(this.interactiveCanvas);
+ };
+ /**
+ * returns whether user is making a gesture with >= 2 fingers (points)
+ * on o touch screen (not on a trackpad). Currently only relates to Darwin
+ * (iOS/iPadOS,MacOS), but may work on other devices in the future if
+ * GestureEvent is standardized.
+ */
+ private isTouchScreenMultiTouchGesture = () => {
+ // we don't want to deselect when using trackpad, and multi-point gestures
+ // only work on touch screens, so checking for >= pointers means we're on a
+ // touchscreen
+ return gesture.pointers.size >= 2;
+ };
+
+ public getName = () => {
+ return (
+ this.state.name ||
+ this.props.name ||
+ `${t("labels.untitled")}-${getDateTime()}`
+ );
+ };
+
+ // fires only on Safari
+ private onGestureStart = withBatchedUpdates((event: GestureEvent) => {
+ event.preventDefault();
+
+ // we only want to deselect on touch screens because user may have selected
+ // elements by mistake while zooming
+ if (this.isTouchScreenMultiTouchGesture()) {
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.state),
+ activeEmbeddable: null,
+ });
+ }
+ gesture.initialScale = this.state.zoom.value;
+ });
+
+ // fires only on Safari
+ private onGestureChange = withBatchedUpdates((event: GestureEvent) => {
+ event.preventDefault();
+
+ // onGestureChange only has zoom factor but not the center.
+ // If we're on iPad or iPhone, then we recognize multi-touch and will
+ // zoom in at the right location in the touchmove handler
+ // (handleCanvasPointerMove).
+ //
+ // On Macbook trackpad, we don't have those events so will zoom in at the
+ // current location instead.
+ //
+ // As such, bail from this handler on touch devices.
+ if (this.isTouchScreenMultiTouchGesture()) {
+ return;
+ }
+
+ const initialScale = gesture.initialScale;
+ if (initialScale) {
+ this.setState((state) => ({
+ ...getStateForZoom(
+ {
+ viewportX: this.lastViewportPosition.x,
+ viewportY: this.lastViewportPosition.y,
+ nextZoom: getNormalizedZoom(initialScale * event.scale),
+ },
+ state,
+ ),
+ }));
+ }
+ });
+
+ // fires only on Safari
+ private onGestureEnd = withBatchedUpdates((event: GestureEvent) => {
+ event.preventDefault();
+ // reselect elements only on touch screens (see onGestureStart)
+ if (this.isTouchScreenMultiTouchGesture()) {
+ this.setState({
+ previousSelectedElementIds: {},
+ selectedElementIds: makeNextSelectedElementIds(
+ this.state.previousSelectedElementIds,
+ this.state,
+ ),
+ });
+ }
+ gesture.initialScale = null;
+ });
+
+ private handleTextWysiwyg(
+ element: ExcalidrawTextElement,
+ {
+ isExistingElement = false,
+ }: {
+ isExistingElement?: boolean;
+ },
+ ) {
+ const elementsMap = this.scene.getElementsMapIncludingDeleted();
+
+ const updateElement = (nextOriginalText: string, isDeleted: boolean) => {
+ this.scene.replaceAllElements([
+ // Not sure why we include deleted elements as well hence using deleted elements map
+ ...this.scene.getElementsIncludingDeleted().map((_element) => {
+ if (_element.id === element.id && isTextElement(_element)) {
+ return newElementWith(_element, {
+ originalText: nextOriginalText,
+ isDeleted: isDeleted ?? _element.isDeleted,
+ // returns (wrapped) text and new dimensions
+ ...refreshTextDimensions(
+ _element,
+ getContainerElement(_element, elementsMap),
+ elementsMap,
+ nextOriginalText,
+ ),
+ });
+ }
+ return _element;
+ }),
+ ]);
+ };
+
+ textWysiwyg({
+ id: element.id,
+ canvas: this.canvas,
+ getViewportCoords: (x, y) => {
+ const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
+ {
+ sceneX: x,
+ sceneY: y,
+ },
+ this.state,
+ );
+ return [
+ viewportX - this.state.offsetLeft,
+ viewportY - this.state.offsetTop,
+ ];
+ },
+ onChange: withBatchedUpdates((nextOriginalText) => {
+ updateElement(nextOriginalText, false);
+ if (isNonDeletedElement(element)) {
+ updateBoundElements(element, this.scene.getNonDeletedElementsMap());
+ }
+ }),
+ onSubmit: withBatchedUpdates(({ viaKeyboard, nextOriginalText }) => {
+ const isDeleted = !nextOriginalText.trim();
+ updateElement(nextOriginalText, isDeleted);
+ // select the created text element only if submitting via keyboard
+ // (when submitting via click it should act as signal to deselect)
+ if (!isDeleted && viaKeyboard) {
+ const elementIdToSelect = element.containerId
+ ? element.containerId
+ : element.id;
+
+ // needed to ensure state is updated before "finalize" action
+ // that's invoked on keyboard-submit as well
+ // TODO either move this into finalize as well, or handle all state
+ // updates in one place, skipping finalize action
+ flushSync(() => {
+ this.setState((prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ ...prevState.selectedElementIds,
+ [elementIdToSelect]: true,
+ },
+ prevState,
+ ),
+ }));
+ });
+ }
+ if (isDeleted) {
+ fixBindingsAfterDeletion(this.scene.getNonDeletedElements(), [
+ element,
+ ]);
+ }
+ if (!isDeleted || isExistingElement) {
+ this.store.shouldCaptureIncrement();
+ }
+
+ flushSync(() => {
+ this.setState({
+ newElement: null,
+ editingTextElement: null,
+ });
+ });
+
+ if (this.state.activeTool.locked) {
+ setCursorForShape(this.interactiveCanvas, this.state);
+ }
+
+ this.focusContainer();
+ }),
+ element,
+ excalidrawContainer: this.excalidrawContainerRef.current,
+ app: this,
+ // when text is selected, it's hard (at least on iOS) to re-position the
+ // caret (i.e. deselect). There's not much use for always selecting
+ // the text on edit anyway (and users can select-all from contextmenu
+ // if needed)
+ autoSelect: !this.device.isTouchScreen,
+ });
+ // deselect all other elements when inserting text
+ this.deselectElements();
+
+ // do an initial update to re-initialize element position since we were
+ // modifying element's x/y for sake of editor (case: syncing to remote)
+ updateElement(element.originalText, false);
+ }
+
+ private deselectElements() {
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.state),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ });
+ }
+
+ private getTextElementAtPosition(
+ x: number,
+ y: number,
+ ): NonDeleted<ExcalidrawTextElement> | null {
+ const element = this.getElementAtPosition(x, y, {
+ includeBoundTextElement: true,
+ });
+ if (element && isTextElement(element) && !element.isDeleted) {
+ return element;
+ }
+ return null;
+ }
+
+ private getElementAtPosition(
+ x: number,
+ y: number,
+ opts?: {
+ preferSelected?: boolean;
+ includeBoundTextElement?: boolean;
+ includeLockedElements?: boolean;
+ },
+ ): NonDeleted<ExcalidrawElement> | null {
+ const allHitElements = this.getElementsAtPosition(
+ x,
+ y,
+ opts?.includeBoundTextElement,
+ opts?.includeLockedElements,
+ );
+
+ if (allHitElements.length > 1) {
+ if (opts?.preferSelected) {
+ for (let index = allHitElements.length - 1; index > -1; index--) {
+ if (this.state.selectedElementIds[allHitElements[index].id]) {
+ return allHitElements[index];
+ }
+ }
+ }
+ const elementWithHighestZIndex =
+ allHitElements[allHitElements.length - 1];
+
+ // If we're hitting element with highest z-index only on its bounding box
+ // while also hitting other element figure, the latter should be considered.
+ return hitElementItself({
+ x,
+ y,
+ element: elementWithHighestZIndex,
+ shape: getElementShape(
+ elementWithHighestZIndex,
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ // when overlapping, we would like to be more precise
+ // this also avoids the need to update past tests
+ threshold: this.getElementHitThreshold() / 2,
+ frameNameBound: isFrameLikeElement(elementWithHighestZIndex)
+ ? this.frameNameBoundsCache.get(elementWithHighestZIndex)
+ : null,
+ })
+ ? elementWithHighestZIndex
+ : allHitElements[allHitElements.length - 2];
+ }
+ if (allHitElements.length === 1) {
+ return allHitElements[0];
+ }
+
+ return null;
+ }
+
+ private getElementsAtPosition(
+ x: number,
+ y: number,
+ includeBoundTextElement: boolean = false,
+ includeLockedElements: boolean = false,
+ ): NonDeleted<ExcalidrawElement>[] {
+ const iframeLikes: Ordered<ExcalidrawIframeElement>[] = [];
+
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+
+ const elements = (
+ includeBoundTextElement && includeLockedElements
+ ? this.scene.getNonDeletedElements()
+ : this.scene
+ .getNonDeletedElements()
+ .filter(
+ (element) =>
+ (includeLockedElements || !element.locked) &&
+ (includeBoundTextElement ||
+ !(isTextElement(element) && element.containerId)),
+ )
+ )
+ .filter((el) => this.hitElement(x, y, el))
+ .filter((element) => {
+ // hitting a frame's element from outside the frame is not considered a hit
+ const containingFrame = getContainingFrame(element, elementsMap);
+ return containingFrame &&
+ this.state.frameRendering.enabled &&
+ this.state.frameRendering.clip
+ ? isCursorInFrame({ x, y }, containingFrame, elementsMap)
+ : true;
+ })
+ .filter((el) => {
+ // The parameter elements comes ordered from lower z-index to higher.
+ // We want to preserve that order on the returned array.
+ // Exception being embeddables which should be on top of everything else in
+ // terms of hit testing.
+ if (isIframeElement(el)) {
+ iframeLikes.push(el);
+ return false;
+ }
+ return true;
+ })
+ .concat(iframeLikes) as NonDeleted<ExcalidrawElement>[];
+
+ return elements;
+ }
+
+ private getElementHitThreshold() {
+ return DEFAULT_COLLISION_THRESHOLD / this.state.zoom.value;
+ }
+
+ private hitElement(
+ x: number,
+ y: number,
+ element: ExcalidrawElement,
+ considerBoundingBox = true,
+ ) {
+ // if the element is selected, then hit test is done against its bounding box
+ if (
+ considerBoundingBox &&
+ this.state.selectedElementIds[element.id] &&
+ shouldShowBoundingBox([element], this.state)
+ ) {
+ const selectionShape = getSelectionBoxShape(
+ element,
+ this.scene.getNonDeletedElementsMap(),
+ isImageElement(element) ? 0 : this.getElementHitThreshold(),
+ );
+
+ // if hitting the bounding box, return early
+ // but if not, we should check for other cases as well (e.g. frame name)
+ if (isPointInShape(pointFrom(x, y), selectionShape)) {
+ return true;
+ }
+ }
+
+ // take bound text element into consideration for hit collision as well
+ const hitBoundTextOfElement = hitElementBoundText(
+ x,
+ y,
+ getBoundTextShape(element, this.scene.getNonDeletedElementsMap()),
+ );
+ if (hitBoundTextOfElement) {
+ return true;
+ }
+
+ return hitElementItself({
+ x,
+ y,
+ element,
+ shape: getElementShape(element, this.scene.getNonDeletedElementsMap()),
+ threshold: this.getElementHitThreshold(),
+ frameNameBound: isFrameLikeElement(element)
+ ? this.frameNameBoundsCache.get(element)
+ : null,
+ });
+ }
+
+ private getTextBindableContainerAtPosition(x: number, y: number) {
+ const elements = this.scene.getNonDeletedElements();
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ if (selectedElements.length === 1) {
+ return isTextBindableContainer(selectedElements[0], false)
+ ? selectedElements[0]
+ : null;
+ }
+ let hitElement = null;
+ // We need to do hit testing from front (end of the array) to back (beginning of the array)
+ for (let index = elements.length - 1; index >= 0; --index) {
+ if (elements[index].isDeleted) {
+ continue;
+ }
+ const [x1, y1, x2, y2] = getElementAbsoluteCoords(
+ elements[index],
+ this.scene.getNonDeletedElementsMap(),
+ );
+ if (
+ isArrowElement(elements[index]) &&
+ hitElementItself({
+ x,
+ y,
+ element: elements[index],
+ shape: getElementShape(
+ elements[index],
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ threshold: this.getElementHitThreshold(),
+ })
+ ) {
+ hitElement = elements[index];
+ break;
+ } else if (x1 < x && x < x2 && y1 < y && y < y2) {
+ hitElement = elements[index];
+ break;
+ }
+ }
+
+ return isTextBindableContainer(hitElement, false) ? hitElement : null;
+ }
+
+ private startTextEditing = ({
+ sceneX,
+ sceneY,
+ insertAtParentCenter = true,
+ container,
+ autoEdit = true,
+ }: {
+ /** X position to insert text at */
+ sceneX: number;
+ /** Y position to insert text at */
+ sceneY: number;
+ /** whether to attempt to insert at element center if applicable */
+ insertAtParentCenter?: boolean;
+ container?: ExcalidrawTextContainer | null;
+ autoEdit?: boolean;
+ }) => {
+ let shouldBindToContainer = false;
+
+ let parentCenterPosition =
+ insertAtParentCenter &&
+ this.getTextWysiwygSnappedToCenterPosition(
+ sceneX,
+ sceneY,
+ this.state,
+ container,
+ );
+ if (container && parentCenterPosition) {
+ const boundTextElementToContainer = getBoundTextElement(
+ container,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ if (!boundTextElementToContainer) {
+ shouldBindToContainer = true;
+ }
+ }
+ let existingTextElement: NonDeleted<ExcalidrawTextElement> | null = null;
+
+ const selectedElements = this.scene.getSelectedElements(this.state);
+
+ if (selectedElements.length === 1) {
+ if (isTextElement(selectedElements[0])) {
+ existingTextElement = selectedElements[0];
+ } else if (container) {
+ existingTextElement = getBoundTextElement(
+ selectedElements[0],
+ this.scene.getNonDeletedElementsMap(),
+ );
+ } else {
+ existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
+ }
+ } else {
+ existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
+ }
+
+ const fontFamily =
+ existingTextElement?.fontFamily || this.state.currentItemFontFamily;
+
+ const lineHeight =
+ existingTextElement?.lineHeight || getLineHeight(fontFamily);
+ const fontSize = this.state.currentItemFontSize;
+
+ if (
+ !existingTextElement &&
+ shouldBindToContainer &&
+ container &&
+ !isArrowElement(container)
+ ) {
+ const fontString = {
+ fontSize,
+ fontFamily,
+ };
+ const minWidth = getApproxMinLineWidth(
+ getFontString(fontString),
+ lineHeight,
+ );
+ const minHeight = getApproxMinLineHeight(fontSize, lineHeight);
+ const newHeight = Math.max(container.height, minHeight);
+ const newWidth = Math.max(container.width, minWidth);
+ mutateElement(container, { height: newHeight, width: newWidth });
+ sceneX = container.x + newWidth / 2;
+ sceneY = container.y + newHeight / 2;
+ if (parentCenterPosition) {
+ parentCenterPosition = this.getTextWysiwygSnappedToCenterPosition(
+ sceneX,
+ sceneY,
+ this.state,
+ container,
+ );
+ }
+ }
+
+ const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
+ x: sceneX,
+ y: sceneY,
+ });
+
+ const element = existingTextElement
+ ? existingTextElement
+ : newTextElement({
+ x: parentCenterPosition
+ ? parentCenterPosition.elementCenterX
+ : sceneX,
+ y: parentCenterPosition
+ ? parentCenterPosition.elementCenterY
+ : sceneY,
+ strokeColor: this.state.currentItemStrokeColor,
+ backgroundColor: this.state.currentItemBackgroundColor,
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roughness: this.state.currentItemRoughness,
+ opacity: this.state.currentItemOpacity,
+ text: "",
+ fontSize,
+ fontFamily,
+ textAlign: parentCenterPosition
+ ? "center"
+ : this.state.currentItemTextAlign,
+ verticalAlign: parentCenterPosition
+ ? VERTICAL_ALIGN.MIDDLE
+ : DEFAULT_VERTICAL_ALIGN,
+ containerId: shouldBindToContainer ? container?.id : undefined,
+ groupIds: container?.groupIds ?? [],
+ lineHeight,
+ angle: container?.angle ?? (0 as Radians),
+ frameId: topLayerFrame ? topLayerFrame.id : null,
+ });
+
+ if (!existingTextElement && shouldBindToContainer && container) {
+ mutateElement(container, {
+ boundElements: (container.boundElements || []).concat({
+ type: "text",
+ id: element.id,
+ }),
+ });
+ }
+ this.setState({ editingTextElement: element });
+
+ if (!existingTextElement) {
+ if (container && shouldBindToContainer) {
+ const containerIndex = this.scene.getElementIndex(container.id);
+ this.scene.insertElementAtIndex(element, containerIndex + 1);
+ } else {
+ this.scene.insertElement(element);
+ }
+ }
+
+ if (autoEdit || existingTextElement || container) {
+ this.handleTextWysiwyg(element, {
+ isExistingElement: !!existingTextElement,
+ });
+ } else {
+ this.setState({
+ newElement: element,
+ multiElement: null,
+ });
+ }
+ };
+
+ private startImageCropping = (image: ExcalidrawImageElement) => {
+ this.store.shouldCaptureIncrement();
+ this.setState({
+ croppingElementId: image.id,
+ });
+ };
+
+ private finishImageCropping = () => {
+ if (this.state.croppingElementId) {
+ this.store.shouldCaptureIncrement();
+ this.setState({
+ croppingElementId: null,
+ });
+ }
+ };
+
+ private handleCanvasDoubleClick = (
+ event: React.MouseEvent<HTMLCanvasElement>,
+ ) => {
+ // case: double-clicking with arrow/line tool selected would both create
+ // text and enter multiElement mode
+ if (this.state.multiElement) {
+ return;
+ }
+ // we should only be able to double click when mode is selection
+ if (this.state.activeTool.type !== "selection") {
+ return;
+ }
+
+ const selectedElements = this.scene.getSelectedElements(this.state);
+
+ let { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
+ event,
+ this.state,
+ );
+
+ if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
+ if (
+ event[KEYS.CTRL_OR_CMD] &&
+ (!this.state.editingLinearElement ||
+ this.state.editingLinearElement.elementId !==
+ selectedElements[0].id) &&
+ !isElbowArrow(selectedElements[0])
+ ) {
+ this.store.shouldCaptureIncrement();
+ this.setState({
+ editingLinearElement: new LinearElementEditor(selectedElements[0]),
+ });
+ return;
+ } else if (
+ this.state.selectedLinearElement &&
+ isElbowArrow(selectedElements[0])
+ ) {
+ const hitCoords = LinearElementEditor.getSegmentMidpointHitCoords(
+ this.state.selectedLinearElement,
+ { x: sceneX, y: sceneY },
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ const midPoint = hitCoords
+ ? LinearElementEditor.getSegmentMidPointIndex(
+ this.state.selectedLinearElement,
+ this.state,
+ hitCoords,
+ this.scene.getNonDeletedElementsMap(),
+ )
+ : -1;
+
+ if (midPoint && midPoint > -1) {
+ this.store.shouldCaptureIncrement();
+ LinearElementEditor.deleteFixedSegment(selectedElements[0], midPoint);
+
+ const nextCoords = LinearElementEditor.getSegmentMidpointHitCoords(
+ {
+ ...this.state.selectedLinearElement,
+ segmentMidPointHoveredCoords: null,
+ },
+ { x: sceneX, y: sceneY },
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ const nextIndex = nextCoords
+ ? LinearElementEditor.getSegmentMidPointIndex(
+ this.state.selectedLinearElement,
+ this.state,
+ nextCoords,
+ this.scene.getNonDeletedElementsMap(),
+ )
+ : null;
+
+ this.setState({
+ selectedLinearElement: {
+ ...this.state.selectedLinearElement,
+ pointerDownState: {
+ ...this.state.selectedLinearElement.pointerDownState,
+ segmentMidpoint: {
+ index: nextIndex,
+ value: hitCoords,
+ added: false,
+ },
+ },
+ segmentMidPointHoveredCoords: nextCoords,
+ },
+ });
+
+ return;
+ }
+ }
+ }
+
+ if (selectedElements.length === 1 && isImageElement(selectedElements[0])) {
+ this.startImageCropping(selectedElements[0]);
+ return;
+ }
+
+ resetCursor(this.interactiveCanvas);
+
+ const selectedGroupIds = getSelectedGroupIds(this.state);
+
+ if (selectedGroupIds.length > 0) {
+ const hitElement = this.getElementAtPosition(sceneX, sceneY);
+
+ const selectedGroupId =
+ hitElement &&
+ getSelectedGroupIdForElement(hitElement, this.state.selectedGroupIds);
+
+ if (selectedGroupId) {
+ this.store.shouldCaptureIncrement();
+ this.setState((prevState) => ({
+ ...prevState,
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: selectedGroupId,
+ selectedElementIds: { [hitElement!.id]: true },
+ },
+ this.scene.getNonDeletedElements(),
+ prevState,
+ this,
+ ),
+ }));
+ return;
+ }
+ }
+
+ resetCursor(this.interactiveCanvas);
+ if (!event[KEYS.CTRL_OR_CMD] && !this.state.viewModeEnabled) {
+ const hitElement = this.getElementAtPosition(sceneX, sceneY);
+
+ if (isIframeLikeElement(hitElement)) {
+ this.setState({
+ activeEmbeddable: { element: hitElement, state: "active" },
+ });
+ return;
+ }
+
+ const container = this.getTextBindableContainerAtPosition(sceneX, sceneY);
+
+ if (container) {
+ if (
+ hasBoundTextElement(container) ||
+ !isTransparent(container.backgroundColor) ||
+ hitElementItself({
+ x: sceneX,
+ y: sceneY,
+ element: container,
+ shape: getElementShape(
+ container,
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ threshold: this.getElementHitThreshold(),
+ })
+ ) {
+ const midPoint = getContainerCenter(
+ container,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+
+ sceneX = midPoint.x;
+ sceneY = midPoint.y;
+ }
+ }
+
+ this.startTextEditing({
+ sceneX,
+ sceneY,
+ insertAtParentCenter: !event.altKey,
+ container,
+ });
+ }
+ };
+
+ private getElementLinkAtPosition = (
+ scenePointer: Readonly<{ x: number; y: number }>,
+ hitElement: NonDeletedExcalidrawElement | null,
+ ): ExcalidrawElement | undefined => {
+ const elements = this.scene.getNonDeletedElements();
+ let hitElementIndex = -1;
+
+ for (let index = elements.length - 1; index >= 0; index--) {
+ const element = elements[index];
+ if (hitElement && element.id === hitElement.id) {
+ hitElementIndex = index;
+ }
+ if (
+ element.link &&
+ index >= hitElementIndex &&
+ isPointHittingLink(
+ element,
+ this.scene.getNonDeletedElementsMap(),
+ this.state,
+ pointFrom(scenePointer.x, scenePointer.y),
+ this.device.editor.isMobile,
+ )
+ ) {
+ return element;
+ }
+ }
+ };
+
+ private redirectToLink = (
+ event: React.PointerEvent<HTMLCanvasElement>,
+ isTouchScreen: boolean,
+ ) => {
+ const draggedDistance = pointDistance(
+ pointFrom(
+ this.lastPointerDownEvent!.clientX,
+ this.lastPointerDownEvent!.clientY,
+ ),
+ pointFrom(
+ this.lastPointerUpEvent!.clientX,
+ this.lastPointerUpEvent!.clientY,
+ ),
+ );
+ if (!this.hitLinkElement || draggedDistance > DRAGGING_THRESHOLD) {
+ return;
+ }
+ const lastPointerDownCoords = viewportCoordsToSceneCoords(
+ this.lastPointerDownEvent!,
+ this.state,
+ );
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+ const lastPointerDownHittingLinkIcon = isPointHittingLink(
+ this.hitLinkElement,
+ elementsMap,
+ this.state,
+ pointFrom(lastPointerDownCoords.x, lastPointerDownCoords.y),
+ this.device.editor.isMobile,
+ );
+ const lastPointerUpCoords = viewportCoordsToSceneCoords(
+ this.lastPointerUpEvent!,
+ this.state,
+ );
+ const lastPointerUpHittingLinkIcon = isPointHittingLink(
+ this.hitLinkElement,
+ elementsMap,
+ this.state,
+ pointFrom(lastPointerUpCoords.x, lastPointerUpCoords.y),
+ this.device.editor.isMobile,
+ );
+ if (lastPointerDownHittingLinkIcon && lastPointerUpHittingLinkIcon) {
+ hideHyperlinkToolip();
+ let url = this.hitLinkElement.link;
+ if (url) {
+ url = normalizeLink(url);
+ let customEvent;
+ if (this.props.onLinkOpen) {
+ customEvent = wrapEvent(EVENT.EXCALIDRAW_LINK, event.nativeEvent);
+ this.props.onLinkOpen(
+ {
+ ...this.hitLinkElement,
+ link: url,
+ },
+ customEvent,
+ );
+ }
+ if (!customEvent?.defaultPrevented) {
+ const target = isLocalLink(url) ? "_self" : "_blank";
+ const newWindow = window.open(undefined, target);
+ // https://mathiasbynens.github.io/rel-noopener/
+ if (newWindow) {
+ newWindow.opener = null;
+ newWindow.location = url;
+ }
+ }
+ }
+ }
+ };
+
+ private getTopLayerFrameAtSceneCoords = (sceneCoords: {
+ x: number;
+ y: number;
+ }) => {
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+ const frames = this.scene
+ .getNonDeletedFramesLikes()
+ .filter((frame): frame is ExcalidrawFrameLikeElement =>
+ isCursorInFrame(sceneCoords, frame, elementsMap),
+ );
+
+ return frames.length ? frames[frames.length - 1] : null;
+ };
+
+ private handleCanvasPointerMove = (
+ event: React.PointerEvent<HTMLCanvasElement>,
+ ) => {
+ this.savePointer(event.clientX, event.clientY, this.state.cursorButton);
+ this.lastPointerMoveEvent = event.nativeEvent;
+
+ if (gesture.pointers.has(event.pointerId)) {
+ gesture.pointers.set(event.pointerId, {
+ x: event.clientX,
+ y: event.clientY,
+ });
+ }
+
+ const initialScale = gesture.initialScale;
+ if (
+ gesture.pointers.size === 2 &&
+ gesture.lastCenter &&
+ initialScale &&
+ gesture.initialDistance
+ ) {
+ const center = getCenter(gesture.pointers);
+ const deltaX = center.x - gesture.lastCenter.x;
+ const deltaY = center.y - gesture.lastCenter.y;
+ gesture.lastCenter = center;
+
+ const distance = getDistance(Array.from(gesture.pointers.values()));
+ const scaleFactor =
+ this.state.activeTool.type === "freedraw" && this.state.penMode
+ ? 1
+ : distance / gesture.initialDistance;
+
+ const nextZoom = scaleFactor
+ ? getNormalizedZoom(initialScale * scaleFactor)
+ : this.state.zoom.value;
+
+ this.setState((state) => {
+ const zoomState = getStateForZoom(
+ {
+ viewportX: center.x,
+ viewportY: center.y,
+ nextZoom,
+ },
+ state,
+ );
+
+ this.translateCanvas({
+ zoom: zoomState.zoom,
+ // 2x multiplier is just a magic number that makes this work correctly
+ // on touchscreen devices (note: if we get report that panning is slower/faster
+ // than actual movement, consider swapping with devicePixelRatio)
+ scrollX: zoomState.scrollX + 2 * (deltaX / nextZoom),
+ scrollY: zoomState.scrollY + 2 * (deltaY / nextZoom),
+ shouldCacheIgnoreZoom: true,
+ });
+ });
+ this.resetShouldCacheIgnoreZoomDebounced();
+ } else {
+ gesture.lastCenter =
+ gesture.initialDistance =
+ gesture.initialScale =
+ null;
+ }
+
+ if (
+ isHoldingSpace ||
+ isPanning ||
+ isDraggingScrollBar ||
+ isHandToolActive(this.state)
+ ) {
+ return;
+ }
+
+ const isPointerOverScrollBars = isOverScrollBars(
+ currentScrollBars,
+ event.clientX - this.state.offsetLeft,
+ event.clientY - this.state.offsetTop,
+ );
+ const isOverScrollBar = isPointerOverScrollBars.isOverEither;
+ if (
+ !this.state.newElement &&
+ !this.state.selectionElement &&
+ !this.state.selectedElementsAreBeingDragged &&
+ !this.state.multiElement
+ ) {
+ if (isOverScrollBar) {
+ resetCursor(this.interactiveCanvas);
+ } else {
+ setCursorForShape(this.interactiveCanvas, this.state);
+ }
+ }
+
+ const scenePointer = viewportCoordsToSceneCoords(event, this.state);
+ const { x: scenePointerX, y: scenePointerY } = scenePointer;
+
+ if (
+ !this.state.newElement &&
+ isActiveToolNonLinearSnappable(this.state.activeTool.type)
+ ) {
+ const { originOffset, snapLines } = getSnapLinesAtPointer(
+ this.scene.getNonDeletedElements(),
+ this,
+ {
+ x: scenePointerX,
+ y: scenePointerY,
+ },
+ event,
+ this.scene.getNonDeletedElementsMap(),
+ );
+
+ this.setState((prevState) => {
+ const nextSnapLines = updateStable(prevState.snapLines, snapLines);
+ const nextOriginOffset = prevState.originSnapOffset
+ ? updateStable(prevState.originSnapOffset, originOffset)
+ : originOffset;
+
+ if (
+ prevState.snapLines === nextSnapLines &&
+ prevState.originSnapOffset === nextOriginOffset
+ ) {
+ return null;
+ }
+ return {
+ snapLines: nextSnapLines,
+ originSnapOffset: nextOriginOffset,
+ };
+ });
+ } else if (
+ !this.state.newElement &&
+ !this.state.selectedElementsAreBeingDragged &&
+ !this.state.selectionElement
+ ) {
+ this.setState((prevState) => {
+ if (prevState.snapLines.length) {
+ return {
+ snapLines: [],
+ };
+ }
+ return null;
+ });
+ }
+
+ if (
+ this.state.editingLinearElement &&
+ !this.state.editingLinearElement.isDragging
+ ) {
+ const editingLinearElement = LinearElementEditor.handlePointerMove(
+ event,
+ scenePointerX,
+ scenePointerY,
+ this,
+ this.scene.getNonDeletedElementsMap(),
+ );
+
+ if (
+ editingLinearElement &&
+ editingLinearElement !== this.state.editingLinearElement
+ ) {
+ // Since we are reading from previous state which is not possible with
+ // automatic batching in React 18 hence using flush sync to synchronously
+ // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
+ flushSync(() => {
+ this.setState({
+ editingLinearElement,
+ });
+ });
+ }
+ if (editingLinearElement?.lastUncommittedPoint != null) {
+ this.maybeSuggestBindingAtCursor(
+ scenePointer,
+ editingLinearElement.elbowed,
+ );
+ } else {
+ // causes stack overflow if not sync
+ flushSync(() => {
+ this.setState({ suggestedBindings: [] });
+ });
+ }
+ }
+
+ if (isBindingElementType(this.state.activeTool.type)) {
+ // Hovering with a selected tool or creating new linear element via click
+ // and point
+ const { newElement } = this.state;
+ if (isBindingElement(newElement, false)) {
+ this.maybeSuggestBindingsForLinearElementAtCoords(
+ newElement,
+ [scenePointer],
+ this.state.startBoundElement,
+ );
+ } else {
+ this.maybeSuggestBindingAtCursor(scenePointer, false);
+ }
+ }
+
+ if (this.state.multiElement) {
+ const { multiElement } = this.state;
+ const { x: rx, y: ry } = multiElement;
+
+ const { points, lastCommittedPoint } = multiElement;
+ const lastPoint = points[points.length - 1];
+
+ setCursorForShape(this.interactiveCanvas, this.state);
+
+ if (lastPoint === lastCommittedPoint) {
+ // if we haven't yet created a temp point and we're beyond commit-zone
+ // threshold, add a point
+ if (
+ pointDistance(
+ pointFrom(scenePointerX - rx, scenePointerY - ry),
+ lastPoint,
+ ) >= LINE_CONFIRM_THRESHOLD
+ ) {
+ mutateElement(
+ multiElement,
+ {
+ points: [
+ ...points,
+ pointFrom<LocalPoint>(scenePointerX - rx, scenePointerY - ry),
+ ],
+ },
+ false,
+ );
+ } else {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
+ // in this branch, we're inside the commit zone, and no uncommitted
+ // point exists. Thus do nothing (don't add/remove points).
+ }
+ } else if (
+ points.length > 2 &&
+ lastCommittedPoint &&
+ pointDistance(
+ pointFrom(scenePointerX - rx, scenePointerY - ry),
+ lastCommittedPoint,
+ ) < LINE_CONFIRM_THRESHOLD
+ ) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
+ mutateElement(
+ multiElement,
+ {
+ points: points.slice(0, -1),
+ },
+ false,
+ );
+ } else {
+ const [gridX, gridY] = getGridPoint(
+ scenePointerX,
+ scenePointerY,
+ event[KEYS.CTRL_OR_CMD] || isElbowArrow(multiElement)
+ ? null
+ : this.getEffectiveGridSize(),
+ );
+
+ const [lastCommittedX, lastCommittedY] =
+ multiElement?.lastCommittedPoint ?? [0, 0];
+
+ let dxFromLastCommitted = gridX - rx - lastCommittedX;
+ let dyFromLastCommitted = gridY - ry - lastCommittedY;
+
+ if (shouldRotateWithDiscreteAngle(event)) {
+ ({ width: dxFromLastCommitted, height: dyFromLastCommitted } =
+ getLockedLinearCursorAlignSize(
+ // actual coordinate of the last committed point
+ lastCommittedX + rx,
+ lastCommittedY + ry,
+ // cursor-grid coordinate
+ gridX,
+ gridY,
+ ));
+ }
+
+ if (isPathALoop(points, this.state.zoom.value)) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
+ }
+ // update last uncommitted point
+ mutateElement(
+ multiElement,
+ {
+ points: [
+ ...points.slice(0, -1),
+ pointFrom<LocalPoint>(
+ lastCommittedX + dxFromLastCommitted,
+ lastCommittedY + dyFromLastCommitted,
+ ),
+ ],
+ },
+ false,
+ {
+ isDragging: true,
+ },
+ );
+
+ // in this path, we're mutating multiElement to reflect
+ // how it will be after adding pointer position as the next point
+ // trigger update here so that new element canvas renders again to reflect this
+ this.triggerRender(false);
+ }
+
+ return;
+ }
+
+ const hasDeselectedButton = Boolean(event.buttons);
+ if (
+ hasDeselectedButton ||
+ (this.state.activeTool.type !== "selection" &&
+ this.state.activeTool.type !== "text" &&
+ this.state.activeTool.type !== "eraser")
+ ) {
+ return;
+ }
+
+ const elements = this.scene.getNonDeletedElements();
+
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ if (
+ selectedElements.length === 1 &&
+ !isOverScrollBar &&
+ !this.state.editingLinearElement
+ ) {
+ // for linear elements, we'd like to prioritize point dragging over edge resizing
+ // therefore, we update and check hovered point index first
+ if (this.state.selectedLinearElement) {
+ this.handleHoverSelectedLinearElement(
+ this.state.selectedLinearElement,
+ scenePointerX,
+ scenePointerY,
+ );
+ }
+
+ if (
+ (!this.state.selectedLinearElement ||
+ this.state.selectedLinearElement.hoverPointIndex === -1) &&
+ this.state.openDialog?.name !== "elementLinkSelector" &&
+ !(selectedElements.length === 1 && isElbowArrow(selectedElements[0]))
+ ) {
+ const elementWithTransformHandleType =
+ getElementWithTransformHandleType(
+ elements,
+ this.state,
+ scenePointerX,
+ scenePointerY,
+ this.state.zoom,
+ event.pointerType,
+ this.scene.getNonDeletedElementsMap(),
+ this.device,
+ );
+ if (
+ elementWithTransformHandleType &&
+ elementWithTransformHandleType.transformHandleType
+ ) {
+ setCursor(
+ this.interactiveCanvas,
+ getCursorForResizingElement(elementWithTransformHandleType),
+ );
+ return;
+ }
+ }
+ } else if (
+ selectedElements.length > 1 &&
+ !isOverScrollBar &&
+ this.state.openDialog?.name !== "elementLinkSelector"
+ ) {
+ const transformHandleType = getTransformHandleTypeFromCoords(
+ getCommonBounds(selectedElements),
+ scenePointerX,
+ scenePointerY,
+ this.state.zoom,
+ event.pointerType,
+ this.device,
+ );
+ if (transformHandleType) {
+ setCursor(
+ this.interactiveCanvas,
+ getCursorForResizingElement({
+ transformHandleType,
+ }),
+ );
+ return;
+ }
+ }
+
+ const hitElement = this.getElementAtPosition(
+ scenePointer.x,
+ scenePointer.y,
+ );
+
+ this.hitLinkElement = this.getElementLinkAtPosition(
+ scenePointer,
+ hitElement,
+ );
+ if (isEraserActive(this.state)) {
+ return;
+ }
+ if (
+ this.hitLinkElement &&
+ !this.state.selectedElementIds[this.hitLinkElement.id]
+ ) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
+ showHyperlinkTooltip(
+ this.hitLinkElement,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ } else {
+ hideHyperlinkToolip();
+ if (
+ hitElement &&
+ (hitElement.link || isEmbeddableElement(hitElement)) &&
+ this.state.selectedElementIds[hitElement.id] &&
+ !this.state.contextMenu &&
+ !this.state.showHyperlinkPopup
+ ) {
+ this.setState({ showHyperlinkPopup: "info" });
+ } else if (this.state.activeTool.type === "text") {
+ setCursor(
+ this.interactiveCanvas,
+ isTextElement(hitElement) ? CURSOR_TYPE.TEXT : CURSOR_TYPE.CROSSHAIR,
+ );
+ } else if (this.state.viewModeEnabled) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
+ } else if (this.state.openDialog?.name === "elementLinkSelector") {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
+ } else if (isOverScrollBar) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
+ } else if (this.state.selectedLinearElement) {
+ this.handleHoverSelectedLinearElement(
+ this.state.selectedLinearElement,
+ scenePointerX,
+ scenePointerY,
+ );
+ } else if (
+ // if using cmd/ctrl, we're not dragging
+ !event[KEYS.CTRL_OR_CMD]
+ ) {
+ if (
+ (hitElement ||
+ this.isHittingCommonBoundingBoxOfSelectedElements(
+ scenePointer,
+ selectedElements,
+ )) &&
+ !hitElement?.locked
+ ) {
+ if (
+ hitElement &&
+ isIframeLikeElement(hitElement) &&
+ this.isIframeLikeElementCenter(
+ hitElement,
+ event,
+ scenePointerX,
+ scenePointerY,
+ )
+ ) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
+ this.setState({
+ activeEmbeddable: { element: hitElement, state: "hover" },
+ });
+ } else if (!hitElement || !isElbowArrow(hitElement)) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
+ if (this.state.activeEmbeddable?.state === "hover") {
+ this.setState({ activeEmbeddable: null });
+ }
+ }
+ }
+ } else {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
+ }
+ }
+
+ if (this.state.openDialog?.name === "elementLinkSelector" && hitElement) {
+ this.setState((prevState) => {
+ return {
+ hoveredElementIds: updateStable(
+ prevState.hoveredElementIds,
+ selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: { [hitElement.id]: true },
+ },
+ this.scene.getNonDeletedElements(),
+ prevState,
+ this,
+ ).selectedElementIds,
+ ),
+ };
+ });
+ } else if (
+ this.state.openDialog?.name === "elementLinkSelector" &&
+ !hitElement
+ ) {
+ this.setState((prevState) => ({
+ hoveredElementIds: updateStable(prevState.hoveredElementIds, {}),
+ }));
+ }
+ };
+
+ private handleEraser = (
+ event: PointerEvent,
+ pointerDownState: PointerDownState,
+ scenePointer: { x: number; y: number },
+ ) => {
+ this.eraserTrail.addPointToPath(scenePointer.x, scenePointer.y);
+
+ let didChange = false;
+
+ const processedGroups = new Set<ExcalidrawElement["id"]>();
+ const nonDeletedElements = this.scene.getNonDeletedElements();
+
+ const processElements = (elements: ExcalidrawElement[]) => {
+ for (const element of elements) {
+ if (element.locked) {
+ return;
+ }
+
+ if (event.altKey) {
+ if (this.elementsPendingErasure.delete(element.id)) {
+ didChange = true;
+ }
+ } else if (!this.elementsPendingErasure.has(element.id)) {
+ didChange = true;
+ this.elementsPendingErasure.add(element.id);
+ }
+
+ // (un)erase groups atomically
+ if (didChange && element.groupIds?.length) {
+ const shallowestGroupId = element.groupIds.at(-1)!;
+ if (!processedGroups.has(shallowestGroupId)) {
+ processedGroups.add(shallowestGroupId);
+ const elems = getElementsInGroup(
+ nonDeletedElements,
+ shallowestGroupId,
+ );
+ for (const elem of elems) {
+ if (event.altKey) {
+ this.elementsPendingErasure.delete(elem.id);
+ } else {
+ this.elementsPendingErasure.add(elem.id);
+ }
+ }
+ }
+ }
+ }
+ };
+
+ const distance = pointDistance(
+ pointFrom(pointerDownState.lastCoords.x, pointerDownState.lastCoords.y),
+ pointFrom(scenePointer.x, scenePointer.y),
+ );
+ const threshold = this.getElementHitThreshold();
+ const p = { ...pointerDownState.lastCoords };
+ let samplingInterval = 0;
+ while (samplingInterval <= distance) {
+ const hitElements = this.getElementsAtPosition(p.x, p.y);
+ processElements(hitElements);
+
+ // Exit since we reached current point
+ if (samplingInterval === distance) {
+ break;
+ }
+
+ // Calculate next point in the line at a distance of sampling interval
+ samplingInterval = Math.min(samplingInterval + threshold, distance);
+
+ const distanceRatio = samplingInterval / distance;
+ const nextX = (1 - distanceRatio) * p.x + distanceRatio * scenePointer.x;
+ const nextY = (1 - distanceRatio) * p.y + distanceRatio * scenePointer.y;
+ p.x = nextX;
+ p.y = nextY;
+ }
+
+ pointerDownState.lastCoords.x = scenePointer.x;
+ pointerDownState.lastCoords.y = scenePointer.y;
+
+ if (didChange) {
+ for (const element of this.scene.getNonDeletedElements()) {
+ if (
+ isBoundToContainer(element) &&
+ (this.elementsPendingErasure.has(element.id) ||
+ this.elementsPendingErasure.has(element.containerId))
+ ) {
+ if (event.altKey) {
+ this.elementsPendingErasure.delete(element.id);
+ this.elementsPendingErasure.delete(element.containerId);
+ } else {
+ this.elementsPendingErasure.add(element.id);
+ this.elementsPendingErasure.add(element.containerId);
+ }
+ }
+ }
+
+ this.elementsPendingErasure = new Set(this.elementsPendingErasure);
+ this.triggerRender();
+ }
+ };
+
+ // set touch moving for mobile context menu
+ private handleTouchMove = (event: React.TouchEvent<HTMLCanvasElement>) => {
+ invalidateContextMenu = true;
+ };
+
+ handleHoverSelectedLinearElement(
+ linearElementEditor: LinearElementEditor,
+ scenePointerX: number,
+ scenePointerY: number,
+ ) {
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+
+ const element = LinearElementEditor.getElement(
+ linearElementEditor.elementId,
+ elementsMap,
+ );
+
+ if (!element) {
+ return;
+ }
+ if (this.state.selectedLinearElement) {
+ let hoverPointIndex = -1;
+ let segmentMidPointHoveredCoords = null;
+ if (
+ hitElementItself({
+ x: scenePointerX,
+ y: scenePointerY,
+ element,
+ shape: getElementShape(
+ element,
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ })
+ ) {
+ hoverPointIndex = LinearElementEditor.getPointIndexUnderCursor(
+ element,
+ elementsMap,
+ this.state.zoom,
+ scenePointerX,
+ scenePointerY,
+ );
+ segmentMidPointHoveredCoords =
+ LinearElementEditor.getSegmentMidpointHitCoords(
+ linearElementEditor,
+ { x: scenePointerX, y: scenePointerY },
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ const isHoveringAPointHandle = isElbowArrow(element)
+ ? hoverPointIndex === 0 ||
+ hoverPointIndex === element.points.length - 1
+ : hoverPointIndex >= 0;
+ if (isHoveringAPointHandle || segmentMidPointHoveredCoords) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
+ } else if (this.hitElement(scenePointerX, scenePointerY, element)) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
+ }
+ } else if (this.hitElement(scenePointerX, scenePointerY, element)) {
+ if (
+ // Ebow arrows can only be moved when unconnected
+ !isElbowArrow(element) ||
+ !(element.startBinding || element.endBinding)
+ ) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
+ }
+ }
+
+ if (
+ this.state.selectedLinearElement.hoverPointIndex !== hoverPointIndex
+ ) {
+ this.setState({
+ selectedLinearElement: {
+ ...this.state.selectedLinearElement,
+ hoverPointIndex,
+ },
+ });
+ }
+
+ if (
+ !LinearElementEditor.arePointsEqual(
+ this.state.selectedLinearElement.segmentMidPointHoveredCoords,
+ segmentMidPointHoveredCoords,
+ )
+ ) {
+ this.setState({
+ selectedLinearElement: {
+ ...this.state.selectedLinearElement,
+ segmentMidPointHoveredCoords,
+ },
+ });
+ }
+ } else {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
+ }
+ }
+
+ private handleCanvasPointerDown = (
+ event: React.PointerEvent<HTMLElement>,
+ ) => {
+ const target = event.target as HTMLElement;
+ // capture subsequent pointer events to the canvas
+ // this makes other elements non-interactive until pointer up
+ if (target.setPointerCapture) {
+ target.setPointerCapture(event.pointerId);
+ }
+
+ this.maybeCleanupAfterMissingPointerUp(event.nativeEvent);
+ this.maybeUnfollowRemoteUser();
+
+ if (this.state.searchMatches) {
+ this.setState((state) => ({
+ searchMatches: state.searchMatches.map((searchMatch) => ({
+ ...searchMatch,
+ focus: false,
+ })),
+ }));
+ editorJotaiStore.set(searchItemInFocusAtom, null);
+ }
+
+ // since contextMenu options are potentially evaluated on each render,
+ // and an contextMenu action may depend on selection state, we must
+ // close the contextMenu before we update the selection on pointerDown
+ // (e.g. resetting selection)
+ if (this.state.contextMenu) {
+ this.setState({ contextMenu: null });
+ }
+
+ if (this.state.snapLines) {
+ this.setAppState({ snapLines: [] });
+ }
+
+ this.updateGestureOnPointerDown(event);
+
+ // if dragging element is freedraw and another pointerdown event occurs
+ // a second finger is on the screen
+ // discard the freedraw element if it is very short because it is likely
+ // just a spike, otherwise finalize the freedraw element when the second
+ // finger is lifted
+ if (
+ event.pointerType === "touch" &&
+ this.state.newElement &&
+ this.state.newElement.type === "freedraw"
+ ) {
+ const element = this.state.newElement as ExcalidrawFreeDrawElement;
+ this.updateScene({
+ ...(element.points.length < 10
+ ? {
+ elements: this.scene
+ .getElementsIncludingDeleted()
+ .filter((el) => el.id !== element.id),
+ }
+ : {}),
+ appState: {
+ newElement: null,
+ editingTextElement: null,
+ startBoundElement: null,
+ suggestedBindings: [],
+ selectedElementIds: makeNextSelectedElementIds(
+ Object.keys(this.state.selectedElementIds)
+ .filter((key) => key !== element.id)
+ .reduce((obj: { [id: string]: true }, key) => {
+ obj[key] = this.state.selectedElementIds[key];
+ return obj;
+ }, {}),
+ this.state,
+ ),
+ },
+ captureUpdate:
+ this.state.openDialog?.name === "elementLinkSelector"
+ ? CaptureUpdateAction.EVENTUALLY
+ : CaptureUpdateAction.NEVER,
+ });
+ return;
+ }
+
+ // remove any active selection when we start to interact with canvas
+ // (mainly, we care about removing selection outside the component which
+ // would prevent our copy handling otherwise)
+ const selection = document.getSelection();
+ if (selection?.anchorNode) {
+ selection.removeAllRanges();
+ }
+ this.maybeOpenContextMenuAfterPointerDownOnTouchDevices(event);
+
+ //fires only once, if pen is detected, penMode is enabled
+ //the user can disable this by toggling the penMode button
+ if (!this.state.penDetected && event.pointerType === "pen") {
+ this.setState((prevState) => {
+ return {
+ penMode: true,
+ penDetected: true,
+ };
+ });
+ }
+
+ if (
+ !this.device.isTouchScreen &&
+ ["pen", "touch"].includes(event.pointerType)
+ ) {
+ this.device = updateObject(this.device, { isTouchScreen: true });
+ }
+
+ if (isPanning) {
+ return;
+ }
+
+ this.lastPointerDownEvent = event;
+
+ // we must exit before we set `cursorButton` state and `savePointer`
+ // else it will send pointer state & laser pointer events in collab when
+ // panning
+ if (this.handleCanvasPanUsingWheelOrSpaceDrag(event)) {
+ return;
+ }
+
+ this.setState({
+ lastPointerDownWith: event.pointerType,
+ cursorButton: "down",
+ });
+ this.savePointer(event.clientX, event.clientY, "down");
+
+ if (
+ event.button === POINTER_BUTTON.ERASER &&
+ this.state.activeTool.type !== TOOL_TYPE.eraser
+ ) {
+ this.setState(
+ {
+ activeTool: updateActiveTool(this.state, {
+ type: TOOL_TYPE.eraser,
+ lastActiveToolBeforeEraser: this.state.activeTool,
+ }),
+ },
+ () => {
+ this.handleCanvasPointerDown(event);
+ const onPointerUp = () => {
+ unsubPointerUp();
+ unsubCleanup?.();
+ if (isEraserActive(this.state)) {
+ this.setState({
+ activeTool: updateActiveTool(this.state, {
+ ...(this.state.activeTool.lastActiveTool || {
+ type: TOOL_TYPE.selection,
+ }),
+ lastActiveToolBeforeEraser: null,
+ }),
+ });
+ }
+ };
+
+ const unsubPointerUp = addEventListener(
+ window,
+ EVENT.POINTER_UP,
+ onPointerUp,
+ {
+ once: true,
+ },
+ );
+ let unsubCleanup: UnsubscribeCallback | undefined;
+ // subscribe inside rAF lest it'd be triggered on the same pointerdown
+ // if we start erasing while coming from blurred document since
+ // we cleanup pointer events on focus
+ requestAnimationFrame(() => {
+ unsubCleanup =
+ this.missingPointerEventCleanupEmitter.once(onPointerUp);
+ });
+ },
+ );
+ return;
+ }
+
+ // only handle left mouse button or touch
+ if (
+ event.button !== POINTER_BUTTON.MAIN &&
+ event.button !== POINTER_BUTTON.TOUCH &&
+ event.button !== POINTER_BUTTON.ERASER
+ ) {
+ return;
+ }
+
+ // don't select while panning
+ if (gesture.pointers.size > 1) {
+ return;
+ }
+
+ // State for the duration of a pointer interaction, which starts with a
+ // pointerDown event, ends with a pointerUp event (or another pointerDown)
+ const pointerDownState = this.initialPointerDownState(event);
+
+ this.setState({
+ selectedElementsAreBeingDragged: false,
+ });
+
+ if (this.handleDraggingScrollBar(event, pointerDownState)) {
+ return;
+ }
+
+ this.clearSelectionIfNotUsingSelection();
+ this.updateBindingEnabledOnPointerMove(event);
+
+ if (this.handleSelectionOnPointerDown(event, pointerDownState)) {
+ return;
+ }
+
+ const allowOnPointerDown =
+ !this.state.penMode ||
+ event.pointerType !== "touch" ||
+ this.state.activeTool.type === "selection" ||
+ this.state.activeTool.type === "text" ||
+ this.state.activeTool.type === "image";
+
+ if (!allowOnPointerDown) {
+ return;
+ }
+
+ if (this.state.activeTool.type === "text") {
+ this.handleTextOnPointerDown(event, pointerDownState);
+ } else if (
+ this.state.activeTool.type === "arrow" ||
+ this.state.activeTool.type === "line"
+ ) {
+ this.handleLinearElementOnPointerDown(
+ event,
+ this.state.activeTool.type,
+ pointerDownState,
+ );
+ } else if (this.state.activeTool.type === "image") {
+ // reset image preview on pointerdown
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.CROSSHAIR);
+
+ // retrieve the latest element as the state may be stale
+ const pendingImageElement =
+ this.state.pendingImageElementId &&
+ this.scene.getElement(this.state.pendingImageElementId);
+
+ if (!pendingImageElement) {
+ return;
+ }
+
+ this.setState({
+ newElement: pendingImageElement as ExcalidrawNonSelectionElement,
+ pendingImageElementId: null,
+ multiElement: null,
+ });
+
+ const { x, y } = viewportCoordsToSceneCoords(event, this.state);
+
+ const frame = this.getTopLayerFrameAtSceneCoords({ x, y });
+
+ mutateElement(pendingImageElement, {
+ x,
+ y,
+ frameId: frame ? frame.id : null,
+ });
+ } else if (this.state.activeTool.type === "freedraw") {
+ this.handleFreeDrawElementOnPointerDown(
+ event,
+ this.state.activeTool.type,
+ pointerDownState,
+ );
+ } else if (this.state.activeTool.type === "custom") {
+ setCursorForShape(this.interactiveCanvas, this.state);
+ } else if (
+ this.state.activeTool.type === TOOL_TYPE.frame ||
+ this.state.activeTool.type === TOOL_TYPE.magicframe
+ ) {
+ this.createFrameElementOnPointerDown(
+ pointerDownState,
+ this.state.activeTool.type,
+ );
+ } else if (this.state.activeTool.type === "laser") {
+ this.laserTrails.startPath(
+ pointerDownState.lastCoords.x,
+ pointerDownState.lastCoords.y,
+ );
+ } else if (
+ this.state.activeTool.type !== "eraser" &&
+ this.state.activeTool.type !== "hand"
+ ) {
+ this.createGenericElementOnPointerDown(
+ this.state.activeTool.type,
+ pointerDownState,
+ );
+ }
+
+ this.props?.onPointerDown?.(this.state.activeTool, pointerDownState);
+ this.onPointerDownEmitter.trigger(
+ this.state.activeTool,
+ pointerDownState,
+ event,
+ );
+
+ if (this.state.activeTool.type === "eraser") {
+ this.eraserTrail.startPath(
+ pointerDownState.lastCoords.x,
+ pointerDownState.lastCoords.y,
+ );
+ }
+
+ const onPointerMove =
+ this.onPointerMoveFromPointerDownHandler(pointerDownState);
+
+ const onPointerUp =
+ this.onPointerUpFromPointerDownHandler(pointerDownState);
+
+ const onKeyDown = this.onKeyDownFromPointerDownHandler(pointerDownState);
+ const onKeyUp = this.onKeyUpFromPointerDownHandler(pointerDownState);
+
+ this.missingPointerEventCleanupEmitter.once((_event) =>
+ onPointerUp(_event || event.nativeEvent),
+ );
+
+ if (!this.state.viewModeEnabled || this.state.activeTool.type === "laser") {
+ window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
+ window.addEventListener(EVENT.POINTER_UP, onPointerUp);
+ window.addEventListener(EVENT.KEYDOWN, onKeyDown);
+ window.addEventListener(EVENT.KEYUP, onKeyUp);
+ pointerDownState.eventListeners.onMove = onPointerMove;
+ pointerDownState.eventListeners.onUp = onPointerUp;
+ pointerDownState.eventListeners.onKeyUp = onKeyUp;
+ pointerDownState.eventListeners.onKeyDown = onKeyDown;
+ }
+ };
+
+ private handleCanvasPointerUp = (
+ event: React.PointerEvent<HTMLCanvasElement>,
+ ) => {
+ this.removePointer(event);
+ this.lastPointerUpEvent = event;
+
+ const scenePointer = viewportCoordsToSceneCoords(
+ { clientX: event.clientX, clientY: event.clientY },
+ this.state,
+ );
+ const clicklength =
+ event.timeStamp - (this.lastPointerDownEvent?.timeStamp ?? 0);
+
+ if (this.device.editor.isMobile && clicklength < 300) {
+ const hitElement = this.getElementAtPosition(
+ scenePointer.x,
+ scenePointer.y,
+ );
+ if (
+ isIframeLikeElement(hitElement) &&
+ this.isIframeLikeElementCenter(
+ hitElement,
+ event,
+ scenePointer.x,
+ scenePointer.y,
+ )
+ ) {
+ this.handleEmbeddableCenterClick(hitElement);
+ return;
+ }
+ }
+
+ if (this.device.isTouchScreen) {
+ const hitElement = this.getElementAtPosition(
+ scenePointer.x,
+ scenePointer.y,
+ );
+ this.hitLinkElement = this.getElementLinkAtPosition(
+ scenePointer,
+ hitElement,
+ );
+ }
+
+ if (
+ this.hitLinkElement &&
+ !this.state.selectedElementIds[this.hitLinkElement.id]
+ ) {
+ if (
+ clicklength < 300 &&
+ isIframeLikeElement(this.hitLinkElement) &&
+ !isPointHittingLinkIcon(
+ this.hitLinkElement,
+ this.scene.getNonDeletedElementsMap(),
+ this.state,
+ pointFrom(scenePointer.x, scenePointer.y),
+ )
+ ) {
+ this.handleEmbeddableCenterClick(this.hitLinkElement);
+ } else {
+ this.redirectToLink(event, this.device.isTouchScreen);
+ }
+ } else if (this.state.viewModeEnabled) {
+ this.setState({
+ activeEmbeddable: null,
+ selectedElementIds: {},
+ });
+ }
+ };
+
+ private maybeOpenContextMenuAfterPointerDownOnTouchDevices = (
+ event: React.PointerEvent<HTMLElement>,
+ ): void => {
+ // deal with opening context menu on touch devices
+ if (event.pointerType === "touch") {
+ invalidateContextMenu = false;
+
+ if (touchTimeout) {
+ // If there's already a touchTimeout, this means that there's another
+ // touch down and we are doing another touch, so we shouldn't open the
+ // context menu.
+ invalidateContextMenu = true;
+ } else {
+ // open the context menu with the first touch's clientX and clientY
+ // if the touch is not moving
+ touchTimeout = window.setTimeout(() => {
+ touchTimeout = 0;
+ if (!invalidateContextMenu) {
+ this.handleCanvasContextMenu(event);
+ }
+ }, TOUCH_CTX_MENU_TIMEOUT);
+ }
+ }
+ };
+
+ private resetContextMenuTimer = () => {
+ clearTimeout(touchTimeout);
+ touchTimeout = 0;
+ invalidateContextMenu = false;
+ };
+
+ /**
+ * pointerup may not fire in certian cases (user tabs away...), so in order
+ * to properly cleanup pointerdown state, we need to fire any hanging
+ * pointerup handlers manually
+ */
+ private maybeCleanupAfterMissingPointerUp = (event: PointerEvent | null) => {
+ lastPointerUp?.();
+ this.missingPointerEventCleanupEmitter.trigger(event).clear();
+ };
+
+ // Returns whether the event is a panning
+ public handleCanvasPanUsingWheelOrSpaceDrag = (
+ event: React.PointerEvent<HTMLElement> | MouseEvent,
+ ): boolean => {
+ if (
+ !(
+ gesture.pointers.size <= 1 &&
+ (event.button === POINTER_BUTTON.WHEEL ||
+ (event.button === POINTER_BUTTON.MAIN && isHoldingSpace) ||
+ isHandToolActive(this.state) ||
+ this.state.viewModeEnabled)
+ )
+ ) {
+ return false;
+ }
+ isPanning = true;
+
+ // due to event.preventDefault below, container wouldn't get focus
+ // automatically
+ this.focusContainer();
+
+ // preventing defualt while text editing messes with cursor/focus
+ if (!this.state.editingTextElement) {
+ // necessary to prevent browser from scrolling the page if excalidraw
+ // not full-page #4489
+ //
+ // as such, the above is broken when panning canvas while in wysiwyg
+ event.preventDefault();
+ }
+
+ let nextPastePrevented = false;
+ const isLinux =
+ typeof window === undefined
+ ? false
+ : /Linux/.test(window.navigator.platform);
+
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.GRABBING);
+ let { clientX: lastX, clientY: lastY } = event;
+ const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
+ const deltaX = lastX - event.clientX;
+ const deltaY = lastY - event.clientY;
+ lastX = event.clientX;
+ lastY = event.clientY;
+
+ /*
+ * Prevent paste event if we move while middle clicking on Linux.
+ * See issue #1383.
+ */
+ if (
+ isLinux &&
+ !nextPastePrevented &&
+ (Math.abs(deltaX) > 1 || Math.abs(deltaY) > 1)
+ ) {
+ nextPastePrevented = true;
+
+ /* Prevent the next paste event */
+ const preventNextPaste = (event: ClipboardEvent) => {
+ document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
+ event.stopPropagation();
+ };
+
+ /*
+ * Reenable next paste in case of disabled middle click paste for
+ * any reason:
+ * - right click paste
+ * - empty clipboard
+ */
+ const enableNextPaste = () => {
+ setTimeout(() => {
+ document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
+ window.removeEventListener(EVENT.POINTER_UP, enableNextPaste);
+ }, 100);
+ };
+
+ document.body.addEventListener(EVENT.PASTE, preventNextPaste);
+ window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
+ }
+
+ this.translateCanvas({
+ scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
+ scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
+ });
+ });
+ const teardown = withBatchedUpdates(
+ (lastPointerUp = () => {
+ lastPointerUp = null;
+ isPanning = false;
+ if (!isHoldingSpace) {
+ if (this.state.viewModeEnabled) {
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
+ } else {
+ setCursorForShape(this.interactiveCanvas, this.state);
+ }
+ }
+ this.setState({
+ cursorButton: "up",
+ });
+ this.savePointer(event.clientX, event.clientY, "up");
+ window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
+ window.removeEventListener(EVENT.POINTER_UP, teardown);
+ window.removeEventListener(EVENT.BLUR, teardown);
+ onPointerMove.flush();
+ }),
+ );
+ window.addEventListener(EVENT.BLUR, teardown);
+ window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {
+ passive: true,
+ });
+ window.addEventListener(EVENT.POINTER_UP, teardown);
+ return true;
+ };
+
+ private updateGestureOnPointerDown(
+ event: React.PointerEvent<HTMLElement>,
+ ): void {
+ gesture.pointers.set(event.pointerId, {
+ x: event.clientX,
+ y: event.clientY,
+ });
+
+ if (gesture.pointers.size === 2) {
+ gesture.lastCenter = getCenter(gesture.pointers);
+ gesture.initialScale = this.state.zoom.value;
+ gesture.initialDistance = getDistance(
+ Array.from(gesture.pointers.values()),
+ );
+ }
+ }
+
+ private initialPointerDownState(
+ event: React.PointerEvent<HTMLElement>,
+ ): PointerDownState {
+ const origin = viewportCoordsToSceneCoords(event, this.state);
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ const [minX, minY, maxX, maxY] = getCommonBounds(selectedElements);
+ const isElbowArrowOnly = selectedElements.findIndex(isElbowArrow) === 0;
+
+ return {
+ origin,
+ withCmdOrCtrl: event[KEYS.CTRL_OR_CMD],
+ originInGrid: tupleToCoors(
+ getGridPoint(
+ origin.x,
+ origin.y,
+ event[KEYS.CTRL_OR_CMD] || isElbowArrowOnly
+ ? null
+ : this.getEffectiveGridSize(),
+ ),
+ ),
+ scrollbars: isOverScrollBars(
+ currentScrollBars,
+ event.clientX - this.state.offsetLeft,
+ event.clientY - this.state.offsetTop,
+ ),
+ // we need to duplicate because we'll be updating this state
+ lastCoords: { ...origin },
+ originalElements: this.scene
+ .getNonDeletedElements()
+ .reduce((acc, element) => {
+ acc.set(element.id, deepCopyElement(element));
+ return acc;
+ }, new Map() as PointerDownState["originalElements"]),
+ resize: {
+ handleType: false,
+ isResizing: false,
+ offset: { x: 0, y: 0 },
+ arrowDirection: "origin",
+ center: { x: (maxX + minX) / 2, y: (maxY + minY) / 2 },
+ },
+ hit: {
+ element: null,
+ allHitElements: [],
+ wasAddedToSelection: false,
+ hasBeenDuplicated: false,
+ hasHitCommonBoundingBoxOfSelectedElements:
+ this.isHittingCommonBoundingBoxOfSelectedElements(
+ origin,
+ selectedElements,
+ ),
+ },
+ drag: {
+ hasOccurred: false,
+ offset: null,
+ },
+ eventListeners: {
+ onMove: null,
+ onUp: null,
+ onKeyUp: null,
+ onKeyDown: null,
+ },
+ boxSelection: {
+ hasOccurred: false,
+ },
+ };
+ }
+
+ // Returns whether the event is a dragging a scrollbar
+ private handleDraggingScrollBar(
+ event: React.PointerEvent<HTMLElement>,
+ pointerDownState: PointerDownState,
+ ): boolean {
+ if (
+ !(pointerDownState.scrollbars.isOverEither && !this.state.multiElement)
+ ) {
+ return false;
+ }
+ isDraggingScrollBar = true;
+ pointerDownState.lastCoords.x = event.clientX;
+ pointerDownState.lastCoords.y = event.clientY;
+ const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
+ const target = event.target;
+ if (!(target instanceof HTMLElement)) {
+ return;
+ }
+
+ this.handlePointerMoveOverScrollbars(event, pointerDownState);
+ });
+ const onPointerUp = withBatchedUpdates(() => {
+ lastPointerUp = null;
+ isDraggingScrollBar = false;
+ setCursorForShape(this.interactiveCanvas, this.state);
+ this.setState({
+ cursorButton: "up",
+ });
+ this.savePointer(event.clientX, event.clientY, "up");
+ window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
+ window.removeEventListener(EVENT.POINTER_UP, onPointerUp);
+ onPointerMove.flush();
+ });
+
+ lastPointerUp = onPointerUp;
+
+ window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
+ window.addEventListener(EVENT.POINTER_UP, onPointerUp);
+ return true;
+ }
+
+ private clearSelectionIfNotUsingSelection = (): void => {
+ if (this.state.activeTool.type !== "selection") {
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.state),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ });
+ }
+ };
+
+ /**
+ * @returns whether the pointer event has been completely handled
+ */
+ private handleSelectionOnPointerDown = (
+ event: React.PointerEvent<HTMLElement>,
+ pointerDownState: PointerDownState,
+ ): boolean => {
+ if (this.state.activeTool.type === "selection") {
+ const elements = this.scene.getNonDeletedElements();
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+ const selectedElements = this.scene.getSelectedElements(this.state);
+
+ if (
+ selectedElements.length === 1 &&
+ !this.state.editingLinearElement &&
+ !isElbowArrow(selectedElements[0]) &&
+ !(
+ this.state.selectedLinearElement &&
+ this.state.selectedLinearElement.hoverPointIndex !== -1
+ )
+ ) {
+ const elementWithTransformHandleType =
+ getElementWithTransformHandleType(
+ elements,
+ this.state,
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ this.state.zoom,
+ event.pointerType,
+ this.scene.getNonDeletedElementsMap(),
+ this.device,
+ );
+ if (elementWithTransformHandleType != null) {
+ if (
+ elementWithTransformHandleType.transformHandleType === "rotation"
+ ) {
+ this.setState({
+ resizingElement: elementWithTransformHandleType.element,
+ });
+ pointerDownState.resize.handleType =
+ elementWithTransformHandleType.transformHandleType;
+ } else if (this.state.croppingElementId) {
+ pointerDownState.resize.handleType =
+ elementWithTransformHandleType.transformHandleType;
+ } else {
+ this.setState({
+ resizingElement: elementWithTransformHandleType.element,
+ });
+ pointerDownState.resize.handleType =
+ elementWithTransformHandleType.transformHandleType;
+ }
+ }
+ } else if (selectedElements.length > 1) {
+ pointerDownState.resize.handleType = getTransformHandleTypeFromCoords(
+ getCommonBounds(selectedElements),
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ this.state.zoom,
+ event.pointerType,
+ this.device,
+ );
+ }
+ if (pointerDownState.resize.handleType) {
+ pointerDownState.resize.isResizing = true;
+ pointerDownState.resize.offset = tupleToCoors(
+ getResizeOffsetXY(
+ pointerDownState.resize.handleType,
+ selectedElements,
+ elementsMap,
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ ),
+ );
+ if (
+ selectedElements.length === 1 &&
+ isLinearElement(selectedElements[0]) &&
+ selectedElements[0].points.length === 2
+ ) {
+ pointerDownState.resize.arrowDirection = getResizeArrowDirection(
+ pointerDownState.resize.handleType,
+ selectedElements[0],
+ );
+ }
+ } else {
+ if (this.state.selectedLinearElement) {
+ const linearElementEditor =
+ this.state.editingLinearElement || this.state.selectedLinearElement;
+ const ret = LinearElementEditor.handlePointerDown(
+ event,
+ this,
+ this.store,
+ pointerDownState.origin,
+ linearElementEditor,
+ this.scene,
+ );
+ if (ret.hitElement) {
+ pointerDownState.hit.element = ret.hitElement;
+ }
+ if (ret.linearElementEditor) {
+ this.setState({ selectedLinearElement: ret.linearElementEditor });
+
+ if (this.state.editingLinearElement) {
+ this.setState({ editingLinearElement: ret.linearElementEditor });
+ }
+ }
+ if (ret.didAddPoint) {
+ return true;
+ }
+ }
+ // hitElement may already be set above, so check first
+ pointerDownState.hit.element =
+ pointerDownState.hit.element ??
+ this.getElementAtPosition(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ );
+
+ this.hitLinkElement = this.getElementLinkAtPosition(
+ pointerDownState.origin,
+ pointerDownState.hit.element,
+ );
+
+ if (this.hitLinkElement) {
+ return true;
+ }
+
+ if (
+ this.state.croppingElementId &&
+ pointerDownState.hit.element?.id !== this.state.croppingElementId
+ ) {
+ this.finishImageCropping();
+ }
+
+ if (pointerDownState.hit.element) {
+ // Early return if pointer is hitting link icon
+ const hitLinkElement = this.getElementLinkAtPosition(
+ {
+ x: pointerDownState.origin.x,
+ y: pointerDownState.origin.y,
+ },
+ pointerDownState.hit.element,
+ );
+ if (hitLinkElement) {
+ return false;
+ }
+ }
+
+ // For overlapped elements one position may hit
+ // multiple elements
+ pointerDownState.hit.allHitElements = this.getElementsAtPosition(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ );
+
+ const hitElement = pointerDownState.hit.element;
+ const someHitElementIsSelected =
+ pointerDownState.hit.allHitElements.some((element) =>
+ this.isASelectedElement(element),
+ );
+ if (
+ (hitElement === null || !someHitElementIsSelected) &&
+ !event.shiftKey &&
+ !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
+ ) {
+ this.clearSelection(hitElement);
+ }
+
+ if (this.state.editingLinearElement) {
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ [this.state.editingLinearElement.elementId]: true,
+ },
+ this.state,
+ ),
+ });
+ // If we click on something
+ } else if (hitElement != null) {
+ // on CMD/CTRL, drill down to hit element regardless of groups etc.
+ if (event[KEYS.CTRL_OR_CMD]) {
+ if (!this.state.selectedElementIds[hitElement.id]) {
+ pointerDownState.hit.wasAddedToSelection = true;
+ }
+ this.setState((prevState) => ({
+ ...editGroupForSelectedElement(prevState, hitElement),
+ previousSelectedElementIds: this.state.selectedElementIds,
+ }));
+ // mark as not completely handled so as to allow dragging etc.
+ return false;
+ }
+
+ // deselect if item is selected
+ // if shift is not clicked, this will always return true
+ // otherwise, it will trigger selection based on current
+ // state of the box
+ if (!this.state.selectedElementIds[hitElement.id]) {
+ // if we are currently editing a group, exiting editing mode and deselect the group.
+ if (
+ this.state.editingGroupId &&
+ !isElementInGroup(hitElement, this.state.editingGroupId)
+ ) {
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.state),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ });
+ }
+
+ // Add hit element to selection. At this point if we're not holding
+ // SHIFT the previously selected element(s) were deselected above
+ // (make sure you use setState updater to use latest state)
+ // With shift-selection, we want to make sure that frames and their containing
+ // elements are not selected at the same time.
+ if (
+ !someHitElementIsSelected &&
+ !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
+ ) {
+ this.setState((prevState) => {
+ let nextSelectedElementIds: { [id: string]: true } = {
+ ...prevState.selectedElementIds,
+ [hitElement.id]: true,
+ };
+
+ const previouslySelectedElements: ExcalidrawElement[] = [];
+
+ Object.keys(prevState.selectedElementIds).forEach((id) => {
+ const element = this.scene.getElement(id);
+ element && previouslySelectedElements.push(element);
+ });
+
+ // if hitElement is frame-like, deselect all of its elements
+ // if they are selected
+ if (isFrameLikeElement(hitElement)) {
+ getFrameChildren(
+ previouslySelectedElements,
+ hitElement.id,
+ ).forEach((element) => {
+ delete nextSelectedElementIds[element.id];
+ });
+ } else if (hitElement.frameId) {
+ // if hitElement is in a frame and its frame has been selected
+ // disable selection for the given element
+ if (nextSelectedElementIds[hitElement.frameId]) {
+ delete nextSelectedElementIds[hitElement.id];
+ }
+ } else {
+ // hitElement is neither a frame nor an element in a frame
+ // but since hitElement could be in a group with some frames
+ // this means selecting hitElement will have the frames selected as well
+ // because we want to keep the invariant:
+ // - frames and their elements are not selected at the same time
+ // we deselect elements in those frames that were previously selected
+
+ const groupIds = hitElement.groupIds;
+ const framesInGroups = new Set(
+ groupIds
+ .flatMap((gid) =>
+ getElementsInGroup(
+ this.scene.getNonDeletedElements(),
+ gid,
+ ),
+ )
+ .filter((element) => isFrameLikeElement(element))
+ .map((frame) => frame.id),
+ );
+
+ if (framesInGroups.size > 0) {
+ previouslySelectedElements.forEach((element) => {
+ if (
+ element.frameId &&
+ framesInGroups.has(element.frameId)
+ ) {
+ // deselect element and groups containing the element
+ delete nextSelectedElementIds[element.id];
+ element.groupIds
+ .flatMap((gid) =>
+ getElementsInGroup(
+ this.scene.getNonDeletedElements(),
+ gid,
+ ),
+ )
+ .forEach((element) => {
+ delete nextSelectedElementIds[element.id];
+ });
+ }
+ });
+ }
+ }
+
+ // Finally, in shape selection mode, we'd like to
+ // keep only one shape or group selected at a time.
+ // This means, if the hitElement is a different shape or group
+ // than the previously selected ones, we deselect the previous ones
+ // and select the hitElement
+ if (prevState.openDialog?.name === "elementLinkSelector") {
+ if (
+ !hitElement.groupIds.some(
+ (gid) => prevState.selectedGroupIds[gid],
+ )
+ ) {
+ nextSelectedElementIds = {
+ [hitElement.id]: true,
+ };
+ }
+ }
+
+ return {
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: nextSelectedElementIds,
+ },
+ this.scene.getNonDeletedElements(),
+ prevState,
+ this,
+ ),
+ showHyperlinkPopup:
+ hitElement.link || isEmbeddableElement(hitElement)
+ ? "info"
+ : false,
+ };
+ });
+ pointerDownState.hit.wasAddedToSelection = true;
+ }
+ }
+ }
+
+ this.setState({
+ previousSelectedElementIds: this.state.selectedElementIds,
+ });
+ }
+ }
+ return false;
+ };
+
+ private isASelectedElement(hitElement: ExcalidrawElement | null): boolean {
+ return hitElement != null && this.state.selectedElementIds[hitElement.id];
+ }
+
+ private isHittingCommonBoundingBoxOfSelectedElements(
+ point: Readonly<{ x: number; y: number }>,
+ selectedElements: readonly ExcalidrawElement[],
+ ): boolean {
+ if (selectedElements.length < 2) {
+ return false;
+ }
+
+ // How many pixels off the shape boundary we still consider a hit
+ const threshold = this.getElementHitThreshold();
+ const [x1, y1, x2, y2] = getCommonBounds(selectedElements);
+ return (
+ point.x > x1 - threshold &&
+ point.x < x2 + threshold &&
+ point.y > y1 - threshold &&
+ point.y < y2 + threshold
+ );
+ }
+
+ private handleTextOnPointerDown = (
+ event: React.PointerEvent<HTMLElement>,
+ pointerDownState: PointerDownState,
+ ): void => {
+ // if we're currently still editing text, clicking outside
+ // should only finalize it, not create another (irrespective
+ // of state.activeTool.locked)
+ if (this.state.editingTextElement) {
+ return;
+ }
+ let sceneX = pointerDownState.origin.x;
+ let sceneY = pointerDownState.origin.y;
+
+ const element = this.getElementAtPosition(sceneX, sceneY, {
+ includeBoundTextElement: true,
+ });
+
+ // FIXME
+ let container = this.getTextBindableContainerAtPosition(sceneX, sceneY);
+
+ if (hasBoundTextElement(element)) {
+ container = element as ExcalidrawTextContainer;
+ sceneX = element.x + element.width / 2;
+ sceneY = element.y + element.height / 2;
+ }
+ this.startTextEditing({
+ sceneX,
+ sceneY,
+ insertAtParentCenter: !event.altKey,
+ container,
+ autoEdit: false,
+ });
+
+ resetCursor(this.interactiveCanvas);
+ if (!this.state.activeTool.locked) {
+ this.setState({
+ activeTool: updateActiveTool(this.state, { type: "selection" }),
+ });
+ }
+ };
+
+ private handleFreeDrawElementOnPointerDown = (
+ event: React.PointerEvent<HTMLElement>,
+ elementType: ExcalidrawFreeDrawElement["type"],
+ pointerDownState: PointerDownState,
+ ) => {
+ // Begin a mark capture. This does not have to update state yet.
+ const [gridX, gridY] = getGridPoint(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ null,
+ );
+
+ const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
+ x: gridX,
+ y: gridY,
+ });
+
+ const simulatePressure = event.pressure === 0.5;
+
+ const element = newFreeDrawElement({
+ type: elementType,
+ x: gridX,
+ y: gridY,
+ strokeColor: this.state.currentItemStrokeColor,
+ backgroundColor: this.state.currentItemBackgroundColor,
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roughness: this.state.currentItemRoughness,
+ opacity: this.state.currentItemOpacity,
+ roundness: null,
+ simulatePressure,
+ locked: false,
+ frameId: topLayerFrame ? topLayerFrame.id : null,
+ points: [pointFrom<LocalPoint>(0, 0)],
+ pressures: simulatePressure ? [] : [event.pressure],
+ });
+
+ this.scene.insertElement(element);
+
+ this.setState((prevState) => {
+ const nextSelectedElementIds = {
+ ...prevState.selectedElementIds,
+ };
+ delete nextSelectedElementIds[element.id];
+ return {
+ selectedElementIds: makeNextSelectedElementIds(
+ nextSelectedElementIds,
+ prevState,
+ ),
+ };
+ });
+
+ const boundElement = getHoveredElementForBinding(
+ pointerDownState.origin,
+ this.scene.getNonDeletedElements(),
+ this.scene.getNonDeletedElementsMap(),
+ this.state.zoom,
+ );
+
+ this.setState({
+ newElement: element,
+ startBoundElement: boundElement,
+ suggestedBindings: [],
+ });
+ };
+
+ public insertIframeElement = ({
+ sceneX,
+ sceneY,
+ width,
+ height,
+ }: {
+ sceneX: number;
+ sceneY: number;
+ width: number;
+ height: number;
+ }) => {
+ const [gridX, gridY] = getGridPoint(
+ sceneX,
+ sceneY,
+ this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
+ ? null
+ : this.getEffectiveGridSize(),
+ );
+
+ const element = newIframeElement({
+ type: "iframe",
+ x: gridX,
+ y: gridY,
+ strokeColor: "transparent",
+ backgroundColor: "transparent",
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roughness: this.state.currentItemRoughness,
+ roundness: this.getCurrentItemRoundness("iframe"),
+ opacity: this.state.currentItemOpacity,
+ locked: false,
+ width,
+ height,
+ });
+
+ this.scene.insertElement(element);
+
+ return element;
+ };
+
+ //create rectangle element with youtube top left on nearest grid point width / hight 640/360
+ public insertEmbeddableElement = ({
+ sceneX,
+ sceneY,
+ link,
+ }: {
+ sceneX: number;
+ sceneY: number;
+ link: string;
+ }) => {
+ const [gridX, gridY] = getGridPoint(
+ sceneX,
+ sceneY,
+ this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
+ ? null
+ : this.getEffectiveGridSize(),
+ );
+
+ const embedLink = getEmbedLink(link);
+
+ if (!embedLink) {
+ return;
+ }
+
+ if (embedLink.error instanceof URIError) {
+ this.setToast({
+ message: t("toast.unrecognizedLinkFormat"),
+ closable: true,
+ });
+ }
+
+ const element = newEmbeddableElement({
+ type: "embeddable",
+ x: gridX,
+ y: gridY,
+ strokeColor: "transparent",
+ backgroundColor: "transparent",
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roughness: this.state.currentItemRoughness,
+ roundness: this.getCurrentItemRoundness("embeddable"),
+ opacity: this.state.currentItemOpacity,
+ locked: false,
+ width: embedLink.intrinsicSize.w,
+ height: embedLink.intrinsicSize.h,
+ link,
+ });
+
+ this.scene.insertElement(element);
+
+ return element;
+ };
+
+ private createImageElement = ({
+ sceneX,
+ sceneY,
+ addToFrameUnderCursor = true,
+ }: {
+ sceneX: number;
+ sceneY: number;
+ addToFrameUnderCursor?: boolean;
+ }) => {
+ const [gridX, gridY] = getGridPoint(
+ sceneX,
+ sceneY,
+ this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
+ ? null
+ : this.getEffectiveGridSize(),
+ );
+
+ const topLayerFrame = addToFrameUnderCursor
+ ? this.getTopLayerFrameAtSceneCoords({
+ x: gridX,
+ y: gridY,
+ })
+ : null;
+
+ const element = newImageElement({
+ type: "image",
+ x: gridX,
+ y: gridY,
+ strokeColor: this.state.currentItemStrokeColor,
+ backgroundColor: this.state.currentItemBackgroundColor,
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roughness: this.state.currentItemRoughness,
+ roundness: null,
+ opacity: this.state.currentItemOpacity,
+ locked: false,
+ frameId: topLayerFrame ? topLayerFrame.id : null,
+ });
+
+ return element;
+ };
+
+ private handleLinearElementOnPointerDown = (
+ event: React.PointerEvent<HTMLElement>,
+ elementType: ExcalidrawLinearElement["type"],
+ pointerDownState: PointerDownState,
+ ): void => {
+ if (this.state.multiElement) {
+ const { multiElement } = this.state;
+
+ // finalize if completing a loop
+ if (
+ multiElement.type === "line" &&
+ isPathALoop(multiElement.points, this.state.zoom.value)
+ ) {
+ mutateElement(multiElement, {
+ lastCommittedPoint:
+ multiElement.points[multiElement.points.length - 1],
+ });
+ this.actionManager.executeAction(actionFinalize);
+ return;
+ }
+
+ // Elbow arrows cannot be created by putting down points
+ // only the start and end points can be defined
+ if (isElbowArrow(multiElement) && multiElement.points.length > 1) {
+ mutateElement(multiElement, {
+ lastCommittedPoint:
+ multiElement.points[multiElement.points.length - 1],
+ });
+ this.actionManager.executeAction(actionFinalize);
+ return;
+ }
+
+ const { x: rx, y: ry, lastCommittedPoint } = multiElement;
+
+ // clicking inside commit zone → finalize arrow
+ if (
+ multiElement.points.length > 1 &&
+ lastCommittedPoint &&
+ pointDistance(
+ pointFrom(
+ pointerDownState.origin.x - rx,
+ pointerDownState.origin.y - ry,
+ ),
+ lastCommittedPoint,
+ ) < LINE_CONFIRM_THRESHOLD
+ ) {
+ this.actionManager.executeAction(actionFinalize);
+ return;
+ }
+
+ this.setState((prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ ...prevState.selectedElementIds,
+ [multiElement.id]: true,
+ },
+ prevState,
+ ),
+ }));
+ // clicking outside commit zone → update reference for last committed
+ // point
+ mutateElement(multiElement, {
+ lastCommittedPoint: multiElement.points[multiElement.points.length - 1],
+ });
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
+ } else {
+ const [gridX, gridY] = getGridPoint(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+
+ const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
+ x: gridX,
+ y: gridY,
+ });
+
+ /* If arrow is pre-arrowheads, it will have undefined for both start and end arrowheads.
+ If so, we want it to be null for start and "arrow" for end. If the linear item is not
+ an arrow, we want it to be null for both. Otherwise, we want it to use the
+ values from appState. */
+
+ const { currentItemStartArrowhead, currentItemEndArrowhead } = this.state;
+ const [startArrowhead, endArrowhead] =
+ elementType === "arrow"
+ ? [currentItemStartArrowhead, currentItemEndArrowhead]
+ : [null, null];
+
+ const element =
+ elementType === "arrow"
+ ? newArrowElement({
+ type: elementType,
+ x: gridX,
+ y: gridY,
+ strokeColor: this.state.currentItemStrokeColor,
+ backgroundColor: this.state.currentItemBackgroundColor,
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roughness: this.state.currentItemRoughness,
+ opacity: this.state.currentItemOpacity,
+ roundness:
+ this.state.currentItemArrowType === ARROW_TYPE.round
+ ? { type: ROUNDNESS.PROPORTIONAL_RADIUS }
+ : // note, roundness doesn't have any effect for elbow arrows,
+ // but it's best to set it to null as well
+ null,
+ startArrowhead,
+ endArrowhead,
+ locked: false,
+ frameId: topLayerFrame ? topLayerFrame.id : null,
+ elbowed: this.state.currentItemArrowType === ARROW_TYPE.elbow,
+ fixedSegments:
+ this.state.currentItemArrowType === ARROW_TYPE.elbow
+ ? []
+ : null,
+ })
+ : newLinearElement({
+ type: elementType,
+ x: gridX,
+ y: gridY,
+ strokeColor: this.state.currentItemStrokeColor,
+ backgroundColor: this.state.currentItemBackgroundColor,
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roughness: this.state.currentItemRoughness,
+ opacity: this.state.currentItemOpacity,
+ roundness:
+ this.state.currentItemRoundness === "round"
+ ? { type: ROUNDNESS.PROPORTIONAL_RADIUS }
+ : null,
+ locked: false,
+ frameId: topLayerFrame ? topLayerFrame.id : null,
+ });
+ this.setState((prevState) => {
+ const nextSelectedElementIds = {
+ ...prevState.selectedElementIds,
+ };
+ delete nextSelectedElementIds[element.id];
+ return {
+ selectedElementIds: makeNextSelectedElementIds(
+ nextSelectedElementIds,
+ prevState,
+ ),
+ };
+ });
+ mutateElement(element, {
+ points: [...element.points, pointFrom<LocalPoint>(0, 0)],
+ });
+ const boundElement = getHoveredElementForBinding(
+ pointerDownState.origin,
+ this.scene.getNonDeletedElements(),
+ this.scene.getNonDeletedElementsMap(),
+ this.state.zoom,
+ isElbowArrow(element),
+ isElbowArrow(element),
+ );
+
+ this.scene.insertElement(element);
+ this.setState({
+ newElement: element,
+ startBoundElement: boundElement,
+ suggestedBindings: [],
+ });
+ }
+ };
+
+ private getCurrentItemRoundness(
+ elementType:
+ | "selection"
+ | "rectangle"
+ | "diamond"
+ | "ellipse"
+ | "iframe"
+ | "embeddable",
+ ) {
+ return this.state.currentItemRoundness === "round"
+ ? {
+ type: isUsingAdaptiveRadius(elementType)
+ ? ROUNDNESS.ADAPTIVE_RADIUS
+ : ROUNDNESS.PROPORTIONAL_RADIUS,
+ }
+ : null;
+ }
+
+ private createGenericElementOnPointerDown = (
+ elementType: ExcalidrawGenericElement["type"] | "embeddable",
+ pointerDownState: PointerDownState,
+ ): void => {
+ const [gridX, gridY] = getGridPoint(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
+ ? null
+ : this.getEffectiveGridSize(),
+ );
+
+ const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
+ x: gridX,
+ y: gridY,
+ });
+
+ const baseElementAttributes = {
+ x: gridX,
+ y: gridY,
+ strokeColor: this.state.currentItemStrokeColor,
+ backgroundColor: this.state.currentItemBackgroundColor,
+ fillStyle: this.state.currentItemFillStyle,
+ strokeWidth: this.state.currentItemStrokeWidth,
+ strokeStyle: this.state.currentItemStrokeStyle,
+ roughness: this.state.currentItemRoughness,
+ opacity: this.state.currentItemOpacity,
+ roundness: this.getCurrentItemRoundness(elementType),
+ locked: false,
+ frameId: topLayerFrame ? topLayerFrame.id : null,
+ } as const;
+
+ let element;
+ if (elementType === "embeddable") {
+ element = newEmbeddableElement({
+ type: "embeddable",
+ ...baseElementAttributes,
+ });
+ } else {
+ element = newElement({
+ type: elementType,
+ ...baseElementAttributes,
+ });
+ }
+
+ if (element.type === "selection") {
+ this.setState({
+ selectionElement: element,
+ });
+ } else {
+ this.scene.insertElement(element);
+ this.setState({
+ multiElement: null,
+ newElement: element,
+ });
+ }
+ };
+
+ private createFrameElementOnPointerDown = (
+ pointerDownState: PointerDownState,
+ type: Extract<ToolType, "frame" | "magicframe">,
+ ): void => {
+ const [gridX, gridY] = getGridPoint(
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
+ ? null
+ : this.getEffectiveGridSize(),
+ );
+
+ const constructorOpts = {
+ x: gridX,
+ y: gridY,
+ opacity: this.state.currentItemOpacity,
+ locked: false,
+ ...FRAME_STYLE,
+ } as const;
+
+ const frame =
+ type === TOOL_TYPE.magicframe
+ ? newMagicFrameElement(constructorOpts)
+ : newFrameElement(constructorOpts);
+
+ this.scene.insertElement(frame);
+
+ this.setState({
+ multiElement: null,
+ newElement: frame,
+ });
+ };
+
+ private maybeCacheReferenceSnapPoints(
+ event: KeyboardModifiersObject,
+ selectedElements: ExcalidrawElement[],
+ recomputeAnyways: boolean = false,
+ ) {
+ if (
+ isSnappingEnabled({
+ event,
+ app: this,
+ selectedElements,
+ }) &&
+ (recomputeAnyways || !SnapCache.getReferenceSnapPoints())
+ ) {
+ SnapCache.setReferenceSnapPoints(
+ getReferenceSnapPoints(
+ this.scene.getNonDeletedElements(),
+ selectedElements,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ );
+ }
+ }
+
+ private maybeCacheVisibleGaps(
+ event: KeyboardModifiersObject,
+ selectedElements: ExcalidrawElement[],
+ recomputeAnyways: boolean = false,
+ ) {
+ if (
+ isSnappingEnabled({
+ event,
+ app: this,
+ selectedElements,
+ }) &&
+ (recomputeAnyways || !SnapCache.getVisibleGaps())
+ ) {
+ SnapCache.setVisibleGaps(
+ getVisibleGaps(
+ this.scene.getNonDeletedElements(),
+ selectedElements,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ );
+ }
+ }
+
+ private onKeyDownFromPointerDownHandler(
+ pointerDownState: PointerDownState,
+ ): (event: KeyboardEvent) => void {
+ return withBatchedUpdates((event: KeyboardEvent) => {
+ if (this.maybeHandleResize(pointerDownState, event)) {
+ return;
+ }
+ this.maybeDragNewGenericElement(pointerDownState, event);
+ });
+ }
+
+ private onKeyUpFromPointerDownHandler(
+ pointerDownState: PointerDownState,
+ ): (event: KeyboardEvent) => void {
+ return withBatchedUpdates((event: KeyboardEvent) => {
+ // Prevents focus from escaping excalidraw tab
+ event.key === KEYS.ALT && event.preventDefault();
+ if (this.maybeHandleResize(pointerDownState, event)) {
+ return;
+ }
+ this.maybeDragNewGenericElement(pointerDownState, event);
+ });
+ }
+
+ private onPointerMoveFromPointerDownHandler(
+ pointerDownState: PointerDownState,
+ ) {
+ return withBatchedUpdatesThrottled((event: PointerEvent) => {
+ if (this.state.openDialog?.name === "elementLinkSelector") {
+ return;
+ }
+ const pointerCoords = viewportCoordsToSceneCoords(event, this.state);
+
+ if (
+ this.state.selectedLinearElement &&
+ this.state.selectedLinearElement.elbowed &&
+ this.state.selectedLinearElement.pointerDownState.segmentMidpoint.index
+ ) {
+ const [gridX, gridY] = getGridPoint(
+ pointerCoords.x,
+ pointerCoords.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+
+ let index =
+ this.state.selectedLinearElement.pointerDownState.segmentMidpoint
+ .index;
+ if (index < 0) {
+ const nextCoords = LinearElementEditor.getSegmentMidpointHitCoords(
+ {
+ ...this.state.selectedLinearElement,
+ segmentMidPointHoveredCoords: null,
+ },
+ { x: gridX, y: gridY },
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ index = nextCoords
+ ? LinearElementEditor.getSegmentMidPointIndex(
+ this.state.selectedLinearElement,
+ this.state,
+ nextCoords,
+ this.scene.getNonDeletedElementsMap(),
+ )
+ : -1;
+ }
+
+ const ret = LinearElementEditor.moveFixedSegment(
+ this.state.selectedLinearElement,
+ index,
+ gridX,
+ gridY,
+ this.scene.getNonDeletedElementsMap(),
+ );
+
+ flushSync(() => {
+ if (this.state.selectedLinearElement) {
+ this.setState({
+ selectedLinearElement: {
+ ...this.state.selectedLinearElement,
+ segmentMidPointHoveredCoords: ret.segmentMidPointHoveredCoords,
+ pointerDownState: ret.pointerDownState,
+ },
+ });
+ }
+ });
+ return;
+ }
+
+ const lastPointerCoords =
+ this.lastPointerMoveCoords ?? pointerDownState.origin;
+ this.lastPointerMoveCoords = pointerCoords;
+
+ // We need to initialize dragOffsetXY only after we've updated
+ // `state.selectedElementIds` on pointerDown. Doing it here in pointerMove
+ // event handler should hopefully ensure we're already working with
+ // the updated state.
+ if (pointerDownState.drag.offset === null) {
+ pointerDownState.drag.offset = tupleToCoors(
+ getDragOffsetXY(
+ this.scene.getSelectedElements(this.state),
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ ),
+ );
+ }
+ const target = event.target;
+ if (!(target instanceof HTMLElement)) {
+ return;
+ }
+
+ if (this.handlePointerMoveOverScrollbars(event, pointerDownState)) {
+ return;
+ }
+
+ if (isEraserActive(this.state)) {
+ this.handleEraser(event, pointerDownState, pointerCoords);
+ return;
+ }
+
+ if (this.state.activeTool.type === "laser") {
+ this.laserTrails.addPointToPath(pointerCoords.x, pointerCoords.y);
+ }
+
+ const [gridX, gridY] = getGridPoint(
+ pointerCoords.x,
+ pointerCoords.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+
+ // for arrows/lines, don't start dragging until a given threshold
+ // to ensure we don't create a 2-point arrow by mistake when
+ // user clicks mouse in a way that it moves a tiny bit (thus
+ // triggering pointermove)
+ if (
+ !pointerDownState.drag.hasOccurred &&
+ (this.state.activeTool.type === "arrow" ||
+ this.state.activeTool.type === "line")
+ ) {
+ if (
+ pointDistance(
+ pointFrom(pointerCoords.x, pointerCoords.y),
+ pointFrom(pointerDownState.origin.x, pointerDownState.origin.y),
+ ) < DRAGGING_THRESHOLD
+ ) {
+ return;
+ }
+ }
+ if (pointerDownState.resize.isResizing) {
+ pointerDownState.lastCoords.x = pointerCoords.x;
+ pointerDownState.lastCoords.y = pointerCoords.y;
+ if (this.maybeHandleCrop(pointerDownState, event)) {
+ return true;
+ }
+ if (this.maybeHandleResize(pointerDownState, event)) {
+ return true;
+ }
+ }
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+
+ if (this.state.selectedLinearElement) {
+ const linearElementEditor =
+ this.state.editingLinearElement || this.state.selectedLinearElement;
+
+ if (
+ LinearElementEditor.shouldAddMidpoint(
+ this.state.selectedLinearElement,
+ pointerCoords,
+ this.state,
+ elementsMap,
+ )
+ ) {
+ const ret = LinearElementEditor.addMidpoint(
+ this.state.selectedLinearElement,
+ pointerCoords,
+ this,
+ !event[KEYS.CTRL_OR_CMD],
+ elementsMap,
+ );
+ if (!ret) {
+ return;
+ }
+
+ // Since we are reading from previous state which is not possible with
+ // automatic batching in React 18 hence using flush sync to synchronously
+ // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
+
+ flushSync(() => {
+ if (this.state.selectedLinearElement) {
+ this.setState({
+ selectedLinearElement: {
+ ...this.state.selectedLinearElement,
+ pointerDownState: ret.pointerDownState,
+ selectedPointsIndices: ret.selectedPointsIndices,
+ },
+ });
+ }
+ if (this.state.editingLinearElement) {
+ this.setState({
+ editingLinearElement: {
+ ...this.state.editingLinearElement,
+ pointerDownState: ret.pointerDownState,
+ selectedPointsIndices: ret.selectedPointsIndices,
+ },
+ });
+ }
+ });
+
+ return;
+ } else if (
+ linearElementEditor.pointerDownState.segmentMidpoint.value !== null &&
+ !linearElementEditor.pointerDownState.segmentMidpoint.added
+ ) {
+ return;
+ }
+
+ const didDrag = LinearElementEditor.handlePointDragging(
+ event,
+ this,
+ pointerCoords.x,
+ pointerCoords.y,
+ (element, pointsSceneCoords) => {
+ this.maybeSuggestBindingsForLinearElementAtCoords(
+ element,
+ pointsSceneCoords,
+ );
+ },
+ linearElementEditor,
+ this.scene,
+ );
+ if (didDrag) {
+ pointerDownState.lastCoords.x = pointerCoords.x;
+ pointerDownState.lastCoords.y = pointerCoords.y;
+ pointerDownState.drag.hasOccurred = true;
+ if (
+ this.state.editingLinearElement &&
+ !this.state.editingLinearElement.isDragging
+ ) {
+ this.setState({
+ editingLinearElement: {
+ ...this.state.editingLinearElement,
+ isDragging: true,
+ },
+ });
+ }
+ if (!this.state.selectedLinearElement.isDragging) {
+ this.setState({
+ selectedLinearElement: {
+ ...this.state.selectedLinearElement,
+ isDragging: true,
+ },
+ });
+ }
+ return;
+ }
+ }
+
+ const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
+ (element) => this.isASelectedElement(element),
+ );
+
+ const isSelectingPointsInLineEditor =
+ this.state.editingLinearElement &&
+ event.shiftKey &&
+ this.state.editingLinearElement.elementId ===
+ pointerDownState.hit.element?.id;
+ if (
+ (hasHitASelectedElement ||
+ pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements) &&
+ !isSelectingPointsInLineEditor
+ ) {
+ const selectedElements = this.scene.getSelectedElements(this.state);
+
+ if (selectedElements.every((element) => element.locked)) {
+ return;
+ }
+
+ const selectedElementsHasAFrame = selectedElements.find((e) =>
+ isFrameLikeElement(e),
+ );
+ const topLayerFrame = this.getTopLayerFrameAtSceneCoords(pointerCoords);
+ const frameToHighlight =
+ topLayerFrame && !selectedElementsHasAFrame ? topLayerFrame : null;
+ // Only update the state if there is a difference
+ if (this.state.frameToHighlight !== frameToHighlight) {
+ flushSync(() => {
+ this.setState({ frameToHighlight });
+ });
+ }
+
+ // Marking that click was used for dragging to check
+ // if elements should be deselected on pointerup
+ pointerDownState.drag.hasOccurred = true;
+
+ // prevent dragging even if we're no longer holding cmd/ctrl otherwise
+ // it would have weird results (stuff jumping all over the screen)
+ // Checking for editingTextElement to avoid jump while editing on mobile #6503
+ if (
+ selectedElements.length > 0 &&
+ !pointerDownState.withCmdOrCtrl &&
+ !this.state.editingTextElement &&
+ this.state.activeEmbeddable?.state !== "active"
+ ) {
+ const dragOffset = {
+ x: pointerCoords.x - pointerDownState.origin.x,
+ y: pointerCoords.y - pointerDownState.origin.y,
+ };
+
+ const originalElements = [
+ ...pointerDownState.originalElements.values(),
+ ];
+
+ // We only drag in one direction if shift is pressed
+ const lockDirection = event.shiftKey;
+
+ if (lockDirection) {
+ const distanceX = Math.abs(dragOffset.x);
+ const distanceY = Math.abs(dragOffset.y);
+
+ const lockX = lockDirection && distanceX < distanceY;
+ const lockY = lockDirection && distanceX > distanceY;
+
+ if (lockX) {
+ dragOffset.x = 0;
+ }
+
+ if (lockY) {
+ dragOffset.y = 0;
+ }
+ }
+
+ // #region move crop region
+ if (this.state.croppingElementId) {
+ const croppingElement = this.scene
+ .getNonDeletedElementsMap()
+ .get(this.state.croppingElementId);
+
+ if (
+ croppingElement &&
+ isImageElement(croppingElement) &&
+ croppingElement.crop !== null &&
+ pointerDownState.hit.element === croppingElement
+ ) {
+ const crop = croppingElement.crop;
+ const image =
+ isInitializedImageElement(croppingElement) &&
+ this.imageCache.get(croppingElement.fileId)?.image;
+
+ if (image && !(image instanceof Promise)) {
+ const instantDragOffset = vectorScale(
+ vector(
+ pointerCoords.x - lastPointerCoords.x,
+ pointerCoords.y - lastPointerCoords.y,
+ ),
+ Math.max(this.state.zoom.value, 2),
+ );
+
+ const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
+ croppingElement,
+ elementsMap,
+ );
+
+ const topLeft = vectorFromPoint(
+ pointRotateRads(
+ pointFrom(x1, y1),
+ pointFrom(cx, cy),
+ croppingElement.angle,
+ ),
+ );
+ const topRight = vectorFromPoint(
+ pointRotateRads(
+ pointFrom(x2, y1),
+ pointFrom(cx, cy),
+ croppingElement.angle,
+ ),
+ );
+ const bottomLeft = vectorFromPoint(
+ pointRotateRads(
+ pointFrom(x1, y2),
+ pointFrom(cx, cy),
+ croppingElement.angle,
+ ),
+ );
+ const topEdge = vectorNormalize(
+ vectorSubtract(topRight, topLeft),
+ );
+ const leftEdge = vectorNormalize(
+ vectorSubtract(bottomLeft, topLeft),
+ );
+
+ // project instantDrafOffset onto leftEdge and topEdge to decompose
+ const offsetVector = vector(
+ vectorDot(instantDragOffset, topEdge),
+ vectorDot(instantDragOffset, leftEdge),
+ );
+
+ const nextCrop = {
+ ...crop,
+ x: clamp(
+ crop.x -
+ offsetVector[0] * Math.sign(croppingElement.scale[0]),
+ 0,
+ image.naturalWidth - crop.width,
+ ),
+ y: clamp(
+ crop.y -
+ offsetVector[1] * Math.sign(croppingElement.scale[1]),
+ 0,
+ image.naturalHeight - crop.height,
+ ),
+ };
+
+ mutateElement(croppingElement, {
+ crop: nextCrop,
+ });
+
+ return;
+ }
+ }
+ }
+
+ // Snap cache *must* be synchronously popuplated before initial drag,
+ // otherwise the first drag even will not snap, causing a jump before
+ // it snaps to its position if previously snapped already.
+ this.maybeCacheVisibleGaps(event, selectedElements);
+ this.maybeCacheReferenceSnapPoints(event, selectedElements);
+
+ const { snapOffset, snapLines } = snapDraggedElements(
+ originalElements,
+ dragOffset,
+ this,
+ event,
+ this.scene.getNonDeletedElementsMap(),
+ );
+
+ this.setState({ snapLines });
+
+ // when we're editing the name of a frame, we want the user to be
+ // able to select and interact with the text input
+ if (!this.state.editingFrame) {
+ dragSelectedElements(
+ pointerDownState,
+ selectedElements,
+ dragOffset,
+ this.scene,
+ snapOffset,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+ }
+
+ this.setState({
+ selectedElementsAreBeingDragged: true,
+ // element is being dragged and selectionElement that was created on pointer down
+ // should be removed
+ selectionElement: null,
+ });
+
+ if (
+ selectedElements.length !== 1 ||
+ !isElbowArrow(selectedElements[0])
+ ) {
+ this.setState({
+ suggestedBindings: getSuggestedBindingsForArrows(
+ selectedElements,
+ this.scene.getNonDeletedElementsMap(),
+ this.state.zoom,
+ ),
+ });
+ }
+
+ // We duplicate the selected element if alt is pressed on pointer move
+ if (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {
+ // Move the currently selected elements to the top of the z index stack, and
+ // put the duplicates where the selected elements used to be.
+ // (the origin point where the dragging started)
+
+ pointerDownState.hit.hasBeenDuplicated = true;
+
+ const nextElements = [];
+ const elementsToAppend = [];
+ const groupIdMap = new Map();
+ const oldIdToDuplicatedId = new Map();
+ const hitElement = pointerDownState.hit.element;
+ const selectedElementIds = new Set(
+ this.scene
+ .getSelectedElements({
+ selectedElementIds: this.state.selectedElementIds,
+ includeBoundTextElement: true,
+ includeElementsInFrames: true,
+ })
+ .map((element) => element.id),
+ );
+
+ const elements = this.scene.getElementsIncludingDeleted();
+
+ for (const element of elements) {
+ const isInSelection =
+ selectedElementIds.has(element.id) ||
+ // case: the state.selectedElementIds might not have been
+ // updated yet by the time this mousemove event is fired
+ (element.id === hitElement?.id &&
+ pointerDownState.hit.wasAddedToSelection);
+ // NOTE (mtolmacs): This is a temporary fix for very large scenes
+ if (
+ Math.abs(element.x) > 1e7 ||
+ Math.abs(element.x) > 1e7 ||
+ Math.abs(element.width) > 1e7 ||
+ Math.abs(element.height) > 1e7
+ ) {
+ console.error(
+ `Alt+dragging element in scene with invalid dimensions`,
+ element.x,
+ element.y,
+ element.width,
+ element.height,
+ isInSelection,
+ );
+
+ return;
+ }
+
+ if (isInSelection) {
+ const duplicatedElement = duplicateElement(
+ this.state.editingGroupId,
+ groupIdMap,
+ element,
+ );
+
+ // NOTE (mtolmacs): This is a temporary fix for very large scenes
+ if (
+ Math.abs(duplicatedElement.x) > 1e7 ||
+ Math.abs(duplicatedElement.x) > 1e7 ||
+ Math.abs(duplicatedElement.width) > 1e7 ||
+ Math.abs(duplicatedElement.height) > 1e7
+ ) {
+ console.error(
+ `Alt+dragging duplicated element with invalid dimensions`,
+ duplicatedElement.x,
+ duplicatedElement.y,
+ duplicatedElement.width,
+ duplicatedElement.height,
+ );
+
+ return;
+ }
+
+ const origElement = pointerDownState.originalElements.get(
+ element.id,
+ )!;
+
+ // NOTE (mtolmacs): This is a temporary fix for very large scenes
+ if (
+ Math.abs(origElement.x) > 1e7 ||
+ Math.abs(origElement.x) > 1e7 ||
+ Math.abs(origElement.width) > 1e7 ||
+ Math.abs(origElement.height) > 1e7
+ ) {
+ console.error(
+ `Alt+dragging duplicated element with invalid dimensions`,
+ origElement.x,
+ origElement.y,
+ origElement.width,
+ origElement.height,
+ );
+
+ return;
+ }
+
+ mutateElement(duplicatedElement, {
+ x: origElement.x,
+ y: origElement.y,
+ });
+
+ // put duplicated element to pointerDownState.originalElements
+ // so that we can snap to the duplicated element without releasing
+ pointerDownState.originalElements.set(
+ duplicatedElement.id,
+ duplicatedElement,
+ );
+
+ nextElements.push(duplicatedElement);
+ elementsToAppend.push(element);
+ oldIdToDuplicatedId.set(element.id, duplicatedElement.id);
+ } else {
+ nextElements.push(element);
+ }
+ }
+
+ let nextSceneElements: ExcalidrawElement[] = [
+ ...nextElements,
+ ...elementsToAppend,
+ ];
+
+ const mappedNewSceneElements = this.props.onDuplicate?.(
+ nextSceneElements,
+ elements,
+ );
+
+ nextSceneElements = mappedNewSceneElements || nextSceneElements;
+
+ syncMovedIndices(nextSceneElements, arrayToMap(elementsToAppend));
+
+ bindTextToShapeAfterDuplication(
+ nextElements,
+ elementsToAppend,
+ oldIdToDuplicatedId,
+ );
+ fixBindingsAfterDuplication(
+ nextSceneElements,
+ elementsToAppend,
+ oldIdToDuplicatedId,
+ "duplicatesServeAsOld",
+ );
+ bindElementsToFramesAfterDuplication(
+ nextSceneElements,
+ elementsToAppend,
+ oldIdToDuplicatedId,
+ );
+
+ this.scene.replaceAllElements(nextSceneElements);
+ this.maybeCacheVisibleGaps(event, selectedElements, true);
+ this.maybeCacheReferenceSnapPoints(event, selectedElements, true);
+ }
+
+ return;
+ }
+ }
+
+ if (this.state.selectionElement) {
+ pointerDownState.lastCoords.x = pointerCoords.x;
+ pointerDownState.lastCoords.y = pointerCoords.y;
+ this.maybeDragNewGenericElement(pointerDownState, event);
+ } else {
+ // It is very important to read this.state within each move event,
+ // otherwise we would read a stale one!
+ const newElement = this.state.newElement;
+
+ if (!newElement) {
+ return;
+ }
+
+ if (newElement.type === "freedraw") {
+ const points = newElement.points;
+ const dx = pointerCoords.x - newElement.x;
+ const dy = pointerCoords.y - newElement.y;
+
+ const lastPoint = points.length > 0 && points[points.length - 1];
+ const discardPoint =
+ lastPoint && lastPoint[0] === dx && lastPoint[1] === dy;
+
+ if (!discardPoint) {
+ const pressures = newElement.simulatePressure
+ ? newElement.pressures
+ : [...newElement.pressures, event.pressure];
+
+ mutateElement(
+ newElement,
+ {
+ points: [...points, pointFrom<LocalPoint>(dx, dy)],
+ pressures,
+ },
+ false,
+ );
+
+ this.setState({
+ newElement,
+ });
+ }
+ } else if (isLinearElement(newElement)) {
+ pointerDownState.drag.hasOccurred = true;
+ const points = newElement.points;
+ let dx = gridX - newElement.x;
+ let dy = gridY - newElement.y;
+
+ if (shouldRotateWithDiscreteAngle(event) && points.length === 2) {
+ ({ width: dx, height: dy } = getLockedLinearCursorAlignSize(
+ newElement.x,
+ newElement.y,
+ pointerCoords.x,
+ pointerCoords.y,
+ ));
+ }
+
+ if (points.length === 1) {
+ mutateElement(
+ newElement,
+ {
+ points: [...points, pointFrom<LocalPoint>(dx, dy)],
+ },
+ false,
+ );
+ } else if (
+ points.length === 2 ||
+ (points.length > 1 && isElbowArrow(newElement))
+ ) {
+ mutateElement(
+ newElement,
+ {
+ points: [...points.slice(0, -1), pointFrom<LocalPoint>(dx, dy)],
+ },
+ false,
+ { isDragging: true },
+ );
+ }
+
+ this.setState({
+ newElement,
+ });
+
+ if (isBindingElement(newElement, false)) {
+ // When creating a linear element by dragging
+ this.maybeSuggestBindingsForLinearElementAtCoords(
+ newElement,
+ [pointerCoords],
+ this.state.startBoundElement,
+ );
+ }
+ } else {
+ pointerDownState.lastCoords.x = pointerCoords.x;
+ pointerDownState.lastCoords.y = pointerCoords.y;
+ this.maybeDragNewGenericElement(pointerDownState, event, false);
+ }
+ }
+
+ if (this.state.activeTool.type === "selection") {
+ pointerDownState.boxSelection.hasOccurred = true;
+
+ const elements = this.scene.getNonDeletedElements();
+
+ // box-select line editor points
+ if (this.state.editingLinearElement) {
+ LinearElementEditor.handleBoxSelection(
+ event,
+ this.state,
+ this.setState.bind(this),
+ this.scene.getNonDeletedElementsMap(),
+ );
+ // regular box-select
+ } else {
+ let shouldReuseSelection = true;
+
+ if (!event.shiftKey && isSomeElementSelected(elements, this.state)) {
+ if (
+ pointerDownState.withCmdOrCtrl &&
+ pointerDownState.hit.element
+ ) {
+ this.setState((prevState) =>
+ selectGroupsForSelectedElements(
+ {
+ ...prevState,
+ selectedElementIds: {
+ [pointerDownState.hit.element!.id]: true,
+ },
+ },
+ this.scene.getNonDeletedElements(),
+ prevState,
+ this,
+ ),
+ );
+ } else {
+ shouldReuseSelection = false;
+ }
+ }
+ const elementsWithinSelection = this.state.selectionElement
+ ? getElementsWithinSelection(
+ elements,
+ this.state.selectionElement,
+ this.scene.getNonDeletedElementsMap(),
+ false,
+ )
+ : [];
+
+ this.setState((prevState) => {
+ const nextSelectedElementIds = {
+ ...(shouldReuseSelection && prevState.selectedElementIds),
+ ...elementsWithinSelection.reduce(
+ (acc: Record<ExcalidrawElement["id"], true>, element) => {
+ acc[element.id] = true;
+ return acc;
+ },
+ {},
+ ),
+ };
+
+ if (pointerDownState.hit.element) {
+ // if using ctrl/cmd, select the hitElement only if we
+ // haven't box-selected anything else
+ if (!elementsWithinSelection.length) {
+ nextSelectedElementIds[pointerDownState.hit.element.id] = true;
+ } else {
+ delete nextSelectedElementIds[pointerDownState.hit.element.id];
+ }
+ }
+
+ prevState = !shouldReuseSelection
+ ? { ...prevState, selectedGroupIds: {}, editingGroupId: null }
+ : prevState;
+
+ return {
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: nextSelectedElementIds,
+ },
+ this.scene.getNonDeletedElements(),
+ prevState,
+ this,
+ ),
+ // select linear element only when we haven't box-selected anything else
+ selectedLinearElement:
+ elementsWithinSelection.length === 1 &&
+ isLinearElement(elementsWithinSelection[0])
+ ? new LinearElementEditor(elementsWithinSelection[0])
+ : null,
+ showHyperlinkPopup:
+ elementsWithinSelection.length === 1 &&
+ (elementsWithinSelection[0].link ||
+ isEmbeddableElement(elementsWithinSelection[0]))
+ ? "info"
+ : false,
+ };
+ });
+ }
+ }
+ });
+ }
+
+ // Returns whether the pointer move happened over either scrollbar
+ private handlePointerMoveOverScrollbars(
+ event: PointerEvent,
+ pointerDownState: PointerDownState,
+ ): boolean {
+ if (pointerDownState.scrollbars.isOverHorizontal) {
+ const x = event.clientX;
+ const dx = x - pointerDownState.lastCoords.x;
+ this.translateCanvas({
+ scrollX: this.state.scrollX - dx / this.state.zoom.value,
+ });
+ pointerDownState.lastCoords.x = x;
+ return true;
+ }
+
+ if (pointerDownState.scrollbars.isOverVertical) {
+ const y = event.clientY;
+ const dy = y - pointerDownState.lastCoords.y;
+ this.translateCanvas({
+ scrollY: this.state.scrollY - dy / this.state.zoom.value,
+ });
+ pointerDownState.lastCoords.y = y;
+ return true;
+ }
+ return false;
+ }
+
+ private onPointerUpFromPointerDownHandler(
+ pointerDownState: PointerDownState,
+ ): (event: PointerEvent) => void {
+ return withBatchedUpdates((childEvent: PointerEvent) => {
+ this.removePointer(childEvent);
+ if (pointerDownState.eventListeners.onMove) {
+ pointerDownState.eventListeners.onMove.flush();
+ }
+ const {
+ newElement,
+ resizingElement,
+ croppingElementId,
+ multiElement,
+ activeTool,
+ isResizing,
+ isRotating,
+ isCropping,
+ } = this.state;
+
+ this.setState((prevState) => ({
+ isResizing: false,
+ isRotating: false,
+ isCropping: false,
+ resizingElement: null,
+ selectionElement: null,
+ frameToHighlight: null,
+ elementsToHighlight: null,
+ cursorButton: "up",
+ snapLines: updateStable(prevState.snapLines, []),
+ originSnapOffset: null,
+ }));
+
+ this.lastPointerMoveCoords = null;
+
+ SnapCache.setReferenceSnapPoints(null);
+ SnapCache.setVisibleGaps(null);
+
+ this.savePointer(childEvent.clientX, childEvent.clientY, "up");
+
+ this.setState({
+ selectedElementsAreBeingDragged: false,
+ });
+ const elementsMap = this.scene.getNonDeletedElementsMap();
+
+ if (
+ pointerDownState.drag.hasOccurred &&
+ pointerDownState.hit?.element?.id
+ ) {
+ const element = elementsMap.get(pointerDownState.hit.element.id);
+ if (isBindableElement(element)) {
+ // Renormalize elbow arrows when they are changed via indirect move
+ element.boundElements
+ ?.filter((e) => e.type === "arrow")
+ .map((e) => elementsMap.get(e.id))
+ .filter((e) => isElbowArrow(e))
+ .forEach((e) => {
+ !!e && mutateElement(e, {}, true);
+ });
+ }
+ }
+
+ // Handle end of dragging a point of a linear element, might close a loop
+ // and sets binding element
+ if (this.state.editingLinearElement) {
+ if (
+ !pointerDownState.boxSelection.hasOccurred &&
+ pointerDownState.hit?.element?.id !==
+ this.state.editingLinearElement.elementId
+ ) {
+ this.actionManager.executeAction(actionFinalize);
+ } else {
+ const editingLinearElement = LinearElementEditor.handlePointerUp(
+ childEvent,
+ this.state.editingLinearElement,
+ this.state,
+ this.scene,
+ );
+ if (editingLinearElement !== this.state.editingLinearElement) {
+ this.setState({
+ editingLinearElement,
+ suggestedBindings: [],
+ });
+ }
+ }
+ } else if (this.state.selectedLinearElement) {
+ // Normalize elbow arrow points, remove close parallel segments
+ if (this.state.selectedLinearElement.elbowed) {
+ const element = LinearElementEditor.getElement(
+ this.state.selectedLinearElement.elementId,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ if (element) {
+ mutateElement(element, {}, true);
+ }
+ }
+
+ if (
+ pointerDownState.hit?.element?.id !==
+ this.state.selectedLinearElement.elementId
+ ) {
+ const selectedELements = this.scene.getSelectedElements(this.state);
+ // set selectedLinearElement to null if there is more than one element selected since we don't want to show linear element handles
+ if (selectedELements.length > 1) {
+ this.setState({ selectedLinearElement: null });
+ }
+ } else {
+ const linearElementEditor = LinearElementEditor.handlePointerUp(
+ childEvent,
+ this.state.selectedLinearElement,
+ this.state,
+ this.scene,
+ );
+
+ const { startBindingElement, endBindingElement } =
+ linearElementEditor;
+ const element = this.scene.getElement(linearElementEditor.elementId);
+ if (isBindingElement(element)) {
+ bindOrUnbindLinearElement(
+ element,
+ startBindingElement,
+ endBindingElement,
+ elementsMap,
+ this.scene,
+ );
+ }
+
+ if (linearElementEditor !== this.state.selectedLinearElement) {
+ this.setState({
+ selectedLinearElement: {
+ ...linearElementEditor,
+ selectedPointsIndices: null,
+ },
+ suggestedBindings: [],
+ });
+ }
+ }
+ }
+
+ this.missingPointerEventCleanupEmitter.clear();
+
+ window.removeEventListener(
+ EVENT.POINTER_MOVE,
+ pointerDownState.eventListeners.onMove!,
+ );
+ window.removeEventListener(
+ EVENT.POINTER_UP,
+ pointerDownState.eventListeners.onUp!,
+ );
+ window.removeEventListener(
+ EVENT.KEYDOWN,
+ pointerDownState.eventListeners.onKeyDown!,
+ );
+ window.removeEventListener(
+ EVENT.KEYUP,
+ pointerDownState.eventListeners.onKeyUp!,
+ );
+
+ if (this.state.pendingImageElementId) {
+ this.setState({ pendingImageElementId: null });
+ }
+
+ this.props?.onPointerUp?.(activeTool, pointerDownState);
+ this.onPointerUpEmitter.trigger(
+ this.state.activeTool,
+ pointerDownState,
+ childEvent,
+ );
+
+ if (newElement?.type === "freedraw") {
+ const pointerCoords = viewportCoordsToSceneCoords(
+ childEvent,
+ this.state,
+ );
+
+ const points = newElement.points;
+ let dx = pointerCoords.x - newElement.x;
+ let dy = pointerCoords.y - newElement.y;
+
+ // Allows dots to avoid being flagged as infinitely small
+ if (dx === points[0][0] && dy === points[0][1]) {
+ dy += 0.0001;
+ dx += 0.0001;
+ }
+
+ const pressures = newElement.simulatePressure
+ ? []
+ : [...newElement.pressures, childEvent.pressure];
+
+ mutateElement(newElement, {
+ points: [...points, pointFrom<LocalPoint>(dx, dy)],
+ pressures,
+ lastCommittedPoint: pointFrom<LocalPoint>(dx, dy),
+ });
+
+ this.actionManager.executeAction(actionFinalize);
+
+ return;
+ }
+ if (isImageElement(newElement)) {
+ const imageElement = newElement;
+ try {
+ this.initializeImageDimensions(imageElement);
+ this.setState(
+ {
+ selectedElementIds: makeNextSelectedElementIds(
+ { [imageElement.id]: true },
+ this.state,
+ ),
+ },
+ () => {
+ this.actionManager.executeAction(actionFinalize);
+ },
+ );
+ } catch (error: any) {
+ console.error(error);
+ this.scene.replaceAllElements(
+ this.scene
+ .getElementsIncludingDeleted()
+ .filter((el) => el.id !== imageElement.id),
+ );
+ this.actionManager.executeAction(actionFinalize);
+ }
+ return;
+ }
+
+ if (isLinearElement(newElement)) {
+ if (newElement!.points.length > 1) {
+ this.store.shouldCaptureIncrement();
+ }
+ const pointerCoords = viewportCoordsToSceneCoords(
+ childEvent,
+ this.state,
+ );
+
+ if (!pointerDownState.drag.hasOccurred && newElement && !multiElement) {
+ mutateElement(newElement, {
+ points: [
+ ...newElement.points,
+ pointFrom<LocalPoint>(
+ pointerCoords.x - newElement.x,
+ pointerCoords.y - newElement.y,
+ ),
+ ],
+ });
+ this.setState({
+ multiElement: newElement,
+ newElement,
+ });
+ } else if (pointerDownState.drag.hasOccurred && !multiElement) {
+ if (
+ isBindingEnabled(this.state) &&
+ isBindingElement(newElement, false)
+ ) {
+ maybeBindLinearElement(
+ newElement,
+ this.state,
+ pointerCoords,
+ this.scene.getNonDeletedElementsMap(),
+ this.scene.getNonDeletedElements(),
+ );
+ }
+ this.setState({ suggestedBindings: [], startBoundElement: null });
+ if (!activeTool.locked) {
+ resetCursor(this.interactiveCanvas);
+ this.setState((prevState) => ({
+ newElement: null,
+ activeTool: updateActiveTool(this.state, {
+ type: "selection",
+ }),
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ ...prevState.selectedElementIds,
+ [newElement.id]: true,
+ },
+ prevState,
+ ),
+ selectedLinearElement: new LinearElementEditor(newElement),
+ }));
+ } else {
+ this.setState((prevState) => ({
+ newElement: null,
+ }));
+ }
+ // so that the scene gets rendered again to display the newly drawn linear as well
+ this.scene.triggerUpdate();
+ }
+ return;
+ }
+
+ if (isTextElement(newElement)) {
+ const minWidth = getMinTextElementWidth(
+ getFontString({
+ fontSize: newElement.fontSize,
+ fontFamily: newElement.fontFamily,
+ }),
+ newElement.lineHeight,
+ );
+
+ if (newElement.width < minWidth) {
+ mutateElement(newElement, {
+ autoResize: true,
+ });
+ }
+
+ this.resetCursor();
+
+ this.handleTextWysiwyg(newElement, {
+ isExistingElement: true,
+ });
+ }
+
+ if (
+ activeTool.type !== "selection" &&
+ newElement &&
+ isInvisiblySmallElement(newElement)
+ ) {
+ // remove invisible element which was added in onPointerDown
+ // update the store snapshot, so that invisible elements are not captured by the store
+ this.updateScene({
+ elements: this.scene
+ .getElementsIncludingDeleted()
+ .filter((el) => el.id !== newElement.id),
+ appState: {
+ newElement: null,
+ },
+ captureUpdate: CaptureUpdateAction.NEVER,
+ });
+
+ return;
+ }
+
+ if (isFrameLikeElement(newElement)) {
+ const elementsInsideFrame = getElementsInNewFrame(
+ this.scene.getElementsIncludingDeleted(),
+ newElement,
+ this.scene.getNonDeletedElementsMap(),
+ );
+
+ this.scene.replaceAllElements(
+ addElementsToFrame(
+ this.scene.getElementsMapIncludingDeleted(),
+ elementsInsideFrame,
+ newElement,
+ this.state,
+ ),
+ );
+ }
+
+ if (newElement) {
+ mutateElement(newElement, getNormalizedDimensions(newElement));
+ // the above does not guarantee the scene to be rendered again, hence the trigger below
+ this.scene.triggerUpdate();
+ }
+
+ if (pointerDownState.drag.hasOccurred) {
+ const sceneCoords = viewportCoordsToSceneCoords(childEvent, this.state);
+
+ // when editing the points of a linear element, we check if the
+ // linear element still is in the frame afterwards
+ // if not, the linear element will be removed from its frame (if any)
+ if (
+ this.state.selectedLinearElement &&
+ this.state.selectedLinearElement.isDragging
+ ) {
+ const linearElement = this.scene.getElement(
+ this.state.selectedLinearElement.elementId,
+ );
+
+ if (linearElement?.frameId) {
+ const frame = getContainingFrame(linearElement, elementsMap);
+
+ if (frame && linearElement) {
+ if (
+ !elementOverlapsWithFrame(
+ linearElement,
+ frame,
+ this.scene.getNonDeletedElementsMap(),
+ )
+ ) {
+ // remove the linear element from all groups
+ // before removing it from the frame as well
+ mutateElement(linearElement, {
+ groupIds: [],
+ });
+
+ removeElementsFromFrame(
+ [linearElement],
+ this.scene.getNonDeletedElementsMap(),
+ );
+
+ this.scene.triggerUpdate();
+ }
+ }
+ }
+ } else {
+ // update the relationships between selected elements and frames
+ const topLayerFrame = this.getTopLayerFrameAtSceneCoords(sceneCoords);
+
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ let nextElements = this.scene.getElementsMapIncludingDeleted();
+
+ const updateGroupIdsAfterEditingGroup = (
+ elements: ExcalidrawElement[],
+ ) => {
+ if (elements.length > 0) {
+ for (const element of elements) {
+ const index = element.groupIds.indexOf(
+ this.state.editingGroupId!,
+ );
+
+ mutateElement(
+ element,
+ {
+ groupIds: element.groupIds.slice(0, index),
+ },
+ false,
+ );
+ }
+
+ nextElements.forEach((element) => {
+ if (
+ element.groupIds.length &&
+ getElementsInGroup(
+ nextElements,
+ element.groupIds[element.groupIds.length - 1],
+ ).length < 2
+ ) {
+ mutateElement(
+ element,
+ {
+ groupIds: [],
+ },
+ false,
+ );
+ }
+ });
+
+ this.setState({
+ editingGroupId: null,
+ });
+ }
+ };
+
+ if (
+ topLayerFrame &&
+ !this.state.selectedElementIds[topLayerFrame.id]
+ ) {
+ const elementsToAdd = selectedElements.filter(
+ (element) =>
+ element.frameId !== topLayerFrame.id &&
+ isElementInFrame(element, nextElements, this.state),
+ );
+
+ if (this.state.editingGroupId) {
+ updateGroupIdsAfterEditingGroup(elementsToAdd);
+ }
+
+ nextElements = addElementsToFrame(
+ nextElements,
+ elementsToAdd,
+ topLayerFrame,
+ this.state,
+ );
+ } else if (!topLayerFrame) {
+ if (this.state.editingGroupId) {
+ const elementsToRemove = selectedElements.filter(
+ (element) =>
+ element.frameId &&
+ !isElementInFrame(element, nextElements, this.state),
+ );
+
+ updateGroupIdsAfterEditingGroup(elementsToRemove);
+ }
+ }
+
+ nextElements = updateFrameMembershipOfSelectedElements(
+ nextElements,
+ this.state,
+ this,
+ );
+
+ this.scene.replaceAllElements(nextElements);
+ }
+ }
+
+ if (resizingElement) {
+ this.store.shouldCaptureIncrement();
+ }
+
+ if (resizingElement && isInvisiblySmallElement(resizingElement)) {
+ // update the store snapshot, so that invisible elements are not captured by the store
+ this.updateScene({
+ elements: this.scene
+ .getElementsIncludingDeleted()
+ .filter((el) => el.id !== resizingElement.id),
+ captureUpdate: CaptureUpdateAction.NEVER,
+ });
+ }
+
+ // handle frame membership for resizing frames and/or selected elements
+ if (pointerDownState.resize.isResizing) {
+ let nextElements = updateFrameMembershipOfSelectedElements(
+ this.scene.getElementsIncludingDeleted(),
+ this.state,
+ this,
+ );
+
+ const selectedFrames = this.scene
+ .getSelectedElements(this.state)
+ .filter((element): element is ExcalidrawFrameLikeElement =>
+ isFrameLikeElement(element),
+ );
+
+ for (const frame of selectedFrames) {
+ nextElements = replaceAllElementsInFrame(
+ nextElements,
+ getElementsInResizingFrame(
+ this.scene.getElementsIncludingDeleted(),
+ frame,
+ this.state,
+ elementsMap,
+ ),
+ frame,
+ this,
+ );
+ }
+
+ this.scene.replaceAllElements(nextElements);
+ }
+
+ // Code below handles selection when element(s) weren't
+ // drag or added to selection on pointer down phase.
+ const hitElement = pointerDownState.hit.element;
+ if (
+ this.state.selectedLinearElement?.elementId !== hitElement?.id &&
+ isLinearElement(hitElement)
+ ) {
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ // set selectedLinearElement when no other element selected except
+ // the one we've hit
+ if (selectedElements.length === 1) {
+ this.setState({
+ selectedLinearElement: new LinearElementEditor(hitElement),
+ });
+ }
+ }
+
+ // click outside the cropping region to exit
+ if (
+ // not in the cropping mode at all
+ !croppingElementId ||
+ // in the cropping mode
+ (croppingElementId &&
+ // not cropping and no hit element
+ ((!hitElement && !isCropping) ||
+ // hitting something else
+ (hitElement && hitElement.id !== croppingElementId)))
+ ) {
+ this.finishImageCropping();
+ }
+
+ const pointerStart = this.lastPointerDownEvent;
+ const pointerEnd = this.lastPointerUpEvent || this.lastPointerMoveEvent;
+
+ if (isEraserActive(this.state) && pointerStart && pointerEnd) {
+ this.eraserTrail.endPath();
+
+ const draggedDistance = pointDistance(
+ pointFrom(pointerStart.clientX, pointerStart.clientY),
+ pointFrom(pointerEnd.clientX, pointerEnd.clientY),
+ );
+
+ if (draggedDistance === 0) {
+ const scenePointer = viewportCoordsToSceneCoords(
+ {
+ clientX: pointerEnd.clientX,
+ clientY: pointerEnd.clientY,
+ },
+ this.state,
+ );
+ const hitElements = this.getElementsAtPosition(
+ scenePointer.x,
+ scenePointer.y,
+ );
+ hitElements.forEach((hitElement) =>
+ this.elementsPendingErasure.add(hitElement.id),
+ );
+ }
+ this.eraseElements();
+ return;
+ } else if (this.elementsPendingErasure.size) {
+ this.restoreReadyToEraseElements();
+ }
+
+ if (
+ hitElement &&
+ !pointerDownState.drag.hasOccurred &&
+ !pointerDownState.hit.wasAddedToSelection &&
+ // if we're editing a line, pointerup shouldn't switch selection if
+ // box selected
+ (!this.state.editingLinearElement ||
+ !pointerDownState.boxSelection.hasOccurred)
+ ) {
+ // when inside line editor, shift selects points instead
+ if (childEvent.shiftKey && !this.state.editingLinearElement) {
+ if (this.state.selectedElementIds[hitElement.id]) {
+ if (isSelectedViaGroup(this.state, hitElement)) {
+ this.setState((_prevState) => {
+ const nextSelectedElementIds = {
+ ..._prevState.selectedElementIds,
+ };
+
+ // We want to unselect all groups hitElement is part of
+ // as well as all elements that are part of the groups
+ // hitElement is part of
+ for (const groupedElement of hitElement.groupIds.flatMap(
+ (groupId) =>
+ getElementsInGroup(
+ this.scene.getNonDeletedElements(),
+ groupId,
+ ),
+ )) {
+ delete nextSelectedElementIds[groupedElement.id];
+ }
+
+ return {
+ selectedGroupIds: {
+ ..._prevState.selectedElementIds,
+ ...hitElement.groupIds
+ .map((gId) => ({ [gId]: false }))
+ .reduce((prev, acc) => ({ ...prev, ...acc }), {}),
+ },
+ selectedElementIds: makeNextSelectedElementIds(
+ nextSelectedElementIds,
+ _prevState,
+ ),
+ };
+ });
+ // if not dragging a linear element point (outside editor)
+ } else if (!this.state.selectedLinearElement?.isDragging) {
+ // remove element from selection while
+ // keeping prev elements selected
+
+ this.setState((prevState) => {
+ const newSelectedElementIds = {
+ ...prevState.selectedElementIds,
+ };
+ delete newSelectedElementIds[hitElement!.id];
+ const newSelectedElements = getSelectedElements(
+ this.scene.getNonDeletedElements(),
+ { selectedElementIds: newSelectedElementIds },
+ );
+
+ return {
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: newSelectedElementIds,
+ },
+ this.scene.getNonDeletedElements(),
+ prevState,
+ this,
+ ),
+ // set selectedLinearElement only if thats the only element selected
+ selectedLinearElement:
+ newSelectedElements.length === 1 &&
+ isLinearElement(newSelectedElements[0])
+ ? new LinearElementEditor(newSelectedElements[0])
+ : prevState.selectedLinearElement,
+ };
+ });
+ }
+ } else if (
+ hitElement.frameId &&
+ this.state.selectedElementIds[hitElement.frameId]
+ ) {
+ // when hitElement is part of a selected frame, deselect the frame
+ // to avoid frame and containing elements selected simultaneously
+ this.setState((prevState) => {
+ const nextSelectedElementIds: {
+ [id: string]: true;
+ } = {
+ ...prevState.selectedElementIds,
+ [hitElement.id]: true,
+ };
+ // deselect the frame
+ delete nextSelectedElementIds[hitElement.frameId!];
+
+ // deselect groups containing the frame
+ (this.scene.getElement(hitElement.frameId!)?.groupIds ?? [])
+ .flatMap((gid) =>
+ getElementsInGroup(this.scene.getNonDeletedElements(), gid),
+ )
+ .forEach((element) => {
+ delete nextSelectedElementIds[element.id];
+ });
+
+ return {
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: nextSelectedElementIds,
+ },
+ this.scene.getNonDeletedElements(),
+ prevState,
+ this,
+ ),
+ showHyperlinkPopup:
+ hitElement.link || isEmbeddableElement(hitElement)
+ ? "info"
+ : false,
+ };
+ });
+ } else {
+ // add element to selection while keeping prev elements selected
+ this.setState((_prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ ..._prevState.selectedElementIds,
+ [hitElement!.id]: true,
+ },
+ _prevState,
+ ),
+ }));
+ }
+ } else {
+ this.setState((prevState) => ({
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: prevState.editingGroupId,
+ selectedElementIds: { [hitElement.id]: true },
+ },
+ this.scene.getNonDeletedElements(),
+ prevState,
+ this,
+ ),
+ selectedLinearElement:
+ isLinearElement(hitElement) &&
+ // Don't set `selectedLinearElement` if its same as the hitElement, this is mainly to prevent resetting the `hoverPointIndex` to -1.
+ // Future we should update the API to take care of setting the correct `hoverPointIndex` when initialized
+ prevState.selectedLinearElement?.elementId !== hitElement.id
+ ? new LinearElementEditor(hitElement)
+ : prevState.selectedLinearElement,
+ }));
+ }
+ }
+
+ if (
+ // not elbow midpoint dragged
+ !(hitElement && isElbowArrow(hitElement)) &&
+ // not dragged
+ !pointerDownState.drag.hasOccurred &&
+ // not resized
+ !this.state.isResizing &&
+ // only hitting the bounding box of the previous hit element
+ ((hitElement &&
+ hitElementBoundingBoxOnly(
+ {
+ x: pointerDownState.origin.x,
+ y: pointerDownState.origin.y,
+ element: hitElement,
+ shape: getElementShape(
+ hitElement,
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ threshold: this.getElementHitThreshold(),
+ frameNameBound: isFrameLikeElement(hitElement)
+ ? this.frameNameBoundsCache.get(hitElement)
+ : null,
+ },
+ elementsMap,
+ )) ||
+ (!hitElement &&
+ pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements))
+ ) {
+ if (this.state.editingLinearElement) {
+ this.setState({ editingLinearElement: null });
+ } else {
+ // Deselect selected elements
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.state),
+ selectedGroupIds: {},
+ editingGroupId: null,
+ activeEmbeddable: null,
+ });
+ }
+ // reset cursor
+ setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
+ return;
+ }
+
+ if (!activeTool.locked && activeTool.type !== "freedraw" && newElement) {
+ this.setState((prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds(
+ {
+ ...prevState.selectedElementIds,
+ [newElement.id]: true,
+ },
+ prevState,
+ ),
+ showHyperlinkPopup:
+ isEmbeddableElement(newElement) && !newElement.link
+ ? "editor"
+ : prevState.showHyperlinkPopup,
+ }));
+ }
+
+ if (
+ activeTool.type !== "selection" ||
+ isSomeElementSelected(this.scene.getNonDeletedElements(), this.state) ||
+ !isShallowEqual(
+ this.state.previousSelectedElementIds,
+ this.state.selectedElementIds,
+ )
+ ) {
+ this.store.shouldCaptureIncrement();
+ }
+
+ if (
+ pointerDownState.drag.hasOccurred ||
+ isResizing ||
+ isRotating ||
+ isCropping
+ ) {
+ // We only allow binding via linear elements, specifically via dragging
+ // the endpoints ("start" or "end").
+ const linearElements = this.scene
+ .getSelectedElements(this.state)
+ .filter(isLinearElement);
+
+ bindOrUnbindLinearElements(
+ linearElements,
+ this.scene.getNonDeletedElementsMap(),
+ this.scene.getNonDeletedElements(),
+ this.scene,
+ isBindingEnabled(this.state),
+ this.state.selectedLinearElement?.selectedPointsIndices ?? [],
+ this.state.zoom,
+ );
+ }
+
+ if (activeTool.type === "laser") {
+ this.laserTrails.endPath();
+ return;
+ }
+
+ if (!activeTool.locked && activeTool.type !== "freedraw") {
+ resetCursor(this.interactiveCanvas);
+ this.setState({
+ newElement: null,
+ suggestedBindings: [],
+ activeTool: updateActiveTool(this.state, { type: "selection" }),
+ });
+ } else {
+ this.setState({
+ newElement: null,
+ suggestedBindings: [],
+ });
+ }
+
+ if (
+ hitElement &&
+ this.lastPointerUpEvent &&
+ this.lastPointerDownEvent &&
+ this.lastPointerUpEvent.timeStamp -
+ this.lastPointerDownEvent.timeStamp <
+ 300 &&
+ gesture.pointers.size <= 1 &&
+ isIframeLikeElement(hitElement) &&
+ this.isIframeLikeElementCenter(
+ hitElement,
+ this.lastPointerUpEvent,
+ pointerDownState.origin.x,
+ pointerDownState.origin.y,
+ )
+ ) {
+ this.handleEmbeddableCenterClick(hitElement);
+ }
+ });
+ }
+
+ private restoreReadyToEraseElements = () => {
+ this.elementsPendingErasure = new Set();
+ this.triggerRender();
+ };
+
+ private eraseElements = () => {
+ let didChange = false;
+ const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
+ if (
+ this.elementsPendingErasure.has(ele.id) ||
+ (ele.frameId && this.elementsPendingErasure.has(ele.frameId)) ||
+ (isBoundToContainer(ele) &&
+ this.elementsPendingErasure.has(ele.containerId))
+ ) {
+ didChange = true;
+ return newElementWith(ele, { isDeleted: true });
+ }
+ return ele;
+ });
+
+ this.elementsPendingErasure = new Set();
+
+ if (didChange) {
+ this.store.shouldCaptureIncrement();
+ this.scene.replaceAllElements(elements);
+ }
+ };
+
+ private initializeImage = async ({
+ imageFile,
+ imageElement: _imageElement,
+ showCursorImagePreview = false,
+ }: {
+ imageFile: File;
+ imageElement: ExcalidrawImageElement;
+ showCursorImagePreview?: boolean;
+ }) => {
+ // at this point this should be guaranteed image file, but we do this check
+ // to satisfy TS down the line
+ if (!isSupportedImageFile(imageFile)) {
+ throw new Error(t("errors.unsupportedFileType"));
+ }
+ const mimeType = imageFile.type;
+
+ setCursor(this.interactiveCanvas, "wait");
+
+ if (mimeType === MIME_TYPES.svg) {
+ try {
+ imageFile = SVGStringToFile(
+ normalizeSVG(await imageFile.text()),
+ imageFile.name,
+ );
+ } catch (error: any) {
+ console.warn(error);
+ throw new Error(t("errors.svgImageInsertError"));
+ }
+ }
+
+ // generate image id (by default the file digest) before any
+ // resizing/compression takes place to keep it more portable
+ const fileId = await ((this.props.generateIdForFile?.(
+ imageFile,
+ ) as Promise<FileId>) || generateIdFromFile(imageFile));
+
+ if (!fileId) {
+ console.warn(
+ "Couldn't generate file id or the supplied `generateIdForFile` didn't resolve to one.",
+ );
+ throw new Error(t("errors.imageInsertError"));
+ }
+
+ const existingFileData = this.files[fileId];
+ if (!existingFileData?.dataURL) {
+ try {
+ imageFile = await resizeImageFile(imageFile, {
+ maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
+ });
+ } catch (error: any) {
+ console.error(
+ "Error trying to resizing image file on insertion",
+ error,
+ );
+ }
+
+ if (imageFile.size > MAX_ALLOWED_FILE_BYTES) {
+ throw new Error(
+ t("errors.fileTooBig", {
+ maxSize: `${Math.trunc(MAX_ALLOWED_FILE_BYTES / 1024 / 1024)}MB`,
+ }),
+ );
+ }
+ }
+
+ if (showCursorImagePreview) {
+ const dataURL = this.files[fileId]?.dataURL;
+ // optimization so that we don't unnecessarily resize the original
+ // full-size file for cursor preview
+ // (it's much faster to convert the resized dataURL to File)
+ const resizedFile = dataURL && dataURLToFile(dataURL);
+
+ this.setImagePreviewCursor(resizedFile || imageFile);
+ }
+
+ const dataURL =
+ this.files[fileId]?.dataURL || (await getDataURL(imageFile));
+
+ const imageElement = mutateElement(
+ _imageElement,
+ {
+ fileId,
+ },
+ false,
+ ) as NonDeleted<InitializedExcalidrawImageElement>;
+
+ return new Promise<NonDeleted<InitializedExcalidrawImageElement>>(
+ async (resolve, reject) => {
+ try {
+ this.addMissingFiles([
+ {
+ mimeType,
+ id: fileId,
+ dataURL,
+ created: Date.now(),
+ lastRetrieved: Date.now(),
+ },
+ ]);
+ const cachedImageData = this.imageCache.get(fileId);
+ if (!cachedImageData) {
+ this.addNewImagesToImageCache();
+ await this.updateImageCache([imageElement]);
+ }
+ if (cachedImageData?.image instanceof Promise) {
+ await cachedImageData.image;
+ }
+ if (
+ this.state.pendingImageElementId !== imageElement.id &&
+ this.state.newElement?.id !== imageElement.id
+ ) {
+ this.initializeImageDimensions(imageElement, true);
+ }
+ resolve(imageElement);
+ } catch (error: any) {
+ console.error(error);
+ reject(new Error(t("errors.imageInsertError")));
+ } finally {
+ if (!showCursorImagePreview) {
+ resetCursor(this.interactiveCanvas);
+ }
+ }
+ },
+ );
+ };
+
+ /**
+ * inserts image into elements array and rerenders
+ */
+ insertImageElement = async (
+ imageElement: ExcalidrawImageElement,
+ imageFile: File,
+ showCursorImagePreview?: boolean,
+ ) => {
+ // we should be handling all cases upstream, but in case we forget to handle
+ // a future case, let's throw here
+ if (!this.isToolSupported("image")) {
+ this.setState({ errorMessage: t("errors.imageToolNotSupported") });
+ return;
+ }
+
+ this.scene.insertElement(imageElement);
+
+ try {
+ return await this.initializeImage({
+ imageFile,
+ imageElement,
+ showCursorImagePreview,
+ });
+ } catch (error: any) {
+ mutateElement(imageElement, {
+ isDeleted: true,
+ });
+ this.actionManager.executeAction(actionFinalize);
+ this.setState({
+ errorMessage: error.message || t("errors.imageInsertError"),
+ });
+ return null;
+ }
+ };
+
+ private setImagePreviewCursor = async (imageFile: File) => {
+ // mustn't be larger than 128 px
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property
+ const cursorImageSizePx = 96;
+ let imagePreview;
+
+ try {
+ imagePreview = await resizeImageFile(imageFile, {
+ maxWidthOrHeight: cursorImageSizePx,
+ });
+ } catch (e: any) {
+ if (e.cause === "UNSUPPORTED") {
+ throw new Error(t("errors.unsupportedFileType"));
+ }
+ throw e;
+ }
+
+ let previewDataURL = await getDataURL(imagePreview);
+
+ // SVG cannot be resized via `resizeImageFile` so we resize by rendering to
+ // a small canvas
+ if (imageFile.type === MIME_TYPES.svg) {
+ const img = await loadHTMLImageElement(previewDataURL);
+
+ let height = Math.min(img.height, cursorImageSizePx);
+ let width = height * (img.width / img.height);
+
+ if (width > cursorImageSizePx) {
+ width = cursorImageSizePx;
+ height = width * (img.height / img.width);
+ }
+
+ const canvas = document.createElement("canvas");
+ canvas.height = height;
+ canvas.width = width;
+ const context = canvas.getContext("2d")!;
+
+ context.drawImage(img, 0, 0, width, height);
+
+ previewDataURL = canvas.toDataURL(MIME_TYPES.svg) as DataURL;
+ }
+
+ if (this.state.pendingImageElementId) {
+ setCursor(this.interactiveCanvas, `url(${previewDataURL}) 4 4, auto`);
+ }
+ };
+
+ private onImageAction = async ({
+ insertOnCanvasDirectly,
+ }: {
+ insertOnCanvasDirectly: boolean;
+ }) => {
+ try {
+ const clientX = this.state.width / 2 + this.state.offsetLeft;
+ const clientY = this.state.height / 2 + this.state.offsetTop;
+
+ const { x, y } = viewportCoordsToSceneCoords(
+ { clientX, clientY },
+ this.state,
+ );
+
+ const imageFile = await fileOpen({
+ description: "Image",
+ extensions: Object.keys(
+ IMAGE_MIME_TYPES,
+ ) as (keyof typeof IMAGE_MIME_TYPES)[],
+ });
+
+ const imageElement = this.createImageElement({
+ sceneX: x,
+ sceneY: y,
+ addToFrameUnderCursor: false,
+ });
+
+ if (insertOnCanvasDirectly) {
+ this.insertImageElement(imageElement, imageFile);
+ this.initializeImageDimensions(imageElement);
+ this.setState(
+ {
+ selectedElementIds: makeNextSelectedElementIds(
+ { [imageElement.id]: true },
+ this.state,
+ ),
+ },
+ () => {
+ this.actionManager.executeAction(actionFinalize);
+ },
+ );
+ } else {
+ this.setState(
+ {
+ pendingImageElementId: imageElement.id,
+ },
+ () => {
+ this.insertImageElement(
+ imageElement,
+ imageFile,
+ /* showCursorImagePreview */ true,
+ );
+ },
+ );
+ }
+ } catch (error: any) {
+ if (error.name !== "AbortError") {
+ console.error(error);
+ } else {
+ console.warn(error);
+ }
+ this.setState(
+ {
+ pendingImageElementId: null,
+ newElement: null,
+ activeTool: updateActiveTool(this.state, { type: "selection" }),
+ },
+ () => {
+ this.actionManager.executeAction(actionFinalize);
+ },
+ );
+ }
+ };
+
+ initializeImageDimensions = (
+ imageElement: ExcalidrawImageElement,
+ forceNaturalSize = false,
+ ) => {
+ const image =
+ isInitializedImageElement(imageElement) &&
+ this.imageCache.get(imageElement.fileId)?.image;
+
+ if (!image || image instanceof Promise) {
+ if (
+ imageElement.width < DRAGGING_THRESHOLD / this.state.zoom.value &&
+ imageElement.height < DRAGGING_THRESHOLD / this.state.zoom.value
+ ) {
+ const placeholderSize = 100 / this.state.zoom.value;
+ mutateElement(imageElement, {
+ x: imageElement.x - placeholderSize / 2,
+ y: imageElement.y - placeholderSize / 2,
+ width: placeholderSize,
+ height: placeholderSize,
+ });
+ }
+
+ return;
+ }
+
+ if (
+ forceNaturalSize ||
+ // if user-created bounding box is below threshold, assume the
+ // intention was to click instead of drag, and use the image's
+ // intrinsic size
+ (imageElement.width < DRAGGING_THRESHOLD / this.state.zoom.value &&
+ imageElement.height < DRAGGING_THRESHOLD / this.state.zoom.value)
+ ) {
+ const minHeight = Math.max(this.state.height - 120, 160);
+ // max 65% of canvas height, clamped to <300px, vh - 120px>
+ const maxHeight = Math.min(
+ minHeight,
+ Math.floor(this.state.height * 0.5) / this.state.zoom.value,
+ );
+
+ const height = Math.min(image.naturalHeight, maxHeight);
+ const width = height * (image.naturalWidth / image.naturalHeight);
+
+ // add current imageElement width/height to account for previous centering
+ // of the placeholder image
+ const x = imageElement.x + imageElement.width / 2 - width / 2;
+ const y = imageElement.y + imageElement.height / 2 - height / 2;
+
+ mutateElement(imageElement, {
+ x,
+ y,
+ width,
+ height,
+ crop: null,
+ });
+ }
+ };
+
+ /** updates image cache, refreshing updated elements and/or setting status
+ to error for images that fail during <img> element creation */
+ private updateImageCache = async (
+ elements: readonly InitializedExcalidrawImageElement[],
+ files = this.files,
+ ) => {
+ const { updatedFiles, erroredFiles } = await _updateImageCache({
+ imageCache: this.imageCache,
+ fileIds: elements.map((element) => element.fileId),
+ files,
+ });
+ if (updatedFiles.size || erroredFiles.size) {
+ for (const element of elements) {
+ if (updatedFiles.has(element.fileId)) {
+ ShapeCache.delete(element);
+ }
+ }
+ }
+ if (erroredFiles.size) {
+ this.scene.replaceAllElements(
+ this.scene.getElementsIncludingDeleted().map((element) => {
+ if (
+ isInitializedImageElement(element) &&
+ erroredFiles.has(element.fileId)
+ ) {
+ return newElementWith(element, {
+ status: "error",
+ });
+ }
+ return element;
+ }),
+ );
+ }
+
+ return { updatedFiles, erroredFiles };
+ };
+
+ /** adds new images to imageCache and re-renders if needed */
+ private addNewImagesToImageCache = async (
+ imageElements: InitializedExcalidrawImageElement[] = getInitializedImageElements(
+ this.scene.getNonDeletedElements(),
+ ),
+ files: BinaryFiles = this.files,
+ ) => {
+ const uncachedImageElements = imageElements.filter(
+ (element) => !element.isDeleted && !this.imageCache.has(element.fileId),
+ );
+
+ if (uncachedImageElements.length) {
+ const { updatedFiles } = await this.updateImageCache(
+ uncachedImageElements,
+ files,
+ );
+ if (updatedFiles.size) {
+ this.scene.triggerUpdate();
+ }
+ }
+ };
+
+ /** generally you should use `addNewImagesToImageCache()` directly if you need
+ * to render new images. This is just a failsafe */
+ private scheduleImageRefresh = throttle(() => {
+ this.addNewImagesToImageCache();
+ }, IMAGE_RENDER_TIMEOUT);
+
+ private updateBindingEnabledOnPointerMove = (
+ event: React.PointerEvent<HTMLElement>,
+ ) => {
+ const shouldEnableBinding = shouldEnableBindingForPointerEvent(event);
+ if (this.state.isBindingEnabled !== shouldEnableBinding) {
+ this.setState({ isBindingEnabled: shouldEnableBinding });
+ }
+ };
+
+ private maybeSuggestBindingAtCursor = (
+ pointerCoords: {
+ x: number;
+ y: number;
+ },
+ considerAll: boolean,
+ ): void => {
+ const hoveredBindableElement = getHoveredElementForBinding(
+ pointerCoords,
+ this.scene.getNonDeletedElements(),
+ this.scene.getNonDeletedElementsMap(),
+ this.state.zoom,
+ false,
+ considerAll,
+ );
+ this.setState({
+ suggestedBindings:
+ hoveredBindableElement != null ? [hoveredBindableElement] : [],
+ });
+ };
+
+ private maybeSuggestBindingsForLinearElementAtCoords = (
+ linearElement: NonDeleted<ExcalidrawLinearElement>,
+ /** scene coords */
+ pointerCoords: {
+ x: number;
+ y: number;
+ }[],
+ // During line creation the start binding hasn't been written yet
+ // into `linearElement`
+ oppositeBindingBoundElement?: ExcalidrawBindableElement | null,
+ ): void => {
+ if (!pointerCoords.length) {
+ return;
+ }
+
+ const suggestedBindings = pointerCoords.reduce(
+ (acc: NonDeleted<ExcalidrawBindableElement>[], coords) => {
+ const hoveredBindableElement = getHoveredElementForBinding(
+ coords,
+ this.scene.getNonDeletedElements(),
+ this.scene.getNonDeletedElementsMap(),
+ this.state.zoom,
+ isElbowArrow(linearElement),
+ isElbowArrow(linearElement),
+ );
+ if (
+ hoveredBindableElement != null &&
+ !isLinearElementSimpleAndAlreadyBound(
+ linearElement,
+ oppositeBindingBoundElement?.id,
+ hoveredBindableElement,
+ )
+ ) {
+ acc.push(hoveredBindableElement);
+ }
+ return acc;
+ },
+ [],
+ );
+
+ this.setState({ suggestedBindings });
+ };
+
+ private clearSelection(hitElement: ExcalidrawElement | null): void {
+ this.setState((prevState) => ({
+ selectedElementIds: makeNextSelectedElementIds({}, prevState),
+ activeEmbeddable: null,
+ selectedGroupIds: {},
+ // Continue editing the same group if the user selected a different
+ // element from it
+ editingGroupId:
+ prevState.editingGroupId &&
+ hitElement != null &&
+ isElementInGroup(hitElement, prevState.editingGroupId)
+ ? prevState.editingGroupId
+ : null,
+ }));
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds({}, this.state),
+ activeEmbeddable: null,
+ previousSelectedElementIds: this.state.selectedElementIds,
+ });
+ }
+
+ private handleInteractiveCanvasRef = (canvas: HTMLCanvasElement | null) => {
+ // canvas is null when unmounting
+ if (canvas !== null) {
+ this.interactiveCanvas = canvas;
+
+ // -----------------------------------------------------------------------
+ // NOTE wheel, touchstart, touchend events must be registered outside
+ // of react because react binds them them passively (so we can't prevent
+ // default on them)
+ this.interactiveCanvas.addEventListener(
+ EVENT.TOUCH_START,
+ this.onTouchStart,
+ { passive: false },
+ );
+ this.interactiveCanvas.addEventListener(EVENT.TOUCH_END, this.onTouchEnd);
+ // -----------------------------------------------------------------------
+ } else {
+ this.interactiveCanvas?.removeEventListener(
+ EVENT.TOUCH_START,
+ this.onTouchStart,
+ );
+ this.interactiveCanvas?.removeEventListener(
+ EVENT.TOUCH_END,
+ this.onTouchEnd,
+ );
+ }
+ };
+
+ private handleAppOnDrop = async (event: React.DragEvent<HTMLDivElement>) => {
+ // must be retrieved first, in the same frame
+ const { file, fileHandle } = await getFileFromEvent(event);
+ const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
+ event,
+ this.state,
+ );
+
+ try {
+ // if image tool not supported, don't show an error here and let it fall
+ // through so we still support importing scene data from images. If no
+ // scene data encoded, we'll show an error then
+ if (isSupportedImageFile(file) && this.isToolSupported("image")) {
+ // first attempt to decode scene from the image if it's embedded
+ // ---------------------------------------------------------------------
+
+ if (file?.type === MIME_TYPES.png || file?.type === MIME_TYPES.svg) {
+ try {
+ const scene = await loadFromBlob(
+ file,
+ this.state,
+ this.scene.getElementsIncludingDeleted(),
+ fileHandle,
+ );
+ this.syncActionResult({
+ ...scene,
+ appState: {
+ ...(scene.appState || this.state),
+ isLoading: false,
+ },
+ replaceFiles: true,
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+ return;
+ } catch (error: any) {
+ // Don't throw for image scene daa
+ if (error.name !== "EncodingError") {
+ throw new Error(t("alerts.couldNotLoadInvalidFile"));
+ }
+ }
+ }
+
+ // if no scene is embedded or we fail for whatever reason, fall back
+ // to importing as regular image
+ // ---------------------------------------------------------------------
+
+ const imageElement = this.createImageElement({ sceneX, sceneY });
+ this.insertImageElement(imageElement, file);
+ this.initializeImageDimensions(imageElement);
+ this.setState({
+ selectedElementIds: makeNextSelectedElementIds(
+ { [imageElement.id]: true },
+ this.state,
+ ),
+ });
+
+ return;
+ }
+ } catch (error: any) {
+ return this.setState({
+ isLoading: false,
+ errorMessage: error.message,
+ });
+ }
+
+ const libraryJSON = event.dataTransfer.getData(MIME_TYPES.excalidrawlib);
+ if (libraryJSON && typeof libraryJSON === "string") {
+ try {
+ const libraryItems = parseLibraryJSON(libraryJSON);
+ this.addElementsFromPasteOrLibrary({
+ elements: distributeLibraryItemsOnSquareGrid(libraryItems),
+ position: event,
+ files: null,
+ });
+ } catch (error: any) {
+ this.setState({ errorMessage: error.message });
+ }
+ return;
+ }
+
+ if (file) {
+ // Attempt to parse an excalidraw/excalidrawlib file
+ await this.loadFileToCanvas(file, fileHandle);
+ }
+
+ if (event.dataTransfer?.types?.includes("text/plain")) {
+ const text = event.dataTransfer?.getData("text");
+ if (
+ text &&
+ embeddableURLValidator(text, this.props.validateEmbeddable) &&
+ (/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(text) ||
+ getEmbedLink(text)?.type === "video")
+ ) {
+ const embeddable = this.insertEmbeddableElement({
+ sceneX,
+ sceneY,
+ link: normalizeLink(text),
+ });
+ if (embeddable) {
+ this.setState({ selectedElementIds: { [embeddable.id]: true } });
+ }
+ }
+ }
+ };
+
+ loadFileToCanvas = async (
+ file: File,
+ fileHandle: FileSystemHandle | null,
+ ) => {
+ file = await normalizeFile(file);
+ try {
+ const elements = this.scene.getElementsIncludingDeleted();
+ let ret;
+ try {
+ ret = await loadSceneOrLibraryFromBlob(
+ file,
+ this.state,
+ elements,
+ fileHandle,
+ );
+ } catch (error: any) {
+ const imageSceneDataError = error instanceof ImageSceneDataError;
+ if (
+ imageSceneDataError &&
+ error.code === "IMAGE_NOT_CONTAINS_SCENE_DATA" &&
+ !this.isToolSupported("image")
+ ) {
+ this.setState({
+ isLoading: false,
+ errorMessage: t("errors.imageToolNotSupported"),
+ });
+ return;
+ }
+ const errorMessage = imageSceneDataError
+ ? t("alerts.cannotRestoreFromImage")
+ : t("alerts.couldNotLoadInvalidFile");
+ this.setState({
+ isLoading: false,
+ errorMessage,
+ });
+ }
+ if (!ret) {
+ return;
+ }
+
+ if (ret.type === MIME_TYPES.excalidraw) {
+ // restore the fractional indices by mutating elements
+ syncInvalidIndices(elements.concat(ret.data.elements));
+
+ // update the store snapshot for old elements, otherwise we would end up with duplicated fractional indices on undo
+ this.store.updateSnapshot(arrayToMap(elements), this.state);
+
+ this.setState({ isLoading: true });
+ this.syncActionResult({
+ ...ret.data,
+ appState: {
+ ...(ret.data.appState || this.state),
+ isLoading: false,
+ },
+ replaceFiles: true,
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+ } else if (ret.type === MIME_TYPES.excalidrawlib) {
+ await this.library
+ .updateLibrary({
+ libraryItems: file,
+ merge: true,
+ openLibraryMenu: true,
+ })
+ .catch((error) => {
+ console.error(error);
+ this.setState({ errorMessage: t("errors.importLibraryError") });
+ });
+ }
+ } catch (error: any) {
+ this.setState({ isLoading: false, errorMessage: error.message });
+ }
+ };
+
+ private handleCanvasContextMenu = (
+ event: React.MouseEvent<HTMLElement | HTMLCanvasElement>,
+ ) => {
+ event.preventDefault();
+
+ if (
+ (("pointerType" in event.nativeEvent &&
+ event.nativeEvent.pointerType === "touch") ||
+ ("pointerType" in event.nativeEvent &&
+ event.nativeEvent.pointerType === "pen" &&
+ // always allow if user uses a pen secondary button
+ event.button !== POINTER_BUTTON.SECONDARY)) &&
+ this.state.activeTool.type !== "selection"
+ ) {
+ return;
+ }
+
+ const { x, y } = viewportCoordsToSceneCoords(event, this.state);
+ const element = this.getElementAtPosition(x, y, {
+ preferSelected: true,
+ includeLockedElements: true,
+ });
+
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ const isHittingCommonBoundBox =
+ this.isHittingCommonBoundingBoxOfSelectedElements(
+ { x, y },
+ selectedElements,
+ );
+
+ const type = element || isHittingCommonBoundBox ? "element" : "canvas";
+
+ const container = this.excalidrawContainerRef.current!;
+ const { top: offsetTop, left: offsetLeft } =
+ container.getBoundingClientRect();
+ const left = event.clientX - offsetLeft;
+ const top = event.clientY - offsetTop;
+
+ trackEvent("contextMenu", "openContextMenu", type);
+
+ this.setState(
+ {
+ ...(element && !this.state.selectedElementIds[element.id]
+ ? {
+ ...this.state,
+ ...selectGroupsForSelectedElements(
+ {
+ editingGroupId: this.state.editingGroupId,
+ selectedElementIds: { [element.id]: true },
+ },
+ this.scene.getNonDeletedElements(),
+ this.state,
+ this,
+ ),
+ selectedLinearElement: isLinearElement(element)
+ ? new LinearElementEditor(element)
+ : null,
+ }
+ : this.state),
+ showHyperlinkPopup: false,
+ },
+ () => {
+ this.setState({
+ contextMenu: { top, left, items: this.getContextMenuItems(type) },
+ });
+ },
+ );
+ };
+
+ private maybeDragNewGenericElement = (
+ pointerDownState: PointerDownState,
+ event: MouseEvent | KeyboardEvent,
+ informMutation = true,
+ ): void => {
+ const selectionElement = this.state.selectionElement;
+ const pointerCoords = pointerDownState.lastCoords;
+ if (selectionElement && this.state.activeTool.type !== "eraser") {
+ dragNewElement({
+ newElement: selectionElement,
+ elementType: this.state.activeTool.type,
+ originX: pointerDownState.origin.x,
+ originY: pointerDownState.origin.y,
+ x: pointerCoords.x,
+ y: pointerCoords.y,
+ width: distance(pointerDownState.origin.x, pointerCoords.x),
+ height: distance(pointerDownState.origin.y, pointerCoords.y),
+ shouldMaintainAspectRatio: shouldMaintainAspectRatio(event),
+ shouldResizeFromCenter: shouldResizeFromCenter(event),
+ zoom: this.state.zoom.value,
+ informMutation,
+ });
+ return;
+ }
+
+ const newElement = this.state.newElement;
+ if (!newElement) {
+ return;
+ }
+
+ let [gridX, gridY] = getGridPoint(
+ pointerCoords.x,
+ pointerCoords.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+
+ const image =
+ isInitializedImageElement(newElement) &&
+ this.imageCache.get(newElement.fileId)?.image;
+ const aspectRatio =
+ image && !(image instanceof Promise) ? image.width / image.height : null;
+
+ this.maybeCacheReferenceSnapPoints(event, [newElement]);
+
+ const { snapOffset, snapLines } = snapNewElement(
+ newElement,
+ this,
+ event,
+ {
+ x:
+ pointerDownState.originInGrid.x +
+ (this.state.originSnapOffset?.x ?? 0),
+ y:
+ pointerDownState.originInGrid.y +
+ (this.state.originSnapOffset?.y ?? 0),
+ },
+ {
+ x: gridX - pointerDownState.originInGrid.x,
+ y: gridY - pointerDownState.originInGrid.y,
+ },
+ this.scene.getNonDeletedElementsMap(),
+ );
+
+ gridX += snapOffset.x;
+ gridY += snapOffset.y;
+
+ this.setState({
+ snapLines,
+ });
+
+ dragNewElement({
+ newElement,
+ elementType: this.state.activeTool.type,
+ originX: pointerDownState.originInGrid.x,
+ originY: pointerDownState.originInGrid.y,
+ x: gridX,
+ y: gridY,
+ width: distance(pointerDownState.originInGrid.x, gridX),
+ height: distance(pointerDownState.originInGrid.y, gridY),
+ shouldMaintainAspectRatio: isImageElement(newElement)
+ ? !shouldMaintainAspectRatio(event)
+ : shouldMaintainAspectRatio(event),
+ shouldResizeFromCenter: shouldResizeFromCenter(event),
+ zoom: this.state.zoom.value,
+ widthAspectRatio: aspectRatio,
+ originOffset: this.state.originSnapOffset,
+ informMutation,
+ });
+
+ this.setState({
+ newElement,
+ });
+
+ // highlight elements that are to be added to frames on frames creation
+ if (
+ this.state.activeTool.type === TOOL_TYPE.frame ||
+ this.state.activeTool.type === TOOL_TYPE.magicframe
+ ) {
+ this.setState({
+ elementsToHighlight: getElementsInResizingFrame(
+ this.scene.getNonDeletedElements(),
+ newElement as ExcalidrawFrameLikeElement,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ ),
+ });
+ }
+ };
+
+ private maybeHandleCrop = (
+ pointerDownState: PointerDownState,
+ event: MouseEvent | KeyboardEvent,
+ ): boolean => {
+ // to crop, we must already be in the cropping mode, where croppingElement has been set
+ if (!this.state.croppingElementId) {
+ return false;
+ }
+
+ const transformHandleType = pointerDownState.resize.handleType;
+ const pointerCoords = pointerDownState.lastCoords;
+ const [x, y] = getGridPoint(
+ pointerCoords.x - pointerDownState.resize.offset.x,
+ pointerCoords.y - pointerDownState.resize.offset.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+
+ const croppingElement = this.scene
+ .getNonDeletedElementsMap()
+ .get(this.state.croppingElementId);
+
+ if (
+ transformHandleType &&
+ croppingElement &&
+ isImageElement(croppingElement)
+ ) {
+ const croppingAtStateStart = pointerDownState.originalElements.get(
+ croppingElement.id,
+ );
+
+ const image =
+ isInitializedImageElement(croppingElement) &&
+ this.imageCache.get(croppingElement.fileId)?.image;
+
+ if (
+ croppingAtStateStart &&
+ isImageElement(croppingAtStateStart) &&
+ image &&
+ !(image instanceof Promise)
+ ) {
+ const [gridX, gridY] = getGridPoint(
+ pointerCoords.x,
+ pointerCoords.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+
+ const dragOffset = {
+ x: gridX - pointerDownState.originInGrid.x,
+ y: gridY - pointerDownState.originInGrid.y,
+ };
+
+ this.maybeCacheReferenceSnapPoints(event, [croppingElement]);
+
+ const { snapOffset, snapLines } = snapResizingElements(
+ [croppingElement],
+ [croppingAtStateStart],
+ this,
+ event,
+ dragOffset,
+ transformHandleType,
+ );
+
+ mutateElement(
+ croppingElement,
+ cropElement(
+ croppingElement,
+ transformHandleType,
+ image.naturalWidth,
+ image.naturalHeight,
+ x + snapOffset.x,
+ y + snapOffset.y,
+ event.shiftKey
+ ? croppingAtStateStart.width / croppingAtStateStart.height
+ : undefined,
+ ),
+ );
+
+ updateBoundElements(
+ croppingElement,
+ this.scene.getNonDeletedElementsMap(),
+ {
+ newSize: {
+ width: croppingElement.width,
+ height: croppingElement.height,
+ },
+ },
+ );
+
+ this.setState({
+ isCropping: transformHandleType && transformHandleType !== "rotation",
+ snapLines,
+ });
+ }
+
+ return true;
+ }
+
+ return false;
+ };
+
+ private maybeHandleResize = (
+ pointerDownState: PointerDownState,
+ event: MouseEvent | KeyboardEvent,
+ ): boolean => {
+ const selectedElements = this.scene.getSelectedElements(this.state);
+ const selectedFrames = selectedElements.filter(
+ (element): element is ExcalidrawFrameLikeElement =>
+ isFrameLikeElement(element),
+ );
+
+ const transformHandleType = pointerDownState.resize.handleType;
+
+ if (
+ // Frames cannot be rotated.
+ (selectedFrames.length > 0 && transformHandleType === "rotation") ||
+ // Elbow arrows cannot be transformed (resized or rotated).
+ (selectedElements.length === 1 && isElbowArrow(selectedElements[0])) ||
+ // Do not resize when in crop mode
+ this.state.croppingElementId
+ ) {
+ return false;
+ }
+
+ this.setState({
+ // TODO: rename this state field to "isScaling" to distinguish
+ // it from the generic "isResizing" which includes scaling and
+ // rotating
+ isResizing: transformHandleType && transformHandleType !== "rotation",
+ isRotating: transformHandleType === "rotation",
+ activeEmbeddable: null,
+ });
+ const pointerCoords = pointerDownState.lastCoords;
+ let [resizeX, resizeY] = getGridPoint(
+ pointerCoords.x - pointerDownState.resize.offset.x,
+ pointerCoords.y - pointerDownState.resize.offset.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+
+ const frameElementsOffsetsMap = new Map<
+ string,
+ {
+ x: number;
+ y: number;
+ }
+ >();
+
+ selectedFrames.forEach((frame) => {
+ const elementsInFrame = getFrameChildren(
+ this.scene.getNonDeletedElements(),
+ frame.id,
+ );
+
+ elementsInFrame.forEach((element) => {
+ frameElementsOffsetsMap.set(frame.id + element.id, {
+ x: element.x - frame.x,
+ y: element.y - frame.y,
+ });
+ });
+ });
+
+ // check needed for avoiding flickering when a key gets pressed
+ // during dragging
+ if (!this.state.selectedElementsAreBeingDragged) {
+ const [gridX, gridY] = getGridPoint(
+ pointerCoords.x,
+ pointerCoords.y,
+ event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
+ );
+
+ const dragOffset = {
+ x: gridX - pointerDownState.originInGrid.x,
+ y: gridY - pointerDownState.originInGrid.y,
+ };
+
+ const originalElements = [...pointerDownState.originalElements.values()];
+
+ this.maybeCacheReferenceSnapPoints(event, selectedElements);
+
+ const { snapOffset, snapLines } = snapResizingElements(
+ selectedElements,
+ getSelectedElements(originalElements, this.state),
+ this,
+ event,
+ dragOffset,
+ transformHandleType,
+ );
+
+ resizeX += snapOffset.x;
+ resizeY += snapOffset.y;
+
+ this.setState({
+ snapLines,
+ });
+ }
+
+ if (
+ transformElements(
+ pointerDownState.originalElements,
+ transformHandleType,
+ selectedElements,
+ this.scene.getElementsMapIncludingDeleted(),
+ this.scene,
+ shouldRotateWithDiscreteAngle(event),
+ shouldResizeFromCenter(event),
+ selectedElements.some((element) => isImageElement(element))
+ ? !shouldMaintainAspectRatio(event)
+ : shouldMaintainAspectRatio(event),
+ resizeX,
+ resizeY,
+ pointerDownState.resize.center.x,
+ pointerDownState.resize.center.y,
+ )
+ ) {
+ const suggestedBindings = getSuggestedBindingsForArrows(
+ selectedElements,
+ this.scene.getNonDeletedElementsMap(),
+ this.state.zoom,
+ );
+
+ const elementsToHighlight = new Set<ExcalidrawElement>();
+ selectedFrames.forEach((frame) => {
+ getElementsInResizingFrame(
+ this.scene.getNonDeletedElements(),
+ frame,
+ this.state,
+ this.scene.getNonDeletedElementsMap(),
+ ).forEach((element) => elementsToHighlight.add(element));
+ });
+
+ this.setState({
+ elementsToHighlight: [...elementsToHighlight],
+ suggestedBindings,
+ });
+
+ return true;
+ }
+ return false;
+ };
+
+ private getContextMenuItems = (
+ type: "canvas" | "element",
+ ): ContextMenuItems => {
+ const options: ContextMenuItems = [];
+
+ options.push(actionCopyAsPng, actionCopyAsSvg);
+
+ // canvas contextMenu
+ // -------------------------------------------------------------------------
+
+ if (type === "canvas") {
+ if (this.state.viewModeEnabled) {
+ return [
+ ...options,
+ actionToggleGridMode,
+ actionToggleZenMode,
+ actionToggleViewMode,
+ actionToggleStats,
+ ];
+ }
+
+ return [
+ actionPaste,
+ CONTEXT_MENU_SEPARATOR,
+ actionCopyAsPng,
+ actionCopyAsSvg,
+ copyText,
+ CONTEXT_MENU_SEPARATOR,
+ actionSelectAll,
+ actionUnlockAllElements,
+ CONTEXT_MENU_SEPARATOR,
+ actionToggleGridMode,
+ actionToggleObjectsSnapMode,
+ actionToggleZenMode,
+ actionToggleViewMode,
+ actionToggleStats,
+ ];
+ }
+
+ // element contextMenu
+ // -------------------------------------------------------------------------
+
+ options.push(copyText);
+
+ if (this.state.viewModeEnabled) {
+ return [actionCopy, ...options];
+ }
+
+ return [
+ CONTEXT_MENU_SEPARATOR,
+ actionCut,
+ actionCopy,
+ actionPaste,
+ CONTEXT_MENU_SEPARATOR,
+ actionSelectAllElementsInFrame,
+ actionRemoveAllElementsFromFrame,
+ actionWrapSelectionInFrame,
+ CONTEXT_MENU_SEPARATOR,
+ actionToggleCropEditor,
+ CONTEXT_MENU_SEPARATOR,
+ ...options,
+ CONTEXT_MENU_SEPARATOR,
+ actionCopyStyles,
+ actionPasteStyles,
+ CONTEXT_MENU_SEPARATOR,
+ actionGroup,
+ actionTextAutoResize,
+ actionUnbindText,
+ actionBindText,
+ actionWrapTextInContainer,
+ actionUngroup,
+ CONTEXT_MENU_SEPARATOR,
+ actionAddToLibrary,
+ CONTEXT_MENU_SEPARATOR,
+ actionSendBackward,
+ actionBringForward,
+ actionSendToBack,
+ actionBringToFront,
+ CONTEXT_MENU_SEPARATOR,
+ actionFlipHorizontal,
+ actionFlipVertical,
+ CONTEXT_MENU_SEPARATOR,
+ actionToggleLinearEditor,
+ CONTEXT_MENU_SEPARATOR,
+ actionLink,
+ actionCopyElementLink,
+ CONTEXT_MENU_SEPARATOR,
+ actionDuplicateSelection,
+ actionToggleElementLock,
+ CONTEXT_MENU_SEPARATOR,
+ actionDeleteSelected,
+ ];
+ };
+
+ private handleWheel = withBatchedUpdates(
+ (
+ event: WheelEvent | React.WheelEvent<HTMLDivElement | HTMLCanvasElement>,
+ ) => {
+ // if not scrolling on canvas/wysiwyg, ignore
+ if (
+ !(
+ event.target instanceof HTMLCanvasElement ||
+ event.target instanceof HTMLTextAreaElement ||
+ event.target instanceof HTMLIFrameElement
+ )
+ ) {
+ // prevent zooming the browser (but allow scrolling DOM)
+ if (event[KEYS.CTRL_OR_CMD]) {
+ event.preventDefault();
+ }
+
+ return;
+ }
+
+ event.preventDefault();
+
+ if (isPanning) {
+ return;
+ }
+
+ const { deltaX, deltaY } = event;
+ // note that event.ctrlKey is necessary to handle pinch zooming
+ if (event.metaKey || event.ctrlKey) {
+ const sign = Math.sign(deltaY);
+ const MAX_STEP = ZOOM_STEP * 100;
+ const absDelta = Math.abs(deltaY);
+ let delta = deltaY;
+ if (absDelta > MAX_STEP) {
+ delta = MAX_STEP * sign;
+ }
+
+ let newZoom = this.state.zoom.value - delta / 100;
+ // increase zoom steps the more zoomed-in we are (applies to >100% only)
+ newZoom +=
+ Math.log10(Math.max(1, this.state.zoom.value)) *
+ -sign *
+ // reduced amplification for small deltas (small movements on a trackpad)
+ Math.min(1, absDelta / 20);
+
+ this.translateCanvas((state) => ({
+ ...getStateForZoom(
+ {
+ viewportX: this.lastViewportPosition.x,
+ viewportY: this.lastViewportPosition.y,
+ nextZoom: getNormalizedZoom(newZoom),
+ },
+ state,
+ ),
+ shouldCacheIgnoreZoom: true,
+ }));
+ this.resetShouldCacheIgnoreZoomDebounced();
+ return;
+ }
+
+ // scroll horizontally when shift pressed
+ if (event.shiftKey) {
+ this.translateCanvas(({ zoom, scrollX }) => ({
+ // on Mac, shift+wheel tends to result in deltaX
+ scrollX: scrollX - (deltaY || deltaX) / zoom.value,
+ }));
+ return;
+ }
+
+ this.translateCanvas(({ zoom, scrollX, scrollY }) => ({
+ scrollX: scrollX - deltaX / zoom.value,
+ scrollY: scrollY - deltaY / zoom.value,
+ }));
+ },
+ );
+
+ private getTextWysiwygSnappedToCenterPosition(
+ x: number,
+ y: number,
+ appState: AppState,
+ container?: ExcalidrawTextContainer | null,
+ ) {
+ if (container) {
+ let elementCenterX = container.x + container.width / 2;
+ let elementCenterY = container.y + container.height / 2;
+
+ const elementCenter = getContainerCenter(
+ container,
+ appState,
+ this.scene.getNonDeletedElementsMap(),
+ );
+ if (elementCenter) {
+ elementCenterX = elementCenter.x;
+ elementCenterY = elementCenter.y;
+ }
+ const distanceToCenter = Math.hypot(
+ x - elementCenterX,
+ y - elementCenterY,
+ );
+ const isSnappedToCenter =
+ distanceToCenter < TEXT_TO_CENTER_SNAP_THRESHOLD;
+ if (isSnappedToCenter) {
+ const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
+ { sceneX: elementCenterX, sceneY: elementCenterY },
+ appState,
+ );
+ return { viewportX, viewportY, elementCenterX, elementCenterY };
+ }
+ }
+ }
+
+ private savePointer = (x: number, y: number, button: "up" | "down") => {
+ if (!x || !y) {
+ return;
+ }
+ const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
+ { clientX: x, clientY: y },
+ this.state,
+ );
+
+ if (isNaN(sceneX) || isNaN(sceneY)) {
+ // sometimes the pointer goes off screen
+ }
+
+ const pointer: CollaboratorPointer = {
+ x: sceneX,
+ y: sceneY,
+ tool: this.state.activeTool.type === "laser" ? "laser" : "pointer",
+ };
+
+ this.props.onPointerUpdate?.({
+ pointer,
+ button,
+ pointersMap: gesture.pointers,
+ });
+ };
+
+ private resetShouldCacheIgnoreZoomDebounced = debounce(() => {
+ if (!this.unmounted) {
+ this.setState({ shouldCacheIgnoreZoom: false });
+ }
+ }, 300);
+
+ private updateDOMRect = (cb?: () => void) => {
+ if (this.excalidrawContainerRef?.current) {
+ const excalidrawContainer = this.excalidrawContainerRef.current;
+ const {
+ width,
+ height,
+ left: offsetLeft,
+ top: offsetTop,
+ } = excalidrawContainer.getBoundingClientRect();
+ const {
+ width: currentWidth,
+ height: currentHeight,
+ offsetTop: currentOffsetTop,
+ offsetLeft: currentOffsetLeft,
+ } = this.state;
+
+ if (
+ width === currentWidth &&
+ height === currentHeight &&
+ offsetLeft === currentOffsetLeft &&
+ offsetTop === currentOffsetTop
+ ) {
+ if (cb) {
+ cb();
+ }
+ return;
+ }
+
+ this.setState(
+ {
+ width,
+ height,
+ offsetLeft,
+ offsetTop,
+ },
+ () => {
+ cb && cb();
+ },
+ );
+ }
+ };
+
+ public refresh = () => {
+ this.setState({ ...this.getCanvasOffsets() });
+ };
+
+ private getCanvasOffsets(): Pick<AppState, "offsetTop" | "offsetLeft"> {
+ if (this.excalidrawContainerRef?.current) {
+ const excalidrawContainer = this.excalidrawContainerRef.current;
+ const { left, top } = excalidrawContainer.getBoundingClientRect();
+ return {
+ offsetLeft: left,
+ offsetTop: top,
+ };
+ }
+ return {
+ offsetLeft: 0,
+ offsetTop: 0,
+ };
+ }
+
+ private async updateLanguage() {
+ const currentLang =
+ languages.find((lang) => lang.code === this.props.langCode) ||
+ defaultLang;
+ await setLanguage(currentLang);
+ this.setAppState({});
+ }
+}
+
+// -----------------------------------------------------------------------------
+// TEST HOOKS
+// -----------------------------------------------------------------------------
+declare global {
+ interface Window {
+ h: {
+ scene: Scene;
+ elements: readonly ExcalidrawElement[];
+ state: AppState;
+ setState: React.Component<any, AppState>["setState"];
+ app: InstanceType<typeof App>;
+ history: History;
+ store: Store;
+ };
+ }
+}
+
+export const createTestHook = () => {
+ if (import.meta.env.MODE === ENV.TEST || import.meta.env.DEV) {
+ window.h = window.h || ({} as Window["h"]);
+
+ Object.defineProperties(window.h, {
+ elements: {
+ configurable: true,
+ get() {
+ return this.app?.scene.getElementsIncludingDeleted();
+ },
+ set(elements: ExcalidrawElement[]) {
+ return this.app?.scene.replaceAllElements(
+ syncInvalidIndices(elements),
+ );
+ },
+ },
+ scene: {
+ configurable: true,
+ get() {
+ return this.app?.scene;
+ },
+ },
+ });
+ }
+};
+
+createTestHook();
+export default App;
diff --git a/packages/excalidraw/components/Avatar.scss b/packages/excalidraw/components/Avatar.scss
new file mode 100644
index 0000000..6565816
--- /dev/null
+++ b/packages/excalidraw/components/Avatar.scss
@@ -0,0 +1,7 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .Avatar {
+ @include avatarStyles;
+ }
+}
diff --git a/packages/excalidraw/components/Avatar.tsx b/packages/excalidraw/components/Avatar.tsx
new file mode 100644
index 0000000..9ddc319
--- /dev/null
+++ b/packages/excalidraw/components/Avatar.tsx
@@ -0,0 +1,41 @@
+import "./Avatar.scss";
+
+import React, { useState } from "react";
+import { getNameInitial } from "../clients";
+import clsx from "clsx";
+
+type AvatarProps = {
+ onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
+ color: string;
+ name: string;
+ src?: string;
+ className?: string;
+};
+
+export const Avatar = ({
+ color,
+ onClick,
+ name,
+ src,
+ className,
+}: AvatarProps) => {
+ const shortName = getNameInitial(name);
+ const [error, setError] = useState(false);
+ const loadImg = !error && src;
+ const style = loadImg ? undefined : { background: color };
+ return (
+ <div className={clsx("Avatar", className)} style={style} onClick={onClick}>
+ {loadImg ? (
+ <img
+ className="Avatar-img"
+ src={src}
+ alt={shortName}
+ referrerPolicy="no-referrer"
+ onError={() => setError(true)}
+ />
+ ) : (
+ shortName
+ )}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/BraveMeasureTextError.tsx b/packages/excalidraw/components/BraveMeasureTextError.tsx
new file mode 100644
index 0000000..1932d7a
--- /dev/null
+++ b/packages/excalidraw/components/BraveMeasureTextError.tsx
@@ -0,0 +1,43 @@
+import Trans from "./Trans";
+
+const BraveMeasureTextError = () => {
+ return (
+ <div data-testid="brave-measure-text-error">
+ <p>
+ <Trans
+ i18nKey="errors.brave_measure_text_error.line1"
+ bold={(el) => <span style={{ fontWeight: 600 }}>{el}</span>}
+ />
+ </p>
+ <p>
+ <Trans
+ i18nKey="errors.brave_measure_text_error.line2"
+ bold={(el) => <span style={{ fontWeight: 600 }}>{el}</span>}
+ />
+ </p>
+ <p>
+ <Trans
+ i18nKey="errors.brave_measure_text_error.line3"
+ link={(el) => (
+ <a href="http://docs.excalidraw.com/docs/@excalidraw/excalidraw/faq#turning-off-aggresive-block-fingerprinting-in-brave-browser">
+ {el}
+ </a>
+ )}
+ />
+ </p>
+ <p>
+ <Trans
+ i18nKey="errors.brave_measure_text_error.line4"
+ issueLink={(el) => (
+ <a href="https://github.com/excalidraw/excalidraw/issues/new">
+ {el}
+ </a>
+ )}
+ discordLink={(el) => <a href="https://discord.gg/UexuTaE">{el}.</a>}
+ />
+ </p>
+ </div>
+ );
+};
+
+export default BraveMeasureTextError;
diff --git a/packages/excalidraw/components/Button.scss b/packages/excalidraw/components/Button.scss
new file mode 100644
index 0000000..9abcf59
--- /dev/null
+++ b/packages/excalidraw/components/Button.scss
@@ -0,0 +1,7 @@
+@import "../css/theme";
+
+.excalidraw {
+ .excalidraw-button {
+ @include outlineButtonStyles;
+ }
+}
diff --git a/packages/excalidraw/components/Button.tsx b/packages/excalidraw/components/Button.tsx
new file mode 100644
index 0000000..779cee5
--- /dev/null
+++ b/packages/excalidraw/components/Button.tsx
@@ -0,0 +1,44 @@
+import clsx from "clsx";
+import React from "react";
+import { composeEventHandlers } from "../utils";
+import "./Button.scss";
+
+interface ButtonProps
+ extends React.DetailedHTMLProps<
+ React.ButtonHTMLAttributes<HTMLButtonElement>,
+ HTMLButtonElement
+ > {
+ type?: "button" | "submit" | "reset";
+ onSelect: () => any;
+ /** whether button is in active state */
+ selected?: boolean;
+ children: React.ReactNode;
+ className?: string;
+}
+
+/**
+ * A generic button component that follows Excalidraw's design system.
+ * Style can be customised using `className` or `style` prop.
+ * Accepts all props that a regular `button` element accepts.
+ */
+export const Button = ({
+ type = "button",
+ onSelect,
+ selected,
+ children,
+ className = "",
+ ...rest
+}: ButtonProps) => {
+ return (
+ <button
+ onClick={composeEventHandlers(rest.onClick, (event) => {
+ onSelect();
+ })}
+ type={type}
+ className={clsx("excalidraw-button", className, { selected })}
+ {...rest}
+ >
+ {children}
+ </button>
+ );
+};
diff --git a/packages/excalidraw/components/ButtonIcon.scss b/packages/excalidraw/components/ButtonIcon.scss
new file mode 100644
index 0000000..e435b69
--- /dev/null
+++ b/packages/excalidraw/components/ButtonIcon.scss
@@ -0,0 +1,12 @@
+@import "../css/theme";
+
+.excalidraw {
+ button.standalone {
+ @include outlineButtonIconStyles;
+
+ & > * {
+ // dissalow pointer events on children, so we always have event.target on the button itself
+ pointer-events: none;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ButtonIcon.tsx b/packages/excalidraw/components/ButtonIcon.tsx
new file mode 100644
index 0000000..cbbd73d
--- /dev/null
+++ b/packages/excalidraw/components/ButtonIcon.tsx
@@ -0,0 +1,37 @@
+import { forwardRef } from "react";
+import type { JSX } from "react";
+import clsx from "clsx";
+
+import "./ButtonIcon.scss";
+
+interface ButtonIconProps {
+ icon: JSX.Element;
+ title: string;
+ className?: string;
+ testId?: string;
+ /** if not supplied, defaults to value identity check */
+ active?: boolean;
+ /** include standalone style (could interfere with parent styles) */
+ standalone?: boolean;
+ onClick: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
+}
+
+export const ButtonIcon = forwardRef<HTMLButtonElement, ButtonIconProps>(
+ (props, ref) => {
+ const { title, className, testId, active, standalone, icon, onClick } =
+ props;
+ return (
+ <button
+ type="button"
+ ref={ref}
+ key={title}
+ title={title}
+ data-testid={testId}
+ className={clsx(className, { standalone, active })}
+ onClick={onClick}
+ >
+ {icon}
+ </button>
+ );
+ },
+);
diff --git a/packages/excalidraw/components/ButtonIconCycle.tsx b/packages/excalidraw/components/ButtonIconCycle.tsx
new file mode 100644
index 0000000..b73a8ec
--- /dev/null
+++ b/packages/excalidraw/components/ButtonIconCycle.tsx
@@ -0,0 +1,29 @@
+import type { JSX } from "react";
+import clsx from "clsx";
+
+export const ButtonIconCycle = <T extends any>({
+ options,
+ value,
+ onChange,
+ group,
+}: {
+ options: { value: T; text: string; icon: JSX.Element }[];
+ value: T | null;
+ onChange: (value: T) => void;
+ group: string;
+}) => {
+ const current = options.find((op) => op.value === value);
+
+ const cycle = () => {
+ const index = options.indexOf(current!);
+ const next = (index + 1) % options.length;
+ onChange(options[next].value);
+ };
+
+ return (
+ <label key={group} className={clsx({ active: current!.value !== null })}>
+ <input type="button" name={group} onClick={cycle} />
+ {current!.icon}
+ </label>
+ );
+};
diff --git a/packages/excalidraw/components/ButtonIconSelect.tsx b/packages/excalidraw/components/ButtonIconSelect.tsx
new file mode 100644
index 0000000..26191b5
--- /dev/null
+++ b/packages/excalidraw/components/ButtonIconSelect.tsx
@@ -0,0 +1,58 @@
+import type { JSX } from "react";
+import clsx from "clsx";
+import { ButtonIcon } from "./ButtonIcon";
+
+// TODO: It might be "clever" to add option.icon to the existing component <ButtonSelect />
+export const ButtonIconSelect = <T extends Object>(
+ props: {
+ options: {
+ value: T;
+ text: string;
+ icon: JSX.Element;
+ testId?: string;
+ /** if not supplied, defaults to value identity check */
+ active?: boolean;
+ }[];
+ value: T | null;
+ type?: "radio" | "button";
+ } & (
+ | { type?: "radio"; group: string; onChange: (value: T) => void }
+ | {
+ type: "button";
+ onClick: (
+ value: T,
+ event: React.MouseEvent<HTMLButtonElement, MouseEvent>,
+ ) => void;
+ }
+ ),
+) => (
+ <div className="buttonList">
+ {props.options.map((option) =>
+ props.type === "button" ? (
+ <ButtonIcon
+ key={option.text}
+ icon={option.icon}
+ title={option.text}
+ testId={option.testId}
+ active={option.active ?? props.value === option.value}
+ onClick={(event) => props.onClick(option.value, event)}
+ />
+ ) : (
+ <label
+ key={option.text}
+ className={clsx({ active: props.value === option.value })}
+ title={option.text}
+ >
+ <input
+ type="radio"
+ name={props.group}
+ onChange={() => props.onChange(option.value)}
+ checked={props.value === option.value}
+ data-testid={option.testId}
+ />
+ {option.icon}
+ </label>
+ ),
+ )}
+ </div>
+);
diff --git a/packages/excalidraw/components/ButtonSelect.tsx b/packages/excalidraw/components/ButtonSelect.tsx
new file mode 100644
index 0000000..c47ff65
--- /dev/null
+++ b/packages/excalidraw/components/ButtonSelect.tsx
@@ -0,0 +1,30 @@
+import clsx from "clsx";
+
+export const ButtonSelect = <T extends Object>({
+ options,
+ value,
+ onChange,
+ group,
+}: {
+ options: { value: T; text: string }[];
+ value: T | null;
+ onChange: (value: T) => void;
+ group: string;
+}) => (
+ <div className="buttonList">
+ {options.map((option) => (
+ <label
+ key={option.text}
+ className={clsx({ active: value === option.value })}
+ >
+ <input
+ type="radio"
+ name={group}
+ onChange={() => onChange(option.value)}
+ checked={value === option.value}
+ />
+ {option.text}
+ </label>
+ ))}
+ </div>
+);
diff --git a/packages/excalidraw/components/ButtonSeparator.tsx b/packages/excalidraw/components/ButtonSeparator.tsx
new file mode 100644
index 0000000..e4dec32
--- /dev/null
+++ b/packages/excalidraw/components/ButtonSeparator.tsx
@@ -0,0 +1,10 @@
+export const ButtonSeparator = () => (
+ <div
+ style={{
+ width: 1,
+ height: "1rem",
+ backgroundColor: "var(--default-border-color)",
+ margin: "0 auto",
+ }}
+ />
+);
diff --git a/packages/excalidraw/components/Card.scss b/packages/excalidraw/components/Card.scss
new file mode 100644
index 0000000..ba0fbc4
--- /dev/null
+++ b/packages/excalidraw/components/Card.scss
@@ -0,0 +1,57 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .Card {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+
+ max-width: 290px;
+
+ margin: 1em;
+
+ text-align: center;
+
+ .Card-icon {
+ font-size: 2.6em;
+ display: flex;
+ flex: 0 0 auto;
+ padding: 1.4rem;
+ border-radius: 50%;
+ background: var(--card-color);
+ color: $oc-white;
+
+ svg {
+ width: 2.8rem;
+ height: 2.8rem;
+ }
+ }
+
+ .Card-details {
+ font-size: 0.96em;
+ min-height: 90px;
+ padding: 0 1em;
+ margin-bottom: auto;
+ }
+
+ & .Card-button.ToolIcon_type_button {
+ height: 2.5rem;
+ margin-top: 1em;
+ margin-bottom: 0.3em;
+ background-color: var(--card-color);
+ &:hover {
+ background-color: var(--card-color-darker);
+ }
+ &:active {
+ background-color: var(--card-color-darkest);
+ }
+ .ToolIcon__label {
+ color: $oc-white;
+ }
+
+ .Spinner {
+ --spinner-color: #fff;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Card.tsx b/packages/excalidraw/components/Card.tsx
new file mode 100644
index 0000000..2ba5a97
--- /dev/null
+++ b/packages/excalidraw/components/Card.tsx
@@ -0,0 +1,28 @@
+import OpenColor from "open-color";
+
+import "./Card.scss";
+
+export const Card: React.FC<{
+ color: keyof OpenColor | "primary";
+ children?: React.ReactNode;
+}> = ({ children, color }) => {
+ return (
+ <div
+ className="Card"
+ style={{
+ ["--card-color" as any]:
+ color === "primary" ? "var(--color-primary)" : OpenColor[color][7],
+ ["--card-color-darker" as any]:
+ color === "primary"
+ ? "var(--color-primary-darker)"
+ : OpenColor[color][8],
+ ["--card-color-darkest" as any]:
+ color === "primary"
+ ? "var(--color-primary-darkest)"
+ : OpenColor[color][9],
+ }}
+ >
+ {children}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/CheckboxItem.scss b/packages/excalidraw/components/CheckboxItem.scss
new file mode 100644
index 0000000..6aaf0aa
--- /dev/null
+++ b/packages/excalidraw/components/CheckboxItem.scss
@@ -0,0 +1,91 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .Checkbox {
+ margin: 4px 0.3em;
+ display: flex;
+ align-items: center;
+
+ cursor: pointer;
+ user-select: none;
+
+ -webkit-tap-highlight-color: transparent;
+
+ &:hover:not(.is-checked) .Checkbox-box:not(:focus) {
+ box-shadow: 0 0 0 2px #{$oc-blue-4};
+ }
+
+ &:hover:not(.is-checked) .Checkbox-box:not(:focus) {
+ svg {
+ display: block;
+ opacity: 0.3;
+ }
+ }
+
+ &:active {
+ .Checkbox-box {
+ box-shadow: 0 0 2px 1px inset #{$oc-blue-7} !important;
+ }
+ }
+
+ &:hover {
+ .Checkbox-box {
+ background-color: fade-out($oc-blue-1, 0.8);
+ }
+ }
+
+ &.is-checked {
+ .Checkbox-box {
+ background-color: #{$oc-blue-1};
+ svg {
+ display: block;
+ }
+ }
+ &:hover .Checkbox-box {
+ background-color: #{$oc-blue-2};
+ }
+ }
+
+ .Checkbox-box {
+ width: 22px;
+ height: 22px;
+ padding: 0;
+ flex: 0 0 auto;
+
+ margin: 0 1em;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ box-shadow: 0 0 0 2px #{$oc-blue-7};
+ background-color: transparent;
+ border-radius: 4px;
+
+ color: #{$oc-blue-7};
+
+ border: 0;
+
+ &:focus {
+ box-shadow: 0 0 0 3px #{$oc-blue-7};
+ }
+
+ svg {
+ display: none;
+ width: 16px;
+ height: 16px;
+ stroke-width: 3px;
+ }
+ }
+
+ .Checkbox-label {
+ display: flex;
+ align-items: center;
+ }
+
+ .excalidraw-tooltip-icon {
+ width: 1em;
+ height: 1em;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/CheckboxItem.tsx b/packages/excalidraw/components/CheckboxItem.tsx
new file mode 100644
index 0000000..21c5cfa
--- /dev/null
+++ b/packages/excalidraw/components/CheckboxItem.tsx
@@ -0,0 +1,36 @@
+import React from "react";
+import clsx from "clsx";
+import { checkIcon } from "./icons";
+
+import "./CheckboxItem.scss";
+
+export const CheckboxItem: React.FC<{
+ checked: boolean;
+ onChange: (checked: boolean, event: React.MouseEvent) => void;
+ className?: string;
+ children?: React.ReactNode;
+}> = ({ children, checked, onChange, className }) => {
+ return (
+ <div
+ className={clsx("Checkbox", className, { "is-checked": checked })}
+ onClick={(event) => {
+ onChange(!checked, event);
+ (
+ (event.currentTarget as HTMLDivElement).querySelector(
+ ".Checkbox-box",
+ ) as HTMLButtonElement
+ ).focus();
+ }}
+ >
+ <button
+ type="button"
+ className="Checkbox-box"
+ role="checkbox"
+ aria-checked={checked}
+ >
+ {checkIcon}
+ </button>
+ <div className="Checkbox-label">{children}</div>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ColorPicker/ColorInput.tsx b/packages/excalidraw/components/ColorPicker/ColorInput.tsx
new file mode 100644
index 0000000..837c887
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/ColorInput.tsx
@@ -0,0 +1,130 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { getColor } from "./ColorPicker";
+import type { ColorPickerType } from "./colorPickerUtils";
+import { activeColorPickerSectionAtom } from "./colorPickerUtils";
+import { eyeDropperIcon } from "../icons";
+import { useAtom } from "../../editor-jotai";
+import { KEYS } from "../../keys";
+import { activeEyeDropperAtom } from "../EyeDropper";
+import clsx from "clsx";
+import { t } from "../../i18n";
+import { useDevice } from "../App";
+import { getShortcutKey } from "../../utils";
+
+interface ColorInputProps {
+ color: string;
+ onChange: (color: string) => void;
+ label: string;
+ colorPickerType: ColorPickerType;
+}
+
+export const ColorInput = ({
+ color,
+ onChange,
+ label,
+ colorPickerType,
+}: ColorInputProps) => {
+ const device = useDevice();
+ const [innerValue, setInnerValue] = useState(color);
+ const [activeSection, setActiveColorPickerSection] = useAtom(
+ activeColorPickerSectionAtom,
+ );
+
+ useEffect(() => {
+ setInnerValue(color);
+ }, [color]);
+
+ const changeColor = useCallback(
+ (inputValue: string) => {
+ const value = inputValue.toLowerCase();
+ const color = getColor(value);
+
+ if (color) {
+ onChange(color);
+ }
+ setInnerValue(value);
+ },
+ [onChange],
+ );
+
+ const inputRef = useRef<HTMLInputElement>(null);
+ const eyeDropperTriggerRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (inputRef.current) {
+ inputRef.current.focus();
+ }
+ }, [activeSection]);
+
+ const [eyeDropperState, setEyeDropperState] = useAtom(activeEyeDropperAtom);
+
+ useEffect(() => {
+ return () => {
+ setEyeDropperState(null);
+ };
+ }, [setEyeDropperState]);
+
+ return (
+ <div className="color-picker__input-label">
+ <div className="color-picker__input-hash">#</div>
+ <input
+ ref={activeSection === "hex" ? inputRef : undefined}
+ style={{ border: 0, padding: 0 }}
+ spellCheck={false}
+ className="color-picker-input"
+ aria-label={label}
+ onChange={(event) => {
+ changeColor(event.target.value);
+ }}
+ value={(innerValue || "").replace(/^#/, "")}
+ onBlur={() => {
+ setInnerValue(color);
+ }}
+ tabIndex={-1}
+ onFocus={() => setActiveColorPickerSection("hex")}
+ onKeyDown={(event) => {
+ if (event.key === KEYS.TAB) {
+ return;
+ } else if (event.key === KEYS.ESCAPE) {
+ eyeDropperTriggerRef.current?.focus();
+ }
+ event.stopPropagation();
+ }}
+ />
+ {/* TODO reenable on mobile with a better UX */}
+ {!device.editor.isMobile && (
+ <>
+ <div
+ style={{
+ width: "1px",
+ height: "1.25rem",
+ backgroundColor: "var(--default-border-color)",
+ }}
+ />
+ <div
+ ref={eyeDropperTriggerRef}
+ className={clsx("excalidraw-eye-dropper-trigger", {
+ selected: eyeDropperState,
+ })}
+ onClick={() =>
+ setEyeDropperState((s) =>
+ s
+ ? null
+ : {
+ keepOpenOnAlt: false,
+ onSelect: (color) => onChange(color),
+ colorPickerType,
+ },
+ )
+ }
+ title={`${t(
+ "labels.eyeDropper",
+ )} — ${KEYS.I.toLocaleUpperCase()} or ${getShortcutKey("Alt")} `}
+ >
+ {eyeDropperIcon}
+ </div>
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ColorPicker/ColorPicker.scss b/packages/excalidraw/components/ColorPicker/ColorPicker.scss
new file mode 100644
index 0000000..39e1845
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/ColorPicker.scss
@@ -0,0 +1,441 @@
+@import "../../css/variables.module.scss";
+
+.excalidraw {
+ .focus-visible-none {
+ &:focus-visible {
+ outline: none !important;
+ }
+ }
+
+ .color-picker__heading {
+ padding: 0 0.5rem;
+ font-size: 0.75rem;
+ text-align: left;
+ }
+
+ .color-picker-container {
+ display: grid;
+ grid-template-columns: 1fr 20px 1.625rem;
+ padding: 0.25rem 0px;
+ align-items: center;
+
+ @include isMobile {
+ max-width: 11rem;
+ }
+ }
+
+ .color-picker__top-picks {
+ display: flex;
+ justify-content: space-between;
+ }
+
+ .color-picker__button {
+ --radius: 0.25rem;
+
+ padding: 0;
+ margin: 0;
+ width: 1.35rem;
+ height: 1.35rem;
+ border: 1px solid var(--color-gray-30);
+ border-radius: var(--radius);
+ filter: var(--theme-filter);
+ background-color: var(--swatch-color);
+ background-position: left center;
+ position: relative;
+ font-family: inherit;
+ box-sizing: border-box;
+
+ &:hover {
+ &::after {
+ content: "";
+ position: absolute;
+ top: -2px;
+ left: -2px;
+ right: -2px;
+ bottom: -2px;
+ box-shadow: 0 0 0 1px var(--color-gray-30);
+ border-radius: calc(var(--radius) + 1px);
+ filter: var(--theme-filter);
+ }
+ }
+
+ &.active {
+ .color-picker__button-outline {
+ position: absolute;
+ top: -2px;
+ left: -2px;
+ right: -2px;
+ bottom: -2px;
+ box-shadow: 0 0 0 1px var(--color-primary-darkest);
+ z-index: 1; // due hover state so this has preference
+ border-radius: calc(var(--radius) + 1px);
+ filter: var(--theme-filter);
+ }
+ }
+
+ &:focus-visible {
+ outline: none;
+
+ &::after {
+ content: "";
+ position: absolute;
+ top: -4px;
+ right: -4px;
+ bottom: -4px;
+ left: -4px;
+ border: 3px solid var(--focus-highlight-color);
+ border-radius: calc(var(--radius) + 1px);
+ }
+
+ &.active {
+ .color-picker__button-outline {
+ display: none;
+ }
+ }
+ }
+
+ &--large {
+ --radius: 0.5rem;
+ width: 1.875rem;
+ height: 1.875rem;
+ }
+
+ &.is-transparent {
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==");
+ }
+
+ &--no-focus-visible {
+ border: 0;
+ &::after {
+ display: none;
+ }
+ &:focus-visible {
+ outline: none !important;
+ }
+ }
+
+ &.active-color {
+ border-radius: calc(var(--radius) + 1px);
+ width: 1.625rem;
+ height: 1.625rem;
+ }
+ }
+
+ .color-picker__button__hotkey-label {
+ position: absolute;
+ right: 4px;
+ bottom: 4px;
+ filter: none;
+ font-size: 11px;
+ }
+
+ .color-picker {
+ background: var(--popup-bg-color);
+ border: 0 solid transparentize($oc-white, 0.75);
+ box-shadow: transparentize($oc-black, 0.75) 0 1px 4px;
+ border-radius: 4px;
+ position: absolute;
+
+ :root[dir="ltr"] & {
+ left: -5.5px;
+ }
+
+ :root[dir="rtl"] & {
+ right: -5.5px;
+ }
+ }
+
+ .color-picker-control-container {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ align-items: center;
+ column-gap: 0.5rem;
+ }
+
+ .color-picker-control-container + .popover {
+ position: static;
+ }
+
+ .color-picker-popover-container {
+ margin-top: -0.25rem;
+
+ :root[dir="ltr"] & {
+ margin-left: 0.5rem;
+ }
+
+ :root[dir="rtl"] & {
+ margin-left: -3rem;
+ }
+ }
+
+ .color-picker-triangle {
+ width: 0;
+ height: 0;
+ border-style: solid;
+ border-width: 0 9px 10px;
+ border-color: transparent transparent var(--popup-bg-color);
+ position: absolute;
+ top: 10px;
+
+ :root[dir="ltr"] & {
+ transform: rotate(270deg);
+ left: -14px;
+ }
+
+ :root[dir="rtl"] & {
+ transform: rotate(90deg);
+ right: -14px;
+ }
+ }
+
+ .color-picker-triangle-shadow {
+ border-color: transparent transparent transparentize($oc-black, 0.9);
+
+ :root[dir="ltr"] & {
+ left: -14px;
+ }
+
+ :root[dir="rtl"] & {
+ right: -16px;
+ }
+ }
+
+ .color-picker-content {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ outline: none;
+ }
+
+ .color-picker-content--default {
+ padding: 0.5rem;
+ display: grid;
+ grid-template-columns: repeat(5, 1.875rem);
+ grid-gap: 0.25rem;
+ border-radius: 4px;
+
+ &:focus {
+ outline: none;
+ box-shadow: 0 0 0 2px var(--focus-highlight-color);
+ }
+ }
+
+ .color-picker-content--canvas {
+ display: flex;
+ flex-direction: column;
+ padding: 0.25rem;
+
+ &-title {
+ color: $oc-gray-6;
+ font-size: 12px;
+ padding: 0 0.25rem;
+ }
+
+ &-colors {
+ padding: 0.5rem 0;
+
+ .color-picker-swatch {
+ margin: 0 0.25rem;
+ }
+ }
+ }
+
+ .color-picker-content .color-input-container {
+ grid-column: 1 / span 5;
+ }
+
+ .color-picker-swatch {
+ position: relative;
+ height: 1.875rem;
+ width: 1.875rem;
+ cursor: pointer;
+ border-radius: 4px;
+ margin: 0;
+ box-sizing: border-box;
+ border: 1px solid #ddd;
+ background-color: currentColor !important;
+ filter: var(--theme-filter);
+
+ &:focus {
+ /* TODO: only show the border when the color is too light to see as a shadow */
+ box-shadow: 0 0 4px 1px currentColor;
+ border-color: var(--select-highlight-color);
+ }
+ }
+
+ .color-picker-transparent {
+ border-radius: 4px;
+ box-shadow: transparentize($oc-black, 0.9) 0 0 0 1px inset;
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+ }
+
+ .color-picker-transparent,
+ .color-picker-label-swatch {
+ background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")
+ left center;
+ }
+
+ .color-picker-hash {
+ height: var(--default-button-size);
+ flex-shrink: 0;
+ padding: 0.5rem 0.5rem 0.5rem 0.75rem;
+ border: 1px solid var(--default-border-color);
+ border-right: 0;
+ box-sizing: border-box;
+
+ :root[dir="ltr"] & {
+ border-radius: var(--border-radius-lg) 0 0 var(--border-radius-lg);
+ }
+
+ :root[dir="rtl"] & {
+ border-radius: 0 var(--border-radius-lg) var(--border-radius-lg) 0;
+ border-right: 1px solid var(--default-border-color);
+ border-left: 0;
+ }
+
+ color: var(--input-label-color);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ }
+
+ .color-input-container {
+ display: flex;
+
+ &:focus-within {
+ box-shadow: 0 0 0 1px var(--color-primary-darkest);
+ border-radius: var(--border-radius-lg);
+ }
+ }
+
+ .color-picker__input-label {
+ display: grid;
+ grid-template-columns: auto 1fr auto auto;
+ gap: 8px;
+ align-items: center;
+ border: 1px solid var(--default-border-color);
+ border-radius: 8px;
+ padding: 0 12px;
+ margin: 8px;
+ box-sizing: border-box;
+
+ &:focus-within {
+ box-shadow: 0 0 0 1px var(--color-primary-darkest);
+ border-radius: var(--border-radius-lg);
+ }
+ }
+
+ .color-picker__input-hash {
+ padding: 0 0.25rem;
+ }
+
+ .color-picker-input {
+ box-sizing: border-box;
+ width: 100%;
+ margin: 0;
+ font-size: 0.875rem;
+ font-family: inherit;
+ background-color: transparent;
+ color: var(--text-primary-color);
+ border: 0;
+ outline: none;
+ height: var(--default-button-size);
+ border: 1px solid var(--default-border-color);
+ border-left: 0;
+ letter-spacing: 0.4px;
+
+ :root[dir="ltr"] & {
+ border-radius: 0 var(--border-radius-lg) var(--border-radius-lg) 0;
+ }
+
+ :root[dir="rtl"] & {
+ border-radius: var(--border-radius-lg) 0 0 var(--border-radius-lg);
+ border-left: 1px solid var(--default-border-color);
+ border-right: 0;
+ }
+
+ padding: 0.5rem;
+ padding-left: 0.25rem;
+ appearance: none;
+
+ &:focus-visible {
+ box-shadow: none;
+ }
+ }
+
+ .color-picker-label-swatch-container {
+ border: 1px solid var(--default-border-color);
+ border-radius: var(--border-radius-lg);
+ width: var(--default-button-size);
+ height: var(--default-button-size);
+ box-sizing: border-box;
+ overflow: hidden;
+ }
+
+ .color-picker-label-swatch {
+ @include outlineButtonStyles;
+ background-color: var(--swatch-color) !important;
+ overflow: hidden;
+ position: relative;
+ filter: var(--theme-filter);
+ border: 0 !important;
+
+ &:after {
+ content: "";
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: var(--swatch-color);
+ }
+ }
+
+ .color-picker-keybinding {
+ position: absolute;
+ bottom: 2px;
+ font-size: 0.7em;
+
+ :root[dir="ltr"] & {
+ right: 2px;
+ }
+
+ :root[dir="rtl"] & {
+ left: 2px;
+ }
+
+ @include isMobile {
+ display: none;
+ }
+ }
+
+ .color-picker-type-canvasBackground .color-picker-keybinding {
+ color: #aaa;
+ }
+
+ .color-picker-type-elementBackground .color-picker-keybinding {
+ color: $oc-white;
+ }
+
+ .color-picker-swatch[aria-label="transparent"] .color-picker-keybinding {
+ color: #aaa;
+ }
+
+ .color-picker-type-elementStroke .color-picker-keybinding {
+ color: #d4d4d4;
+ }
+
+ &.theme--dark {
+ .color-picker-type-elementBackground .color-picker-keybinding {
+ color: $oc-black;
+ }
+ .color-picker-swatch[aria-label="transparent"] .color-picker-keybinding {
+ color: $oc-black;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ColorPicker/ColorPicker.tsx b/packages/excalidraw/components/ColorPicker/ColorPicker.tsx
new file mode 100644
index 0000000..74d5527
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/ColorPicker.tsx
@@ -0,0 +1,246 @@
+import { isTransparent } from "../../utils";
+import type { ExcalidrawElement } from "../../element/types";
+import type { AppState } from "../../types";
+import { TopPicks } from "./TopPicks";
+import { ButtonSeparator } from "../ButtonSeparator";
+import { Picker } from "./Picker";
+import * as Popover from "@radix-ui/react-popover";
+import type { ColorPickerType } from "./colorPickerUtils";
+import { activeColorPickerSectionAtom } from "./colorPickerUtils";
+import { useExcalidrawContainer } from "../App";
+import type { ColorTuple, ColorPaletteCustom } from "../../colors";
+import { COLOR_PALETTE } from "../../colors";
+import PickerHeading from "./PickerHeading";
+import { t } from "../../i18n";
+import clsx from "clsx";
+import { useRef } from "react";
+import { useAtom } from "../../editor-jotai";
+import { ColorInput } from "./ColorInput";
+import { activeEyeDropperAtom } from "../EyeDropper";
+import { PropertiesPopover } from "../PropertiesPopover";
+
+import "./ColorPicker.scss";
+
+const isValidColor = (color: string) => {
+ const style = new Option().style;
+ style.color = color;
+ return !!style.color;
+};
+
+export const getColor = (color: string): string | null => {
+ if (isTransparent(color)) {
+ return color;
+ }
+
+ // testing for `#` first fixes a bug on Electron (more specfically, an
+ // Obsidian popout window), where a hex color without `#` is (incorrectly)
+ // considered valid
+ return isValidColor(`#${color}`)
+ ? `#${color}`
+ : isValidColor(color)
+ ? color
+ : null;
+};
+
+interface ColorPickerProps {
+ type: ColorPickerType;
+ color: string;
+ onChange: (color: string) => void;
+ label: string;
+ elements: readonly ExcalidrawElement[];
+ appState: AppState;
+ palette?: ColorPaletteCustom | null;
+ topPicks?: ColorTuple;
+ updateData: (formData?: any) => void;
+}
+
+const ColorPickerPopupContent = ({
+ type,
+ color,
+ onChange,
+ label,
+ elements,
+ palette = COLOR_PALETTE,
+ updateData,
+}: Pick<
+ ColorPickerProps,
+ | "type"
+ | "color"
+ | "onChange"
+ | "label"
+ | "elements"
+ | "palette"
+ | "updateData"
+>) => {
+ const { container } = useExcalidrawContainer();
+ const [, setActiveColorPickerSection] = useAtom(activeColorPickerSectionAtom);
+
+ const [eyeDropperState, setEyeDropperState] = useAtom(activeEyeDropperAtom);
+
+ const colorInputJSX = (
+ <div>
+ <PickerHeading>{t("colorPicker.hexCode")}</PickerHeading>
+ <ColorInput
+ color={color}
+ label={label}
+ onChange={(color) => {
+ onChange(color);
+ }}
+ colorPickerType={type}
+ />
+ </div>
+ );
+
+ const popoverRef = useRef<HTMLDivElement>(null);
+
+ const focusPickerContent = () => {
+ popoverRef.current
+ ?.querySelector<HTMLDivElement>(".color-picker-content")
+ ?.focus();
+ };
+
+ return (
+ <PropertiesPopover
+ container={container}
+ style={{ maxWidth: "13rem" }}
+ onFocusOutside={(event) => {
+ // refocus due to eye dropper
+ focusPickerContent();
+ event.preventDefault();
+ }}
+ onPointerDownOutside={(event) => {
+ if (eyeDropperState) {
+ // prevent from closing if we click outside the popover
+ // while eyedropping (e.g. click when clicking the sidebar;
+ // the eye-dropper-backdrop is prevented downstream)
+ event.preventDefault();
+ }
+ }}
+ onClose={() => {
+ updateData({ openPopup: null });
+ setActiveColorPickerSection(null);
+ }}
+ >
+ {palette ? (
+ <Picker
+ palette={palette}
+ color={color}
+ onChange={(changedColor) => {
+ onChange(changedColor);
+ }}
+ onEyeDropperToggle={(force) => {
+ setEyeDropperState((state) => {
+ if (force) {
+ state = state || {
+ keepOpenOnAlt: true,
+ onSelect: onChange,
+ colorPickerType: type,
+ };
+ state.keepOpenOnAlt = true;
+ return state;
+ }
+
+ return force === false || state
+ ? null
+ : {
+ keepOpenOnAlt: false,
+ onSelect: onChange,
+ colorPickerType: type,
+ };
+ });
+ }}
+ onEscape={(event) => {
+ if (eyeDropperState) {
+ setEyeDropperState(null);
+ } else {
+ updateData({ openPopup: null });
+ }
+ }}
+ label={label}
+ type={type}
+ elements={elements}
+ updateData={updateData}
+ >
+ {colorInputJSX}
+ </Picker>
+ ) : (
+ colorInputJSX
+ )}
+ </PropertiesPopover>
+ );
+};
+
+const ColorPickerTrigger = ({
+ label,
+ color,
+ type,
+}: {
+ color: string;
+ label: string;
+ type: ColorPickerType;
+}) => {
+ return (
+ <Popover.Trigger
+ type="button"
+ className={clsx("color-picker__button active-color properties-trigger", {
+ "is-transparent": color === "transparent" || !color,
+ })}
+ aria-label={label}
+ style={color ? { "--swatch-color": color } : undefined}
+ title={
+ type === "elementStroke"
+ ? t("labels.showStroke")
+ : t("labels.showBackground")
+ }
+ >
+ <div className="color-picker__button-outline" />
+ </Popover.Trigger>
+ );
+};
+
+export const ColorPicker = ({
+ type,
+ color,
+ onChange,
+ label,
+ elements,
+ palette = COLOR_PALETTE,
+ topPicks,
+ updateData,
+ appState,
+}: ColorPickerProps) => {
+ return (
+ <div>
+ <div role="dialog" aria-modal="true" className="color-picker-container">
+ <TopPicks
+ activeColor={color}
+ onChange={onChange}
+ type={type}
+ topPicks={topPicks}
+ />
+ <ButtonSeparator />
+ <Popover.Root
+ open={appState.openPopup === type}
+ onOpenChange={(open) => {
+ updateData({ openPopup: open ? type : null });
+ }}
+ >
+ {/* serves as an active color indicator as well */}
+ <ColorPickerTrigger color={color} label={label} type={type} />
+ {/* popup content */}
+ {appState.openPopup === type && (
+ <ColorPickerPopupContent
+ type={type}
+ color={color}
+ onChange={onChange}
+ label={label}
+ elements={elements}
+ palette={palette}
+ updateData={updateData}
+ />
+ )}
+ </Popover.Root>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ColorPicker/CustomColorList.tsx b/packages/excalidraw/components/ColorPicker/CustomColorList.tsx
new file mode 100644
index 0000000..5fe1e3e
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/CustomColorList.tsx
@@ -0,0 +1,63 @@
+import clsx from "clsx";
+import { useAtom } from "../../editor-jotai";
+import { useEffect, useRef } from "react";
+import { activeColorPickerSectionAtom } from "./colorPickerUtils";
+import HotkeyLabel from "./HotkeyLabel";
+
+interface CustomColorListProps {
+ colors: string[];
+ color: string;
+ onChange: (color: string) => void;
+ label: string;
+}
+
+export const CustomColorList = ({
+ colors,
+ color,
+ onChange,
+ label,
+}: CustomColorListProps) => {
+ const [activeColorPickerSection, setActiveColorPickerSection] = useAtom(
+ activeColorPickerSectionAtom,
+ );
+
+ const btnRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ if (btnRef.current) {
+ btnRef.current.focus();
+ }
+ }, [color, activeColorPickerSection]);
+
+ return (
+ <div className="color-picker-content--default">
+ {colors.map((c, i) => {
+ return (
+ <button
+ ref={color === c ? btnRef : undefined}
+ tabIndex={-1}
+ type="button"
+ className={clsx(
+ "color-picker__button color-picker__button--large",
+ {
+ active: color === c,
+ "is-transparent": c === "transparent" || !c,
+ },
+ )}
+ onClick={() => {
+ onChange(c);
+ setActiveColorPickerSection("custom");
+ }}
+ title={c}
+ aria-label={label}
+ style={{ "--swatch-color": c }}
+ key={i}
+ >
+ <div className="color-picker__button-outline" />
+ <HotkeyLabel color={c} keyLabel={i + 1} isCustomColor />
+ </button>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ColorPicker/HotkeyLabel.tsx b/packages/excalidraw/components/ColorPicker/HotkeyLabel.tsx
new file mode 100644
index 0000000..145060d
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/HotkeyLabel.tsx
@@ -0,0 +1,29 @@
+import React from "react";
+import { getContrastYIQ } from "./colorPickerUtils";
+
+interface HotkeyLabelProps {
+ color: string;
+ keyLabel: string | number;
+ isCustomColor?: boolean;
+ isShade?: boolean;
+}
+const HotkeyLabel = ({
+ color,
+ keyLabel,
+ isCustomColor = false,
+ isShade = false,
+}: HotkeyLabelProps) => {
+ return (
+ <div
+ className="color-picker__button__hotkey-label"
+ style={{
+ color: getContrastYIQ(color, isCustomColor),
+ }}
+ >
+ {isShade && "⇧"}
+ {keyLabel}
+ </div>
+ );
+};
+
+export default HotkeyLabel;
diff --git a/packages/excalidraw/components/ColorPicker/Picker.tsx b/packages/excalidraw/components/ColorPicker/Picker.tsx
new file mode 100644
index 0000000..88d6876
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/Picker.tsx
@@ -0,0 +1,178 @@
+import React, { useEffect, useState } from "react";
+import { t } from "../../i18n";
+
+import type { ExcalidrawElement } from "../../element/types";
+import { ShadeList } from "./ShadeList";
+
+import PickerColorList from "./PickerColorList";
+import { useAtom } from "../../editor-jotai";
+import { CustomColorList } from "./CustomColorList";
+import { colorPickerKeyNavHandler } from "./keyboardNavHandlers";
+import PickerHeading from "./PickerHeading";
+import type { ColorPickerType } from "./colorPickerUtils";
+import {
+ activeColorPickerSectionAtom,
+ getColorNameAndShadeFromColor,
+ getMostUsedCustomColors,
+ isCustomColor,
+} from "./colorPickerUtils";
+import type { ColorPaletteCustom } from "../../colors";
+import {
+ DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX,
+ DEFAULT_ELEMENT_STROKE_COLOR_INDEX,
+} from "../../colors";
+import { KEYS } from "../../keys";
+import { EVENT } from "../../constants";
+
+interface PickerProps {
+ color: string;
+ onChange: (color: string) => void;
+ label: string;
+ type: ColorPickerType;
+ elements: readonly ExcalidrawElement[];
+ palette: ColorPaletteCustom;
+ updateData: (formData?: any) => void;
+ children?: React.ReactNode;
+ onEyeDropperToggle: (force?: boolean) => void;
+ onEscape: (event: React.KeyboardEvent | KeyboardEvent) => void;
+}
+
+export const Picker = ({
+ color,
+ onChange,
+ label,
+ type,
+ elements,
+ palette,
+ updateData,
+ children,
+ onEyeDropperToggle,
+ onEscape,
+}: PickerProps) => {
+ const [customColors] = React.useState(() => {
+ if (type === "canvasBackground") {
+ return [];
+ }
+ return getMostUsedCustomColors(elements, type, palette);
+ });
+
+ const [activeColorPickerSection, setActiveColorPickerSection] = useAtom(
+ activeColorPickerSectionAtom,
+ );
+
+ const colorObj = getColorNameAndShadeFromColor({
+ color,
+ palette,
+ });
+
+ useEffect(() => {
+ if (!activeColorPickerSection) {
+ const isCustom = isCustomColor({ color, palette });
+ const isCustomButNotInList = isCustom && !customColors.includes(color);
+
+ setActiveColorPickerSection(
+ isCustomButNotInList
+ ? "hex"
+ : isCustom
+ ? "custom"
+ : colorObj?.shade != null
+ ? "shades"
+ : "baseColors",
+ );
+ }
+ }, [
+ activeColorPickerSection,
+ color,
+ palette,
+ setActiveColorPickerSection,
+ colorObj,
+ customColors,
+ ]);
+
+ const [activeShade, setActiveShade] = useState(
+ colorObj?.shade ??
+ (type === "elementBackground"
+ ? DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX
+ : DEFAULT_ELEMENT_STROKE_COLOR_INDEX),
+ );
+
+ useEffect(() => {
+ if (colorObj?.shade != null) {
+ setActiveShade(colorObj.shade);
+ }
+
+ const keyup = (event: KeyboardEvent) => {
+ if (event.key === KEYS.ALT) {
+ onEyeDropperToggle(false);
+ }
+ };
+ document.addEventListener(EVENT.KEYUP, keyup, { capture: true });
+ return () => {
+ document.removeEventListener(EVENT.KEYUP, keyup, { capture: true });
+ };
+ }, [colorObj, onEyeDropperToggle]);
+
+ const pickerRef = React.useRef<HTMLDivElement>(null);
+
+ return (
+ <div role="dialog" aria-modal="true" aria-label={t("labels.colorPicker")}>
+ <div
+ ref={pickerRef}
+ onKeyDown={(event) => {
+ const handled = colorPickerKeyNavHandler({
+ event,
+ activeColorPickerSection,
+ palette,
+ color,
+ onChange,
+ onEyeDropperToggle,
+ customColors,
+ setActiveColorPickerSection,
+ updateData,
+ activeShade,
+ onEscape,
+ });
+
+ if (handled) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }}
+ className="color-picker-content properties-content"
+ // to allow focusing by clicking but not by tabbing
+ tabIndex={-1}
+ >
+ {!!customColors.length && (
+ <div>
+ <PickerHeading>
+ {t("colorPicker.mostUsedCustomColors")}
+ </PickerHeading>
+ <CustomColorList
+ colors={customColors}
+ color={color}
+ label={t("colorPicker.mostUsedCustomColors")}
+ onChange={onChange}
+ />
+ </div>
+ )}
+
+ <div>
+ <PickerHeading>{t("colorPicker.colors")}</PickerHeading>
+ <PickerColorList
+ color={color}
+ label={label}
+ palette={palette}
+ onChange={onChange}
+ activeShade={activeShade}
+ />
+ </div>
+
+ <div>
+ <PickerHeading>{t("colorPicker.shades")}</PickerHeading>
+ <ShadeList hex={color} onChange={onChange} palette={palette} />
+ </div>
+ {children}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ColorPicker/PickerColorList.tsx b/packages/excalidraw/components/ColorPicker/PickerColorList.tsx
new file mode 100644
index 0000000..f43559d
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/PickerColorList.tsx
@@ -0,0 +1,91 @@
+import clsx from "clsx";
+import { useAtom } from "../../editor-jotai";
+import { useEffect, useRef } from "react";
+import {
+ activeColorPickerSectionAtom,
+ colorPickerHotkeyBindings,
+ getColorNameAndShadeFromColor,
+} from "./colorPickerUtils";
+import HotkeyLabel from "./HotkeyLabel";
+import type { ColorPaletteCustom } from "../../colors";
+import type { TranslationKeys } from "../../i18n";
+import { t } from "../../i18n";
+
+interface PickerColorListProps {
+ palette: ColorPaletteCustom;
+ color: string;
+ onChange: (color: string) => void;
+ label: string;
+ activeShade: number;
+}
+
+const PickerColorList = ({
+ palette,
+ color,
+ onChange,
+ label,
+ activeShade,
+}: PickerColorListProps) => {
+ const colorObj = getColorNameAndShadeFromColor({
+ color: color || "transparent",
+ palette,
+ });
+ const [activeColorPickerSection, setActiveColorPickerSection] = useAtom(
+ activeColorPickerSectionAtom,
+ );
+
+ const btnRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ if (btnRef.current && activeColorPickerSection === "baseColors") {
+ btnRef.current.focus();
+ }
+ }, [colorObj?.colorName, activeColorPickerSection]);
+
+ return (
+ <div className="color-picker-content--default">
+ {Object.entries(palette).map(([key, value], index) => {
+ const color =
+ (Array.isArray(value) ? value[activeShade] : value) || "transparent";
+
+ const keybinding = colorPickerHotkeyBindings[index];
+ const label = t(
+ `colors.${key.replace(/\d+/, "")}` as unknown as TranslationKeys,
+ null,
+ "",
+ );
+
+ return (
+ <button
+ ref={colorObj?.colorName === key ? btnRef : undefined}
+ tabIndex={-1}
+ type="button"
+ className={clsx(
+ "color-picker__button color-picker__button--large",
+ {
+ active: colorObj?.colorName === key,
+ "is-transparent": color === "transparent" || !color,
+ },
+ )}
+ onClick={() => {
+ onChange(color);
+ setActiveColorPickerSection("baseColors");
+ }}
+ title={`${label}${
+ color.startsWith("#") ? ` ${color}` : ""
+ } — ${keybinding}`}
+ aria-label={`${label} — ${keybinding}`}
+ style={color ? { "--swatch-color": color } : undefined}
+ data-testid={`color-${key}`}
+ key={key}
+ >
+ <div className="color-picker__button-outline" />
+ <HotkeyLabel color={color} keyLabel={keybinding} />
+ </button>
+ );
+ })}
+ </div>
+ );
+};
+
+export default PickerColorList;
diff --git a/packages/excalidraw/components/ColorPicker/PickerHeading.tsx b/packages/excalidraw/components/ColorPicker/PickerHeading.tsx
new file mode 100644
index 0000000..3999a49
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/PickerHeading.tsx
@@ -0,0 +1,7 @@
+import type { ReactNode } from "react";
+
+const PickerHeading = ({ children }: { children: ReactNode }) => (
+ <div className="color-picker__heading">{children}</div>
+);
+
+export default PickerHeading;
diff --git a/packages/excalidraw/components/ColorPicker/ShadeList.tsx b/packages/excalidraw/components/ColorPicker/ShadeList.tsx
new file mode 100644
index 0000000..8d3d4cc
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/ShadeList.tsx
@@ -0,0 +1,105 @@
+import clsx from "clsx";
+import { useAtom } from "../../editor-jotai";
+import { useEffect, useRef } from "react";
+import {
+ activeColorPickerSectionAtom,
+ getColorNameAndShadeFromColor,
+} from "./colorPickerUtils";
+import HotkeyLabel from "./HotkeyLabel";
+import { t } from "../../i18n";
+import type { ColorPaletteCustom } from "../../colors";
+
+interface ShadeListProps {
+ hex: string;
+ onChange: (color: string) => void;
+ palette: ColorPaletteCustom;
+}
+
+export const ShadeList = ({ hex, onChange, palette }: ShadeListProps) => {
+ const colorObj = getColorNameAndShadeFromColor({
+ color: hex || "transparent",
+ palette,
+ });
+
+ const [activeColorPickerSection, setActiveColorPickerSection] = useAtom(
+ activeColorPickerSectionAtom,
+ );
+
+ const btnRef = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ if (btnRef.current && activeColorPickerSection === "shades") {
+ btnRef.current.focus();
+ }
+ }, [colorObj, activeColorPickerSection]);
+
+ if (colorObj) {
+ const { colorName, shade } = colorObj;
+
+ const shades = palette[colorName];
+
+ if (Array.isArray(shades)) {
+ return (
+ <div className="color-picker-content--default shades">
+ {shades.map((color, i) => (
+ <button
+ ref={
+ i === shade && activeColorPickerSection === "shades"
+ ? btnRef
+ : undefined
+ }
+ tabIndex={-1}
+ key={i}
+ type="button"
+ className={clsx(
+ "color-picker__button color-picker__button--large",
+ { active: i === shade },
+ )}
+ aria-label="Shade"
+ title={`${colorName} - ${i + 1}`}
+ style={color ? { "--swatch-color": color } : undefined}
+ onClick={() => {
+ onChange(color);
+ setActiveColorPickerSection("shades");
+ }}
+ >
+ <div className="color-picker__button-outline" />
+ <HotkeyLabel color={color} keyLabel={i + 1} isShade />
+ </button>
+ ))}
+ </div>
+ );
+ }
+ }
+
+ return (
+ <div
+ className="color-picker-content--default"
+ style={{ position: "relative" }}
+ tabIndex={-1}
+ >
+ <button
+ type="button"
+ tabIndex={-1}
+ className="color-picker__button color-picker__button--large color-picker__button--no-focus-visible"
+ />
+ <div
+ tabIndex={-1}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ textAlign: "center",
+ fontSize: "0.75rem",
+ }}
+ >
+ {t("colorPicker.noShades")}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ColorPicker/TopPicks.tsx b/packages/excalidraw/components/ColorPicker/TopPicks.tsx
new file mode 100644
index 0000000..5c69d1e
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/TopPicks.tsx
@@ -0,0 +1,65 @@
+import clsx from "clsx";
+import type { ColorPickerType } from "./colorPickerUtils";
+import {
+ DEFAULT_CANVAS_BACKGROUND_PICKS,
+ DEFAULT_ELEMENT_BACKGROUND_PICKS,
+ DEFAULT_ELEMENT_STROKE_PICKS,
+} from "../../colors";
+
+interface TopPicksProps {
+ onChange: (color: string) => void;
+ type: ColorPickerType;
+ activeColor: string;
+ topPicks?: readonly string[];
+}
+
+export const TopPicks = ({
+ onChange,
+ type,
+ activeColor,
+ topPicks,
+}: TopPicksProps) => {
+ let colors;
+ if (type === "elementStroke") {
+ colors = DEFAULT_ELEMENT_STROKE_PICKS;
+ }
+
+ if (type === "elementBackground") {
+ colors = DEFAULT_ELEMENT_BACKGROUND_PICKS;
+ }
+
+ if (type === "canvasBackground") {
+ colors = DEFAULT_CANVAS_BACKGROUND_PICKS;
+ }
+
+ // this one can overwrite defaults
+ if (topPicks) {
+ colors = topPicks;
+ }
+
+ if (!colors) {
+ console.error("Invalid type for TopPicks");
+ return null;
+ }
+
+ return (
+ <div className="color-picker__top-picks">
+ {colors.map((color: string) => (
+ <button
+ className={clsx("color-picker__button", {
+ active: color === activeColor,
+ "is-transparent": color === "transparent" || !color,
+ })}
+ style={{ "--swatch-color": color }}
+ key={color}
+ type="button"
+ title={color}
+ onClick={() => onChange(color)}
+ data-testid={`color-top-pick-${color}`}
+ >
+ <div className="color-picker__button-outline" />
+ </button>
+ ))}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ColorPicker/colorPickerUtils.ts b/packages/excalidraw/components/ColorPicker/colorPickerUtils.ts
new file mode 100644
index 0000000..2733b7a
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/colorPickerUtils.ts
@@ -0,0 +1,133 @@
+import type { ExcalidrawElement } from "../../element/types";
+import type { ColorPickerColor, ColorPaletteCustom } from "../../colors";
+import { MAX_CUSTOM_COLORS_USED_IN_CANVAS } from "../../colors";
+import { atom } from "../../editor-jotai";
+
+export const getColorNameAndShadeFromColor = ({
+ palette,
+ color,
+}: {
+ palette: ColorPaletteCustom;
+ color: string;
+}): {
+ colorName: ColorPickerColor;
+ shade: number | null;
+} | null => {
+ for (const [colorName, colorVal] of Object.entries(palette)) {
+ if (Array.isArray(colorVal)) {
+ const shade = colorVal.indexOf(color);
+ if (shade > -1) {
+ return { colorName: colorName as ColorPickerColor, shade };
+ }
+ } else if (colorVal === color) {
+ return { colorName: colorName as ColorPickerColor, shade: null };
+ }
+ }
+ return null;
+};
+
+export const colorPickerHotkeyBindings = [
+ ["q", "w", "e", "r", "t"],
+ ["a", "s", "d", "f", "g"],
+ ["z", "x", "c", "v", "b"],
+].flat();
+
+export const isCustomColor = ({
+ color,
+ palette,
+}: {
+ color: string;
+ palette: ColorPaletteCustom;
+}) => {
+ const paletteValues = Object.values(palette).flat();
+ return !paletteValues.includes(color);
+};
+
+export const getMostUsedCustomColors = (
+ elements: readonly ExcalidrawElement[],
+ type: "elementBackground" | "elementStroke",
+ palette: ColorPaletteCustom,
+) => {
+ const elementColorTypeMap = {
+ elementBackground: "backgroundColor",
+ elementStroke: "strokeColor",
+ };
+
+ const colors = elements.filter((element) => {
+ if (element.isDeleted) {
+ return false;
+ }
+
+ const color =
+ element[elementColorTypeMap[type] as "backgroundColor" | "strokeColor"];
+
+ return isCustomColor({ color, palette });
+ });
+
+ const colorCountMap = new Map<string, number>();
+ colors.forEach((element) => {
+ const color =
+ element[elementColorTypeMap[type] as "backgroundColor" | "strokeColor"];
+ if (colorCountMap.has(color)) {
+ colorCountMap.set(color, colorCountMap.get(color)! + 1);
+ } else {
+ colorCountMap.set(color, 1);
+ }
+ });
+
+ return [...colorCountMap.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .map((c) => c[0])
+ .slice(0, MAX_CUSTOM_COLORS_USED_IN_CANVAS);
+};
+
+export type ActiveColorPickerSectionAtomType =
+ | "custom"
+ | "baseColors"
+ | "shades"
+ | "hex"
+ | null;
+export const activeColorPickerSectionAtom =
+ atom<ActiveColorPickerSectionAtomType>(null);
+
+const calculateContrast = (r: number, g: number, b: number) => {
+ const yiq = (r * 299 + g * 587 + b * 114) / 1000;
+ return yiq >= 160 ? "black" : "white";
+};
+
+// inspiration from https://stackoverflow.com/a/11868398
+export const getContrastYIQ = (bgHex: string, isCustomColor: boolean) => {
+ if (isCustomColor) {
+ const style = new Option().style;
+ style.color = bgHex;
+
+ if (style.color) {
+ const rgb = style.color
+ .replace(/^(rgb|rgba)\(/, "")
+ .replace(/\)$/, "")
+ .replace(/\s/g, "")
+ .split(",");
+ const r = parseInt(rgb[0]);
+ const g = parseInt(rgb[1]);
+ const b = parseInt(rgb[2]);
+
+ return calculateContrast(r, g, b);
+ }
+ }
+
+ // TODO: ? is this wanted?
+ if (bgHex === "transparent") {
+ return "black";
+ }
+
+ const r = parseInt(bgHex.substring(1, 3), 16);
+ const g = parseInt(bgHex.substring(3, 5), 16);
+ const b = parseInt(bgHex.substring(5, 7), 16);
+
+ return calculateContrast(r, g, b);
+};
+
+export type ColorPickerType =
+ | "canvasBackground"
+ | "elementBackground"
+ | "elementStroke";
diff --git a/packages/excalidraw/components/ColorPicker/keyboardNavHandlers.ts b/packages/excalidraw/components/ColorPicker/keyboardNavHandlers.ts
new file mode 100644
index 0000000..7767692
--- /dev/null
+++ b/packages/excalidraw/components/ColorPicker/keyboardNavHandlers.ts
@@ -0,0 +1,286 @@
+import { KEYS } from "../../keys";
+import type {
+ ColorPickerColor,
+ ColorPalette,
+ ColorPaletteCustom,
+} from "../../colors";
+import { COLORS_PER_ROW, COLOR_PALETTE } from "../../colors";
+import type { ValueOf } from "../../utility-types";
+import type { ActiveColorPickerSectionAtomType } from "./colorPickerUtils";
+import {
+ colorPickerHotkeyBindings,
+ getColorNameAndShadeFromColor,
+} from "./colorPickerUtils";
+
+const arrowHandler = (
+ eventKey: string,
+ currentIndex: number | null,
+ length: number,
+) => {
+ const rows = Math.ceil(length / COLORS_PER_ROW);
+
+ currentIndex = currentIndex ?? -1;
+
+ switch (eventKey) {
+ case "ArrowLeft": {
+ const prevIndex = currentIndex - 1;
+ return prevIndex < 0 ? length - 1 : prevIndex;
+ }
+ case "ArrowRight": {
+ return (currentIndex + 1) % length;
+ }
+ case "ArrowDown": {
+ const nextIndex = currentIndex + COLORS_PER_ROW;
+ return nextIndex >= length ? currentIndex % COLORS_PER_ROW : nextIndex;
+ }
+ case "ArrowUp": {
+ const prevIndex = currentIndex - COLORS_PER_ROW;
+ const newIndex =
+ prevIndex < 0 ? COLORS_PER_ROW * rows + prevIndex : prevIndex;
+ return newIndex >= length ? undefined : newIndex;
+ }
+ }
+};
+
+interface HotkeyHandlerProps {
+ e: React.KeyboardEvent;
+ colorObj: { colorName: ColorPickerColor; shade: number | null } | null;
+ onChange: (color: string) => void;
+ palette: ColorPaletteCustom;
+ customColors: string[];
+ setActiveColorPickerSection: (
+ update: React.SetStateAction<ActiveColorPickerSectionAtomType>,
+ ) => void;
+ activeShade: number;
+}
+
+/**
+ * @returns true if the event was handled
+ */
+const hotkeyHandler = ({
+ e,
+ colorObj,
+ onChange,
+ palette,
+ customColors,
+ setActiveColorPickerSection,
+ activeShade,
+}: HotkeyHandlerProps): boolean => {
+ if (colorObj?.shade != null) {
+ // shift + numpad is extremely messed up on windows apparently
+ if (
+ ["Digit1", "Digit2", "Digit3", "Digit4", "Digit5"].includes(e.code) &&
+ e.shiftKey
+ ) {
+ const newShade = Number(e.code.slice(-1)) - 1;
+ onChange(palette[colorObj.colorName][newShade]);
+ setActiveColorPickerSection("shades");
+ return true;
+ }
+ }
+
+ if (["1", "2", "3", "4", "5"].includes(e.key)) {
+ const c = customColors[Number(e.key) - 1];
+ if (c) {
+ onChange(customColors[Number(e.key) - 1]);
+ setActiveColorPickerSection("custom");
+ return true;
+ }
+ }
+
+ if (colorPickerHotkeyBindings.includes(e.key)) {
+ const index = colorPickerHotkeyBindings.indexOf(e.key);
+ const paletteKey = Object.keys(palette)[index] as keyof ColorPalette;
+ const paletteValue = palette[paletteKey];
+ const r = Array.isArray(paletteValue)
+ ? paletteValue[activeShade]
+ : paletteValue;
+ onChange(r);
+ setActiveColorPickerSection("baseColors");
+ return true;
+ }
+ return false;
+};
+
+interface ColorPickerKeyNavHandlerProps {
+ event: React.KeyboardEvent;
+ activeColorPickerSection: ActiveColorPickerSectionAtomType;
+ palette: ColorPaletteCustom;
+ color: string;
+ onChange: (color: string) => void;
+ customColors: string[];
+ setActiveColorPickerSection: (
+ update: React.SetStateAction<ActiveColorPickerSectionAtomType>,
+ ) => void;
+ updateData: (formData?: any) => void;
+ activeShade: number;
+ onEyeDropperToggle: (force?: boolean) => void;
+ onEscape: (event: React.KeyboardEvent | KeyboardEvent) => void;
+}
+
+/**
+ * @returns true if the event was handled
+ */
+export const colorPickerKeyNavHandler = ({
+ event,
+ activeColorPickerSection,
+ palette,
+ color,
+ onChange,
+ customColors,
+ setActiveColorPickerSection,
+ updateData,
+ activeShade,
+ onEyeDropperToggle,
+ onEscape,
+}: ColorPickerKeyNavHandlerProps): boolean => {
+ if (event[KEYS.CTRL_OR_CMD]) {
+ return false;
+ }
+
+ if (event.key === KEYS.ESCAPE) {
+ onEscape(event);
+ return true;
+ }
+
+ // checkt using `key` to ignore combos with Alt modifier
+ if (event.key === KEYS.ALT) {
+ onEyeDropperToggle(true);
+ return true;
+ }
+
+ if (event.key === KEYS.I) {
+ onEyeDropperToggle();
+ return true;
+ }
+
+ const colorObj = getColorNameAndShadeFromColor({ color, palette });
+
+ if (event.key === KEYS.TAB) {
+ const sectionsMap: Record<
+ NonNullable<ActiveColorPickerSectionAtomType>,
+ boolean
+ > = {
+ custom: !!customColors.length,
+ baseColors: true,
+ shades: colorObj?.shade != null,
+ hex: true,
+ };
+
+ const sections = Object.entries(sectionsMap).reduce((acc, [key, value]) => {
+ if (value) {
+ acc.push(key as ActiveColorPickerSectionAtomType);
+ }
+ return acc;
+ }, [] as ActiveColorPickerSectionAtomType[]);
+
+ const activeSectionIndex = sections.indexOf(activeColorPickerSection);
+ const indexOffset = event.shiftKey ? -1 : 1;
+ const nextSectionIndex =
+ activeSectionIndex + indexOffset > sections.length - 1
+ ? 0
+ : activeSectionIndex + indexOffset < 0
+ ? sections.length - 1
+ : activeSectionIndex + indexOffset;
+
+ const nextSection = sections[nextSectionIndex];
+
+ if (nextSection) {
+ setActiveColorPickerSection(nextSection);
+ }
+
+ if (nextSection === "custom") {
+ onChange(customColors[0]);
+ } else if (nextSection === "baseColors") {
+ const baseColorName = (
+ Object.entries(palette) as [string, ValueOf<ColorPalette>][]
+ ).find(([name, shades]) => {
+ if (Array.isArray(shades)) {
+ return shades.includes(color);
+ } else if (shades === color) {
+ return name;
+ }
+ return null;
+ });
+
+ if (!baseColorName) {
+ onChange(COLOR_PALETTE.black);
+ }
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ return true;
+ }
+
+ if (
+ hotkeyHandler({
+ e: event,
+ colorObj,
+ onChange,
+ palette,
+ customColors,
+ setActiveColorPickerSection,
+ activeShade,
+ })
+ ) {
+ return true;
+ }
+
+ if (activeColorPickerSection === "shades") {
+ if (colorObj) {
+ const { shade } = colorObj;
+ const newShade = arrowHandler(event.key, shade, COLORS_PER_ROW);
+
+ if (newShade !== undefined) {
+ onChange(palette[colorObj.colorName][newShade]);
+ return true;
+ }
+ }
+ }
+
+ if (activeColorPickerSection === "baseColors") {
+ if (colorObj) {
+ const { colorName } = colorObj;
+ const colorNames = Object.keys(palette) as (keyof ColorPalette)[];
+ const indexOfColorName = colorNames.indexOf(colorName);
+
+ const newColorIndex = arrowHandler(
+ event.key,
+ indexOfColorName,
+ colorNames.length,
+ );
+
+ if (newColorIndex !== undefined) {
+ const newColorName = colorNames[newColorIndex];
+ const newColorNameValue = palette[newColorName];
+
+ onChange(
+ Array.isArray(newColorNameValue)
+ ? newColorNameValue[activeShade]
+ : newColorNameValue,
+ );
+ return true;
+ }
+ }
+ }
+
+ if (activeColorPickerSection === "custom") {
+ const indexOfColor = customColors.indexOf(color);
+
+ const newColorIndex = arrowHandler(
+ event.key,
+ indexOfColor,
+ customColors.length,
+ );
+
+ if (newColorIndex !== undefined) {
+ const newColor = customColors[newColorIndex];
+ onChange(newColor);
+ return true;
+ }
+ }
+
+ return false;
+};
diff --git a/packages/excalidraw/components/CommandPalette/CommandPalette.scss b/packages/excalidraw/components/CommandPalette/CommandPalette.scss
new file mode 100644
index 0000000..ebb7e4f
--- /dev/null
+++ b/packages/excalidraw/components/CommandPalette/CommandPalette.scss
@@ -0,0 +1,137 @@
+@import "../../css/variables.module.scss";
+
+$verticalBreakpoint: 861px;
+
+.excalidraw {
+ .command-palette-dialog {
+ user-select: none;
+
+ .Modal__content {
+ height: auto;
+ max-height: 100%;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ max-height: 750px;
+ height: 100%;
+ }
+
+ .Island {
+ height: 100%;
+ padding: 1.5rem;
+ }
+
+ .Dialog__content {
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+ }
+
+ .shortcuts-wrapper {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ margin-top: 12px;
+ gap: 1.5rem;
+ }
+
+ .shortcut {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 16px;
+ font-size: 10px;
+ gap: 0.25rem;
+
+ .shortcut-wrapper {
+ display: flex;
+ }
+
+ .shortcut-plus {
+ margin: 0px 4px;
+ }
+
+ .shortcut-key {
+ padding: 0px 4px;
+ height: 16px;
+ border-radius: 4px;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ background-color: var(--color-primary-light);
+ }
+
+ .shortcut-desc {
+ margin-left: 4px;
+ color: var(--color-gray-50);
+ }
+ }
+
+ .commands {
+ overflow-y: auto;
+ box-sizing: border-box;
+ margin-top: 12px;
+ color: var(--popup-text-color);
+ user-select: none;
+
+ .command-category {
+ display: flex;
+ flex-direction: column;
+ padding: 12px 0px;
+ margin-right: 0.25rem;
+ }
+
+ .command-category-title {
+ font-size: 1rem;
+ font-weight: 600;
+ margin-bottom: 6px;
+ display: flex;
+ align-items: center;
+ }
+
+ .command-item {
+ color: var(--popup-text-color);
+ height: 2.5rem;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ box-sizing: border-box;
+ padding: 0 0.5rem;
+ border-radius: var(--border-radius-lg);
+ cursor: pointer;
+
+ &:active {
+ background-color: var(--color-surface-low);
+ }
+
+ .name {
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ }
+ }
+
+ .item-selected {
+ background-color: var(--color-surface-mid);
+ }
+
+ .item-disabled {
+ opacity: 0.3;
+ cursor: not-allowed;
+ }
+
+ .no-match {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ margin-top: 36px;
+ }
+ }
+
+ .icon {
+ width: 16px;
+ height: 16px;
+ margin-right: 6px;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/CommandPalette/CommandPalette.tsx b/packages/excalidraw/components/CommandPalette/CommandPalette.tsx
new file mode 100644
index 0000000..cc3c782
--- /dev/null
+++ b/packages/excalidraw/components/CommandPalette/CommandPalette.tsx
@@ -0,0 +1,956 @@
+import { useEffect, useRef, useState } from "react";
+import {
+ useApp,
+ useAppProps,
+ useExcalidrawActionManager,
+ useExcalidrawSetAppState,
+} from "../App";
+import { KEYS } from "../../keys";
+import { Dialog } from "../Dialog";
+import { TextField } from "../TextField";
+import clsx from "clsx";
+import { getSelectedElements } from "../../scene";
+import type { Action } from "../../actions/types";
+import type { TranslationKeys } from "../../i18n";
+import { t } from "../../i18n";
+import type { ShortcutName } from "../../actions/shortcuts";
+import { getShortcutFromShortcutName } from "../../actions/shortcuts";
+import { DEFAULT_SIDEBAR, EVENT } from "../../constants";
+import {
+ LockedIcon,
+ UnlockedIcon,
+ clockIcon,
+ searchIcon,
+ boltIcon,
+ bucketFillIcon,
+ ExportImageIcon,
+ mermaidLogoIcon,
+ brainIconThin,
+ LibraryIcon,
+} from "../icons";
+import fuzzy from "fuzzy";
+import { useUIAppState } from "../../context/ui-appState";
+import type { AppProps, AppState, UIAppState } from "../../types";
+import {
+ capitalizeString,
+ getShortcutKey,
+ isWritableElement,
+} from "../../utils";
+import { atom, useAtom, editorJotaiStore } from "../../editor-jotai";
+import { deburr } from "../../deburr";
+import type { MarkRequired } from "../../utility-types";
+import { InlineIcon } from "../InlineIcon";
+import { SHAPES } from "../../shapes";
+import { canChangeBackgroundColor, canChangeStrokeColor } from "../Actions";
+import { useStableCallback } from "../../hooks/useStableCallback";
+import {
+ actionClearCanvas,
+ actionLink,
+ actionToggleSearchMenu,
+} from "../../actions";
+import { activeConfirmDialogAtom } from "../ActiveConfirmDialog";
+import type { CommandPaletteItem } from "./types";
+import * as defaultItems from "./defaultCommandPaletteItems";
+import { trackEvent } from "../../analytics";
+import { useStable } from "../../hooks/useStable";
+
+import "./CommandPalette.scss";
+import {
+ actionCopyElementLink,
+ actionLinkToElement,
+} from "../../actions/actionElementLink";
+
+const lastUsedPaletteItem = atom<CommandPaletteItem | null>(null);
+
+export const DEFAULT_CATEGORIES = {
+ app: "App",
+ export: "Export",
+ tools: "Tools",
+ editor: "Editor",
+ elements: "Elements",
+ links: "Links",
+};
+
+const getCategoryOrder = (category: string) => {
+ switch (category) {
+ case DEFAULT_CATEGORIES.app:
+ return 1;
+ case DEFAULT_CATEGORIES.export:
+ return 2;
+ case DEFAULT_CATEGORIES.editor:
+ return 3;
+ case DEFAULT_CATEGORIES.tools:
+ return 4;
+ case DEFAULT_CATEGORIES.elements:
+ return 5;
+ case DEFAULT_CATEGORIES.links:
+ return 6;
+ default:
+ return 10;
+ }
+};
+
+const CommandShortcutHint = ({
+ shortcut,
+ className,
+ children,
+}: {
+ shortcut: string;
+ className?: string;
+ children?: React.ReactNode;
+}) => {
+ const shortcuts = shortcut.replace("++", "+$").split("+");
+
+ return (
+ <div className={clsx("shortcut", className)}>
+ {shortcuts.map((item, idx) => {
+ return (
+ <div className="shortcut-wrapper" key={item}>
+ <div className="shortcut-key">{item === "$" ? "+" : item}</div>
+ </div>
+ );
+ })}
+ <div className="shortcut-desc">{children}</div>
+ </div>
+ );
+};
+
+const isCommandPaletteToggleShortcut = (event: KeyboardEvent) => {
+ return (
+ !event.altKey &&
+ event[KEYS.CTRL_OR_CMD] &&
+ ((event.shiftKey && event.key.toLowerCase() === KEYS.P) ||
+ event.key === KEYS.SLASH)
+ );
+};
+
+type CommandPaletteProps = {
+ customCommandPaletteItems?: CommandPaletteItem[];
+};
+
+export const CommandPalette = Object.assign(
+ (props: CommandPaletteProps) => {
+ const uiAppState = useUIAppState();
+ const setAppState = useExcalidrawSetAppState();
+
+ useEffect(() => {
+ const commandPaletteShortcut = (event: KeyboardEvent) => {
+ if (isCommandPaletteToggleShortcut(event)) {
+ event.preventDefault();
+ event.stopPropagation();
+ setAppState((appState) => {
+ const nextState =
+ appState.openDialog?.name === "commandPalette"
+ ? null
+ : ({ name: "commandPalette" } as const);
+
+ if (nextState) {
+ trackEvent("command_palette", "open", "shortcut");
+ }
+
+ return {
+ openDialog: nextState,
+ };
+ });
+ }
+ };
+ window.addEventListener(EVENT.KEYDOWN, commandPaletteShortcut, {
+ capture: true,
+ });
+ return () =>
+ window.removeEventListener(EVENT.KEYDOWN, commandPaletteShortcut, {
+ capture: true,
+ });
+ }, [setAppState]);
+
+ if (uiAppState.openDialog?.name !== "commandPalette") {
+ return null;
+ }
+
+ return <CommandPaletteInner {...props} />;
+ },
+ {
+ defaultItems,
+ },
+);
+
+function CommandPaletteInner({
+ customCommandPaletteItems,
+}: CommandPaletteProps) {
+ const app = useApp();
+ const uiAppState = useUIAppState();
+ const setAppState = useExcalidrawSetAppState();
+ const appProps = useAppProps();
+ const actionManager = useExcalidrawActionManager();
+
+ const [lastUsed, setLastUsed] = useAtom(lastUsedPaletteItem);
+ const [allCommands, setAllCommands] = useState<
+ MarkRequired<CommandPaletteItem, "haystack" | "order">[] | null
+ >(null);
+
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const stableDeps = useStable({
+ uiAppState,
+ customCommandPaletteItems,
+ appProps,
+ });
+
+ useEffect(() => {
+ // these props change often and we don't want them to re-run the effect
+ // which would renew `allCommands`, cascading down and resetting state.
+ //
+ // This means that the commands won't update on appState/appProps changes
+ // while the command palette is open
+ const { uiAppState, customCommandPaletteItems, appProps } = stableDeps;
+
+ const getActionLabel = (action: Action) => {
+ let label = "";
+ if (action.label) {
+ if (typeof action.label === "function") {
+ label = t(
+ action.label(
+ app.scene.getNonDeletedElements(),
+ uiAppState as AppState,
+ app,
+ ) as unknown as TranslationKeys,
+ );
+ } else {
+ label = t(action.label as unknown as TranslationKeys);
+ }
+ }
+ return label;
+ };
+
+ const getActionIcon = (action: Action) => {
+ if (typeof action.icon === "function") {
+ return action.icon(uiAppState, app.scene.getNonDeletedElements());
+ }
+ return action.icon;
+ };
+
+ let commandsFromActions: CommandPaletteItem[] = [];
+
+ const actionToCommand = (
+ action: Action,
+ category: string,
+ transformer?: (
+ command: CommandPaletteItem,
+ action: Action,
+ ) => CommandPaletteItem,
+ ): CommandPaletteItem => {
+ const command: CommandPaletteItem = {
+ label: getActionLabel(action),
+ icon: getActionIcon(action),
+ category,
+ shortcut: getShortcutFromShortcutName(action.name as ShortcutName),
+ keywords: action.keywords,
+ predicate: action.predicate,
+ viewMode: action.viewMode,
+ perform: () => {
+ actionManager.executeAction(action, "commandPalette");
+ },
+ };
+
+ return transformer ? transformer(command, action) : command;
+ };
+
+ if (uiAppState && app.scene && actionManager) {
+ const elementsCommands: CommandPaletteItem[] = [
+ actionManager.actions.group,
+ actionManager.actions.ungroup,
+ actionManager.actions.cut,
+ actionManager.actions.copy,
+ actionManager.actions.deleteSelectedElements,
+ actionManager.actions.wrapSelectionInFrame,
+ actionManager.actions.copyStyles,
+ actionManager.actions.pasteStyles,
+ actionManager.actions.bringToFront,
+ actionManager.actions.bringForward,
+ actionManager.actions.sendBackward,
+ actionManager.actions.sendToBack,
+ actionManager.actions.alignTop,
+ actionManager.actions.alignBottom,
+ actionManager.actions.alignLeft,
+ actionManager.actions.alignRight,
+ actionManager.actions.alignVerticallyCentered,
+ actionManager.actions.alignHorizontallyCentered,
+ actionManager.actions.duplicateSelection,
+ actionManager.actions.flipHorizontal,
+ actionManager.actions.flipVertical,
+ actionManager.actions.zoomToFitSelection,
+ actionManager.actions.zoomToFitSelectionInViewport,
+ actionManager.actions.increaseFontSize,
+ actionManager.actions.decreaseFontSize,
+ actionManager.actions.toggleLinearEditor,
+ actionManager.actions.cropEditor,
+ actionLink,
+ actionCopyElementLink,
+ actionLinkToElement,
+ ].map((action: Action) =>
+ actionToCommand(
+ action,
+ DEFAULT_CATEGORIES.elements,
+ (command, action) => ({
+ ...command,
+ predicate: action.predicate
+ ? action.predicate
+ : (elements, appState, appProps, app) => {
+ const selectedElements = getSelectedElements(
+ elements,
+ appState,
+ );
+ return selectedElements.length > 0;
+ },
+ }),
+ ),
+ );
+ const toolCommands: CommandPaletteItem[] = [
+ actionManager.actions.toggleHandTool,
+ actionManager.actions.setFrameAsActiveTool,
+ ].map((action) => actionToCommand(action, DEFAULT_CATEGORIES.tools));
+
+ const editorCommands: CommandPaletteItem[] = [
+ actionManager.actions.undo,
+ actionManager.actions.redo,
+ actionManager.actions.zoomIn,
+ actionManager.actions.zoomOut,
+ actionManager.actions.resetZoom,
+ actionManager.actions.zoomToFit,
+ actionManager.actions.zenMode,
+ actionManager.actions.viewMode,
+ actionManager.actions.gridMode,
+ actionManager.actions.objectsSnapMode,
+ actionManager.actions.toggleShortcuts,
+ actionManager.actions.selectAll,
+ actionManager.actions.toggleElementLock,
+ actionManager.actions.unlockAllElements,
+ actionManager.actions.stats,
+ ].map((action) => actionToCommand(action, DEFAULT_CATEGORIES.editor));
+
+ const exportCommands: CommandPaletteItem[] = [
+ actionManager.actions.saveToActiveFile,
+ actionManager.actions.saveFileToDisk,
+ actionManager.actions.copyAsPng,
+ actionManager.actions.copyAsSvg,
+ ].map((action) => actionToCommand(action, DEFAULT_CATEGORIES.export));
+
+ commandsFromActions = [
+ ...elementsCommands,
+ ...editorCommands,
+ {
+ label: getActionLabel(actionClearCanvas),
+ icon: getActionIcon(actionClearCanvas),
+ shortcut: getShortcutFromShortcutName(
+ actionClearCanvas.name as ShortcutName,
+ ),
+ category: DEFAULT_CATEGORIES.editor,
+ keywords: ["delete", "destroy"],
+ viewMode: false,
+ perform: () => {
+ editorJotaiStore.set(activeConfirmDialogAtom, "clearCanvas");
+ },
+ },
+ {
+ label: t("buttons.exportImage"),
+ category: DEFAULT_CATEGORIES.export,
+ icon: ExportImageIcon,
+ shortcut: getShortcutFromShortcutName("imageExport"),
+ keywords: [
+ "export",
+ "image",
+ "png",
+ "jpeg",
+ "svg",
+ "clipboard",
+ "picture",
+ ],
+ perform: () => {
+ setAppState({ openDialog: { name: "imageExport" } });
+ },
+ },
+ ...exportCommands,
+ ];
+
+ const additionalCommands: CommandPaletteItem[] = [
+ {
+ label: t("toolBar.library"),
+ category: DEFAULT_CATEGORIES.app,
+ icon: LibraryIcon,
+ viewMode: false,
+ perform: () => {
+ if (uiAppState.openSidebar) {
+ setAppState({
+ openSidebar: null,
+ });
+ } else {
+ setAppState({
+ openSidebar: {
+ name: DEFAULT_SIDEBAR.name,
+ tab: DEFAULT_SIDEBAR.defaultTab,
+ },
+ });
+ }
+ },
+ },
+ {
+ label: t("search.title"),
+ category: DEFAULT_CATEGORIES.app,
+ icon: searchIcon,
+ viewMode: true,
+ perform: () => {
+ actionManager.executeAction(actionToggleSearchMenu);
+ },
+ },
+ {
+ label: t("labels.changeStroke"),
+ keywords: ["color", "outline"],
+ category: DEFAULT_CATEGORIES.elements,
+ icon: bucketFillIcon,
+ viewMode: false,
+ predicate: (elements, appState) => {
+ const selectedElements = getSelectedElements(elements, appState);
+ return (
+ selectedElements.length > 0 &&
+ canChangeStrokeColor(appState, selectedElements)
+ );
+ },
+ perform: () => {
+ setAppState((prevState) => ({
+ openMenu: prevState.openMenu === "shape" ? null : "shape",
+ openPopup: "elementStroke",
+ }));
+ },
+ },
+ {
+ label: t("labels.changeBackground"),
+ keywords: ["color", "fill"],
+ icon: bucketFillIcon,
+ category: DEFAULT_CATEGORIES.elements,
+ viewMode: false,
+ predicate: (elements, appState) => {
+ const selectedElements = getSelectedElements(elements, appState);
+ return (
+ selectedElements.length > 0 &&
+ canChangeBackgroundColor(appState, selectedElements)
+ );
+ },
+ perform: () => {
+ setAppState((prevState) => ({
+ openMenu: prevState.openMenu === "shape" ? null : "shape",
+ openPopup: "elementBackground",
+ }));
+ },
+ },
+ {
+ label: t("labels.canvasBackground"),
+ keywords: ["color"],
+ icon: bucketFillIcon,
+ category: DEFAULT_CATEGORIES.editor,
+ viewMode: false,
+ perform: () => {
+ setAppState((prevState) => ({
+ openMenu: prevState.openMenu === "canvas" ? null : "canvas",
+ openPopup: "canvasBackground",
+ }));
+ },
+ },
+ ...SHAPES.reduce((acc: CommandPaletteItem[], shape) => {
+ const { value, icon, key, numericKey } = shape;
+
+ if (
+ appProps.UIOptions.tools?.[
+ value as Extract<
+ typeof value,
+ keyof AppProps["UIOptions"]["tools"]
+ >
+ ] === false
+ ) {
+ return acc;
+ }
+
+ const letter =
+ key && capitalizeString(typeof key === "string" ? key : key[0]);
+ const shortcut = letter || numericKey;
+
+ const command: CommandPaletteItem = {
+ label: t(`toolBar.${value}`),
+ category: DEFAULT_CATEGORIES.tools,
+ shortcut,
+ icon,
+ keywords: ["toolbar"],
+ viewMode: false,
+ perform: ({ event }) => {
+ if (value === "image") {
+ app.setActiveTool({
+ type: value,
+ insertOnCanvasDirectly: event.type === EVENT.KEYDOWN,
+ });
+ } else {
+ app.setActiveTool({ type: value });
+ }
+ },
+ };
+
+ acc.push(command);
+
+ return acc;
+ }, []),
+ ...toolCommands,
+ {
+ label: t("toolBar.lock"),
+ category: DEFAULT_CATEGORIES.tools,
+ icon: uiAppState.activeTool.locked ? LockedIcon : UnlockedIcon,
+ shortcut: KEYS.Q.toLocaleUpperCase(),
+ viewMode: false,
+ perform: () => {
+ app.toggleLock();
+ },
+ },
+ {
+ label: `${t("labels.textToDiagram")}...`,
+ category: DEFAULT_CATEGORIES.tools,
+ icon: brainIconThin,
+ viewMode: false,
+ predicate: appProps.aiEnabled,
+ perform: () => {
+ setAppState((state) => ({
+ ...state,
+ openDialog: {
+ name: "ttd",
+ tab: "text-to-diagram",
+ },
+ }));
+ },
+ },
+ {
+ label: `${t("toolBar.mermaidToExcalidraw")}...`,
+ category: DEFAULT_CATEGORIES.tools,
+ icon: mermaidLogoIcon,
+ viewMode: false,
+ predicate: appProps.aiEnabled,
+ perform: () => {
+ setAppState((state) => ({
+ ...state,
+ openDialog: {
+ name: "ttd",
+ tab: "mermaid",
+ },
+ }));
+ },
+ },
+ // {
+ // label: `${t("toolBar.magicframe")}...`,
+ // category: DEFAULT_CATEGORIES.tools,
+ // icon: MagicIconThin,
+ // viewMode: false,
+ // predicate: appProps.aiEnabled,
+ // perform: () => {
+ // app.onMagicframeToolSelect();
+ // },
+ // },
+ ];
+
+ const allCommands = [
+ ...commandsFromActions,
+ ...additionalCommands,
+ ...(customCommandPaletteItems || []),
+ ].map((command) => {
+ return {
+ ...command,
+ icon: command.icon || boltIcon,
+ order: command.order ?? getCategoryOrder(command.category),
+ haystack: `${deburr(command.label.toLocaleLowerCase())} ${
+ command.keywords?.join(" ") || ""
+ }`,
+ };
+ });
+
+ setAllCommands(allCommands);
+ setLastUsed(
+ allCommands.find((command) => command.label === lastUsed?.label) ??
+ null,
+ );
+ }
+ }, [
+ stableDeps,
+ app,
+ actionManager,
+ setAllCommands,
+ lastUsed?.label,
+ setLastUsed,
+ setAppState,
+ ]);
+
+ const [commandSearch, setCommandSearch] = useState("");
+ const [currentCommand, setCurrentCommand] =
+ useState<CommandPaletteItem | null>(null);
+ const [commandsByCategory, setCommandsByCategory] = useState<
+ Record<string, CommandPaletteItem[]>
+ >({});
+
+ const closeCommandPalette = (cb?: () => void) => {
+ setAppState(
+ {
+ openDialog: null,
+ },
+ cb,
+ );
+ setCommandSearch("");
+ };
+
+ const executeCommand = (
+ command: CommandPaletteItem,
+ event: React.MouseEvent | React.KeyboardEvent | KeyboardEvent,
+ ) => {
+ if (uiAppState.openDialog?.name === "commandPalette") {
+ event.stopPropagation();
+ event.preventDefault();
+ document.body.classList.add("excalidraw-animations-disabled");
+ closeCommandPalette(() => {
+ command.perform({ actionManager, event });
+ setLastUsed(command);
+
+ requestAnimationFrame(() => {
+ document.body.classList.remove("excalidraw-animations-disabled");
+ });
+ });
+ }
+ };
+
+ const isCommandAvailable = useStableCallback(
+ (command: CommandPaletteItem) => {
+ if (command.viewMode === false && uiAppState.viewModeEnabled) {
+ return false;
+ }
+
+ return typeof command.predicate === "function"
+ ? command.predicate(
+ app.scene.getNonDeletedElements(),
+ uiAppState as AppState,
+ appProps,
+ app,
+ )
+ : command.predicate === undefined || command.predicate;
+ },
+ );
+
+ const handleKeyDown = useStableCallback((event: KeyboardEvent) => {
+ const ignoreAlphanumerics =
+ isWritableElement(event.target) ||
+ isCommandPaletteToggleShortcut(event) ||
+ event.key === KEYS.ESCAPE;
+
+ if (
+ ignoreAlphanumerics &&
+ event.key !== KEYS.ARROW_UP &&
+ event.key !== KEYS.ARROW_DOWN &&
+ event.key !== KEYS.ENTER
+ ) {
+ return;
+ }
+
+ const matchingCommands = Object.values(commandsByCategory).flat();
+ const shouldConsiderLastUsed =
+ lastUsed && !commandSearch && isCommandAvailable(lastUsed);
+
+ if (event.key === KEYS.ARROW_UP) {
+ event.preventDefault();
+ const index = matchingCommands.findIndex(
+ (item) => item.label === currentCommand?.label,
+ );
+
+ if (shouldConsiderLastUsed) {
+ if (index === 0) {
+ setCurrentCommand(lastUsed);
+ return;
+ }
+
+ if (currentCommand === lastUsed) {
+ const nextItem = matchingCommands[matchingCommands.length - 1];
+ if (nextItem) {
+ setCurrentCommand(nextItem);
+ }
+ return;
+ }
+ }
+
+ let nextIndex;
+
+ if (index === -1) {
+ nextIndex = matchingCommands.length - 1;
+ } else {
+ nextIndex =
+ index === 0
+ ? matchingCommands.length - 1
+ : (index - 1) % matchingCommands.length;
+ }
+
+ const nextItem = matchingCommands[nextIndex];
+ if (nextItem) {
+ setCurrentCommand(nextItem);
+ }
+
+ return;
+ }
+
+ if (event.key === KEYS.ARROW_DOWN) {
+ event.preventDefault();
+ const index = matchingCommands.findIndex(
+ (item) => item.label === currentCommand?.label,
+ );
+
+ if (shouldConsiderLastUsed) {
+ if (!currentCommand || index === matchingCommands.length - 1) {
+ setCurrentCommand(lastUsed);
+ return;
+ }
+
+ if (currentCommand === lastUsed) {
+ const nextItem = matchingCommands[0];
+ if (nextItem) {
+ setCurrentCommand(nextItem);
+ }
+ return;
+ }
+ }
+
+ const nextIndex = (index + 1) % matchingCommands.length;
+ const nextItem = matchingCommands[nextIndex];
+ if (nextItem) {
+ setCurrentCommand(nextItem);
+ }
+
+ return;
+ }
+
+ if (event.key === KEYS.ENTER) {
+ if (currentCommand) {
+ setTimeout(() => {
+ executeCommand(currentCommand, event);
+ });
+ }
+ }
+
+ if (ignoreAlphanumerics) {
+ return;
+ }
+
+ // prevent regular editor shortcuts
+ event.stopPropagation();
+
+ // if alphanumeric keypress and we're not inside the input, focus it
+ if (/^[a-zA-Z0-9]$/.test(event.key)) {
+ inputRef?.current?.focus();
+ return;
+ }
+
+ event.preventDefault();
+ });
+
+ useEffect(() => {
+ window.addEventListener(EVENT.KEYDOWN, handleKeyDown, {
+ capture: true,
+ });
+ return () =>
+ window.removeEventListener(EVENT.KEYDOWN, handleKeyDown, {
+ capture: true,
+ });
+ }, [handleKeyDown]);
+
+ useEffect(() => {
+ if (!allCommands) {
+ return;
+ }
+
+ const getNextCommandsByCategory = (commands: CommandPaletteItem[]) => {
+ const nextCommandsByCategory: Record<string, CommandPaletteItem[]> = {};
+ for (const command of commands) {
+ if (nextCommandsByCategory[command.category]) {
+ nextCommandsByCategory[command.category].push(command);
+ } else {
+ nextCommandsByCategory[command.category] = [command];
+ }
+ }
+
+ return nextCommandsByCategory;
+ };
+
+ let matchingCommands = allCommands
+ .filter(isCommandAvailable)
+ .sort((a, b) => a.order - b.order);
+
+ const showLastUsed =
+ !commandSearch && lastUsed && isCommandAvailable(lastUsed);
+
+ if (!commandSearch) {
+ setCommandsByCategory(
+ getNextCommandsByCategory(
+ showLastUsed
+ ? matchingCommands.filter(
+ (command) => command.label !== lastUsed?.label,
+ )
+ : matchingCommands,
+ ),
+ );
+ setCurrentCommand(showLastUsed ? lastUsed : matchingCommands[0] || null);
+ return;
+ }
+
+ const _query = deburr(
+ commandSearch.toLocaleLowerCase().replace(/[<>_| -]/g, ""),
+ );
+ matchingCommands = fuzzy
+ .filter(_query, matchingCommands, {
+ extract: (command) => command.haystack,
+ })
+ .sort((a, b) => b.score - a.score)
+ .map((item) => item.original);
+
+ setCommandsByCategory(getNextCommandsByCategory(matchingCommands));
+ setCurrentCommand(matchingCommands[0] ?? null);
+ }, [commandSearch, allCommands, isCommandAvailable, lastUsed]);
+
+ return (
+ <Dialog
+ onCloseRequest={() => closeCommandPalette()}
+ closeOnClickOutside
+ title={false}
+ size={720}
+ autofocus
+ className="command-palette-dialog"
+ >
+ <TextField
+ value={commandSearch}
+ placeholder={t("commandPalette.search.placeholder")}
+ onChange={(value) => {
+ setCommandSearch(value);
+ }}
+ selectOnRender
+ ref={inputRef}
+ />
+
+ {!app.device.viewport.isMobile && (
+ <div className="shortcuts-wrapper">
+ <CommandShortcutHint shortcut="↑↓">
+ {t("commandPalette.shortcuts.select")}
+ </CommandShortcutHint>
+ <CommandShortcutHint shortcut="↵">
+ {t("commandPalette.shortcuts.confirm")}
+ </CommandShortcutHint>
+ <CommandShortcutHint shortcut={getShortcutKey("Esc")}>
+ {t("commandPalette.shortcuts.close")}
+ </CommandShortcutHint>
+ </div>
+ )}
+
+ <div className="commands">
+ {lastUsed && !commandSearch && (
+ <div className="command-category">
+ <div className="command-category-title">
+ {t("commandPalette.recents")}
+ <div
+ className="icon"
+ style={{
+ marginLeft: "6px",
+ }}
+ >
+ {clockIcon}
+ </div>
+ </div>
+ <CommandItem
+ command={lastUsed}
+ isSelected={lastUsed.label === currentCommand?.label}
+ onClick={(event) => executeCommand(lastUsed, event)}
+ disabled={!isCommandAvailable(lastUsed)}
+ onMouseMove={() => setCurrentCommand(lastUsed)}
+ showShortcut={!app.device.viewport.isMobile}
+ appState={uiAppState}
+ />
+ </div>
+ )}
+
+ {Object.keys(commandsByCategory).length > 0 ? (
+ Object.keys(commandsByCategory).map((category, idx) => {
+ return (
+ <div className="command-category" key={category}>
+ <div className="command-category-title">{category}</div>
+ {commandsByCategory[category].map((command) => (
+ <CommandItem
+ key={command.label}
+ command={command}
+ isSelected={command.label === currentCommand?.label}
+ onClick={(event) => executeCommand(command, event)}
+ onMouseMove={() => setCurrentCommand(command)}
+ showShortcut={!app.device.viewport.isMobile}
+ appState={uiAppState}
+ />
+ ))}
+ </div>
+ );
+ })
+ ) : allCommands ? (
+ <div className="no-match">
+ <div className="icon">{searchIcon}</div>{" "}
+ {t("commandPalette.search.noMatch")}
+ </div>
+ ) : null}
+ </div>
+ </Dialog>
+ );
+}
+
+const CommandItem = ({
+ command,
+ isSelected,
+ disabled,
+ onMouseMove,
+ onClick,
+ showShortcut,
+ appState,
+}: {
+ command: CommandPaletteItem;
+ isSelected: boolean;
+ disabled?: boolean;
+ onMouseMove: () => void;
+ onClick: (event: React.MouseEvent) => void;
+ showShortcut: boolean;
+ appState: UIAppState;
+}) => {
+ const noop = () => {};
+
+ return (
+ <div
+ className={clsx("command-item", {
+ "item-selected": isSelected,
+ "item-disabled": disabled,
+ })}
+ ref={(ref) => {
+ if (isSelected && !disabled) {
+ ref?.scrollIntoView?.({
+ block: "nearest",
+ });
+ }
+ }}
+ onClick={disabled ? noop : onClick}
+ onMouseMove={disabled ? noop : onMouseMove}
+ title={disabled ? t("commandPalette.itemNotAvailable") : ""}
+ >
+ <div className="name">
+ {command.icon && (
+ <InlineIcon
+ icon={
+ typeof command.icon === "function"
+ ? command.icon(appState)
+ : command.icon
+ }
+ />
+ )}
+ {command.label}
+ </div>
+ {showShortcut && command.shortcut && (
+ <CommandShortcutHint shortcut={command.shortcut} />
+ )}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/CommandPalette/defaultCommandPaletteItems.ts b/packages/excalidraw/components/CommandPalette/defaultCommandPaletteItems.ts
new file mode 100644
index 0000000..dea14ff
--- /dev/null
+++ b/packages/excalidraw/components/CommandPalette/defaultCommandPaletteItems.ts
@@ -0,0 +1,11 @@
+import { actionToggleTheme } from "../../actions";
+import type { CommandPaletteItem } from "./types";
+
+export const toggleTheme: CommandPaletteItem = {
+ ...actionToggleTheme,
+ category: "App",
+ label: "Toggle theme",
+ perform: ({ actionManager }) => {
+ actionManager.executeAction(actionToggleTheme, "commandPalette");
+ },
+};
diff --git a/packages/excalidraw/components/CommandPalette/types.ts b/packages/excalidraw/components/CommandPalette/types.ts
new file mode 100644
index 0000000..957d699
--- /dev/null
+++ b/packages/excalidraw/components/CommandPalette/types.ts
@@ -0,0 +1,26 @@
+import type { ActionManager } from "../../actions/manager";
+import type { Action } from "../../actions/types";
+import type { UIAppState } from "../../types";
+
+export type CommandPaletteItem = {
+ label: string;
+ /** additional keywords to match against
+ * (appended to haystack, not displayed) */
+ keywords?: string[];
+ /**
+ * string we should match against when searching
+ * (deburred name + keywords)
+ */
+ haystack?: string;
+ icon?: React.ReactNode | ((appState: UIAppState) => React.ReactNode);
+ category: string;
+ order?: number;
+ predicate?: boolean | Action["predicate"];
+ shortcut?: string;
+ /** if false, command will not show while in view mode */
+ viewMode?: boolean;
+ perform: (data: {
+ actionManager: ActionManager;
+ event: React.MouseEvent | React.KeyboardEvent | KeyboardEvent;
+ }) => void;
+};
diff --git a/packages/excalidraw/components/ConfirmDialog.scss b/packages/excalidraw/components/ConfirmDialog.scss
new file mode 100644
index 0000000..1fa36fc
--- /dev/null
+++ b/packages/excalidraw/components/ConfirmDialog.scss
@@ -0,0 +1,11 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .confirm-dialog {
+ &-buttons {
+ display: flex;
+ column-gap: 0.5rem;
+ justify-content: flex-end;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ConfirmDialog.tsx b/packages/excalidraw/components/ConfirmDialog.tsx
new file mode 100644
index 0000000..81073ec
--- /dev/null
+++ b/packages/excalidraw/components/ConfirmDialog.tsx
@@ -0,0 +1,78 @@
+import { flushSync } from "react-dom";
+import { t } from "../i18n";
+import type { DialogProps } from "./Dialog";
+import { Dialog } from "./Dialog";
+
+import "./ConfirmDialog.scss";
+import DialogActionButton from "./DialogActionButton";
+import { isLibraryMenuOpenAtom } from "./LibraryMenu";
+import { useExcalidrawContainer, useExcalidrawSetAppState } from "./App";
+import { useSetAtom } from "../editor-jotai";
+
+interface Props extends Omit<DialogProps, "onCloseRequest"> {
+ onConfirm: () => void;
+ onCancel: () => void;
+ confirmText?: string;
+ cancelText?: string;
+}
+const ConfirmDialog = (props: Props) => {
+ const {
+ onConfirm,
+ onCancel,
+ children,
+ confirmText = t("buttons.confirm"),
+ cancelText = t("buttons.cancel"),
+ className = "",
+ ...rest
+ } = props;
+ const setAppState = useExcalidrawSetAppState();
+ const setIsLibraryMenuOpen = useSetAtom(isLibraryMenuOpenAtom);
+ const { container } = useExcalidrawContainer();
+
+ return (
+ <Dialog
+ onCloseRequest={onCancel}
+ size="small"
+ {...rest}
+ className={`confirm-dialog ${className}`}
+ >
+ {children}
+ <div className="confirm-dialog-buttons">
+ <DialogActionButton
+ label={cancelText}
+ onClick={() => {
+ setAppState({ openMenu: null });
+ setIsLibraryMenuOpen(false);
+ // flush any pending updates synchronously,
+ // otherwise it could lead to crash in some chromium versions (131.0.6778.86),
+ // when `.focus` is invoked with container in some intermediate state
+ // (container seems mounted in DOM, but focus still causes a crash)
+ flushSync(() => {
+ onCancel();
+ });
+
+ container?.focus();
+ }}
+ />
+ <DialogActionButton
+ label={confirmText}
+ onClick={() => {
+ setAppState({ openMenu: null });
+ setIsLibraryMenuOpen(false);
+ // flush any pending updates synchronously,
+ // otherwise it leads to crash in some chromium versions (131.0.6778.86),
+ // when `.focus` is invoked with container in some intermediate state
+ // (container seems mounted in DOM, but focus still causes a crash)
+ flushSync(() => {
+ onConfirm();
+ });
+
+ container?.focus();
+ }}
+ actionType="danger"
+ />
+ </div>
+ </Dialog>
+ );
+};
+export default ConfirmDialog;
diff --git a/packages/excalidraw/components/ContextMenu.scss b/packages/excalidraw/components/ContextMenu.scss
new file mode 100644
index 0000000..3bedf2b
--- /dev/null
+++ b/packages/excalidraw/components/ContextMenu.scss
@@ -0,0 +1,98 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .context-menu {
+ position: relative;
+ border-radius: 4px;
+ box-shadow: 0 3px 10px transparentize($oc-black, 0.8);
+ padding: 0;
+ list-style: none;
+ user-select: none;
+ margin: -0.25rem 0 0 0.125rem;
+ padding: 0.5rem 0;
+ background-color: var(--popup-secondary-bg-color);
+ border: 1px solid var(--button-gray-3);
+ cursor: default;
+ }
+
+ .context-menu button {
+ color: var(--popup-text-color);
+ }
+
+ .context-menu-item {
+ position: relative;
+ width: 100%;
+ min-width: 9.5rem;
+ margin: 0;
+ padding: 0.25rem 1rem 0.25rem 1.25rem;
+ text-align: start;
+ border-radius: 0;
+ background-color: transparent;
+ border: none;
+ white-space: nowrap;
+ font-family: inherit;
+
+ display: grid;
+ grid-template-columns: 1fr 0.2fr;
+ align-items: center;
+
+ &.checkmark::before {
+ position: absolute;
+ left: 6px;
+ margin-bottom: 1px;
+ content: "\2713";
+ }
+
+ &.dangerous {
+ .context-menu-item__label {
+ color: $oc-red-7;
+ }
+ }
+
+ .context-menu-item__label {
+ justify-self: start;
+ margin-inline-end: 20px;
+ }
+ .context-menu-item__shortcut {
+ justify-self: end;
+ opacity: 0.6;
+ font-family: inherit;
+ font-size: 0.7rem;
+ }
+ }
+
+ .context-menu-item:hover {
+ color: var(--popup-bg-color);
+ background-color: var(--select-highlight-color);
+
+ &.dangerous {
+ .context-menu-item__label {
+ color: var(--popup-bg-color);
+ }
+ background-color: $oc-red-6;
+ }
+ }
+
+ .context-menu-item:focus {
+ z-index: 1;
+ }
+
+ @include isMobile {
+ .context-menu-item {
+ display: block;
+
+ .context-menu-item__label {
+ margin-inline-end: 0;
+ }
+
+ .context-menu-item__shortcut {
+ display: none;
+ }
+ }
+ }
+
+ .context-menu-item-separator {
+ border: none;
+ border-top: 1px solid $oc-gray-5;
+ }
+}
diff --git a/packages/excalidraw/components/ContextMenu.tsx b/packages/excalidraw/components/ContextMenu.tsx
new file mode 100644
index 0000000..517e5fa
--- /dev/null
+++ b/packages/excalidraw/components/ContextMenu.tsx
@@ -0,0 +1,128 @@
+import clsx from "clsx";
+import { Popover } from "./Popover";
+import type { TranslationKeys } from "../i18n";
+import { t } from "../i18n";
+
+import "./ContextMenu.scss";
+import type { ShortcutName } from "../actions/shortcuts";
+import { getShortcutFromShortcutName } from "../actions/shortcuts";
+import type { Action } from "../actions/types";
+import type { ActionManager } from "../actions/manager";
+import { useExcalidrawAppState, useExcalidrawElements } from "./App";
+import React from "react";
+
+export type ContextMenuItem = typeof CONTEXT_MENU_SEPARATOR | Action;
+
+export type ContextMenuItems = (ContextMenuItem | false | null | undefined)[];
+
+type ContextMenuProps = {
+ actionManager: ActionManager;
+ items: ContextMenuItems;
+ top: number;
+ left: number;
+ onClose: (callback?: () => void) => void;
+};
+
+export const CONTEXT_MENU_SEPARATOR = "separator";
+
+export const ContextMenu = React.memo(
+ ({ actionManager, items, top, left, onClose }: ContextMenuProps) => {
+ const appState = useExcalidrawAppState();
+ const elements = useExcalidrawElements();
+
+ const filteredItems = items.reduce((acc: ContextMenuItem[], item) => {
+ if (
+ item &&
+ (item === CONTEXT_MENU_SEPARATOR ||
+ !item.predicate ||
+ item.predicate(
+ elements,
+ appState,
+ actionManager.app.props,
+ actionManager.app,
+ ))
+ ) {
+ acc.push(item);
+ }
+ return acc;
+ }, []);
+
+ return (
+ <Popover
+ onCloseRequest={() => {
+ onClose();
+ }}
+ top={top}
+ left={left}
+ fitInViewport={true}
+ offsetLeft={appState.offsetLeft}
+ offsetTop={appState.offsetTop}
+ viewportWidth={appState.width}
+ viewportHeight={appState.height}
+ >
+ <ul
+ className="context-menu"
+ onContextMenu={(event) => event.preventDefault()}
+ >
+ {filteredItems.map((item, idx) => {
+ if (item === CONTEXT_MENU_SEPARATOR) {
+ if (
+ !filteredItems[idx - 1] ||
+ filteredItems[idx - 1] === CONTEXT_MENU_SEPARATOR
+ ) {
+ return null;
+ }
+ return <hr key={idx} className="context-menu-item-separator" />;
+ }
+
+ const actionName = item.name;
+ let label = "";
+ if (item.label) {
+ if (typeof item.label === "function") {
+ label = t(
+ item.label(
+ elements,
+ appState,
+ actionManager.app,
+ ) as unknown as TranslationKeys,
+ );
+ } else {
+ label = t(item.label as unknown as TranslationKeys);
+ }
+ }
+
+ return (
+ <li
+ key={idx}
+ data-testid={actionName}
+ onClick={() => {
+ // we need update state before executing the action in case
+ // the action uses the appState it's being passed (that still
+ // contains a defined contextMenu) to return the next state.
+ onClose(() => {
+ actionManager.executeAction(item, "contextMenu");
+ });
+ }}
+ >
+ <button
+ type="button"
+ className={clsx("context-menu-item", {
+ dangerous: actionName === "deleteSelectedElements",
+ checkmark: item.checked?.(appState),
+ })}
+ >
+ <div className="context-menu-item__label">{label}</div>
+ <kbd className="context-menu-item__shortcut">
+ {actionName
+ ? getShortcutFromShortcutName(actionName as ShortcutName)
+ : ""}
+ </kbd>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </Popover>
+ );
+ },
+);
diff --git a/packages/excalidraw/components/DarkModeToggle.tsx b/packages/excalidraw/components/DarkModeToggle.tsx
new file mode 100644
index 0000000..6292ba5
--- /dev/null
+++ b/packages/excalidraw/components/DarkModeToggle.tsx
@@ -0,0 +1,52 @@
+import "./ToolIcon.scss";
+
+import { t } from "../i18n";
+import { ToolButton } from "./ToolButton";
+import { THEME } from "../constants";
+import type { Theme } from "../element/types";
+
+// We chose to use only explicit toggle and not a third option for system value,
+// but this could be added in the future.
+export const DarkModeToggle = (props: {
+ value: Theme;
+ onChange: (value: Theme) => void;
+ title?: string;
+}) => {
+ const title =
+ props.title ||
+ (props.value === THEME.DARK
+ ? t("buttons.lightMode")
+ : t("buttons.darkMode"));
+
+ return (
+ <ToolButton
+ type="icon"
+ icon={props.value === THEME.LIGHT ? ICONS.MOON : ICONS.SUN}
+ title={title}
+ aria-label={title}
+ onClick={() =>
+ props.onChange(props.value === THEME.DARK ? THEME.LIGHT : THEME.DARK)
+ }
+ data-testid="toggle-dark-mode"
+ />
+ );
+};
+
+const ICONS = {
+ SUN: (
+ <svg width="512" height="512" className="rtl-mirror" viewBox="0 0 512 512">
+ <path
+ fill="currentColor"
+ d="M256 160c-52.9 0-96 43.1-96 96s43.1 96 96 96 96-43.1 96-96-43.1-96-96-96zm246.4 80.5l-94.7-47.3 33.5-100.4c4.5-13.6-8.4-26.5-21.9-21.9l-100.4 33.5-47.4-94.8c-6.4-12.8-24.6-12.8-31 0l-47.3 94.7L92.7 70.8c-13.6-4.5-26.5 8.4-21.9 21.9l33.5 100.4-94.7 47.4c-12.8 6.4-12.8 24.6 0 31l94.7 47.3-33.5 100.5c-4.5 13.6 8.4 26.5 21.9 21.9l100.4-33.5 47.3 94.7c6.4 12.8 24.6 12.8 31 0l47.3-94.7 100.4 33.5c13.6 4.5 26.5-8.4 21.9-21.9l-33.5-100.4 94.7-47.3c13-6.5 13-24.7.2-31.1zm-155.9 106c-49.9 49.9-131.1 49.9-181 0-49.9-49.9-49.9-131.1 0-181 49.9-49.9 131.1-49.9 181 0 49.9 49.9 49.9 131.1 0 181z"
+ ></path>
+ </svg>
+ ),
+ MOON: (
+ <svg width="512" height="512" className="rtl-mirror" viewBox="0 0 512 512">
+ <path
+ fill="currentColor"
+ d="M283.211 512c78.962 0 151.079-35.925 198.857-94.792 7.068-8.708-.639-21.43-11.562-19.35-124.203 23.654-238.262-71.576-238.262-196.954 0-72.222 38.662-138.635 101.498-174.394 9.686-5.512 7.25-20.197-3.756-22.23A258.156 258.156 0 0 0 283.211 0c-141.309 0-256 114.511-256 256 0 141.309 114.511 256 256 256z"
+ ></path>
+ </svg>
+ ),
+};
diff --git a/packages/excalidraw/components/DefaultSidebar.test.tsx b/packages/excalidraw/components/DefaultSidebar.test.tsx
new file mode 100644
index 0000000..ac1e296
--- /dev/null
+++ b/packages/excalidraw/components/DefaultSidebar.test.tsx
@@ -0,0 +1,144 @@
+import React from "react";
+import { DEFAULT_SIDEBAR } from "../constants";
+import { DefaultSidebar } from "../index";
+import {
+ fireEvent,
+ waitFor,
+ withExcalidrawDimensions,
+} from "../tests/test-utils";
+import {
+ assertExcalidrawWithSidebar,
+ assertSidebarDockButton,
+} from "./Sidebar/siderbar.test.helpers";
+
+const { h } = window;
+
+describe("DefaultSidebar", () => {
+ it("when `docked={undefined}` & `onDock={undefined}`, should allow docking", async () => {
+ await assertExcalidrawWithSidebar(
+ <DefaultSidebar />,
+ DEFAULT_SIDEBAR.name,
+ async () => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+
+ const { dockButton } = await assertSidebarDockButton(true);
+
+ fireEvent.click(dockButton);
+ await waitFor(() => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(true);
+ expect(dockButton).toHaveClass("selected");
+ });
+
+ fireEvent.click(dockButton);
+ await waitFor(() => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+ expect(dockButton).not.toHaveClass("selected");
+ });
+ },
+ );
+ });
+
+ it("when `docked={undefined}` & `onDock`, should allow docking", async () => {
+ await assertExcalidrawWithSidebar(
+ <DefaultSidebar onDock={() => {}} />,
+ DEFAULT_SIDEBAR.name,
+ async () => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+
+ const { dockButton } = await assertSidebarDockButton(true);
+
+ fireEvent.click(dockButton);
+ await waitFor(() => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(true);
+ expect(dockButton).toHaveClass("selected");
+ });
+
+ fireEvent.click(dockButton);
+ await waitFor(() => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+ expect(dockButton).not.toHaveClass("selected");
+ });
+ },
+ );
+ });
+
+ it("when `docked={true}` & `onDock`, should allow docking", async () => {
+ await assertExcalidrawWithSidebar(
+ <DefaultSidebar onDock={() => {}} />,
+ DEFAULT_SIDEBAR.name,
+ async () => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+
+ const { dockButton } = await assertSidebarDockButton(true);
+
+ fireEvent.click(dockButton);
+ await waitFor(() => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(true);
+ expect(dockButton).toHaveClass("selected");
+ });
+
+ fireEvent.click(dockButton);
+ await waitFor(() => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+ expect(dockButton).not.toHaveClass("selected");
+ });
+ },
+ );
+ });
+
+ it("when `onDock={false}`, should disable docking", async () => {
+ await assertExcalidrawWithSidebar(
+ <DefaultSidebar onDock={false} />,
+ DEFAULT_SIDEBAR.name,
+ async () => {
+ await withExcalidrawDimensions(
+ { width: 1920, height: 1080 },
+ async () => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+
+ await assertSidebarDockButton(false);
+ },
+ );
+ },
+ );
+ });
+
+ it("when `docked={true}` & `onDock={false}`, should force-dock sidebar", async () => {
+ await assertExcalidrawWithSidebar(
+ <DefaultSidebar docked onDock={false} />,
+ DEFAULT_SIDEBAR.name,
+ async () => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+
+ const { sidebar } = await assertSidebarDockButton(false);
+ expect(sidebar).toHaveClass("sidebar--docked");
+ },
+ );
+ });
+
+ it("when `docked={true}` & `onDock={undefined}`, should force-dock sidebar", async () => {
+ await assertExcalidrawWithSidebar(
+ <DefaultSidebar docked />,
+ DEFAULT_SIDEBAR.name,
+ async () => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+
+ const { sidebar } = await assertSidebarDockButton(false);
+ expect(sidebar).toHaveClass("sidebar--docked");
+ },
+ );
+ });
+
+ it("when `docked={false}` & `onDock={undefined}`, should force-undock sidebar", async () => {
+ await assertExcalidrawWithSidebar(
+ <DefaultSidebar docked={false} />,
+ DEFAULT_SIDEBAR.name,
+ async () => {
+ expect(h.state.defaultSidebarDockedPreference).toBe(false);
+
+ const { sidebar } = await assertSidebarDockButton(false);
+ expect(sidebar).not.toHaveClass("sidebar--docked");
+ },
+ );
+ });
+});
diff --git a/packages/excalidraw/components/DefaultSidebar.tsx b/packages/excalidraw/components/DefaultSidebar.tsx
new file mode 100644
index 0000000..70b0c2d
--- /dev/null
+++ b/packages/excalidraw/components/DefaultSidebar.tsx
@@ -0,0 +1,121 @@
+import clsx from "clsx";
+import {
+ CANVAS_SEARCH_TAB,
+ DEFAULT_SIDEBAR,
+ LIBRARY_SIDEBAR_TAB,
+} from "../constants";
+import { useTunnels } from "../context/tunnels";
+import { useUIAppState } from "../context/ui-appState";
+import type { MarkOptional, Merge } from "../utility-types";
+import { composeEventHandlers } from "../utils";
+import { useExcalidrawSetAppState } from "./App";
+import { withInternalFallback } from "./hoc/withInternalFallback";
+import { LibraryMenu } from "./LibraryMenu";
+import type { SidebarProps, SidebarTriggerProps } from "./Sidebar/common";
+import { Sidebar } from "./Sidebar/Sidebar";
+import "../components/dropdownMenu/DropdownMenu.scss";
+import { SearchMenu } from "./SearchMenu";
+import { LibraryIcon, searchIcon } from "./icons";
+
+const DefaultSidebarTrigger = withInternalFallback(
+ "DefaultSidebarTrigger",
+ (
+ props: Omit<SidebarTriggerProps, "name"> &
+ React.HTMLAttributes<HTMLDivElement>,
+ ) => {
+ const { DefaultSidebarTriggerTunnel } = useTunnels();
+ return (
+ <DefaultSidebarTriggerTunnel.In>
+ <Sidebar.Trigger
+ {...props}
+ className="default-sidebar-trigger"
+ name={DEFAULT_SIDEBAR.name}
+ />
+ </DefaultSidebarTriggerTunnel.In>
+ );
+ },
+);
+DefaultSidebarTrigger.displayName = "DefaultSidebarTrigger";
+
+const DefaultTabTriggers = ({ children }: { children: React.ReactNode }) => {
+ const { DefaultSidebarTabTriggersTunnel } = useTunnels();
+ return (
+ <DefaultSidebarTabTriggersTunnel.In>
+ {children}
+ </DefaultSidebarTabTriggersTunnel.In>
+ );
+};
+DefaultTabTriggers.displayName = "DefaultTabTriggers";
+
+export const DefaultSidebar = Object.assign(
+ withInternalFallback(
+ "DefaultSidebar",
+ ({
+ children,
+ className,
+ onDock,
+ docked,
+ ...rest
+ }: Merge<
+ MarkOptional<Omit<SidebarProps, "name">, "children">,
+ {
+ /** pass `false` to disable docking */
+ onDock?: SidebarProps["onDock"] | false;
+ }
+ >) => {
+ const appState = useUIAppState();
+ const setAppState = useExcalidrawSetAppState();
+
+ const { DefaultSidebarTabTriggersTunnel } = useTunnels();
+
+ const isForceDocked = appState.openSidebar?.tab === CANVAS_SEARCH_TAB;
+
+ return (
+ <Sidebar
+ {...rest}
+ name="default"
+ key="default"
+ className={clsx("default-sidebar", className)}
+ docked={
+ isForceDocked || (docked ?? appState.defaultSidebarDockedPreference)
+ }
+ onDock={
+ // `onDock=false` disables docking.
+ // if `docked` passed, but no onDock passed, disable manual docking.
+ isForceDocked || onDock === false || (!onDock && docked != null)
+ ? undefined
+ : // compose to allow the host app to listen on default behavior
+ composeEventHandlers(onDock, (docked) => {
+ setAppState({ defaultSidebarDockedPreference: docked });
+ })
+ }
+ >
+ <Sidebar.Tabs>
+ <Sidebar.Header>
+ <Sidebar.TabTriggers>
+ <Sidebar.TabTrigger tab={CANVAS_SEARCH_TAB}>
+ {searchIcon}
+ </Sidebar.TabTrigger>
+ <Sidebar.TabTrigger tab={LIBRARY_SIDEBAR_TAB}>
+ {LibraryIcon}
+ </Sidebar.TabTrigger>
+ <DefaultSidebarTabTriggersTunnel.Out />
+ </Sidebar.TabTriggers>
+ </Sidebar.Header>
+ <Sidebar.Tab tab={LIBRARY_SIDEBAR_TAB}>
+ <LibraryMenu />
+ </Sidebar.Tab>
+ <Sidebar.Tab tab={CANVAS_SEARCH_TAB}>
+ <SearchMenu />
+ </Sidebar.Tab>
+ {children}
+ </Sidebar.Tabs>
+ </Sidebar>
+ );
+ },
+ ),
+ {
+ Trigger: DefaultSidebarTrigger,
+ TabTriggers: DefaultTabTriggers,
+ },
+);
diff --git a/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodePlugin.tsx b/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodePlugin.tsx
new file mode 100644
index 0000000..9505999
--- /dev/null
+++ b/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodePlugin.tsx
@@ -0,0 +1,17 @@
+import { useLayoutEffect } from "react";
+import { useApp } from "../App";
+import type { GenerateDiagramToCode } from "../../types";
+
+export const DiagramToCodePlugin = (props: {
+ generate: GenerateDiagramToCode;
+}) => {
+ const app = useApp();
+
+ useLayoutEffect(() => {
+ app.setPlugins({
+ diagramToCode: { generate: props.generate },
+ });
+ }, [app, props.generate]);
+
+ return null;
+};
diff --git a/packages/excalidraw/components/Dialog.scss b/packages/excalidraw/components/Dialog.scss
new file mode 100644
index 0000000..622d304
--- /dev/null
+++ b/packages/excalidraw/components/Dialog.scss
@@ -0,0 +1,54 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .Dialog {
+ user-select: text;
+ cursor: auto;
+ }
+
+ .Dialog__title {
+ margin: 0;
+ text-align: left;
+ font-size: 1.25rem;
+ border-bottom: 1px solid var(--dialog-border-color);
+ padding: 0 0 0.75rem;
+ margin-bottom: 1.5rem;
+ }
+
+ .Dialog__close {
+ color: var(--color-gray-40);
+ margin: 0;
+ position: absolute;
+ top: 0.75rem;
+ right: 0.5rem;
+ border: 0;
+ background-color: transparent;
+ line-height: 0;
+ cursor: pointer;
+
+ &:hover {
+ color: var(--color-gray-60);
+ }
+ &:active {
+ color: var(--color-gray-40);
+ }
+
+ svg {
+ width: 1.5rem;
+ height: 1.5rem;
+ }
+
+ & + .Dialog__content {
+ --offset: 28px;
+ height: calc(100% - var(--offset)) !important;
+ margin-top: var(--offset) !important;
+ }
+ }
+
+ .Dialog--fullscreen {
+ .Dialog__close {
+ top: 1.25rem;
+ right: 1.25rem;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Dialog.tsx b/packages/excalidraw/components/Dialog.tsx
new file mode 100644
index 0000000..0a105cf
--- /dev/null
+++ b/packages/excalidraw/components/Dialog.tsx
@@ -0,0 +1,134 @@
+import clsx from "clsx";
+import React, { useEffect, useState } from "react";
+import { useCallbackRefState } from "../hooks/useCallbackRefState";
+import {
+ useExcalidrawContainer,
+ useDevice,
+ useExcalidrawSetAppState,
+} from "./App";
+import { KEYS } from "../keys";
+import "./Dialog.scss";
+import { Island } from "./Island";
+import { Modal } from "./Modal";
+import { queryFocusableElements } from "../utils";
+import { isLibraryMenuOpenAtom } from "./LibraryMenu";
+import { useSetAtom } from "../editor-jotai";
+import { t } from "../i18n";
+import { CloseIcon } from "./icons";
+
+export type DialogSize = number | "small" | "regular" | "wide" | undefined;
+
+export interface DialogProps {
+ children: React.ReactNode;
+ className?: string;
+ size?: DialogSize;
+ onCloseRequest(): void;
+ title: React.ReactNode | false;
+ autofocus?: boolean;
+ closeOnClickOutside?: boolean;
+}
+
+function getDialogSize(size: DialogSize): number {
+ if (size && typeof size === "number") {
+ return size;
+ }
+
+ switch (size) {
+ case "small":
+ return 550;
+ case "wide":
+ return 1024;
+ case "regular":
+ default:
+ return 800;
+ }
+}
+
+export const Dialog = (props: DialogProps) => {
+ const [islandNode, setIslandNode] = useCallbackRefState<HTMLDivElement>();
+ const [lastActiveElement] = useState(document.activeElement);
+ const { id } = useExcalidrawContainer();
+ const isFullscreen = useDevice().viewport.isMobile;
+
+ useEffect(() => {
+ if (!islandNode) {
+ return;
+ }
+
+ const focusableElements = queryFocusableElements(islandNode);
+
+ setTimeout(() => {
+ if (focusableElements.length > 0 && props.autofocus !== false) {
+ // If there's an element other than close, focus it.
+ (focusableElements[1] || focusableElements[0]).focus();
+ }
+ });
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === KEYS.TAB) {
+ const focusableElements = queryFocusableElements(islandNode);
+ const { activeElement } = document;
+ const currentIndex = focusableElements.findIndex(
+ (element) => element === activeElement,
+ );
+
+ if (currentIndex === 0 && event.shiftKey) {
+ focusableElements[focusableElements.length - 1].focus();
+ event.preventDefault();
+ } else if (
+ currentIndex === focusableElements.length - 1 &&
+ !event.shiftKey
+ ) {
+ focusableElements[0].focus();
+ event.preventDefault();
+ }
+ }
+ };
+
+ islandNode.addEventListener("keydown", handleKeyDown);
+
+ return () => islandNode.removeEventListener("keydown", handleKeyDown);
+ }, [islandNode, props.autofocus]);
+
+ const setAppState = useExcalidrawSetAppState();
+ const setIsLibraryMenuOpen = useSetAtom(isLibraryMenuOpenAtom);
+
+ const onClose = () => {
+ setAppState({ openMenu: null });
+ setIsLibraryMenuOpen(false);
+ (lastActiveElement as HTMLElement).focus();
+ props.onCloseRequest();
+ };
+
+ return (
+ <Modal
+ className={clsx("Dialog", props.className, {
+ "Dialog--fullscreen": isFullscreen,
+ })}
+ labelledBy="dialog-title"
+ maxWidth={getDialogSize(props.size)}
+ onCloseRequest={onClose}
+ closeOnClickOutside={props.closeOnClickOutside}
+ >
+ <Island ref={setIslandNode}>
+ {props.title && (
+ <h2 id={`${id}-dialog-title`} className="Dialog__title">
+ <span className="Dialog__titleContent">{props.title}</span>
+ </h2>
+ )}
+ {isFullscreen && (
+ <button
+ className="Dialog__close"
+ onClick={onClose}
+ title={t("buttons.close")}
+ aria-label={t("buttons.close")}
+ type="button"
+ >
+ {CloseIcon}
+ </button>
+ )}
+ <div className="Dialog__content">{props.children}</div>
+ </Island>
+ </Modal>
+ );
+};
diff --git a/packages/excalidraw/components/DialogActionButton.scss b/packages/excalidraw/components/DialogActionButton.scss
new file mode 100644
index 0000000..54c44ba
--- /dev/null
+++ b/packages/excalidraw/components/DialogActionButton.scss
@@ -0,0 +1,47 @@
+.excalidraw {
+ .Dialog__action-button {
+ position: relative;
+ display: flex;
+ column-gap: 0.5rem;
+ align-items: center;
+ padding: 0.5rem 1.5rem;
+ border: 1px solid var(--default-border-color);
+ background-color: transparent;
+ height: 3rem;
+ border-radius: var(--border-radius-lg);
+ letter-spacing: 0.4px;
+ color: inherit;
+ font-family: inherit;
+ font-size: 0.875rem;
+ font-weight: 600;
+ user-select: none;
+
+ svg {
+ display: block;
+ width: 1rem;
+ height: 1rem;
+ }
+
+ &--danger {
+ background-color: var(--color-danger);
+ border-color: var(--color-danger);
+ color: #fff;
+ }
+
+ &--primary {
+ background-color: var(--color-primary);
+ border-color: var(--color-primary);
+ color: #fff;
+ }
+ }
+
+ &.theme--dark {
+ .Dialog__action-button--danger {
+ color: var(--color-gray-100);
+ }
+
+ .Dialog__action-button--primary {
+ color: var(--color-gray-100);
+ }
+ }
+}
diff --git a/packages/excalidraw/components/DialogActionButton.tsx b/packages/excalidraw/components/DialogActionButton.tsx
new file mode 100644
index 0000000..0c4f9d5
--- /dev/null
+++ b/packages/excalidraw/components/DialogActionButton.tsx
@@ -0,0 +1,46 @@
+import clsx from "clsx";
+import type { ReactNode } from "react";
+import "./DialogActionButton.scss";
+import Spinner from "./Spinner";
+
+interface DialogActionButtonProps {
+ label: string;
+ children?: ReactNode;
+ actionType?: "primary" | "danger";
+ isLoading?: boolean;
+}
+
+const DialogActionButton = ({
+ label,
+ onClick,
+ className,
+ children,
+ actionType,
+ type = "button",
+ isLoading,
+ ...rest
+}: DialogActionButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => {
+ const cs = actionType ? `Dialog__action-button--${actionType}` : "";
+
+ return (
+ <button
+ className={clsx("Dialog__action-button", cs, className)}
+ type={type}
+ aria-label={label}
+ onClick={onClick}
+ {...rest}
+ >
+ {children && (
+ <div style={isLoading ? { visibility: "hidden" } : {}}>{children}</div>
+ )}
+ <div style={isLoading ? { visibility: "hidden" } : {}}>{label}</div>
+ {isLoading && (
+ <div style={{ position: "absolute", inset: 0 }}>
+ <Spinner />
+ </div>
+ )}
+ </button>
+ );
+};
+
+export default DialogActionButton;
diff --git a/packages/excalidraw/components/ElementLinkDialog.scss b/packages/excalidraw/components/ElementLinkDialog.scss
new file mode 100644
index 0000000..9923230
--- /dev/null
+++ b/packages/excalidraw/components/ElementLinkDialog.scss
@@ -0,0 +1,87 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .ElementLinkDialog {
+ position: absolute;
+ top: var(--editor-container-padding);
+ left: var(--editor-container-padding);
+
+ z-index: var(--zIndex-modal);
+
+ border-radius: 10px;
+ padding: 1.5rem;
+
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ box-shadow: var(--shadow-island);
+ background-color: var(--island-bg-color);
+
+ @include isMobile {
+ left: 0;
+ margin-left: 0.5rem;
+ margin-right: 0.5rem;
+ width: calc(100% - 1rem);
+ box-sizing: border-box;
+ z-index: 5;
+ }
+
+ .ElementLinkDialog__header {
+ h2 {
+ margin-top: 0;
+ margin-bottom: 0.5rem;
+
+ @include isMobile {
+ font-size: 1.25rem;
+ }
+ }
+
+ p {
+ margin: 0;
+
+ @include isMobile {
+ font-size: 0.875rem;
+ }
+ }
+
+ margin-bottom: 1.5rem;
+
+ @include isMobile {
+ margin-bottom: 1rem;
+ }
+ }
+
+ .ElementLinkDialog__input {
+ display: flex;
+
+ .ElementLinkDialog__input-field {
+ flex: 1;
+ }
+
+ .ElementLinkDialog__remove {
+ color: $oc-red-9;
+ margin-left: 1rem;
+
+ .ToolIcon__icon {
+ width: 2rem;
+ height: 2rem;
+ }
+
+ .ToolIcon__icon svg {
+ color: $oc-red-6;
+ }
+ }
+ }
+
+ .ElementLinkDialog__actions {
+ display: flex;
+ justify-content: flex-end;
+ margin-top: 1.5rem;
+
+ @include isMobile {
+ font-size: 0.875rem;
+ margin-top: 1rem;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ElementLinkDialog.tsx b/packages/excalidraw/components/ElementLinkDialog.tsx
new file mode 100644
index 0000000..2ec3eaa
--- /dev/null
+++ b/packages/excalidraw/components/ElementLinkDialog.tsx
@@ -0,0 +1,174 @@
+import { TextField } from "./TextField";
+import type { AppProps, AppState, UIAppState } from "../types";
+import DialogActionButton from "./DialogActionButton";
+import { getSelectedElements } from "../scene";
+import {
+ defaultGetElementLinkFromSelection,
+ getLinkIdAndTypeFromSelection,
+} from "../element/elementLink";
+import { mutateElement } from "../element/mutateElement";
+import { useCallback, useEffect, useState } from "react";
+import { t } from "../i18n";
+import type { ElementsMap, ExcalidrawElement } from "../element/types";
+import { ToolButton } from "./ToolButton";
+import { TrashIcon } from "./icons";
+import { KEYS } from "../keys";
+
+import "./ElementLinkDialog.scss";
+import { normalizeLink } from "../data/url";
+
+const ElementLinkDialog = ({
+ sourceElementId,
+ onClose,
+ elementsMap,
+ appState,
+ generateLinkForSelection = defaultGetElementLinkFromSelection,
+}: {
+ sourceElementId: ExcalidrawElement["id"];
+ elementsMap: ElementsMap;
+ appState: UIAppState;
+ onClose?: () => void;
+ generateLinkForSelection: AppProps["generateLinkForSelection"];
+}) => {
+ const originalLink = elementsMap.get(sourceElementId)?.link ?? null;
+
+ const [nextLink, setNextLink] = useState<string | null>(originalLink);
+ const [linkEdited, setLinkEdited] = useState(false);
+
+ useEffect(() => {
+ const selectedElements = getSelectedElements(elementsMap, appState);
+ let nextLink = originalLink;
+
+ if (selectedElements.length > 0 && generateLinkForSelection) {
+ const idAndType = getLinkIdAndTypeFromSelection(
+ selectedElements,
+ appState as AppState,
+ );
+
+ if (idAndType) {
+ nextLink = normalizeLink(
+ generateLinkForSelection(idAndType.id, idAndType.type),
+ );
+ }
+ }
+
+ setNextLink(nextLink);
+ }, [
+ elementsMap,
+ appState,
+ appState.selectedElementIds,
+ originalLink,
+ generateLinkForSelection,
+ ]);
+
+ const handleConfirm = useCallback(() => {
+ if (nextLink && nextLink !== elementsMap.get(sourceElementId)?.link) {
+ const elementToLink = elementsMap.get(sourceElementId);
+ elementToLink &&
+ mutateElement(elementToLink, {
+ link: nextLink,
+ });
+ }
+
+ if (!nextLink && linkEdited && sourceElementId) {
+ const elementToLink = elementsMap.get(sourceElementId);
+ elementToLink &&
+ mutateElement(elementToLink, {
+ link: null,
+ });
+ }
+
+ onClose?.();
+ }, [sourceElementId, nextLink, elementsMap, linkEdited, onClose]);
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (
+ appState.openDialog?.name === "elementLinkSelector" &&
+ event.key === KEYS.ENTER
+ ) {
+ handleConfirm();
+ }
+
+ if (
+ appState.openDialog?.name === "elementLinkSelector" &&
+ event.key === KEYS.ESCAPE
+ ) {
+ onClose?.();
+ }
+ };
+
+ window.addEventListener("keydown", handleKeyDown);
+
+ return () => {
+ window.removeEventListener("keydown", handleKeyDown);
+ };
+ }, [appState, onClose, handleConfirm]);
+
+ return (
+ <div className="ElementLinkDialog">
+ <div className="ElementLinkDialog__header">
+ <h2>{t("elementLink.title")}</h2>
+ <p>{t("elementLink.desc")}</p>
+ </div>
+
+ <div className="ElementLinkDialog__input">
+ <TextField
+ value={nextLink ?? ""}
+ onChange={(value) => {
+ if (!linkEdited) {
+ setLinkEdited(true);
+ }
+ setNextLink(value);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === KEYS.ENTER) {
+ handleConfirm();
+ }
+ }}
+ className="ElementLinkDialog__input-field"
+ selectOnRender
+ />
+
+ {originalLink && nextLink && (
+ <ToolButton
+ type="button"
+ title={t("buttons.remove")}
+ aria-label={t("buttons.remove")}
+ label={t("buttons.remove")}
+ onClick={() => {
+ // removes the link from the input
+ // but doesn't update the element
+
+ // when confirmed, will remove the link from the element
+ setNextLink(null);
+ setLinkEdited(true);
+ }}
+ className="ElementLinkDialog__remove"
+ icon={TrashIcon}
+ />
+ )}
+ </div>
+
+ <div className="ElementLinkDialog__actions">
+ <DialogActionButton
+ label={t("buttons.cancel")}
+ onClick={() => {
+ onClose?.();
+ }}
+ style={{
+ marginRight: 10,
+ }}
+ />
+
+ <DialogActionButton
+ label={t("buttons.confirm")}
+ onClick={handleConfirm}
+ actionType="primary"
+ />
+ </div>
+ </div>
+ );
+};
+
+export default ElementLinkDialog;
diff --git a/packages/excalidraw/components/ErrorDialog.tsx b/packages/excalidraw/components/ErrorDialog.tsx
new file mode 100644
index 0000000..74d265f
--- /dev/null
+++ b/packages/excalidraw/components/ErrorDialog.tsx
@@ -0,0 +1,40 @@
+import React, { useState } from "react";
+import { t } from "../i18n";
+
+import { Dialog } from "./Dialog";
+import { useExcalidrawContainer } from "./App";
+
+export const ErrorDialog = ({
+ children,
+ onClose,
+}: {
+ children?: React.ReactNode;
+ onClose?: () => void;
+}) => {
+ const [modalIsShown, setModalIsShown] = useState(!!children);
+ const { container: excalidrawContainer } = useExcalidrawContainer();
+
+ const handleClose = React.useCallback(() => {
+ setModalIsShown(false);
+
+ if (onClose) {
+ onClose();
+ }
+ // TODO: Fix the A11y issues so this is never needed since we should always focus on last active element
+ excalidrawContainer?.focus();
+ }, [onClose, excalidrawContainer]);
+
+ return (
+ <>
+ {modalIsShown && (
+ <Dialog
+ size="small"
+ onCloseRequest={handleClose}
+ title={t("errorDialog.title")}
+ >
+ <div style={{ whiteSpace: "pre-wrap" }}>{children}</div>
+ </Dialog>
+ )}
+ </>
+ );
+};
diff --git a/packages/excalidraw/components/ExcalidrawLogo.scss b/packages/excalidraw/components/ExcalidrawLogo.scss
new file mode 100644
index 0000000..e59e8a9
--- /dev/null
+++ b/packages/excalidraw/components/ExcalidrawLogo.scss
@@ -0,0 +1,73 @@
+.excalidraw {
+ .ExcalidrawLogo {
+ --logo-icon--xs: 2rem;
+ --logo-text--xs: 1.5rem;
+
+ --logo-icon--small: 2.5rem;
+ --logo-text--small: 1.75rem;
+
+ --logo-icon--normal: 3rem;
+ --logo-text--normal: 2.2rem;
+
+ --logo-icon--large: 90px;
+ --logo-text--large: 65px;
+
+ display: flex;
+ align-items: center;
+
+ svg {
+ flex: 0 0 auto;
+ }
+
+ .ExcalidrawLogo-icon {
+ width: auto;
+ color: var(--color-logo-icon);
+ }
+
+ .ExcalidrawLogo-text {
+ margin-left: 0.75rem;
+ width: auto;
+ color: var(--color-logo-text);
+ }
+
+ &.is-xs {
+ .ExcalidrawLogo-icon {
+ height: var(--logo-icon--xs);
+ }
+
+ .ExcalidrawLogo-text {
+ height: var(--logo-text--xs);
+ }
+ }
+
+ &.is-small {
+ .ExcalidrawLogo-icon {
+ height: var(--logo-icon--small);
+ }
+
+ .ExcalidrawLogo-text {
+ height: var(--logo-text--small);
+ }
+ }
+
+ &.is-normal {
+ .ExcalidrawLogo-icon {
+ height: var(--logo-icon--normal);
+ }
+
+ .ExcalidrawLogo-text {
+ height: var(--logo-text--normal);
+ }
+ }
+
+ &.is-large {
+ .ExcalidrawLogo-icon {
+ height: var(--logo-icon--large);
+ }
+
+ .ExcalidrawLogo-text {
+ height: var(--logo-text--large);
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ExcalidrawLogo.tsx b/packages/excalidraw/components/ExcalidrawLogo.tsx
new file mode 100644
index 0000000..01d07fc
--- /dev/null
+++ b/packages/excalidraw/components/ExcalidrawLogo.tsx
@@ -0,0 +1,69 @@
+import "./ExcalidrawLogo.scss";
+
+const LogoIcon = () => (
+ <svg
+ viewBox="0 0 40 40"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className="ExcalidrawLogo-icon"
+ >
+ <path
+ d="M39.9 32.889a.326.326 0 0 0-.279-.056c-2.094-3.083-4.774-6-7.343-8.833l-.419-.472a.212.212 0 0 0-.056-.139.586.586 0 0 0-.167-.111l-.084-.083-.056-.056c-.084-.167-.28-.278-.475-.167-.782.39-1.507.973-2.206 1.528-.92.722-1.842 1.445-2.708 2.25a8.405 8.405 0 0 0-.977 1.028c-.14.194-.028.361.14.444-.615.611-1.23 1.223-1.843 1.861a.315.315 0 0 0-.084.223c0 .083.056.166.111.194l1.09.833v.028c1.535 1.528 4.244 3.611 7.12 5.861.418.334.865.667 1.284 1 .195.223.39.473.558.695.084.11.28.139.391.055.056.056.14.111.196.167a.398.398 0 0 0 .167.056.255.255 0 0 0 .224-.111.394.394 0 0 0 .055-.167c.029 0 .028.028.056.028a.318.318 0 0 0 .224-.084l5.082-5.528a.309.309 0 0 0 0-.444Zm-14.63-1.917a.485.485 0 0 0 .111.14c.586.5 1.2 1 1.843 1.555l-2.569-1.945-.251-.166c-.056-.028-.112-.084-.168-.111l-.195-.167.056-.056.055-.055.112-.111c.866-.861 2.346-2.306 3.1-3.028-.81.805-2.43 3.167-2.095 3.944Zm8.767 6.89-2.122-1.612a44.713 44.713 0 0 0-2.625-2.5c1.145.861 2.122 1.611 2.262 1.75 1.117.972 1.06.806 1.815 1.445l.921.666a1.06 1.06 0 0 1-.251.25Zm.558.416-.056-.028c.084-.055.168-.111.252-.194l-.196.222ZM1.089 5.75c.055.361.14.722.195 1.056.335 1.833.67 3.5 1.284 4.75l.252.944c.084.361.223.806.363.917 1.424 1.25 3.602 3.11 5.947 4.889a.295.295 0 0 0 .363 0s0 .027.028.027a.254.254 0 0 0 .196.084.318.318 0 0 0 .223-.084c2.988-3.305 5.221-6.027 6.813-8.305.112-.111.14-.278.14-.417.111-.111.195-.25.307-.333.111-.111.111-.306 0-.39l-.028-.027c0-.055-.028-.139-.084-.167-.698-.666-1.2-1.138-1.731-1.638-.922-.862-1.871-1.75-3.881-3.75l-.028-.028c-.028-.028-.056-.056-.112-.056-.558-.194-1.703-.389-3.127-.639C6.087 2.223 3.21 1.723.614.944c0 0-.168 0-.196.028l-.083.084c-.028.027-.056.055-.224.11h.056-.056c.028.167.028.278.084.473 0 .055.112.5.112.555l.782 3.556Zm15.496 3.278-.335-.334c.084.112.196.195.335.334Zm-3.546 4.666-.056.056c0-.028.028-.056.056-.056Zm-2.038-10c.168.167.866.834 1.033.973-.726-.334-2.54-1.167-3.379-1.445.838.167 1.983.334 2.346.472ZM1.424 2.306c.419.722.754 3.222 1.089 5.666-.196-.778-.335-1.555-.503-2.278-.251-1.277-.503-2.416-.838-3.416.056 0 .14 0 .252.028Zm-.168-.584c-.112 0-.223-.028-.307-.028 0-.027 0-.055-.028-.055.14 0 .223.028.335.083Zm-1.089.222c0-.027 0-.027 0 0ZM39.453 1.333c.028-.11-.558-.61-.363-.639.42-.027.42-.666 0-.666-.558.028-1.144.166-1.675.25-.977.194-1.982.389-2.96.61-2.205.473-4.383.973-6.561 1.557-.67.194-1.424.333-2.066.666-.224.111-.196.333-.084.472-.056.028-.084.028-.14.056-.195.028-.363.056-.558.083-.168.028-.252.167-.224.334 0 .027.028.083.028.11-1.173 1.556-2.485 3.195-3.909 4.945-1.396 1.611-2.876 3.306-4.356 5.056-4.719 5.5-10.052 11.75-15.943 17.25a.268.268 0 0 0 0 .389c.028.027.056.055.084.055-.084.084-.168.14-.252.222-.056.056-.084.111-.084.167a.605.605 0 0 0-.111.139c-.112.111-.112.305.028.389.111.11.307.11.39-.028.029-.028.029-.056.056-.056a.44.44 0 0 1 .615 0c.335.362.67.723.977 1.028l-.698-.583c-.112-.111-.307-.083-.39.028-.113.11-.085.305.027.389l7.427 6.194c.056.056.112.056.196.056s.14-.028.195-.084l.168-.166c.028.027.083.027.111.027.084 0 .14-.027.196-.083 10.052-10.055 18.15-17.639 27.42-24.417.083-.055.111-.166.111-.25.112 0 .196-.083.251-.194 1.704-5.194 2.039-9.806 2.15-12.083v-.028c0-.028.028-.056.028-.083.028-.056.028-.084.028-.084a1.626 1.626 0 0 0-.111-1.028ZM21.472 9.5c.446-.5.893-1.028 1.34-1.5-2.876 3.778-7.65 9.583-14.408 16.5 4.607-5.083 9.242-10.333 13.068-15ZM5.193 35.778h.084-.084Zm3.462 3.194c-.027-.028-.027-.028 0-.028v.028Zm4.16-3.583c.224-.25.448-.472.699-.722 0 0 0 .027.028.027-.252.223-.475.445-.726.695Zm1.146-1.111c.14-.14.279-.334.446-.5l.028-.028c1.648-1.694 3.351-3.389 5.082-5.111l.028-.028c.419-.333.921-.694 1.368-1.028a379.003 379.003 0 0 0-6.952 6.695ZM24.794 6.472c-.921 1.195-1.954 2.778-2.82 4.028-2.736 3.944-11.532 13.583-11.727 13.75a1976.983 1976.983 0 0 1-8.042 7.639l-.167.167c-.14-.167-.14-.417.028-.556C14.49 19.861 22.03 10.167 25.074 5.917c-.084.194-.14.36-.28.555Zm4.83 5.695c-1.116-.64-1.646-1.64-1.34-2.611l.084-.334c.028-.083.084-.194.14-.277.307-.5.754-.917 1.257-1.167.027 0 .055 0 .083-.028-.028-.056-.028-.139-.028-.222.028-.167.14-.278.335-.278.335 0 1.369.306 1.76.639.111.083.223.194.335.305.14.167.363.445.474.667.056.028.112.306.196.445.056.222.111.472.084.694-.028.028 0 .194-.028.194a2.668 2.668 0 0 1-.363 1.028c-.028.028-.028.056-.056.084l-.028.027c-.14.223-.335.417-.53.556-.643.444-1.369.583-2.095.389 0 0-.195-.084-.28-.111Zm8.154-.834a39.098 39.098 0 0 1-.893 3.167c0 .028-.028.083 0 .111-.056 0-.084.028-.14.056-2.206 1.61-4.356 3.305-6.506 5.028 1.843-1.64 3.686-3.306 5.613-4.945.558-.5.949-1.139 1.06-1.861l.28-1.667v-.055c.14-.334.67-.195.586.166Z"
+ fill="currentColor"
+ />
+ </svg>
+);
+
+const LogoText = () => (
+ <svg
+ viewBox="0 0 450 55"
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ className="ExcalidrawLogo-text"
+ >
+ <path
+ d="M429.27 96.74c2.47-1.39 4.78-3.02 6.83-4.95 1.43-1.35 2.73-2.86 3.81-4.51-.66.9-1.4 1.77-2.23 2.59-2.91 2.84-5.72 5.09-8.42 6.87h.01ZM343.6 69.36c.33 3.13.58 6.27.79 9.4.09 1.37.18 2.75.25 4.12-.12-4.46-.27-8.93-.5-13.39-.11-2.08-.24-4.16-.4-6.24-.06 1.79-.11 3.85-.13 6.11h-.01ZM378.47 98.34c.01-.37.07-1.13.01-6.51-.11 1.9-.22 3.81-.31 5.71-.07 1.42-.22 2.91-.16 4.35.39.03.78.07 1.17.1-.92-.85-.76-2.01-.72-3.66l.01.01ZM344.09 86.12c-.09-2.41-.22-4.83-.39-7.24v12.21c.15-.05.32-.09.47-.14.05-1.61-.03-3.23-.09-4.83h.01ZM440.69 66.79c-.22-.34-.45-.67-.69-.99-3.71-4.87-9.91-7.14-15.65-8.55-1.05-.26-2.12-.49-3.18-.71 2.29.59 4.48 1.26 6.64 2.02 7.19 2.54 10.57 5.41 12.88 8.23ZM305.09 72.46l1.2 3.6c.84 2.53 1.67 5.06 2.46 7.61.24.78.5 1.57.73 2.36.22-.04.44-.08.67-.12a776.9 776.9 0 0 1-5.01-13.57c-.02.04-.03.09-.05.13v-.01ZM345.49 90.25v.31c1.48-.42 3.05-.83 4.66-1.2-1.56.25-3.12.52-4.66.89ZM371.02 90.22c0-.57-.04-1.14-.11-1.71-.06-.02-.12-.04-.19-.05-.21-.05-.43-.08-.65-.11.42.16.74.88.95 1.87ZM398.93 54.23c-.13 0-.27-.01-.4-.02l.03.4c.11-.15.23-.27.37-.38ZM401.57 62.28v-.15c-1.22-.24-2.86-.61-3.23-1.25-.09-.15-.18-.51-.27-.98-.09.37-.2.73-.33 1.09 1.24.56 2.52.98 3.83 1.29ZM421.73 88.68c-2.97 1.65-6.28 3.12-9.69 3.68v.18c4.72-.14 11.63-3.85 16.33-8.38-2.04 1.75-4.33 3.24-6.63 4.53l-.01-.01ZM411.28 80.92c-.05-1.2-.09-2.4-.15-3.6-.21 5.66-.46 11.38-.47 14.51.24-.02.48-.04.71-.07.15-3.61.05-7.23-.09-10.83v-.01Z"
+ transform="translate(-144.023 -51.76)"
+ />
+ <path
+ d="M425.38 67.41c-3.5-1.45-7.19-2.57-14.06-3.62.09 1.97.06 4.88-.03 8.12.03.04.06.09.06.15.19 1.36.28 2.73.37 4.1.25 3.77.39 7.55.41 11.33 0 1.38-.01 2.76-.07 4.13 1.4-.25 2.78-.65 4.12-1.15 4.07-1.5 7.94-3.78 11.28-6.54 2.33-1.92 5.13-4.49 5.88-7.58.63-3.53-2.45-6.68-7.97-8.96l.01.02ZM411.35 92.53v-.06l-.34.03c.11.01.22.03.34.03ZM314.26 64.06c-.23-.59-.47-1.17-.7-1.75.57 1.62 1.11 3.25 1.6 4.9l.15.54 2.35 6.05c.32.82.66 1.64.98 2.46-1.38-4.1-2.83-8.17-4.39-12.2h.01ZM156.82 103.07c-.18.13-.38.23-.58.33 1.32-.03 2.66-.2 3.93-.34.86-.09 1.72-.22 2.58-.33-2.12.1-4.12.17-5.94.34h.01ZM210.14 68.88s.03.04.05.07c.18-.31.39-.64.58-.96-.21.3-.42.6-.64.89h.01ZM201.65 82.8c-.5.77-1.02 1.56-1.49 2.37 1.11-1.55 2.21-3.1 3.2-4.59-.23.23-.49.51-.75.79-.32.47-.65.95-.96 1.43ZM194.03 98.66c-.33-.4-.65-.84-1.05-1.17-.24-.2-.07-.49.17-.56-.23-.26-.42-.5-.63-.75 1.51-2.55 3.93-5.87 6.4-9.28-.17-.08-.29-.28-.2-.49.04-.09.09-.17.13-.26-1.21 1.78-2.42 3.55-3.61 5.33-.87 1.31-1.74 2.64-2.54 4-.29.5-.63 1.04-.87 1.61.81.65 1.63 1.27 2.47 1.88-.09-.11-.18-.21-.27-.32v.01ZM307.79 82.93c-1-3.17-2.05-6.32-3.1-9.48-1.62 4.08-3.69 9.17-6.16 15.19 3.32-1.04 6.77-1.87 10.27-2.5-.32-1.08-.67-2.15-1.01-3.21ZM149.5 80.7c.05-1.71.04-3.43 0-5.14-.1 2.26-.16 4.51-.22 6.77-.02.73-.03 1.46-.04 2.19.14-1.27.2-2.55.24-3.82h.02ZM228.98 98.3c.39 1.25.91 3.03.94 3.91.06-.03.12-.07.17-.1.08-1.29-.55-2.65-1.11-3.81ZM307.72 53.36c.81.5 1.53 1.04 2.07 1.49-.38-.8-.78-1.58-1.21-2.35-.17.03-.34.06-.51.11-.43.12-.86.26-1.29.41.35-.01.53.1.94.34ZM283.69 96.14c3.91-7.25 6.89-13.35 8.88-18.15l1.1-2.66c-1.27 2.64-2.56 5.27-3.83 7.9-1.53 3.15-3.06 6.31-4.58 9.47-.87 1.81-1.76 3.62-2.54 5.47.04.02.07.04.11.07.05.05.1.09.15.14.05-.73.27-1.48.71-2.24ZM289.92 103.23s-.04.01-.05.03c0-.02.04-.03.05-.04.05-.05.11-.1.16-.15l.21-.21c-.55 0-1.5-.27-2.55-.72.4.26.8.51 1.22.74.24.13.48.26.73.37.05.02.1.03.14.05a.27.27 0 0 1 .08-.07h.01ZM269.23 68.49c-.39-.19-.82-.48-1.33-.87-3.06-1.56-6.31-2.78-9.36-2.35-3.5.49-5.7 1.11-7.74 2.44 5.71-2.6 12.82-2.07 18.44.79l-.01-.01ZM177.87 53.69l1.06.03c-.96-.22-2-.25-2.89-.3-4.95-.26-9.99.33-14.86 1.19-2.44.43-4.88.95-7.28 1.59 9.09-1.76 15.69-2.77 23.97-2.51ZM219.85 55.51c-.18.12-.36.27-.56.45-.45.53-.86 1.11-1.26 1.66-1.91 2.61-3.71 5.31-5.57 7.95l-.12.18 8.05-10.11c-.18-.05-.36-.1-.55-.13h.01ZM510.71 54.1c.12-.15.29-.3.53-.45.69-.4 3.72-.63 5.87-.74-.36-.02-.73-.04-1.09-.05-1.84-.03-3.67.09-5.49.35.05.3.12.59.18.88v.01ZM510.76 86.02c1.37-3.07 2.49-6.27 3.57-9.46.55-1.64 1.12-3.3 1.6-4.97-1.59 4.01-3.67 9.14-6.2 15.3.24-.08.5-.14.74-.22.1-.22.19-.44.29-.65ZM566.95 75.76c.11-.02.23.03.31.11-.05-.13-.09-.26-.14-.39-.05.09-.11.18-.17.28ZM511.33 86.41c3.08-.89 6.24-1.62 9.46-2.14-1.51-3.98-2.98-7.96-4.39-11.87-.05.15-.09.31-.14.46-1.02 3.32-2.15 6.61-3.39 9.85-.48 1.25-.98 2.49-1.53 3.7h-.01ZM578.24 74.45c.11-.44.23-.87.35-1.31-.31.7-.64 1.39-.97 2.08.09.21.19.4.28.61.12-.46.23-.92.35-1.38h-.01ZM520.62 53.11c-.09 0-.18-.01-.28-.02.38.34.29 1.08.93 2.53l6.65 17.15c2.2 5.68 4.69 11.36 7.41 16.87l1.06 2.17c-2.95-7.05-5.92-14.08-8.87-21.13-1.58-3.79-3.16-7.59-4.7-11.4-.78-1.92-1.73-3.89-2.25-5.91-.03-.1 0-.19.04-.26h.01ZM578.78 77.87c1.45-5.77 3.07-10.43 3.58-13.36.05-.34.16-.88.31-1.55-.67 1.79-1.37 3.56-2.08 5.33-.12.43-.23.86-.35 1.29-.65 2.43-1.29 4.86-1.9 7.3.14.33.29.65.43 1l.01-.01ZM545.3 94.66c.02-.44.03-.83.05-1.12.02-1.01.05-2.02.11-3.02.03-6.66-.46-14.33-1.46-22.8-.13-.42-.27-1.24-.56-2.89 0-.02 0-.04-.01-.06.62 6.61.95 13.25 1.32 19.87.17 3.08.33 6.16.52 9.23.02.25.03.52.04.78l-.01.01ZM580.77 102.81c.13.2.27.38.37.49.27-.11.53-.22.8-.32-.43.09-.82.05-1.17-.16v-.01ZM530.48 104.07h.33c-.36-.13-.71-.32-1.04-.56.14.24.3.47.45.7.06-.08.14-.13.26-.13v-.01ZM542.63 58.82c.06.23.11.47.15.71.14-.33.36-.62.7-.86-.28.05-.57.11-.85.15ZM583.81 57.87c.15-.7.29-1.41.42-2.11-.14.45-.28.9-.42 1.34-.46 1.44-.89 2.89-1.31 4.34.44-1.19.88-2.37 1.31-3.57ZM523.62 91.48c-4.66 1.17-9.05 2.89-14.02 5.27 4.65-1.84 9.48-3.29 14.28-4.63-.09-.22-.17-.41-.26-.64ZM460.64 78.3c-.04-2.9-.11-5.81-.28-8.71-.1-1.68-.17-3.43-.5-5.09-.07.02-.14.03-.2.05.3 6.54.45 12.17.51 17.12.17-.07.34-.14.51-.2 0-1.06-.01-2.11-.03-3.17h-.01ZM470.63 63.24c-3.38-.26-6.81.32-10.1 1.1.41 2.01.47 4.14.57 6.18.18 3.55.25 7.11.27 10.67 3.31-1.38 6.5-3.12 9.3-5.35 1.96-1.56 3.86-3.41 5.02-5.66.73-1.41 1.19-3.22.26-4.65-1.09-1.7-3.46-2.14-5.32-2.29ZM460.29 63.68c1-.24 2.01-.46 3.04-.65-1.15.16-2.37.38-3.71.69v.13c.07-.02.15-.04.22-.05.11-.13.3-.18.45-.11v-.01ZM457.24 100.96c.43-.03.86-.07 1.29-.11.14-.49.27-.99.38-1.49-.44.7-1 1.23-1.67 1.6ZM482.88 104.98c-.18.23-.36.38-.55.47.14.09.27.19.4.28a70.76 70.76 0 0 0 4.37-4.63c.76-.89 1.52-1.81 2.19-2.77-.3-.27-.61-.53-.92-.79-.07 1.94-4.62 6.32-5.49 7.45v-.01Z"
+ transform="translate(-144.023 -51.76)"
+ />
+ <path
+ d="M474.36 63.31c-.4-.16-.84-.27-1.29-.37 1.56.42 3.08 1.22 3.76 2.74.62 1.4.32 2.95-.28 4.32.7-1.22.94-2.34.74-3.47-.24-1.33-1.19-2.54-2.93-3.21v-.01ZM477.34 89.18c-1.2-.81-2.4-1.62-3.6-2.42-.14.1-.26.19-.4.29 1.4.67 2.73 1.39 4 2.13ZM465.88 93.85c.37.25.74.5 1.1.75.46.32.92.65 1.38.97-1.57-1.2-2.01-1.61-2.49-1.72h.01ZM574.92 90.06c-2.28-5.21-4.93-11.13-5.67-12.26-.1-.15-1.57-3.01-1.63-3.08 0 0-.01.02-.02.02.4 1.37 1.09 2.69 1.65 3.99 2.14 4.95 4.36 9.86 6.67 14.73.6 1.26 1.21 2.52 1.83 3.78-.75-2.01-1.64-4.45-2.83-7.18ZM448.73 65.29c.1.2.22.38.34.57.22-.02.43-.06.65-.08v-.08c-.14-.05-.25 0-.99-.41ZM460.16 94.81c-.02.31-.06.59-.1.89-.03 1.71-.33 3.43-.79 5.07.15-.02.3-.03.45-.05.01-.04.02-.08.03-.11.09-.34.15-.69.2-1.03.17-1.07.25-2.16.33-3.24.05-.69.08-1.39.12-2.08-.27.1-.27.26-.24.57v-.02Z"
+ transform="translate(-144.023 -51.76)"
+ />
+ <path
+ d="m328.67 98.12-3.22-6.58c-1.29-2.63-2.53-5.29-3.72-7.97-.25-.85-.52-1.69-.79-2.53-.81-2.57-1.67-5.12-2.55-7.67-1.92-5.53-3.9-11.08-6.32-16.41-.72-1.58-1.46-3.44-2.63-4.79-.03-.17-.16-.29-.34-.36a.282.282 0 0 0-.23-.04c-.06-.01-.12 0-.18.01-.74.06-1.5.38-2.19.61-2.22.77-4.4 1.64-6.63 2.38-.03-.08-.06-.16-.09-.25-.15-.42-.82-.24-.67.19.03.09.07.19.1.28l-.18.06c-.36.11-.28.6 0 .68.18 1.18.63 2.36.98 3.49.03.09.06.17.08.26-.08.23-.17.46-.24.64-.37.98-.79 1.94-1.21 2.9-1.27 2.89-2.62 5.75-3.98 8.6-3.18 6.67-6.44 13.31-9.64 19.97-1.08 2.25-2.2 4.5-3.15 6.81-.13.32.24.5.5.37 1.34 1.33 2.84 2.5 4.4 3.57.65.44 1.31.87 2.01 1.24.4.22.86.48 1.33.5.24.01.35-.19.33-.37.11-.1.21-.21.28-.28.41-.41.81-.84 1.2-1.26.85-.92 1.69-1.87 2.5-2.84 6.31-2.34 12.6-4.31 18.71-5.84 2.14 5.3 3.43 8.43 3.97 9.58.55 1.05 1.15 1.88 1.82 2.52 1.32.56 6.96-.03 9.23-1.96.87-1.28 1.19-2.67.93-4.15-.09-.5-.22-.95-.4-1.33l-.01-.03Zm-20.09-45.61c.43.77.83 1.56 1.21 2.35-.54-.45-1.27-.99-2.07-1.49-.42-.24-.6-.35-.94-.34.43-.15.85-.29 1.29-.41.17-.05.34-.08.51-.11Zm-25.86 45.66c.78-1.85 1.67-3.66 2.54-5.47 1.51-3.16 3.05-6.31 4.58-9.47 1.28-2.63 2.56-5.26 3.83-7.9l-1.1 2.66c-1.99 4.79-4.97 10.9-8.88 18.15-.43.76-.66 1.51-.71 2.24-.05-.05-.1-.09-.15-.14a.259.259 0 0 0-.11-.07Zm6.24 4.71c-.42-.23-.82-.48-1.22-.74 1.05.45 2 .72 2.55.72l-.21.21c-.05.05-.11.1-.16.15-.01.01-.04.03-.05.04 0-.02.03-.02.05-.03a.27.27 0 0 0-.08.07c-.05-.02-.1-.03-.14-.05-.25-.1-.49-.24-.73-.37h-.01Zm15.73-29.43c1.05 3.15 2.1 6.31 3.1 9.48.34 1.06.69 2.13 1.01 3.21-3.5.63-6.95 1.46-10.27 2.5 2.48-6.03 4.54-11.11 6.16-15.19Zm4.79 12.57c-.23-.79-.49-1.58-.73-2.36-.79-2.54-1.63-5.08-2.46-7.61l-1.2-3.6c.02-.04.04-.09.05-.13 1.6 4.45 3.28 9 5.01 13.57l-.67.12v.01Zm5.83-18.27-.15-.54c-.49-1.64-1.03-3.28-1.6-4.9.23.58.47 1.17.7 1.75 1.56 4.03 3.01 8.1 4.39 12.2-.33-.82-.67-1.64-.98-2.46l-2.35-6.05h-.01ZM390.43 79.37c-.13-10.43-.22-17.5-.24-19.97-.24-1.6.21-2.88-.65-3.65-.14-.13-.32-.23-.52-.32h.03c.45 0 .45-.69 0-.7-1.75-.03-3.5-.04-5.25-.14-1.38-.08-2.76-.21-4.15-.31-.07 0-.12.01-.17.04-.21-.07-.47.03-.45.31l.03.45c-.11.14-.19.3-.22.5-.21 1.26-.32 13.67-.36 23.59-.32 5.79-.67 11.57-.97 17.36-.09 1.73-.29 3.54-.21 5.3-.39.02-.38.64.04.69v.12c.05.44.74.45.7 0v-.06c1.1.09 2.2.21 3.3.3 1.14.19 2.44.2 3.29.17 1.73-.05 2.92-.05 3.8-.37.45-.05.9-.11 1.35-.17.44-.06.25-.73-.19-.67h-.01c.24-.32.45-.72.62-1.25.66-1.84.41-6.36.34-11.33l-.13-9.9.02.01Zm-12.26 18.17c.09-1.91.2-3.81.31-5.71.06 5.38 0 6.14-.01 6.51-.05 1.65-.21 2.81.72 3.66-.39-.04-.78-.07-1.17-.1-.06-1.44.09-2.93.16-4.35l-.01-.01ZM588.97 53.85c-2.06-.25-3.17-.51-3.76-.6a.3.3 0 0 1 .04-.08c.22-.39-.39-.75-.6-.35-.56 1.02-.9 2.19-1.26 3.29-.61 1.88-1.17 3.78-1.72 5.68-.63 2.19-1.24 4.39-1.83 6.59-.81 2.03-1.67 4.05-2.61 6.03-1.7-3.64-3.11-6.04-4.03-7.57-2.26-3.74-2.85-5.48-3.57-6.08l.31-.09c.43-.12.25-.8-.19-.67-1.06.3-2.12.6-3.17.95-.93.32-1.85.69-2.76 1.07-.13.05-.19.16-.22.27-.04.02-.08.05-.11.07-.04-.06-.07-.12-.11-.18a.354.354 0 0 0-.48-.12c-.16.09-.22.32-.13.48l.33.54c0 .09.02.18.06.28.51 1.16.78 1.38.72 1.47-2.42 3.44-5.41 7.86-6.2 9.1-1.27 1.97-2.01 3.14-2.45 3.84l-.91-6.56-.43-4.1c-.19-1.85-.37-3.23-.53-4.13-.19-1.1-.3-2.15-.45-3.16-.2-1.36-.29-2.06-.47-2.42h.04c.45.02.45-.68 0-.7-3.43-.16-6.81.94-10.17 1.48-.24-.22-.73-.04-.58.32.24.59.33 1.25.43 1.87.17 1.06.29 2.13.4 3.2.32 3.09.53 6.2.74 9.3.44 6.75.77 13.51 1.17 20.26.11 1.95.13 3.96.46 5.89.05.3.37.31.55.14.74 1.71 2.87 1.27 6.13 1.27 1.34 0 2.39.04 2.99-.11.02.32.48.53.63.18 3.61-8.26 7.41-16.46 12.05-24.2.03-.05.04-.1.05-.15.3.73.64 1.45.94 2.16.97 2.26 1.97 4.52 2.98 6.76 2.26 5.03 4.54 10.07 7.09 14.96.47.9.94 1.79 1.47 2.65.2.32.4.67.66.96-.18.25 0 .68.34.54.91-.38 1.82-.75 2.76-1.07 1.04-.35 2.11-.65 3.17-.95.39-.11.28-.66-.07-.68.62-.4.95-.96.87-1.91-.3-3.34.72-7.47.86-8.52l2.14-11.43c1.75-10.74 3.13-17.51 3.23-20.86.02-.49.08-2.84.13-3.24.17-1.25.48-1-4.96-1.65l.03-.02Zm-46.19 5.67c-.04-.24-.09-.48-.15-.71l.85-.15c-.34.24-.56.53-.7.86Zm1.95 25.12c-.36-6.63-.7-13.26-1.32-19.87 0 .02 0 .04.01.06.29 1.65.44 2.47.56 2.89 1 8.46 1.5 16.14 1.46 22.8-.06.99-.1 2-.11 3.02-.01.29-.03.68-.05 1.12-.01-.26-.03-.53-.04-.78-.19-3.08-.35-6.16-.52-9.23l.01-.01Zm36.4 18.66c-.11-.11-.24-.29-.37-.49.35.21.74.26 1.17.16-.27.11-.53.22-.8.32v.01Zm-.89-33.72c.12-.43.23-.86.35-1.29.71-1.77 1.41-3.55 2.08-5.33-.15.68-.26 1.22-.31 1.55-.5 2.94-2.13 7.59-3.58 13.36-.15-.35-.29-.66-.43-1 .61-2.44 1.25-4.87 1.9-7.3l-.01.01Zm3.56-12.48c.14-.44.28-.89.42-1.34-.13.7-.27 1.41-.42 2.11-.43 1.19-.86 2.38-1.31 3.57.42-1.45.85-2.9 1.31-4.34Zm-5.22 16.05c-.11.44-.23.87-.35 1.31-.12.46-.23.92-.35 1.38-.1-.22-.19-.4-.28-.61.34-.69.66-1.38.97-2.08h.01Zm-11.64 2.62c.06-.1.12-.19.17-.28.05.13.09.26.14.39a.398.398 0 0 0-.31-.11Zm2.3 2.98c-.56-1.3-1.25-2.63-1.65-3.99 0 0 .01-.02.02-.02.06.08 1.52 2.93 1.63 3.08.73 1.13 3.38 7.04 5.67 12.26 1.2 2.73 2.08 5.17 2.83 7.18-.62-1.25-1.23-2.51-1.83-3.78-2.31-4.87-4.53-9.78-6.67-14.73ZM275.92 87.03c-1.06-2.18-1.13-3.45-2.44-2.93-1.52.57-2.94 1.3-4.5 2.1-1.4.72-2.68 1.44-3.92 2.12.01-.25-.24-.5-.51-.34-4.8 2.93-12.41 4.7-17.28 1.31-1.98-1.77-3.32-4.15-3.97-5.78-.29-.95-.49-1.94-.63-2.93-.14-3.34 1.58-6.53 3.9-9.12.8-.79 1.68-1.51 2.66-2.12 3.7-2.3 8.22-3.07 12.51-2.51 2.71.35 5.32 1.24 7.71 2.55.39.22.75-.39.35-.6-.18-.1-.37-.18-.55-.27.56.27 1.03.33 1.51.19l-.48.39c-.15.11-.23.3-.13.48.09.15.33.24.48.13 1.3-.97 2.46-2.09 3.45-3.37.37-.29.64-.6.65-.97v-.02c.08-.33-.03-.7-.21-1.08-.31-.87-.98-2.01-2.19-3.26-2.43-2.52-3.79-3.45-5.68-4.26-1.14-.49-3.12-1.06-4.42-1.23-3.28-.42-10.64-1.21-18.18 4.11-7.74 5.46-11.94 12.3-12.23 20.61-.08 2.06.04 3.98.34 5.71.74 4.18 2.57 8 5.44 11.34 4.26 4.99 9.76 7.52 16.34 7.52 4.85 0 9.69-1.77 14.89-4.62.23-.12.45-.23.68-.35 2.19-1.1 4.37-2.23 6.46-3.5.49-.3 1.03-.61 1.5-.98 1.47-.87 1.11-1.12.49-2.95-.39-1.14-.76-2.7-2.06-5.36l.02-.01Zm-17.38-21.76c3.05-.42 6.31.79 9.36 2.35.51.39.94.68 1.33.87-5.61-2.86-12.72-3.39-18.44-.79 2.05-1.33 4.24-1.95 7.74-2.44l.01.01ZM443.67 72.67c-.4-2.2-1.15-4.33-2.37-6.22-1.49-2.32-3.58-4.19-5.91-5.64-6.17-3.81-13.75-5.11-20.83-6.01-3.23-.41-6.47-.69-9.72-.92l-1.39-.12c-.85-.07-1.52-.1-2.05-.1-1.08-.06-2.17-.12-3.25-.17-.08 0-.14.02-.19.05-.1.05-.18.14-.16.3.27 2.55-.01 5.12-.92 7.52-.15.38.4.56.62.28 1.32.59 2.68 1.05 4.08 1.37 0 2.78-.14 7.58-.33 12.91 0 0 0 .02-.01.03-.61 3.66-.79 7.42-1 11.12-.23 4.01-.43 8.03-.44 12.05 0 .64 0 1.28.03 1.93.02.31 0 .68.15.96.06.11.14.16.24.17-.2.17-.21.54.11.59 3.83.67 7.78.71 11.68.25 2.3-.19 4.87-.65 7.65-1.56 1.85-.54 3.67-1.18 5.43-1.91 7.2-3.02 14.31-8.07 17.35-15.53.76-1.86 1.17-3.8 1.31-5.75.3-1.93.28-3.82-.09-5.58l.01-.02Zm-19.32-15.42c5.74 1.41 11.94 3.68 15.65 8.55.25.32.47.65.69.99-2.3-2.82-5.68-5.69-12.88-8.23-2.16-.76-4.35-1.43-6.64-2.02 1.06.21 2.13.45 3.18.71Zm-25.82-3.04c.13 0 .27.01.4.02-.14.1-.26.23-.37.38 0-.13-.02-.26-.03-.4Zm34.82 22.17c-.75 3.09-3.55 5.66-5.88 7.58-3.35 2.76-7.21 5.03-11.28 6.54-1.33.49-2.71.9-4.12 1.15.06-1.38.08-2.76.07-4.13-.02-3.78-.16-7.56-.41-11.33-.09-1.37-.18-2.74-.37-4.1 0-.06-.03-.11-.06-.15.09-3.25.12-6.16.03-8.12 6.86 1.05 10.56 2.17 14.06 3.62 5.52 2.28 8.59 5.44 7.97 8.96l-.01-.02Zm-22 16.15c-.12 0-.23-.02-.34-.03l.34-.03v.06Zm-.69-.7c0-3.13.26-8.84.47-14.51.06 1.2.11 2.41.15 3.6.15 3.6.25 7.23.09 10.83-.24.03-.48.05-.71.07v.01Zm-12.33-30.94c.37.63 2.01 1.01 3.23 1.25v.15c-1.31-.31-2.59-.73-3.83-1.29.12-.36.23-.72.33-1.09.08.48.18.84.27.98Zm13.7 31.65v-.18c3.41-.56 6.71-2.02 9.69-3.68 2.31-1.28 4.59-2.78 6.63-4.53-4.69 4.53-11.61 8.24-16.33 8.38l.01.01Zm24.07-.75c-2.05 1.93-4.37 3.56-6.83 4.95 2.7-1.78 5.52-4.03 8.42-6.87.82-.82 1.56-1.69 2.23-2.59-1.08 1.65-2.38 3.16-3.81 4.51h-.01ZM187.16 92.14c-.79-2.47-2.1-7.12-3.1-6.87-.19-.01-2.09.77-4.08 1.54-3.06 1.18-5.91 2.13-10.09 2.82-2.74.42-5.87 1.01-10.61 1.06.04-3.34.05-6.01.05-7.99 7.97-.65 12.33-2.11 16.37-3.55 1.11-.39 2.69-1.01 2.63-1.8-.08-.35-.55-1.39-1.17-2.61-.47-1.16-.98-2.31-1.61-3.38-.42-.71-1.04-1.69-1.86-2.06-.11-.08-.22-.13-.29-.12-.02 0-.04 0-.07.01-.19-.04-.39-.05-.6-.01-.17.03-.24.15-.25.28-.04.02-.09.04-.14.05-4.33 1.48-8.85 2.33-13.24 3.61a499.1 499.1 0 0 0-.31-8.19c4.51-.99 8.88-1.38 13.11-1.82 3.68-.38 6.28.12 7.47.34.59.11.9.16 1.16.18h.1c-.1.37.44.66.62.28.02-.04.03-.08.05-.13.15.2.53.22.62-.1.17-.58.19-1.21.21-1.81v-.36c.03-.15.05-.3.07-.45.52-2.47.33-5.09-.64-7.44-.11-.27-.44-.28-.6-.14-.08-.21-.15-.42-.24-.62-.19-.41-.79-.05-.6.35.03.07.05.15.09.22-.98-.42-2.15-.54-3.17-.63-2.17-.19-4.37-.14-6.54 0-5.7.35-11.4 1.3-16.91 2.79-2.08.56-4.13 1.22-6.14 2-4.54 1.05-3.79 1.51-2.17 6.07.18.51.46 1.68.54 1.94.82 2.47 1.08 2.13 3.1 2.13s0 .05 0 .08h.52c-.48 2.66-.51 5.45-.62 8.13-.15 3.48-.22 6.96-.28 10.45 0 .41-.01.82-.02 1.23-.16.29-.33.57-.51.85-.05.38-.09.77-.14 1.18-.42 3.52-.59 6.48-.52 8.8v.34c.02.47.05.76.06.87.16 1.57-.26 3.47 1.35 3.79 1.61.32 3.5.55 4.85.55.11 0 .22-.02.33-.02 1.79.24 3.67.05 5.45-.12 2.85-.28 5.69-.7 8.51-1.19 3.03-.53 6.05-1.14 9.04-1.86 2.4-.58 4.82-1.19 7.13-2.06.51-.19 1.73-.57 2.46-1.14 1.81-.68 2.18-1 1.57-2.67-.23-.62-.48-1.49-.91-2.78l-.03-.02Zm-11.12-38.71c.89.05 1.93.08 2.89.3-.33 0-.68-.02-1.06-.03-8.28-.26-14.88.75-23.97 2.51 2.41-.64 4.85-1.16 7.28-1.59 4.87-.86 9.91-1.45 14.86-1.19Zm-26.53 22.13c.03 1.71.04 3.43 0 5.14-.04 1.27-.11 2.55-.24 3.82 0-.73.02-1.46.04-2.19.05-2.26.12-4.51.22-6.77h-.02Zm6.73 27.85c.2-.1.4-.21.58-.33 1.82-.17 3.82-.24 5.94-.34-.86.11-1.72.24-2.58.33-1.27.14-2.61.31-3.93.34h-.01ZM534.48 85.44c-3.52-8.38-7.07-16.75-10.5-25.17-.63-1.54-1.25-3.09-1.86-4.65-.31-.8-.65-1.6-.87-2.43-.04-.17-.17-.24-.31-.25.1-.2 0-.51-.29-.53-1.59-.08-3.18-.22-4.78-.25-1.96-.03-3.91.13-5.84.42-.31.05-.31.38-.13.56-.03.06-.05.14-.04.22.23 1.54.63 3.06 1.16 4.53.13.35.27.7.41 1.06l-2.68 6.18c-.11.03-.2.09-.25.22-.67 1.9-1.52 3.73-2.34 5.56a536.85 536.85 0 0 1-3.9 8.45c-2.64 5.64-5.34 11.25-7.91 16.93-.44.97-.88 1.94-1.29 2.93-.2.48-.47 1-.55 1.52v.05c-.02.12.02.26.16.34 1.19.73 2.41 1.41 3.66 2.05 1.2.62 2.45 1.25 3.76 1.61.43.12.62-.55.19-.67-1.13-.31-2.2-.83-3.24-1.36 1.09.36 2.1.69 2.75.93 2.82 1.01 2.38 1.1 4.3-3.75 2.1-1.09 4.34-1.96 6.53-2.79 4.35-1.64 8.8-3.03 13.27-4.29.82 2.01 1.77 3.97 2.72 5.92.35.83.62 1.45.79 1.82.22.42.45.8.69 1.15.17.33.33.67.5 1 .42.8.84 1.63 1.4 2.35.23.29.6 0 .55-.31 1.53-.02 3.06-.07 4.58-.27.92-.12 1.82-.32 2.71-.54 1.39-.27 3.85-1.11 3.74-1.42-.67-1.96-1.55-3.87-2.34-5.78-1.57-3.78-3.16-7.56-4.75-11.33v-.01Zm-11.65-26.16c1.54 3.81 3.12 7.6 4.7 11.4 2.94 7.05 5.91 14.09 8.87 21.13l-1.06-2.17c-2.71-5.51-5.2-11.19-7.41-16.87l-6.65-17.15c-.65-1.45-.55-2.19-.93-2.53.09 0 .18.01.28.02a.29.29 0 0 0-.04.26c.52 2.02 1.47 3.98 2.25 5.91h-.01Zm-6.58 13.58c.05-.15.09-.31.14-.46 1.41 3.92 2.88 7.9 4.39 11.87-3.22.52-6.38 1.25-9.46 2.14.55-1.22 1.05-2.46 1.53-3.7 1.24-3.24 2.37-6.53 3.39-9.85h.01Zm-.23-20c.36 0 .73.03 1.09.05-2.15.1-5.18.33-5.87.74-.24.15-.41.3-.53.45-.06-.29-.13-.58-.18-.88 1.82-.26 3.65-.39 5.49-.35v-.01Zm-.09 18.72c-.49 1.67-1.05 3.33-1.6 4.97-1.07 3.19-2.19 6.38-3.57 9.46-.09.21-.19.43-.29.65-.25.07-.5.14-.74.22 2.53-6.16 4.61-11.29 6.2-15.3Zm-6.34 25.16c4.97-2.38 9.37-4.1 14.02-5.27l.26.64c-4.8 1.35-9.63 2.8-14.28 4.63Zm20.17 6.76c.33.23.68.42 1.04.56h-.33c-.12 0-.21.06-.26.13-.15-.23-.31-.45-.45-.7v.01ZM226.57 91.75c-3.55-4.74-6.68-9.11-9.31-12.99 9.2-15.25 10.05-17.81 10.35-18.38.17-.34 1.09-2.27.64-2.53-1.13-.65-1.03-.65-2.97-1.71-1.19-.65-3.04-1.61-4.53-2.12-1.71-.59-1.24-.36-3 2.77-.06.1-.11.2-.17.3-.75 1.02-1.48 2.05-2.2 3.09-1.88 2.71-3.73 5.45-5.69 8.1-3.68-4.91-6.88-8.76-9.51-11.43-.15-.15-.3-.29-.46-.42-1.27-1.28-7.24 3.53-7.93 5.58-.09.09-.19.16-.28.25-.27.26.03.64.33.58.19.65.5 1.29.94 1.91 3.85 5.06 7.19 9.76 9.94 14-1.23 2.61-3.06 5-4.67 7.38l-2.28 3.33c-.5.66-.93 1.23-1.29 1.69-.67.93-2.09 2.61-2.3 3.87-.51.85-1.16 1.84-1.29 2.83-.06.44.61.63.67.19.01-.08.04-.15.06-.22 1.36 1.08 2.76 2.11 4.19 3.11 1.3.91 2.62 1.85 4.04 2.56.21.1.4 0 .48-.17.24.07.48.14.72.2.44.1.62-.57.19-.67-2.02-.48-3.77-1.57-5.23-3.02-.47-.46-.9-.96-1.32-1.46 1.74 1.35 4.2 2.89 5.89 4.14 1.39 1.03 2.85-2.27 4.22-4.2 1.86-2.64 3.96-5.86 5.52-8.29l10.39 14.51c.67.81 1.14 1.21 1.57 1.36-.05.24.12.51.41.4 1.53-.58 3.05-1.19 4.54-1.87 1.52-.69 3.06-1.45 4.36-2.5a.28.28 0 0 0 .12-.23c1.66-1.1.81-1.74-1.41-4.91-1.13-1.58-1.71-2.36-3.7-5.01l-.03-.02Zm2.41 6.54c.56 1.15 1.19 2.52 1.11 3.81-.06.04-.12.07-.17.1-.03-.88-.55-2.66-.94-3.91Zm-16.51-32.73c1.86-2.65 3.65-5.35 5.57-7.95.4-.55.81-1.13 1.26-1.66.19-.18.38-.33.56-.45.18.03.36.08.55.13l-8.05 10.11.12-.18h-.01ZM192.7 95.48c.79-1.37 1.66-2.69 2.54-4 1.19-1.79 2.4-3.56 3.61-5.33-.04.09-.09.17-.13.26-.1.22.03.41.2.49-2.47 3.42-4.89 6.73-6.4 9.28.21.24.4.48.63.75-.24.07-.4.36-.17.56.4.33.72.77 1.05 1.17.09.11.18.21.27.32-.84-.61-1.66-1.24-2.47-1.88.24-.57.58-1.11.87-1.61v-.01Zm7.46-10.32c.47-.81.98-1.59 1.49-2.37.31-.48.64-.95.96-1.43.26-.29.52-.56.75-.79-.99 1.48-2.09 3.03-3.2 4.59Zm10.03-16.22s-.03-.05-.05-.07c.22-.29.43-.59.64-.89-.2.32-.4.65-.58.96h-.01ZM371.54 87.96c-.01-.08-.01-.16-.03-.23-.06-.38-.58-.29-.66.03-.3-.05-.6-.08-.81-.11-1.14-.15-2.29-.19-3.44-.2 1.04-.09 2.09-.18 3.14-.23.45-.02.45-.72 0-.7-6.57.35-13.14 1.23-19.65 2.11-1.53.21-3.05.42-4.57.68-.01 0-.02.01-.04.01-.04-3.33-.13-6.66-.24-9.99-.19-5.7-.4-11.41-.88-17.1-.13-1.51-.23-3.07-.49-4.58 0-.25 0-.48-.02-.68-.06-1.19-.04-2.61-.68-2.78-.16-.07-.72-.16-1.5-.24.22-.17.16-.62-.2-.63-1.19-.04-2.39.09-3.57.23-1.2.14-2.41.32-3.59.6-.16-.1-.41-.06-.5.12-.06.02-.13.03-.19.05-.35.1-.29.55-.03.66-.26.6-.19 2.27-.21 3-.02.66-.66 33.73-.9 40.3-.03.65.06 1.12.04 1.45-.16 3.05.87 4.96 6.34 3.93 1.09-.08 2.75-.77 5.36-1.43 4.13-1.04 5.78-1.52 6.2-1.65 6.43-1.69 6.78-1.97 11.72-2.43.55-.05 4.8-.38 6.03-.3.64.04 1.19.07 1.65.1.09 0 .16-.03.24-.05.1.27.56.33.66-.02.39-1.32.61-2.71.78-4.08.2-1.61.29-3.24.15-4.86.24.03.52-.23.38-.53-.09-.2-.27-.33-.49-.43v-.02Zm-.63.56c.07.57.11 1.14.11 1.71-.21-.99-.53-1.71-.95-1.87.22.03.44.06.65.11.06.01.12.04.19.05Zm-25.41 1.73c1.54-.36 3.1-.64 4.66-.89-1.61.37-3.18.77-4.66 1.2v-.31Zm-.86-7.37c-.07-1.37-.16-2.75-.25-4.12-.21-3.13-.45-6.27-.79-9.4.02-2.25.08-4.31.13-6.11.16 2.08.29 4.16.4 6.24.23 4.46.38 8.93.5 13.39h.01Zm-.94-4c.16 2.41.29 4.83.39 7.24.06 1.6.14 3.22.09 4.83-.15.05-.32.09-.47.14V78.88h-.01ZM483.72 92.83c-3.05-2.28-6.22-4.4-9.38-6.51 8.86-6.49 13.49-12.95 13.73-19.23.04-.76 0-1.5-.13-2.2-.67-3.82-3.5-6.68-8.39-8.48.13.04.27.08.4.13 3.92 1.39 7.74 4.23 8.5 8.56.34 1.95-.05 3.96-.98 5.69-.21.4.39.75.6.35 1.86-3.46 1.46-7.55-.97-10.63-3.53-4.47-9.76-5.88-15.16-6.16-2.32-.12-4.64-.04-6.95.19-6 .32-12.71 1.68-17.63 3.21-.37.11-.67.23-.92.35-.2-.17-.62.02-.57.37v.03c-.64.68-.18 1.64.48 3.21.38.91.67 1.89 1.15 2.58.32.76.68 1.51 1.13 2.19.14.21.38.19.53.07.19-.02.38-.05.57-.08v1.57c-.06.06-.1.13-.11.23-.27 4.18-.34 8.38-.48 12.57l-.3 9.03c-.24 3.91-.44 6.77-.46 7.26-.05.88-.11 1.95.07 2.81-.01.22-.02.43-.04.65 0 .11-.02.23-.03.35 0 .05-.03.27-.01.16-.05.4.5.59.64.28.05.04.12.08.2.08 1.75.13 3.5.28 5.25.3 1.69.02 3.38-.12 5.06-.32.08.23.36.39.55.15.06-.08.11-.17.16-.26.18-.09.24-.32.18-.48.05-.2.1-.4.13-.6.16-.86.25-1.74.33-2.62.11-1.17.17-2.34.23-3.51.15-.01.32-.03.52-.04.36-.03 1.73-.15 2.06-.15.39 0 .7-.02.95-.04 1.76 1.11 3.45 2.35 5.14 3.55 2.83 2.01 5.64 4.04 8.47 6.04 1.42 1 2.85 2 4.29 2.97.1.06.19.07.27.04.08 0 .17-.02.25-.1 1.61-1.56 3.15-3.18 4.6-4.88.75-.88 1.49-1.78 2.15-2.73.01.01.03.02.04.03.34.3.83-.2.49-.49-2.16-1.9-4.34-3.76-6.64-5.48l.03-.01Zm-6.38-3.65a55.72 55.72 0 0 0-4-2.13c.14-.1.26-.19.4-.29 1.2.81 2.4 1.61 3.6 2.42Zm-20.1 11.78c.67-.37 1.23-.91 1.67-1.6-.11.5-.24 1-.38 1.49-.43.04-.86.08-1.29.11Zm2.38-37.24c1.34-.31 2.56-.52 3.71-.69-1.03.19-2.04.41-3.04.65-.14-.07-.34-.02-.45.11-.07.02-.15.04-.22.05v-.13.01Zm.04.84c.07-.02.14-.03.2-.05.34 1.66.41 3.41.5 5.09.17 2.9.24 5.81.28 8.71l.03 3.17c-.17.07-.34.14-.51.2-.06-4.96-.21-10.58-.51-17.12h.01Zm16.04 5.62c-1.16 2.25-3.06 4.1-5.02 5.66-2.8 2.23-5.99 3.97-9.3 5.35-.01-3.56-.09-7.12-.27-10.67-.1-2.04-.16-4.16-.57-6.18 3.3-.78 6.72-1.36 10.1-1.1 1.85.14 4.23.59 5.32 2.29.92 1.43.46 3.24-.26 4.65Zm.85-.18c.6-1.37.9-2.92.28-4.32-.67-1.52-2.2-2.32-3.76-2.74.46.1.89.21 1.29.37 1.74.67 2.69 1.88 2.93 3.21.2 1.13-.05 2.25-.74 3.47V70Zm-27.47-4.14c-.12-.19-.23-.38-.34-.57.74.42.85.36.99.41v.08c-.22.03-.43.06-.65.08Zm11.21 30.46c-.08 1.08-.16 2.17-.33 3.24-.05.35-.11.69-.2 1.03 0 .04-.02.07-.03.11-.15.02-.3.04-.45.05.45-1.64.76-3.36.79-5.07.03-.29.08-.57.1-.89-.03-.31-.03-.47.24-.57-.04.69-.07 1.39-.12 2.08v.02Zm5.6-2.47c.48.11.92.52 2.49 1.72-.46-.32-.92-.65-1.38-.97-.37-.25-.73-.5-1.1-.75h-.01Zm21.23 7.24a70.76 70.76 0 0 1-4.37 4.63c-.14-.09-.27-.19-.4-.28.19-.09.37-.24.55-.47.87-1.14 5.43-5.51 5.49-7.45.31.26.62.53.92.79-.67.97-1.42 1.88-2.19 2.77v.01Z"
+ fill="currentColor"
+ transform="translate(-144.023 -51.76)"
+ />
+ </svg>
+);
+
+type LogoSize = "xs" | "small" | "normal" | "large" | "custom";
+
+interface LogoProps {
+ size?: LogoSize;
+ withText?: boolean;
+ style?: React.CSSProperties;
+ /**
+ * If true, the logo will not be wrapped in a Link component.
+ * The link prop will be ignored as well.
+ * It will merely be a plain div.
+ */
+ isNotLink?: boolean;
+}
+
+export const ExcalidrawLogo = ({
+ style,
+ size = "small",
+ withText,
+}: LogoProps) => {
+ return (
+ <div className={`ExcalidrawLogo is-${size}`} style={style}>
+ <LogoIcon />
+ {withText && <LogoText />}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ExportDialog.scss b/packages/excalidraw/components/ExportDialog.scss
new file mode 100644
index 0000000..d114f25
--- /dev/null
+++ b/packages/excalidraw/components/ExportDialog.scss
@@ -0,0 +1,129 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .ExportDialog__preview {
+ --preview-padding: calc(var(--space-factor) * 4);
+
+ background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")
+ left center;
+ text-align: center;
+ padding: var(--preview-padding);
+ margin-bottom: calc(var(--space-factor) * 3);
+
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+
+ .ExportDialog__preview canvas {
+ max-width: calc(100% - var(--preview-padding) * 2);
+ max-height: 25rem;
+ }
+
+ &.theme--dark .ExportDialog__preview canvas {
+ filter: none;
+ }
+
+ .ExportDialog__actions {
+ width: 100%;
+ display: flex;
+ grid-gap: calc(var(--space-factor) * 2);
+ align-items: top;
+ justify-content: space-between;
+ }
+
+ @include isMobile {
+ .ExportDialog {
+ display: flex;
+ flex-direction: column;
+ }
+
+ .ExportDialog__actions {
+ flex-direction: column;
+ align-items: center;
+ }
+
+ .ExportDialog__actions > * {
+ margin-bottom: calc(var(--space-factor) * 3);
+ }
+
+ .ExportDialog__preview canvas {
+ max-height: 30vh;
+ }
+
+ .ExportDialog__dialog,
+ .ExportDialog__dialog .Island {
+ height: 100%;
+ box-sizing: border-box;
+ }
+
+ .ExportDialog__dialog .Island {
+ overflow-y: auto;
+ }
+ }
+
+ .ExportDialog--json {
+ .ExportDialog-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ justify-items: center;
+ row-gap: 2em;
+
+ @media (max-width: 460px) {
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ .Card-details {
+ min-height: 40px;
+ }
+ }
+
+ .ProjectName {
+ width: fit-content;
+ margin: 1em auto;
+ align-items: flex-start;
+ flex-direction: column;
+
+ .TextInput {
+ width: auto;
+ }
+ }
+
+ .ProjectName-label {
+ margin: 0.625em 0;
+ font-weight: bold;
+ }
+ }
+ }
+
+ button.ExportDialog-imageExportButton {
+ border: 0;
+
+ width: 5rem;
+ height: 5rem;
+ margin: 0 0.2em;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ border-radius: 1rem;
+ background-color: var(--button-color);
+ box-shadow: 0 3px 5px -1px rgba(0, 0, 0, 0.28),
+ 0 6px 10px 0 rgba(0, 0, 0, 0.14);
+
+ font-family: Cascadia;
+ font-size: 1.8em;
+ color: $oc-white;
+
+ &:hover {
+ background-color: var(--button-color-darker);
+ }
+ &:active {
+ background-color: var(--button-color-darkest);
+ box-shadow: none;
+ }
+
+ svg {
+ width: 0.9em;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/EyeDropper.scss b/packages/excalidraw/components/EyeDropper.scss
new file mode 100644
index 0000000..da706b4
--- /dev/null
+++ b/packages/excalidraw/components/EyeDropper.scss
@@ -0,0 +1,48 @@
+.excalidraw {
+ .excalidraw-eye-dropper-container,
+ .excalidraw-eye-dropper-backdrop {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ z-index: var(--zIndex-eyeDropperBackdrop);
+ touch-action: none;
+ }
+
+ .excalidraw-eye-dropper-container {
+ pointer-events: none;
+ }
+
+ .excalidraw-eye-dropper-backdrop {
+ pointer-events: all;
+ }
+
+ .excalidraw-eye-dropper-preview {
+ pointer-events: none;
+ width: 3rem;
+ height: 3rem;
+ position: fixed;
+ z-index: var(--zIndex-eyeDropperPreview);
+ border-radius: 1rem;
+ border: 1px solid var(--default-border-color);
+ filter: var(--theme-filter);
+ }
+
+ .excalidraw-eye-dropper-trigger {
+ width: 1.25rem;
+ height: 1.25rem;
+ cursor: pointer;
+ padding: 4px;
+ margin-right: -4px;
+ margin-left: -2px;
+ border-radius: 0.5rem;
+ color: var(--icon-fill-color);
+
+ &:hover {
+ background: var(--button-hover-bg);
+ }
+ &.selected {
+ color: var(--color-primary);
+ background: var(--color-primary-light);
+ }
+ }
+}
diff --git a/packages/excalidraw/components/EyeDropper.tsx b/packages/excalidraw/components/EyeDropper.tsx
new file mode 100644
index 0000000..429c68a
--- /dev/null
+++ b/packages/excalidraw/components/EyeDropper.tsx
@@ -0,0 +1,235 @@
+import { useEffect, useRef } from "react";
+import { createPortal } from "react-dom";
+import { rgbToHex } from "../colors";
+import { EVENT } from "../constants";
+import { useUIAppState } from "../context/ui-appState";
+import { useCreatePortalContainer } from "../hooks/useCreatePortalContainer";
+import { useOutsideClick } from "../hooks/useOutsideClick";
+import { KEYS } from "../keys";
+import { getSelectedElements } from "../scene";
+import { useApp, useExcalidrawContainer, useExcalidrawElements } from "./App";
+import { useStable } from "../hooks/useStable";
+
+import "./EyeDropper.scss";
+import type { ColorPickerType } from "./ColorPicker/colorPickerUtils";
+import type { ExcalidrawElement } from "../element/types";
+import { atom } from "../editor-jotai";
+
+export type EyeDropperProperties = {
+ keepOpenOnAlt: boolean;
+ swapPreviewOnAlt?: boolean;
+ /** called when user picks color (on pointerup) */
+ onSelect: (color: string, event: PointerEvent) => void;
+ /**
+ * property of selected elements to update live when alt-dragging.
+ * Supply `null` if not applicable (e.g. updating the canvas bg instead of
+ * elements)
+ **/
+ colorPickerType: ColorPickerType;
+};
+
+export const activeEyeDropperAtom = atom<null | EyeDropperProperties>(null);
+
+export const EyeDropper: React.FC<{
+ onCancel: () => void;
+ onSelect: EyeDropperProperties["onSelect"];
+ /** called when color changes, on pointerdown for preview */
+ onChange: (
+ type: ColorPickerType,
+ color: string,
+ selectedElements: ExcalidrawElement[],
+ event: { altKey: boolean },
+ ) => void;
+ colorPickerType: EyeDropperProperties["colorPickerType"];
+}> = ({ onCancel, onChange, onSelect, colorPickerType }) => {
+ const eyeDropperContainer = useCreatePortalContainer({
+ className: "excalidraw-eye-dropper-backdrop",
+ parentSelector: ".excalidraw-eye-dropper-container",
+ });
+ const appState = useUIAppState();
+ const elements = useExcalidrawElements();
+ const app = useApp();
+
+ const selectedElements = getSelectedElements(elements, appState);
+
+ const stableProps = useStable({
+ app,
+ onCancel,
+ onChange,
+ onSelect,
+ selectedElements,
+ });
+
+ const { container: excalidrawContainer } = useExcalidrawContainer();
+
+ useEffect(() => {
+ const colorPreviewDiv = ref.current;
+
+ if (!colorPreviewDiv || !app.canvas || !eyeDropperContainer) {
+ return;
+ }
+
+ let isHoldingPointerDown = false;
+
+ const ctx = app.canvas.getContext("2d")!;
+
+ const getCurrentColor = ({
+ clientX,
+ clientY,
+ }: {
+ clientX: number;
+ clientY: number;
+ }) => {
+ const pixel = ctx.getImageData(
+ (clientX - appState.offsetLeft) * window.devicePixelRatio,
+ (clientY - appState.offsetTop) * window.devicePixelRatio,
+ 1,
+ 1,
+ ).data;
+
+ return rgbToHex(pixel[0], pixel[1], pixel[2]);
+ };
+
+ const mouseMoveListener = ({
+ clientX,
+ clientY,
+ altKey,
+ }: {
+ clientX: number;
+ clientY: number;
+ altKey: boolean;
+ }) => {
+ // FIXME swap offset when the preview gets outside viewport
+ colorPreviewDiv.style.top = `${clientY + 20}px`;
+ colorPreviewDiv.style.left = `${clientX + 20}px`;
+
+ const currentColor = getCurrentColor({ clientX, clientY });
+
+ if (isHoldingPointerDown) {
+ stableProps.onChange(
+ colorPickerType,
+ currentColor,
+ stableProps.selectedElements,
+ { altKey },
+ );
+ }
+
+ colorPreviewDiv.style.background = currentColor;
+ };
+
+ const onCancel = () => {
+ stableProps.onCancel();
+ };
+
+ const onSelect: Required<EyeDropperProperties>["onSelect"] = (
+ color,
+ event,
+ ) => {
+ stableProps.onSelect(color, event);
+ };
+
+ const pointerDownListener = (event: PointerEvent) => {
+ isHoldingPointerDown = true;
+ // NOTE we can't event.preventDefault() as that would stop
+ // pointermove events
+ event.stopImmediatePropagation();
+ };
+
+ const pointerUpListener = (event: PointerEvent) => {
+ isHoldingPointerDown = false;
+
+ // since we're not preventing default on pointerdown, the focus would
+ // goes back to `body` so we want to refocus the editor container instead
+ excalidrawContainer?.focus();
+
+ event.stopImmediatePropagation();
+ event.preventDefault();
+
+ onSelect(getCurrentColor(event), event);
+ };
+
+ const keyDownListener = (event: KeyboardEvent) => {
+ if (event.key === KEYS.ESCAPE) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ onCancel();
+ }
+ };
+
+ // -------------------------------------------------------------------------
+
+ eyeDropperContainer.tabIndex = -1;
+ // focus container so we can listen on keydown events
+ eyeDropperContainer.focus();
+
+ // init color preview else it would show only after the first mouse move
+ mouseMoveListener({
+ clientX: stableProps.app.lastViewportPosition.x,
+ clientY: stableProps.app.lastViewportPosition.y,
+ altKey: false,
+ });
+
+ eyeDropperContainer.addEventListener(EVENT.KEYDOWN, keyDownListener);
+ eyeDropperContainer.addEventListener(
+ EVENT.POINTER_DOWN,
+ pointerDownListener,
+ );
+ eyeDropperContainer.addEventListener(EVENT.POINTER_UP, pointerUpListener);
+ window.addEventListener("pointermove", mouseMoveListener, {
+ passive: true,
+ });
+ window.addEventListener(EVENT.BLUR, onCancel);
+
+ return () => {
+ isHoldingPointerDown = false;
+ eyeDropperContainer.removeEventListener(EVENT.KEYDOWN, keyDownListener);
+ eyeDropperContainer.removeEventListener(
+ EVENT.POINTER_DOWN,
+ pointerDownListener,
+ );
+ eyeDropperContainer.removeEventListener(
+ EVENT.POINTER_UP,
+ pointerUpListener,
+ );
+ window.removeEventListener("pointermove", mouseMoveListener);
+ window.removeEventListener(EVENT.BLUR, onCancel);
+ };
+ }, [
+ stableProps,
+ app.canvas,
+ eyeDropperContainer,
+ colorPickerType,
+ excalidrawContainer,
+ appState.offsetLeft,
+ appState.offsetTop,
+ ]);
+
+ const ref = useRef<HTMLDivElement>(null);
+
+ useOutsideClick(
+ ref,
+ () => {
+ onCancel();
+ },
+ (event) => {
+ if (
+ event.target.closest(
+ ".excalidraw-eye-dropper-trigger, .excalidraw-eye-dropper-backdrop",
+ )
+ ) {
+ return true;
+ }
+ // consider all other clicks as outside
+ return false;
+ },
+ );
+
+ if (!eyeDropperContainer) {
+ return null;
+ }
+
+ return createPortal(
+ <div ref={ref} className="excalidraw-eye-dropper-preview" />,
+ eyeDropperContainer,
+ );
+};
diff --git a/packages/excalidraw/components/FilledButton.scss b/packages/excalidraw/components/FilledButton.scss
new file mode 100644
index 0000000..1f689e9
--- /dev/null
+++ b/packages/excalidraw/components/FilledButton.scss
@@ -0,0 +1,317 @@
+@import "../css/variables.module.scss";
+
+@keyframes successStatusAnimation {
+ 0% {
+ transform: scale(0.35);
+ }
+
+ 50% {
+ transform: scale(1.25);
+ }
+
+ 100% {
+ transform: scale(1);
+ }
+}
+
+.excalidraw {
+ .ExcButton {
+ --text-color: transparent;
+ --border-color: transparent;
+ --back-color: transparent;
+
+ color: var(--text-color);
+ background-color: var(--back-color);
+ border-color: var(--border-color);
+
+ &:hover {
+ transition: all 150ms ease-out;
+ }
+
+ .Spinner {
+ --spinner-color: var(--color-surface-lowest);
+ }
+
+ .ExcButton__statusIcon {
+ visibility: visible;
+ position: absolute;
+
+ width: 1.2rem;
+ height: 1.2rem;
+
+ animation: successStatusAnimation 0.5s cubic-bezier(0.3, 1, 0.6, 1);
+ }
+
+ &.ExcButton--status-loading,
+ &.ExcButton--status-success {
+ pointer-events: none;
+
+ .ExcButton__contents {
+ visibility: hidden;
+ }
+ }
+
+ &[disabled] {
+ pointer-events: none;
+ }
+
+ &,
+ &__contents {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ flex-shrink: 0;
+ flex-wrap: nowrap;
+ // needed because of .Spinner
+ position: relative;
+ }
+
+ &--color-primary {
+ &.ExcButton--variant-filled {
+ --text-color: var(--color-surface-lowest);
+ --back-color: var(--color-primary);
+
+ .Spinner {
+ --spinner-color: var(--text-color);
+ }
+
+ &:hover {
+ --back-color: var(--color-brand-hover);
+ }
+
+ &:active {
+ --back-color: var(--color-brand-active);
+ }
+ }
+
+ &.ExcButton--variant-outlined,
+ &.ExcButton--variant-icon {
+ --text-color: var(--color-primary);
+ --border-color: var(--color-primary);
+ --back-color: transparent;
+
+ .Spinner {
+ --spinner-color: var(--text-color);
+ }
+
+ &:hover {
+ --text-color: var(--color-brand-hover);
+ --border-color: var(--color-brand-hover);
+ }
+
+ &:active {
+ --text-color: var(--color-brand-active);
+ --border-color: var(--color-brand-active);
+ }
+ }
+ }
+
+ &--color-danger {
+ &.ExcButton--variant-filled {
+ --text-color: var(--color-danger-text);
+ --back-color: var(--color-danger-dark);
+
+ .Spinner {
+ --spinner-color: var(--text-color);
+ }
+
+ &:hover {
+ --back-color: var(--color-danger-darker);
+ }
+
+ &:active {
+ --back-color: var(--color-danger-darkest);
+ }
+ }
+
+ &.ExcButton--variant-outlined,
+ &.ExcButton--variant-icon {
+ --text-color: var(--color-danger);
+ --border-color: var(--color-danger);
+ --back-color: transparent;
+
+ .Spinner {
+ --spinner-color: var(--text-color);
+ }
+
+ &:hover {
+ --text-color: var(--color-danger-darkest);
+ --border-color: var(--color-danger-darkest);
+ }
+
+ &:active {
+ --text-color: var(--color-danger-darker);
+ --border-color: var(--color-danger-darker);
+ }
+ }
+ }
+
+ &--color-success {
+ &.ExcButton--variant-filled {
+ --text-color: var(--color-success-text);
+ --back-color: var(--color-success);
+
+ .Spinner {
+ --spinner-color: var(--color-success);
+ }
+
+ &:hover {
+ --back-color: var(--color-success-darker);
+ }
+
+ &:active {
+ --back-color: var(--color-success-darkest);
+ }
+ }
+
+ &.ExcButton--variant-outlined,
+ &.ExcButton--variant-icon {
+ --text-color: var(--color-success-contrast);
+ --border-color: var(--color-success-contrast);
+ --back-color: transparent;
+
+ .Spinner {
+ --spinner-color: var(--color-success-contrast);
+ }
+
+ &:hover {
+ --text-color: var(--color-success-contrast-hover);
+ --border-color: var(--color-success-contrast-hover);
+ }
+
+ &:active {
+ --text-color: var(--color-success-contrast-active);
+ --border-color: var(--color-success-contrast-active);
+ }
+ }
+ }
+
+ &--color-muted {
+ &.ExcButton--variant-filled {
+ --text-color: var(--island-bg-color);
+ --back-color: var(--color-gray-50);
+
+ .Spinner {
+ --spinner-color: var(--text-color);
+ }
+
+ &:hover {
+ --back-color: var(--color-gray-60);
+ }
+
+ &:active {
+ --back-color: var(--color-gray-80);
+ }
+ }
+
+ &.ExcButton--variant-outlined,
+ &.ExcButton--variant-icon {
+ --text-color: var(--color-muted-background);
+ --border-color: var(--color-muted);
+ --back-color: var(--island-bg-color);
+
+ .Spinner {
+ --spinner-color: var(--text-color);
+ }
+
+ &:hover {
+ --text-color: var(--color-muted-background-darker);
+ --border-color: var(--color-muted-darker);
+ }
+
+ &:active {
+ --text-color: var(--color-muted-background-darker);
+ --border-color: var(--color-muted-darkest);
+ }
+ }
+ }
+
+ &--color-warning {
+ &.ExcButton--variant-filled {
+ --text-color: black;
+ --back-color: var(--color-warning-dark);
+
+ .Spinner {
+ --spinner-color: var(--text-color);
+ }
+
+ &:hover {
+ --back-color: var(--color-warning-darker);
+ }
+
+ &:active {
+ --back-color: var(--color-warning-darkest);
+ }
+ }
+
+ &.ExcButton--variant-outlined,
+ &.ExcButton--variant-icon {
+ --text-color: var(--color-warning-dark);
+ --border-color: var(--color-warning-dark);
+ --back-color: var(--input-bg-color);
+
+ .Spinner {
+ --spinner-color: var(--text-color);
+ }
+
+ &:hover {
+ --text-color: var(--color-warning-darker);
+ --border-color: var(--color-warning-darker);
+ }
+
+ &:active {
+ --text-color: var(--color-warning-darkest);
+ --border-color: var(--color-warning-darkest);
+ }
+ }
+ }
+
+ border-radius: 0.5rem;
+ border-width: 1px;
+ border-style: solid;
+
+ font-family: var(--font-family);
+
+ user-select: none;
+
+ &--size-large {
+ font-weight: 600;
+ font-size: 0.875rem;
+ min-height: 3rem;
+ padding: 0.5rem 1.5rem;
+
+ letter-spacing: 0.4px;
+
+ .ExcButton__contents {
+ gap: 0.75rem;
+ }
+ }
+
+ &--size-medium {
+ font-weight: 600;
+ font-size: 0.75rem;
+ min-height: 2.5rem;
+ padding: 0.5rem 1rem;
+
+ letter-spacing: normal;
+
+ .ExcButton__contents {
+ gap: 0.5rem;
+ }
+ }
+
+ &--variant-icon {
+ padding: 0.5rem 0.75rem;
+ width: 3rem;
+ }
+
+ &--fullWidth {
+ width: 100%;
+ }
+
+ &__icon {
+ width: 1.25rem;
+ height: 1.25rem;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/FilledButton.tsx b/packages/excalidraw/components/FilledButton.tsx
new file mode 100644
index 0000000..1360908
--- /dev/null
+++ b/packages/excalidraw/components/FilledButton.tsx
@@ -0,0 +1,114 @@
+import React, { forwardRef, useState } from "react";
+import clsx from "clsx";
+
+import "./FilledButton.scss";
+import { AbortError } from "../errors";
+import Spinner from "./Spinner";
+import { isPromiseLike } from "../utils";
+import { tablerCheckIcon } from "./icons";
+
+export type ButtonVariant = "filled" | "outlined" | "icon";
+export type ButtonColor =
+ | "primary"
+ | "danger"
+ | "warning"
+ | "muted"
+ | "success";
+export type ButtonSize = "medium" | "large";
+
+export type FilledButtonProps = {
+ label: string;
+
+ children?: React.ReactNode;
+ onClick?: (event: React.MouseEvent) => void;
+ status?: null | "loading" | "success";
+
+ variant?: ButtonVariant;
+ color?: ButtonColor;
+ size?: ButtonSize;
+ className?: string;
+ fullWidth?: boolean;
+
+ icon?: React.ReactNode;
+};
+
+export const FilledButton = forwardRef<HTMLButtonElement, FilledButtonProps>(
+ (
+ {
+ children,
+ icon,
+ onClick,
+ label,
+ variant = "filled",
+ color = "primary",
+ size = "medium",
+ fullWidth,
+ className,
+ status,
+ },
+ ref,
+ ) => {
+ const [isLoading, setIsLoading] = useState(false);
+
+ const _onClick = async (event: React.MouseEvent) => {
+ const ret = onClick?.(event);
+
+ if (isPromiseLike(ret)) {
+ // delay loading state to prevent flicker in case of quick response
+ const timer = window.setTimeout(() => {
+ setIsLoading(true);
+ }, 50);
+ try {
+ await ret;
+ } catch (error: any) {
+ if (!(error instanceof AbortError)) {
+ throw error;
+ } else {
+ console.warn(error);
+ }
+ } finally {
+ clearTimeout(timer);
+ setIsLoading(false);
+ }
+ }
+ };
+
+ const _status = isLoading ? "loading" : status;
+ color = _status === "success" ? "success" : color;
+
+ return (
+ <button
+ className={clsx(
+ "ExcButton",
+ `ExcButton--color-${color}`,
+ `ExcButton--variant-${variant}`,
+ `ExcButton--size-${size}`,
+ `ExcButton--status-${_status}`,
+ { "ExcButton--fullWidth": fullWidth },
+ className,
+ )}
+ onClick={_onClick}
+ type="button"
+ aria-label={label}
+ ref={ref}
+ disabled={_status === "loading" || _status === "success"}
+ >
+ <div className="ExcButton__contents">
+ {_status === "loading" ? (
+ <Spinner className="ExcButton__statusIcon" />
+ ) : (
+ _status === "success" && (
+ <div className="ExcButton__statusIcon">{tablerCheckIcon}</div>
+ )
+ )}
+ {icon && (
+ <div className="ExcButton__icon" aria-hidden>
+ {icon}
+ </div>
+ )}
+ {variant !== "icon" && (children ?? label)}
+ </div>
+ </button>
+ );
+ },
+);
diff --git a/packages/excalidraw/components/FixedSideContainer.scss b/packages/excalidraw/components/FixedSideContainer.scss
new file mode 100644
index 0000000..cc99d47
--- /dev/null
+++ b/packages/excalidraw/components/FixedSideContainer.scss
@@ -0,0 +1,39 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .FixedSideContainer {
+ position: absolute;
+ pointer-events: none;
+ }
+
+ .FixedSideContainer > * {
+ pointer-events: var(--ui-pointerEvents);
+ }
+
+ .FixedSideContainer_side_top {
+ left: var(--editor-container-padding);
+ top: var(--editor-container-padding);
+ right: var(--editor-container-padding);
+ bottom: var(--editor-container-padding);
+ }
+
+ .FixedSideContainer_side_top.zen-mode {
+ right: 42px;
+ }
+}
+
+/* TODO: if these are used, make sure to implement RTL support
+.FixedSideContainer_side_left {
+ left: var(--space-factor);
+ top: var(--space-factor);
+ bottom: var(--space-factor);
+ z-index: 1;
+}
+
+.FixedSideContainer_side_right {
+ right: var(--space-factor);
+ top: var(--space-factor);
+ bottom: var(--space-factor);
+ z-index: 3;
+}
+*/
diff --git a/packages/excalidraw/components/FixedSideContainer.tsx b/packages/excalidraw/components/FixedSideContainer.tsx
new file mode 100644
index 0000000..76aee99
--- /dev/null
+++ b/packages/excalidraw/components/FixedSideContainer.tsx
@@ -0,0 +1,26 @@
+import "./FixedSideContainer.scss";
+
+import React from "react";
+import clsx from "clsx";
+
+type FixedSideContainerProps = {
+ children: React.ReactNode;
+ side: "top" | "left" | "right";
+ className?: string;
+};
+
+export const FixedSideContainer = ({
+ children,
+ side,
+ className,
+}: FixedSideContainerProps) => (
+ <div
+ className={clsx(
+ "FixedSideContainer",
+ `FixedSideContainer_side_${side}`,
+ className,
+ )}
+ >
+ {children}
+ </div>
+);
diff --git a/packages/excalidraw/components/FollowMode/FollowMode.scss b/packages/excalidraw/components/FollowMode/FollowMode.scss
new file mode 100644
index 0000000..383b3ce
--- /dev/null
+++ b/packages/excalidraw/components/FollowMode/FollowMode.scss
@@ -0,0 +1,59 @@
+.excalidraw {
+ .follow-mode {
+ position: absolute;
+ box-sizing: border-box;
+ pointer-events: none;
+ border: 2px solid var(--color-primary-hover);
+ z-index: 9999;
+ display: flex;
+ align-items: flex-end;
+ justify-content: center;
+
+ &__badge {
+ background-color: var(--color-primary-hover);
+ color: var(--color-primary-light);
+ padding: 0.25rem 0.5rem;
+ margin-bottom: 0.5rem;
+ border-radius: 0.5rem;
+ pointer-events: all;
+ font-size: 0.75rem;
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+
+ &__label {
+ display: flex;
+ white-space: pre-wrap;
+ line-height: 1;
+ }
+
+ &__username {
+ display: block;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 100px;
+ }
+ }
+
+ &__disconnect-btn {
+ all: unset;
+ cursor: pointer;
+ border-radius: 0.25rem;
+
+ &:hover {
+ background-color: var(--color-primary-darker);
+ }
+
+ &:active {
+ background-color: var(--color-primary-darkest);
+ }
+
+ svg {
+ display: block;
+ width: 1rem;
+ height: 1rem;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/FollowMode/FollowMode.tsx b/packages/excalidraw/components/FollowMode/FollowMode.tsx
new file mode 100644
index 0000000..89581bf
--- /dev/null
+++ b/packages/excalidraw/components/FollowMode/FollowMode.tsx
@@ -0,0 +1,42 @@
+import type { UserToFollow } from "../../types";
+import { CloseIcon } from "../icons";
+import "./FollowMode.scss";
+
+interface FollowModeProps {
+ width: number;
+ height: number;
+ userToFollow: UserToFollow;
+ onDisconnect: () => void;
+}
+
+const FollowMode = ({
+ height,
+ width,
+ userToFollow,
+ onDisconnect,
+}: FollowModeProps) => {
+ return (
+ <div className="follow-mode" style={{ width, height }}>
+ <div className="follow-mode__badge">
+ <div className="follow-mode__badge__label">
+ Following{" "}
+ <span
+ className="follow-mode__badge__username"
+ title={userToFollow.username}
+ >
+ {userToFollow.username}
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={onDisconnect}
+ className="follow-mode__disconnect-btn"
+ >
+ {CloseIcon}
+ </button>
+ </div>
+ </div>
+ );
+};
+
+export default FollowMode;
diff --git a/packages/excalidraw/components/FontPicker/FontPicker.scss b/packages/excalidraw/components/FontPicker/FontPicker.scss
new file mode 100644
index 0000000..5a57258
--- /dev/null
+++ b/packages/excalidraw/components/FontPicker/FontPicker.scss
@@ -0,0 +1,15 @@
+@import "../../css/variables.module.scss";
+
+.excalidraw {
+ .FontPicker__container {
+ display: grid;
+ grid-template-columns: calc(1rem + 3 * var(--default-button-size)) 1rem 1fr; // calc ~ 2 gaps + 4 buttons
+ align-items: center;
+
+ @include isMobile {
+ max-width: calc(
+ 2rem + 4 * var(--default-button-size)
+ ); // 4 gaps + 4 buttons
+ }
+ }
+}
diff --git a/packages/excalidraw/components/FontPicker/FontPicker.tsx b/packages/excalidraw/components/FontPicker/FontPicker.tsx
new file mode 100644
index 0000000..4585c58
--- /dev/null
+++ b/packages/excalidraw/components/FontPicker/FontPicker.tsx
@@ -0,0 +1,110 @@
+import React, { useCallback, useMemo } from "react";
+import * as Popover from "@radix-ui/react-popover";
+
+import { FontPickerList } from "./FontPickerList";
+import { FontPickerTrigger } from "./FontPickerTrigger";
+import { ButtonIconSelect } from "../ButtonIconSelect";
+import {
+ FontFamilyCodeIcon,
+ FontFamilyNormalIcon,
+ FreedrawIcon,
+} from "../icons";
+import { ButtonSeparator } from "../ButtonSeparator";
+import type { FontFamilyValues } from "../../element/types";
+import { FONT_FAMILY } from "../../constants";
+import { t } from "../../i18n";
+
+import "./FontPicker.scss";
+
+export const DEFAULT_FONTS = [
+ {
+ value: FONT_FAMILY.Excalifont,
+ icon: FreedrawIcon,
+ text: t("labels.handDrawn"),
+ testId: "font-family-hand-drawn",
+ },
+ {
+ value: FONT_FAMILY.Nunito,
+ icon: FontFamilyNormalIcon,
+ text: t("labels.normal"),
+ testId: "font-family-normal",
+ },
+ {
+ value: FONT_FAMILY["Comic Shanns"],
+ icon: FontFamilyCodeIcon,
+ text: t("labels.code"),
+ testId: "font-family-code",
+ },
+];
+
+const defaultFontFamilies = new Set(DEFAULT_FONTS.map((x) => x.value));
+
+export const isDefaultFont = (fontFamily: number | null) => {
+ if (!fontFamily) {
+ return false;
+ }
+
+ return defaultFontFamilies.has(fontFamily);
+};
+
+interface FontPickerProps {
+ isOpened: boolean;
+ selectedFontFamily: FontFamilyValues | null;
+ hoveredFontFamily: FontFamilyValues | null;
+ onSelect: (fontFamily: FontFamilyValues) => void;
+ onHover: (fontFamily: FontFamilyValues) => void;
+ onLeave: () => void;
+ onPopupChange: (open: boolean) => void;
+}
+
+export const FontPicker = React.memo(
+ ({
+ isOpened,
+ selectedFontFamily,
+ hoveredFontFamily,
+ onSelect,
+ onHover,
+ onLeave,
+ onPopupChange,
+ }: FontPickerProps) => {
+ const defaultFonts = useMemo(() => DEFAULT_FONTS, []);
+ const onSelectCallback = useCallback(
+ (value: number | false) => {
+ if (value) {
+ onSelect(value);
+ }
+ },
+ [onSelect],
+ );
+
+ return (
+ <div role="dialog" aria-modal="true" className="FontPicker__container">
+ <ButtonIconSelect<FontFamilyValues | false>
+ type="button"
+ options={defaultFonts}
+ value={selectedFontFamily}
+ onClick={onSelectCallback}
+ />
+ <ButtonSeparator />
+ <Popover.Root open={isOpened} onOpenChange={onPopupChange}>
+ <FontPickerTrigger selectedFontFamily={selectedFontFamily} />
+ {isOpened && (
+ <FontPickerList
+ selectedFontFamily={selectedFontFamily}
+ hoveredFontFamily={hoveredFontFamily}
+ onSelect={onSelectCallback}
+ onHover={onHover}
+ onLeave={onLeave}
+ onOpen={() => onPopupChange(true)}
+ onClose={() => onPopupChange(false)}
+ />
+ )}
+ </Popover.Root>
+ </div>
+ );
+ },
+ (prev, next) =>
+ prev.isOpened === next.isOpened &&
+ prev.selectedFontFamily === next.selectedFontFamily &&
+ prev.hoveredFontFamily === next.hoveredFontFamily,
+);
diff --git a/packages/excalidraw/components/FontPicker/FontPickerList.tsx b/packages/excalidraw/components/FontPicker/FontPickerList.tsx
new file mode 100644
index 0000000..3a680b8
--- /dev/null
+++ b/packages/excalidraw/components/FontPicker/FontPickerList.tsx
@@ -0,0 +1,272 @@
+import type { JSX } from "react";
+import React, {
+ useMemo,
+ useState,
+ useRef,
+ useEffect,
+ useCallback,
+ type KeyboardEventHandler,
+} from "react";
+import { useApp, useAppProps, useExcalidrawContainer } from "../App";
+import { PropertiesPopover } from "../PropertiesPopover";
+import { QuickSearch } from "../QuickSearch";
+import { ScrollableList } from "../ScrollableList";
+import DropdownMenuGroup from "../dropdownMenu/DropdownMenuGroup";
+import DropdownMenuItem, {
+ DropDownMenuItemBadgeType,
+ DropDownMenuItemBadge,
+} from "../dropdownMenu/DropdownMenuItem";
+import { type FontFamilyValues } from "../../element/types";
+import { arrayToList, debounce, getFontFamilyString } from "../../utils";
+import { t } from "../../i18n";
+import { fontPickerKeyHandler } from "./keyboardNavHandlers";
+import { Fonts } from "../../fonts";
+import type { ValueOf } from "../../utility-types";
+import { FontFamilyNormalIcon } from "../icons";
+
+export interface FontDescriptor {
+ value: number;
+ icon: JSX.Element;
+ text: string;
+ deprecated?: true;
+ badge?: {
+ type: ValueOf<typeof DropDownMenuItemBadgeType>;
+ placeholder: string;
+ };
+}
+
+interface FontPickerListProps {
+ selectedFontFamily: FontFamilyValues | null;
+ hoveredFontFamily: FontFamilyValues | null;
+ onSelect: (value: number) => void;
+ onHover: (value: number) => void;
+ onLeave: () => void;
+ onOpen: () => void;
+ onClose: () => void;
+}
+
+export const FontPickerList = React.memo(
+ ({
+ selectedFontFamily,
+ hoveredFontFamily,
+ onSelect,
+ onHover,
+ onLeave,
+ onOpen,
+ onClose,
+ }: FontPickerListProps) => {
+ const { container } = useExcalidrawContainer();
+ const { fonts } = useApp();
+ const { showDeprecatedFonts } = useAppProps();
+
+ const [searchTerm, setSearchTerm] = useState("");
+ const inputRef = useRef<HTMLInputElement>(null);
+ const allFonts = useMemo(
+ () =>
+ Array.from(Fonts.registered.entries())
+ .filter(
+ ([_, { metadata }]) => !metadata.serverSide && !metadata.fallback,
+ )
+ .map(([familyId, { metadata, fontFaces }]) => {
+ const fontDescriptor = {
+ value: familyId,
+ icon: metadata.icon ?? FontFamilyNormalIcon,
+ text: fontFaces[0]?.fontFace?.family ?? "Unknown",
+ };
+
+ if (metadata.deprecated) {
+ Object.assign(fontDescriptor, {
+ deprecated: metadata.deprecated,
+ badge: {
+ type: DropDownMenuItemBadgeType.RED,
+ placeholder: t("fontList.badge.old"),
+ },
+ });
+ }
+
+ return fontDescriptor as FontDescriptor;
+ })
+ .sort((a, b) =>
+ a.text.toLowerCase() > b.text.toLowerCase() ? 1 : -1,
+ ),
+ [],
+ );
+
+ const sceneFamilies = useMemo(
+ () => new Set(fonts.getSceneFamilies()),
+ // cache per selected font family, so hover re-render won't mess it up
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [selectedFontFamily],
+ );
+
+ const sceneFonts = useMemo(
+ () => allFonts.filter((font) => sceneFamilies.has(font.value)), // always show all the fonts in the scene, even those that were deprecated
+ [allFonts, sceneFamilies],
+ );
+
+ const availableFonts = useMemo(
+ () =>
+ allFonts.filter(
+ (font) =>
+ !sceneFamilies.has(font.value) &&
+ (showDeprecatedFonts || !font.deprecated), // skip deprecated fonts
+ ),
+ [allFonts, sceneFamilies, showDeprecatedFonts],
+ );
+
+ const filteredFonts = useMemo(
+ () =>
+ arrayToList(
+ [...sceneFonts, ...availableFonts].filter((font) =>
+ font.text?.toLowerCase().includes(searchTerm),
+ ),
+ ),
+ [sceneFonts, availableFonts, searchTerm],
+ );
+
+ const hoveredFont = useMemo(() => {
+ let font;
+
+ if (hoveredFontFamily) {
+ font = filteredFonts.find((font) => font.value === hoveredFontFamily);
+ } else if (selectedFontFamily) {
+ font = filteredFonts.find((font) => font.value === selectedFontFamily);
+ }
+
+ if (!font && searchTerm) {
+ if (filteredFonts[0]?.value) {
+ // hover first element on search
+ onHover(filteredFonts[0].value);
+ } else {
+ // re-render cache on no results
+ onLeave();
+ }
+ }
+
+ return font;
+ }, [
+ hoveredFontFamily,
+ selectedFontFamily,
+ searchTerm,
+ filteredFonts,
+ onHover,
+ onLeave,
+ ]);
+
+ const onKeyDown = useCallback<KeyboardEventHandler<HTMLDivElement>>(
+ (event) => {
+ const handled = fontPickerKeyHandler({
+ event,
+ inputRef,
+ hoveredFont,
+ filteredFonts,
+ onSelect,
+ onHover,
+ onClose,
+ });
+
+ if (handled) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ },
+ [hoveredFont, filteredFonts, onSelect, onHover, onClose],
+ );
+
+ useEffect(() => {
+ onOpen();
+
+ return () => {
+ onClose();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const sceneFilteredFonts = useMemo(
+ () => filteredFonts.filter((font) => sceneFamilies.has(font.value)),
+ [filteredFonts, sceneFamilies],
+ );
+
+ const availableFilteredFonts = useMemo(
+ () => filteredFonts.filter((font) => !sceneFamilies.has(font.value)),
+ [filteredFonts, sceneFamilies],
+ );
+
+ const renderFont = (font: FontDescriptor, index: number) => (
+ <DropdownMenuItem
+ key={font.value}
+ icon={font.icon}
+ value={font.value}
+ order={index}
+ textStyle={{
+ fontFamily: getFontFamilyString({ fontFamily: font.value }),
+ }}
+ hovered={font.value === hoveredFont?.value}
+ selected={font.value === selectedFontFamily}
+ // allow to tab between search and selected font
+ tabIndex={font.value === selectedFontFamily ? 0 : -1}
+ onClick={(e) => {
+ onSelect(Number(e.currentTarget.value));
+ }}
+ onMouseMove={() => {
+ if (hoveredFont?.value !== font.value) {
+ onHover(font.value);
+ }
+ }}
+ >
+ {font.text}
+ {font.badge && (
+ <DropDownMenuItemBadge type={font.badge.type}>
+ {font.badge.placeholder}
+ </DropDownMenuItemBadge>
+ )}
+ </DropdownMenuItem>
+ );
+
+ const groups = [];
+
+ if (sceneFilteredFonts.length) {
+ groups.push(
+ <DropdownMenuGroup title={t("fontList.sceneFonts")} key="group_1">
+ {sceneFilteredFonts.map(renderFont)}
+ </DropdownMenuGroup>,
+ );
+ }
+
+ if (availableFilteredFonts.length) {
+ groups.push(
+ <DropdownMenuGroup title={t("fontList.availableFonts")} key="group_2">
+ {availableFilteredFonts.map((font, index) =>
+ renderFont(font, index + sceneFilteredFonts.length),
+ )}
+ </DropdownMenuGroup>,
+ );
+ }
+
+ return (
+ <PropertiesPopover
+ className="properties-content"
+ container={container}
+ style={{ width: "15rem" }}
+ onClose={onClose}
+ onPointerLeave={onLeave}
+ onKeyDown={onKeyDown}
+ >
+ <QuickSearch
+ ref={inputRef}
+ placeholder={t("quickSearch.placeholder")}
+ onChange={debounce(setSearchTerm, 20)}
+ />
+ <ScrollableList
+ className="dropdown-menu fonts manual-hover"
+ placeholder={t("fontList.empty")}
+ >
+ {groups.length ? groups : null}
+ </ScrollableList>
+ </PropertiesPopover>
+ );
+ },
+ (prev, next) =>
+ prev.selectedFontFamily === next.selectedFontFamily &&
+ prev.hoveredFontFamily === next.hoveredFontFamily,
+);
diff --git a/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx b/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx
new file mode 100644
index 0000000..8652dab
--- /dev/null
+++ b/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx
@@ -0,0 +1,38 @@
+import * as Popover from "@radix-ui/react-popover";
+import { useMemo } from "react";
+import { ButtonIcon } from "../ButtonIcon";
+import { TextIcon } from "../icons";
+import type { FontFamilyValues } from "../../element/types";
+import { t } from "../../i18n";
+import { isDefaultFont } from "./FontPicker";
+
+interface FontPickerTriggerProps {
+ selectedFontFamily: FontFamilyValues | null;
+}
+
+export const FontPickerTrigger = ({
+ selectedFontFamily,
+}: FontPickerTriggerProps) => {
+ const isTriggerActive = useMemo(
+ () => Boolean(selectedFontFamily && !isDefaultFont(selectedFontFamily)),
+ [selectedFontFamily],
+ );
+
+ return (
+ <Popover.Trigger asChild>
+ {/* Empty div as trigger so it's stretched 100% due to different button sizes */}
+ <div>
+ <ButtonIcon
+ standalone
+ icon={TextIcon}
+ title={t("labels.showFonts")}
+ className="properties-trigger"
+ testId={"font-family-show-fonts"}
+ active={isTriggerActive}
+ // no-op
+ onClick={() => {}}
+ />
+ </div>
+ </Popover.Trigger>
+ );
+};
diff --git a/packages/excalidraw/components/FontPicker/keyboardNavHandlers.ts b/packages/excalidraw/components/FontPicker/keyboardNavHandlers.ts
new file mode 100644
index 0000000..19c4adc
--- /dev/null
+++ b/packages/excalidraw/components/FontPicker/keyboardNavHandlers.ts
@@ -0,0 +1,66 @@
+import type { Node } from "../../utils";
+import { KEYS } from "../../keys";
+import { type FontDescriptor } from "./FontPickerList";
+
+interface FontPickerKeyNavHandlerProps {
+ event: React.KeyboardEvent<HTMLDivElement>;
+ inputRef: React.RefObject<HTMLInputElement | null>;
+ hoveredFont: Node<FontDescriptor> | undefined;
+ filteredFonts: Node<FontDescriptor>[];
+ onClose: () => void;
+ onSelect: (value: number) => void;
+ onHover: (value: number) => void;
+}
+
+export const fontPickerKeyHandler = ({
+ event,
+ inputRef,
+ hoveredFont,
+ filteredFonts,
+ onClose,
+ onSelect,
+ onHover,
+}: FontPickerKeyNavHandlerProps) => {
+ if (
+ !event[KEYS.CTRL_OR_CMD] &&
+ event.shiftKey &&
+ event.key.toLowerCase() === KEYS.F
+ ) {
+ // refocus input on the popup trigger shortcut
+ inputRef.current?.focus();
+ return true;
+ }
+
+ if (event.key === KEYS.ESCAPE) {
+ onClose();
+ return true;
+ }
+
+ if (event.key === KEYS.ENTER) {
+ if (hoveredFont?.value) {
+ onSelect(hoveredFont.value);
+ }
+
+ return true;
+ }
+
+ if (event.key === KEYS.ARROW_DOWN) {
+ if (hoveredFont?.next) {
+ onHover(hoveredFont.next.value);
+ } else if (filteredFonts[0]?.value) {
+ onHover(filteredFonts[0].value);
+ }
+
+ return true;
+ }
+
+ if (event.key === KEYS.ARROW_UP) {
+ if (hoveredFont?.prev) {
+ onHover(hoveredFont.prev.value);
+ } else if (filteredFonts[filteredFonts.length - 1]?.value) {
+ onHover(filteredFonts[filteredFonts.length - 1].value);
+ }
+
+ return true;
+ }
+};
diff --git a/packages/excalidraw/components/HandButton.tsx b/packages/excalidraw/components/HandButton.tsx
new file mode 100644
index 0000000..ce63791
--- /dev/null
+++ b/packages/excalidraw/components/HandButton.tsx
@@ -0,0 +1,32 @@
+import "./ToolIcon.scss";
+
+import clsx from "clsx";
+import { ToolButton } from "./ToolButton";
+import { handIcon } from "./icons";
+import { KEYS } from "../keys";
+
+type LockIconProps = {
+ title?: string;
+ name?: string;
+ checked: boolean;
+ onChange?(): void;
+ isMobile?: boolean;
+};
+
+export const HandButton = (props: LockIconProps) => {
+ return (
+ <ToolButton
+ className={clsx("Shape", { fillable: false })}
+ type="radio"
+ icon={handIcon}
+ name="editor-current-shape"
+ checked={props.checked}
+ title={`${props.title} — H`}
+ keyBindingLabel={!props.isMobile ? KEYS.H.toLocaleUpperCase() : undefined}
+ aria-label={`${props.title} — H`}
+ aria-keyshortcuts={KEYS.H}
+ data-testid={`toolbar-hand`}
+ onChange={() => props.onChange?.()}
+ />
+ );
+};
diff --git a/packages/excalidraw/components/HelpButton.tsx b/packages/excalidraw/components/HelpButton.tsx
new file mode 100644
index 0000000..ce38724
--- /dev/null
+++ b/packages/excalidraw/components/HelpButton.tsx
@@ -0,0 +1,20 @@
+import { t } from "../i18n";
+import { HelpIcon } from "./icons";
+
+type HelpButtonProps = {
+ name?: string;
+ id?: string;
+ onClick?(): void;
+};
+
+export const HelpButton = (props: HelpButtonProps) => (
+ <button
+ className="help-icon"
+ onClick={props.onClick}
+ type="button"
+ title={`${t("helpDialog.title")} — ?`}
+ aria-label={t("helpDialog.title")}
+ >
+ {HelpIcon}
+ </button>
+);
diff --git a/packages/excalidraw/components/HelpDialog.scss b/packages/excalidraw/components/HelpDialog.scss
new file mode 100644
index 0000000..ce4dd44
--- /dev/null
+++ b/packages/excalidraw/components/HelpDialog.scss
@@ -0,0 +1,130 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .HelpDialog {
+ .Modal__content {
+ max-width: 960px;
+ }
+
+ h3 {
+ margin: 1.5rem 0;
+ font-weight: 700;
+ font-size: 1.125rem;
+ }
+
+ &__header {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.75rem;
+ }
+
+ &__btn {
+ --background: var(--color-surface-mid);
+
+ display: flex;
+ column-gap: 0.5rem;
+ align-items: center;
+ background-color: var(--background);
+ padding: 0.625rem 1rem;
+ border: 1px solid var(--background);
+ border-radius: var(--border-radius-lg);
+ color: var(--text-primary-color);
+ font-weight: 600;
+ font-size: 0.75rem;
+ letter-spacing: 0.4px;
+
+ @at-root .excalidraw.theme--dark#{&} {
+ --background: var(--color-surface-high);
+ &:hover {
+ --background: #363541;
+ }
+ }
+
+ &:hover {
+ --background: var(--color-surface-high);
+ text-decoration: none;
+ }
+
+ &:active {
+ border-color: var(--color-primary);
+ }
+ }
+
+ &__link-icon {
+ line-height: 0;
+ svg {
+ width: 1rem;
+ height: 1rem;
+ }
+ }
+
+ &__islands-container {
+ display: grid;
+ @media screen and (min-width: 1024px) {
+ grid-template-columns: 1fr 1fr;
+ }
+ grid-column-gap: 1.5rem;
+ grid-row-gap: 2rem;
+ }
+
+ @media screen and (min-width: 1024px) {
+ &__island--tools {
+ grid-area: 1 / 1 / 2 / 2;
+ }
+ &__island--view {
+ grid-area: 2 / 1 / 3 / 2;
+ }
+ &__island--editor {
+ grid-area: 1 / 2 / 3 / 3;
+ }
+ }
+
+ &__island {
+ h4 {
+ font-size: 1rem;
+ font-weight: 700;
+ margin: 0;
+ margin-bottom: 0.625rem;
+ }
+
+ &-content {
+ border: 1px solid var(--dialog-border-color);
+ border-radius: var(--border-radius-lg);
+ }
+ }
+
+ &__shortcut {
+ border-bottom: 1px solid var(--dialog-border-color);
+ padding: 0.375rem 0.75rem;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ font-size: 0.875rem;
+ column-gap: 0.5rem;
+
+ &:last-child {
+ border-bottom: none;
+ }
+ }
+
+ &__key-container {
+ display: flex;
+ align-items: center;
+ column-gap: 0.25rem;
+ flex-shrink: 0;
+ }
+
+ &__key {
+ display: flex;
+ box-sizing: border-box;
+ font-size: 0.625rem;
+ background-color: var(--color-primary-light);
+ border-radius: var(--border-radius-md);
+ padding: 0.5rem;
+ word-break: keep-all;
+ align-items: center;
+ font-family: inherit;
+ line-height: 1;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/HelpDialog.tsx b/packages/excalidraw/components/HelpDialog.tsx
new file mode 100644
index 0000000..926096c
--- /dev/null
+++ b/packages/excalidraw/components/HelpDialog.tsx
@@ -0,0 +1,503 @@
+import type { JSX } from "react";
+import React from "react";
+import { t } from "../i18n";
+import { KEYS } from "../keys";
+import { Dialog } from "./Dialog";
+import { getShortcutKey } from "../utils";
+import "./HelpDialog.scss";
+import { ExternalLinkIcon, GithubIcon, youtubeIcon } from "./icons";
+import { probablySupportsClipboardBlob } from "../clipboard";
+import { isDarwin, isFirefox, isWindows } from "../constants";
+import { getShortcutFromShortcutName } from "../actions/shortcuts";
+
+const Header = () => (
+ <div className="HelpDialog__header">
+ <a
+ className="HelpDialog__btn"
+ href="https://docs.excalidraw.com"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <div className="HelpDialog__link-icon">{ExternalLinkIcon}</div>
+ {t("helpDialog.documentation")}
+ </a>
+ <a
+ className="HelpDialog__btn"
+ href="https://plus.excalidraw.com/blog"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <div className="HelpDialog__link-icon">{ExternalLinkIcon}</div>
+ {t("helpDialog.blog")}
+ </a>
+ <a
+ className="HelpDialog__btn"
+ href="https://github.com/excalidraw/excalidraw/issues"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <div className="HelpDialog__link-icon">{GithubIcon}</div>
+ {t("helpDialog.github")}
+ </a>
+ <a
+ className="HelpDialog__btn"
+ href="https://youtube.com/@excalidraw"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <div className="HelpDialog__link-icon">{youtubeIcon}</div>
+ YouTube
+ </a>
+ </div>
+);
+
+const Section = (props: { title: string; children: React.ReactNode }) => (
+ <>
+ <h3>{props.title}</h3>
+ <div className="HelpDialog__islands-container">{props.children}</div>
+ </>
+);
+
+const ShortcutIsland = (props: {
+ caption: string;
+ children: React.ReactNode;
+ className?: string;
+}) => (
+ <div className={`HelpDialog__island ${props.className}`}>
+ <h4 className="HelpDialog__island-title">{props.caption}</h4>
+ <div className="HelpDialog__island-content">{props.children}</div>
+ </div>
+);
+
+function* intersperse(as: JSX.Element[][], delim: string | null) {
+ let first = true;
+ for (const x of as) {
+ if (!first) {
+ yield delim;
+ }
+ first = false;
+ yield x;
+ }
+}
+
+const upperCaseSingleChars = (str: string) => {
+ return str.replace(/\b[a-z]\b/, (c) => c.toUpperCase());
+};
+
+const Shortcut = ({
+ label,
+ shortcuts,
+ isOr = true,
+}: {
+ label: string;
+ shortcuts: string[];
+ isOr?: boolean;
+}) => {
+ const splitShortcutKeys = shortcuts.map((shortcut) => {
+ const keys = shortcut.endsWith("++")
+ ? [...shortcut.slice(0, -2).split("+"), "+"]
+ : shortcut.split("+");
+
+ return keys.map((key) => (
+ <ShortcutKey key={key}>{upperCaseSingleChars(key)}</ShortcutKey>
+ ));
+ });
+
+ return (
+ <div className="HelpDialog__shortcut">
+ <div>{label}</div>
+ <div className="HelpDialog__key-container">
+ {[...intersperse(splitShortcutKeys, isOr ? t("helpDialog.or") : null)]}
+ </div>
+ </div>
+ );
+};
+
+const ShortcutKey = (props: { children: React.ReactNode }) => (
+ <kbd className="HelpDialog__key" {...props} />
+);
+
+export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
+ const handleClose = React.useCallback(() => {
+ if (onClose) {
+ onClose();
+ }
+ }, [onClose]);
+
+ return (
+ <>
+ <Dialog
+ onCloseRequest={handleClose}
+ title={t("helpDialog.title")}
+ className={"HelpDialog"}
+ >
+ <Header />
+ <Section title={t("helpDialog.shortcuts")}>
+ <ShortcutIsland
+ className="HelpDialog__island--tools"
+ caption={t("helpDialog.tools")}
+ >
+ <Shortcut label={t("toolBar.hand")} shortcuts={[KEYS.H]} />
+ <Shortcut
+ label={t("toolBar.selection")}
+ shortcuts={[KEYS.V, KEYS["1"]]}
+ />
+ <Shortcut
+ label={t("toolBar.rectangle")}
+ shortcuts={[KEYS.R, KEYS["2"]]}
+ />
+ <Shortcut
+ label={t("toolBar.diamond")}
+ shortcuts={[KEYS.D, KEYS["3"]]}
+ />
+ <Shortcut
+ label={t("toolBar.ellipse")}
+ shortcuts={[KEYS.O, KEYS["4"]]}
+ />
+ <Shortcut
+ label={t("toolBar.arrow")}
+ shortcuts={[KEYS.A, KEYS["5"]]}
+ />
+ <Shortcut
+ label={t("toolBar.line")}
+ shortcuts={[KEYS.L, KEYS["6"]]}
+ />
+ <Shortcut
+ label={t("toolBar.freedraw")}
+ shortcuts={[KEYS.P, KEYS["7"]]}
+ />
+ <Shortcut
+ label={t("toolBar.text")}
+ shortcuts={[KEYS.T, KEYS["8"]]}
+ />
+ <Shortcut label={t("toolBar.image")} shortcuts={[KEYS["9"]]} />
+ <Shortcut
+ label={t("toolBar.eraser")}
+ shortcuts={[KEYS.E, KEYS["0"]]}
+ />
+ <Shortcut label={t("toolBar.frame")} shortcuts={[KEYS.F]} />
+ <Shortcut label={t("toolBar.laser")} shortcuts={[KEYS.K]} />
+ <Shortcut
+ label={t("labels.eyeDropper")}
+ shortcuts={[KEYS.I, "Shift+S", "Shift+G"]}
+ />
+ <Shortcut
+ label={t("helpDialog.editLineArrowPoints")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Enter")]}
+ />
+ <Shortcut
+ label={t("helpDialog.editText")}
+ shortcuts={[getShortcutKey("Enter")]}
+ />
+ <Shortcut
+ label={t("helpDialog.textNewLine")}
+ shortcuts={[
+ getShortcutKey("Enter"),
+ getShortcutKey("Shift+Enter"),
+ ]}
+ />
+ <Shortcut
+ label={t("helpDialog.textFinish")}
+ shortcuts={[
+ getShortcutKey("Esc"),
+ getShortcutKey("CtrlOrCmd+Enter"),
+ ]}
+ />
+ <Shortcut
+ label={t("helpDialog.curvedArrow")}
+ shortcuts={[
+ "A",
+ t("helpDialog.click"),
+ t("helpDialog.click"),
+ t("helpDialog.click"),
+ ]}
+ isOr={false}
+ />
+ <Shortcut
+ label={t("helpDialog.curvedLine")}
+ shortcuts={[
+ "L",
+ t("helpDialog.click"),
+ t("helpDialog.click"),
+ t("helpDialog.click"),
+ ]}
+ isOr={false}
+ />
+ <Shortcut
+ label={t("helpDialog.cropStart")}
+ shortcuts={[t("helpDialog.doubleClick"), getShortcutKey("Enter")]}
+ isOr={true}
+ />
+ <Shortcut
+ label={t("helpDialog.cropFinish")}
+ shortcuts={[getShortcutKey("Enter"), getShortcutKey("Escape")]}
+ isOr={true}
+ />
+ <Shortcut label={t("toolBar.lock")} shortcuts={[KEYS.Q]} />
+ <Shortcut
+ label={t("helpDialog.preventBinding")}
+ shortcuts={[getShortcutKey("CtrlOrCmd")]}
+ />
+ <Shortcut
+ label={t("toolBar.link")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+K")]}
+ />
+ </ShortcutIsland>
+ <ShortcutIsland
+ className="HelpDialog__island--view"
+ caption={t("helpDialog.view")}
+ >
+ <Shortcut
+ label={t("buttons.zoomIn")}
+ shortcuts={[getShortcutKey("CtrlOrCmd++")]}
+ />
+ <Shortcut
+ label={t("buttons.zoomOut")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+-")]}
+ />
+ <Shortcut
+ label={t("buttons.resetZoom")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+0")]}
+ />
+ <Shortcut
+ label={t("helpDialog.zoomToFit")}
+ shortcuts={["Shift+1"]}
+ />
+ <Shortcut
+ label={t("helpDialog.zoomToSelection")}
+ shortcuts={["Shift+2"]}
+ />
+ <Shortcut
+ label={t("helpDialog.movePageUpDown")}
+ shortcuts={["PgUp/PgDn"]}
+ />
+ <Shortcut
+ label={t("helpDialog.movePageLeftRight")}
+ shortcuts={["Shift+PgUp/PgDn"]}
+ />
+ <Shortcut
+ label={t("buttons.zenMode")}
+ shortcuts={[getShortcutKey("Alt+Z")]}
+ />
+ <Shortcut
+ label={t("buttons.objectsSnapMode")}
+ shortcuts={[getShortcutKey("Alt+S")]}
+ />
+ <Shortcut
+ label={t("labels.toggleGrid")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+'")]}
+ />
+ <Shortcut
+ label={t("labels.viewMode")}
+ shortcuts={[getShortcutKey("Alt+R")]}
+ />
+ <Shortcut
+ label={t("labels.toggleTheme")}
+ shortcuts={[getShortcutKey("Alt+Shift+D")]}
+ />
+ <Shortcut
+ label={t("stats.fullTitle")}
+ shortcuts={[getShortcutKey("Alt+/")]}
+ />
+ <Shortcut
+ label={t("search.title")}
+ shortcuts={[getShortcutFromShortcutName("searchMenu")]}
+ />
+ <Shortcut
+ label={t("commandPalette.title")}
+ shortcuts={
+ isFirefox
+ ? [getShortcutFromShortcutName("commandPalette")]
+ : [
+ getShortcutFromShortcutName("commandPalette"),
+ getShortcutFromShortcutName("commandPalette", 1),
+ ]
+ }
+ />
+ </ShortcutIsland>
+ <ShortcutIsland
+ className="HelpDialog__island--editor"
+ caption={t("helpDialog.editor")}
+ >
+ <Shortcut
+ label={t("helpDialog.createFlowchart")}
+ shortcuts={[getShortcutKey(`CtrlOrCmd+Arrow Key`)]}
+ isOr={true}
+ />
+ <Shortcut
+ label={t("helpDialog.navigateFlowchart")}
+ shortcuts={[getShortcutKey(`Alt+Arrow Key`)]}
+ isOr={true}
+ />
+ <Shortcut
+ label={t("labels.moveCanvas")}
+ shortcuts={[
+ getShortcutKey(`Space+${t("helpDialog.drag")}`),
+ getShortcutKey(`Wheel+${t("helpDialog.drag")}`),
+ ]}
+ isOr={true}
+ />
+ <Shortcut
+ label={t("buttons.clearReset")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Delete")]}
+ />
+ <Shortcut
+ label={t("labels.delete")}
+ shortcuts={[getShortcutKey("Delete")]}
+ />
+ <Shortcut
+ label={t("labels.cut")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+X")]}
+ />
+ <Shortcut
+ label={t("labels.copy")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+C")]}
+ />
+ <Shortcut
+ label={t("labels.paste")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+V")]}
+ />
+ <Shortcut
+ label={t("labels.pasteAsPlaintext")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+V")]}
+ />
+ <Shortcut
+ label={t("labels.selectAll")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+A")]}
+ />
+ <Shortcut
+ label={t("labels.multiSelect")}
+ shortcuts={[getShortcutKey(`Shift+${t("helpDialog.click")}`)]}
+ />
+ <Shortcut
+ label={t("helpDialog.deepSelect")}
+ shortcuts={[getShortcutKey(`CtrlOrCmd+${t("helpDialog.click")}`)]}
+ />
+ <Shortcut
+ label={t("helpDialog.deepBoxSelect")}
+ shortcuts={[getShortcutKey(`CtrlOrCmd+${t("helpDialog.drag")}`)]}
+ />
+ {/* firefox supports clipboard API under a flag, so we'll
+ show users what they can do in the error message */}
+ {(probablySupportsClipboardBlob || isFirefox) && (
+ <Shortcut
+ label={t("labels.copyAsPng")}
+ shortcuts={[getShortcutKey("Shift+Alt+C")]}
+ />
+ )}
+ <Shortcut
+ label={t("labels.copyStyles")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Alt+C")]}
+ />
+ <Shortcut
+ label={t("labels.pasteStyles")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Alt+V")]}
+ />
+ <Shortcut
+ label={t("labels.sendToBack")}
+ shortcuts={[
+ isDarwin
+ ? getShortcutKey("CtrlOrCmd+Alt+[")
+ : getShortcutKey("CtrlOrCmd+Shift+["),
+ ]}
+ />
+ <Shortcut
+ label={t("labels.bringToFront")}
+ shortcuts={[
+ isDarwin
+ ? getShortcutKey("CtrlOrCmd+Alt+]")
+ : getShortcutKey("CtrlOrCmd+Shift+]"),
+ ]}
+ />
+ <Shortcut
+ label={t("labels.sendBackward")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+[")]}
+ />
+ <Shortcut
+ label={t("labels.bringForward")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+]")]}
+ />
+ <Shortcut
+ label={t("labels.alignTop")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Up")]}
+ />
+ <Shortcut
+ label={t("labels.alignBottom")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Down")]}
+ />
+ <Shortcut
+ label={t("labels.alignLeft")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Left")]}
+ />
+ <Shortcut
+ label={t("labels.alignRight")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Right")]}
+ />
+ <Shortcut
+ label={t("labels.duplicateSelection")}
+ shortcuts={[
+ getShortcutKey("CtrlOrCmd+D"),
+ getShortcutKey(`Alt+${t("helpDialog.drag")}`),
+ ]}
+ />
+ <Shortcut
+ label={t("helpDialog.toggleElementLock")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+L")]}
+ />
+ <Shortcut
+ label={t("buttons.undo")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Z")]}
+ />
+ <Shortcut
+ label={t("buttons.redo")}
+ shortcuts={
+ isWindows
+ ? [
+ getShortcutKey("CtrlOrCmd+Y"),
+ getShortcutKey("CtrlOrCmd+Shift+Z"),
+ ]
+ : [getShortcutKey("CtrlOrCmd+Shift+Z")]
+ }
+ />
+ <Shortcut
+ label={t("labels.group")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+G")]}
+ />
+ <Shortcut
+ label={t("labels.ungroup")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+G")]}
+ />
+ <Shortcut
+ label={t("labels.flipHorizontal")}
+ shortcuts={[getShortcutKey("Shift+H")]}
+ />
+ <Shortcut
+ label={t("labels.flipVertical")}
+ shortcuts={[getShortcutKey("Shift+V")]}
+ />
+ <Shortcut
+ label={t("labels.showStroke")}
+ shortcuts={[getShortcutKey("S")]}
+ />
+ <Shortcut
+ label={t("labels.showBackground")}
+ shortcuts={[getShortcutKey("G")]}
+ />
+ <Shortcut
+ label={t("labels.showFonts")}
+ shortcuts={[getShortcutKey("Shift+F")]}
+ />
+ <Shortcut
+ label={t("labels.decreaseFontSize")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+<")]}
+ />
+ <Shortcut
+ label={t("labels.increaseFontSize")}
+ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+>")]}
+ />
+ </ShortcutIsland>
+ </Section>
+ </Dialog>
+ </>
+ );
+};
diff --git a/packages/excalidraw/components/HintViewer.scss b/packages/excalidraw/components/HintViewer.scss
new file mode 100644
index 0000000..7ed7e62
--- /dev/null
+++ b/packages/excalidraw/components/HintViewer.scss
@@ -0,0 +1,38 @@
+@import "../css/variables.module.scss";
+
+// this is loosely based on the longest hint text
+$wide-viewport-width: 1000px;
+
+.excalidraw {
+ .HintViewer {
+ pointer-events: none;
+ box-sizing: border-box;
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ left: 0;
+ top: 100%;
+ max-width: 100%;
+ width: 100%;
+ margin-top: 0.5rem;
+ text-align: center;
+ color: var(--color-gray-40);
+ font-size: 0.75rem;
+
+ @include isMobile {
+ position: static;
+ padding-right: 2rem;
+ }
+
+ > span {
+ padding: 0.25rem;
+ }
+ }
+
+ &.theme--dark {
+ .HintViewer {
+ color: var(--color-gray-60);
+ }
+ }
+}
diff --git a/packages/excalidraw/components/HintViewer.tsx b/packages/excalidraw/components/HintViewer.tsx
new file mode 100644
index 0000000..f09f658
--- /dev/null
+++ b/packages/excalidraw/components/HintViewer.tsx
@@ -0,0 +1,194 @@
+import { t } from "../i18n";
+import type { AppClassProperties, Device, UIAppState } from "../types";
+import {
+ isFlowchartNodeElement,
+ isImageElement,
+ isLinearElement,
+ isTextBindableContainer,
+ isTextElement,
+} from "../element/typeChecks";
+import { getShortcutKey } from "../utils";
+import { isEraserActive } from "../appState";
+
+import "./HintViewer.scss";
+import { isNodeInFlowchart } from "../element/flowchart";
+import { isGridModeEnabled } from "../snapping";
+import { CANVAS_SEARCH_TAB, DEFAULT_SIDEBAR } from "../constants";
+
+interface HintViewerProps {
+ appState: UIAppState;
+ isMobile: boolean;
+ device: Device;
+ app: AppClassProperties;
+}
+
+const getHints = ({
+ appState,
+ isMobile,
+ device,
+ app,
+}: HintViewerProps): null | string | string[] => {
+ const { activeTool, isResizing, isRotating, lastPointerDownWith } = appState;
+ const multiMode = appState.multiElement !== null;
+
+ if (
+ appState.openSidebar?.name === DEFAULT_SIDEBAR.name &&
+ appState.openSidebar.tab === CANVAS_SEARCH_TAB &&
+ appState.searchMatches?.length
+ ) {
+ return t("hints.dismissSearch");
+ }
+
+ if (appState.openSidebar && !device.editor.canFitSidebar) {
+ return null;
+ }
+
+ if (isEraserActive(appState)) {
+ return t("hints.eraserRevert");
+ }
+ if (activeTool.type === "arrow" || activeTool.type === "line") {
+ if (multiMode) {
+ return t("hints.linearElementMulti");
+ }
+ if (activeTool.type === "arrow") {
+ return t("hints.arrowTool", { arrowShortcut: getShortcutKey("A") });
+ }
+ return t("hints.linearElement");
+ }
+
+ if (activeTool.type === "freedraw") {
+ return t("hints.freeDraw");
+ }
+
+ if (activeTool.type === "text") {
+ return t("hints.text");
+ }
+
+ if (activeTool.type === "embeddable") {
+ return t("hints.embeddable");
+ }
+
+ if (appState.activeTool.type === "image" && appState.pendingImageElementId) {
+ return t("hints.placeImage");
+ }
+
+ const selectedElements = app.scene.getSelectedElements(appState);
+
+ if (
+ isResizing &&
+ lastPointerDownWith === "mouse" &&
+ selectedElements.length === 1
+ ) {
+ const targetElement = selectedElements[0];
+ if (isLinearElement(targetElement) && targetElement.points.length === 2) {
+ return t("hints.lockAngle");
+ }
+ return isImageElement(targetElement)
+ ? t("hints.resizeImage")
+ : t("hints.resize");
+ }
+
+ if (isRotating && lastPointerDownWith === "mouse") {
+ return t("hints.rotate");
+ }
+
+ if (selectedElements.length === 1 && isTextElement(selectedElements[0])) {
+ return t("hints.text_selected");
+ }
+
+ if (appState.editingTextElement) {
+ return t("hints.text_editing");
+ }
+
+ if (appState.croppingElementId) {
+ return t("hints.leaveCropEditor");
+ }
+
+ if (selectedElements.length === 1 && isImageElement(selectedElements[0])) {
+ return t("hints.enterCropEditor");
+ }
+
+ if (activeTool.type === "selection") {
+ if (
+ appState.selectionElement &&
+ !selectedElements.length &&
+ !appState.editingTextElement &&
+ !appState.editingLinearElement
+ ) {
+ return t("hints.deepBoxSelect");
+ }
+
+ if (isGridModeEnabled(app) && appState.selectedElementsAreBeingDragged) {
+ return t("hints.disableSnapping");
+ }
+
+ if (!selectedElements.length && !isMobile) {
+ return t("hints.canvasPanning");
+ }
+
+ if (selectedElements.length === 1) {
+ if (isLinearElement(selectedElements[0])) {
+ if (appState.editingLinearElement) {
+ return appState.editingLinearElement.selectedPointsIndices
+ ? t("hints.lineEditor_pointSelected")
+ : t("hints.lineEditor_nothingSelected");
+ }
+ return t("hints.lineEditor_info");
+ }
+ if (
+ !appState.newElement &&
+ !appState.selectedElementsAreBeingDragged &&
+ isTextBindableContainer(selectedElements[0])
+ ) {
+ if (isFlowchartNodeElement(selectedElements[0])) {
+ if (
+ isNodeInFlowchart(
+ selectedElements[0],
+ app.scene.getNonDeletedElementsMap(),
+ )
+ ) {
+ return [t("hints.bindTextToElement"), t("hints.createFlowchart")];
+ }
+
+ return [t("hints.bindTextToElement"), t("hints.createFlowchart")];
+ }
+
+ return t("hints.bindTextToElement");
+ }
+ }
+ }
+
+ return null;
+};
+
+export const HintViewer = ({
+ appState,
+ isMobile,
+ device,
+ app,
+}: HintViewerProps) => {
+ const hints = getHints({
+ appState,
+ isMobile,
+ device,
+ app,
+ });
+
+ if (!hints) {
+ return null;
+ }
+
+ const hint = Array.isArray(hints)
+ ? hints
+ .map((hint) => {
+ return getShortcutKey(hint).replace(/\. ?$/, "");
+ })
+ .join(". ")
+ : getShortcutKey(hints);
+
+ return (
+ <div className="HintViewer">
+ <span>{hint}</span>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/IconPicker.scss b/packages/excalidraw/components/IconPicker.scss
new file mode 100644
index 0000000..b9b47b3
--- /dev/null
+++ b/packages/excalidraw/components/IconPicker.scss
@@ -0,0 +1,109 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .picker {
+ padding: 0.5rem;
+ background: var(--popup-bg-color);
+ border: 0 solid transparentize($oc-white, 0.75);
+ box-shadow: var(--shadow-island);
+ border-radius: 4px;
+ position: absolute;
+ :root[dir="rtl"] & {
+ padding: 0.4rem;
+ }
+ }
+
+ .picker-container button,
+ .picker button {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ &:focus-visible {
+ outline: transparent;
+ background-color: var(--button-gray-2);
+ & svg {
+ opacity: 1;
+ }
+ }
+
+ &:hover {
+ background-color: var(--button-gray-2);
+ }
+
+ &:active {
+ background-color: var(--button-gray-3);
+ }
+
+ &:disabled {
+ cursor: not-allowed;
+ }
+
+ svg {
+ margin: 0;
+ width: 36px;
+ height: 18px;
+ pointer-events: none;
+ }
+ }
+
+ .picker button {
+ padding: 0.25rem 0.28rem 0.35rem 0.25rem;
+ }
+
+ .picker-content {
+ display: grid;
+ grid-template-columns: repeat(4, auto);
+ grid-gap: 0.5rem;
+ border-radius: 4px;
+ }
+
+ .picker-collapsible {
+ font-size: 0.75rem;
+ padding: 0.5rem 0;
+ }
+
+ .picker-keybinding {
+ position: absolute;
+ bottom: 2px;
+ font-size: 0.7em;
+ color: var(--keybinding-color);
+
+ :root[dir="ltr"] & {
+ right: 2px;
+ }
+
+ :root[dir="rtl"] & {
+ left: 2px;
+ }
+ @include isMobile {
+ display: none;
+ }
+ }
+
+ .picker-type-canvasBackground .picker-keybinding {
+ color: #aaa;
+ }
+
+ .picker-type-elementBackground .picker-keybinding {
+ color: $oc-white;
+ }
+
+ .picker-swatch[aria-label="transparent"] .picker-keybinding {
+ color: #aaa;
+ }
+
+ .picker-type-elementStroke .picker-keybinding {
+ color: #d4d4d4;
+ }
+
+ &.theme--dark {
+ .picker-type-elementBackground .picker-keybinding {
+ color: $oc-black;
+ }
+ .picker-swatch[aria-label="transparent"] .picker-keybinding {
+ color: $oc-black;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/IconPicker.tsx b/packages/excalidraw/components/IconPicker.tsx
new file mode 100644
index 0000000..ee83f90
--- /dev/null
+++ b/packages/excalidraw/components/IconPicker.tsx
@@ -0,0 +1,239 @@
+import type { JSX } from "react";
+import React, { useEffect } from "react";
+import * as Popover from "@radix-ui/react-popover";
+import { isArrowKey, KEYS } from "../keys";
+import { getLanguage, t } from "../i18n";
+import clsx from "clsx";
+import Collapsible from "./Stats/Collapsible";
+import { atom, useAtom } from "../editor-jotai";
+import { useDevice } from "./App";
+
+import "./IconPicker.scss";
+
+const moreOptionsAtom = atom(false);
+
+type Option<T> = {
+ value: T;
+ text: string;
+ icon: JSX.Element;
+ keyBinding: string | null;
+};
+
+function Picker<T>({
+ options,
+ value,
+ label,
+ onChange,
+ onClose,
+ numberOfOptionsToAlwaysShow = options.length,
+}: {
+ label: string;
+ value: T;
+ options: readonly Option<T>[];
+ onChange: (value: T) => void;
+ onClose: () => void;
+ numberOfOptionsToAlwaysShow?: number;
+}) {
+ const device = useDevice();
+
+ const handleKeyDown = (event: React.KeyboardEvent) => {
+ const pressedOption = options.find(
+ (option) => option.keyBinding === event.key.toLowerCase(),
+ )!;
+
+ if (!(event.metaKey || event.altKey || event.ctrlKey) && pressedOption) {
+ // Keybinding navigation
+ onChange(pressedOption.value);
+
+ event.preventDefault();
+ } else if (event.key === KEYS.TAB) {
+ const index = options.findIndex((option) => option.value === value);
+ const nextIndex = event.shiftKey
+ ? (options.length + index - 1) % options.length
+ : (index + 1) % options.length;
+ onChange(options[nextIndex].value);
+ } else if (isArrowKey(event.key)) {
+ // Arrow navigation
+ const isRTL = getLanguage().rtl;
+ const index = options.findIndex((option) => option.value === value);
+ if (index !== -1) {
+ const length = options.length;
+ let nextIndex = index;
+
+ switch (event.key) {
+ // Select the next option
+ case isRTL ? KEYS.ARROW_LEFT : KEYS.ARROW_RIGHT:
+ nextIndex = (index + 1) % length;
+ break;
+ // Select the previous option
+ case isRTL ? KEYS.ARROW_RIGHT : KEYS.ARROW_LEFT:
+ nextIndex = (length + index - 1) % length;
+ break;
+ // Go the next row
+ case KEYS.ARROW_DOWN: {
+ nextIndex = (index + (numberOfOptionsToAlwaysShow ?? 1)) % length;
+ break;
+ }
+ // Go the previous row
+ case KEYS.ARROW_UP: {
+ nextIndex =
+ (length + index - (numberOfOptionsToAlwaysShow ?? 1)) % length;
+ break;
+ }
+ }
+
+ onChange(options[nextIndex].value);
+ }
+ event.preventDefault();
+ } else if (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) {
+ // Close on escape or enter
+ event.preventDefault();
+ onClose();
+ }
+ event.nativeEvent.stopImmediatePropagation();
+ event.stopPropagation();
+ };
+
+ const [showMoreOptions, setShowMoreOptions] = useAtom(moreOptionsAtom);
+
+ const alwaysVisibleOptions = React.useMemo(
+ () => options.slice(0, numberOfOptionsToAlwaysShow),
+ [options, numberOfOptionsToAlwaysShow],
+ );
+ const moreOptions = React.useMemo(
+ () => options.slice(numberOfOptionsToAlwaysShow),
+ [options, numberOfOptionsToAlwaysShow],
+ );
+
+ useEffect(() => {
+ if (!alwaysVisibleOptions.some((option) => option.value === value)) {
+ setShowMoreOptions(true);
+ }
+ }, [value, alwaysVisibleOptions, setShowMoreOptions]);
+
+ const renderOptions = (options: Option<T>[]) => {
+ return (
+ <div className="picker-content">
+ {options.map((option, i) => (
+ <button
+ type="button"
+ className={clsx("picker-option", {
+ active: value === option.value,
+ })}
+ onClick={(event) => {
+ onChange(option.value);
+ }}
+ title={`${option.text} ${
+ option.keyBinding && `— ${option.keyBinding.toUpperCase()}`
+ }`}
+ aria-label={option.text || "none"}
+ aria-keyshortcuts={option.keyBinding || undefined}
+ key={option.text}
+ ref={(ref) => {
+ if (value === option.value) {
+ // Use a timeout here to render focus properly
+ setTimeout(() => {
+ ref?.focus();
+ }, 0);
+ }
+ }}
+ >
+ {option.icon}
+ {option.keyBinding && (
+ <span className="picker-keybinding">{option.keyBinding}</span>
+ )}
+ </button>
+ ))}
+ </div>
+ );
+ };
+
+ return (
+ <Popover.Content
+ side={
+ device.editor.isMobile && !device.viewport.isLandscape
+ ? "top"
+ : "bottom"
+ }
+ align="start"
+ sideOffset={12}
+ style={{ zIndex: "var(--zIndex-popup)" }}
+ onKeyDown={handleKeyDown}
+ >
+ <div
+ className={`picker`}
+ role="dialog"
+ aria-modal="true"
+ aria-label={label}
+ >
+ {renderOptions(alwaysVisibleOptions)}
+
+ {moreOptions.length > 0 && (
+ <Collapsible
+ label={t("labels.more_options")}
+ open={showMoreOptions}
+ openTrigger={() => {
+ setShowMoreOptions((value) => !value);
+ }}
+ className="picker-collapsible"
+ >
+ {renderOptions(moreOptions)}
+ </Collapsible>
+ )}
+ </div>
+ </Popover.Content>
+ );
+}
+
+export function IconPicker<T>({
+ value,
+ label,
+ options,
+ onChange,
+ group = "",
+ numberOfOptionsToAlwaysShow,
+}: {
+ label: string;
+ value: T;
+ options: readonly {
+ value: T;
+ text: string;
+ icon: JSX.Element;
+ keyBinding: string | null;
+ }[];
+ onChange: (value: T) => void;
+ numberOfOptionsToAlwaysShow?: number;
+ group?: string;
+}) {
+ const [isActive, setActive] = React.useState(false);
+ const rPickerButton = React.useRef<any>(null);
+
+ return (
+ <div>
+ <Popover.Root open={isActive} onOpenChange={(open) => setActive(open)}>
+ <Popover.Trigger
+ name={group}
+ type="button"
+ aria-label={label}
+ onClick={() => setActive(!isActive)}
+ ref={rPickerButton}
+ className={isActive ? "active" : ""}
+ >
+ {options.find((option) => option.value === value)?.icon}
+ </Popover.Trigger>
+ {isActive && (
+ <Picker
+ options={options}
+ value={value}
+ label={label}
+ onChange={onChange}
+ onClose={() => {
+ setActive(false);
+ }}
+ numberOfOptionsToAlwaysShow={numberOfOptionsToAlwaysShow}
+ />
+ )}
+ </Popover.Root>
+ </div>
+ );
+}
diff --git a/packages/excalidraw/components/ImageExportDialog.scss b/packages/excalidraw/components/ImageExportDialog.scss
new file mode 100644
index 0000000..ea9e74f
--- /dev/null
+++ b/packages/excalidraw/components/ImageExportDialog.scss
@@ -0,0 +1,175 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ --ImageExportModal-preview-border: #d6d6d6;
+
+ &.theme--dark {
+ --ImageExportModal-preview-border: #5c5c5c;
+ }
+
+ .ImageExportModal {
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+
+ user-select: none;
+
+ & h3 {
+ font-family: "Assistant";
+ font-style: normal;
+ font-weight: 700;
+ font-size: 1.313rem;
+ line-height: 130%;
+ padding: 0;
+ margin: 0;
+
+ @include isMobile {
+ display: none;
+ }
+ }
+
+ & > h3 {
+ display: none;
+
+ @include isMobile {
+ display: block;
+ }
+ }
+
+ @include isMobile {
+ flex-direction: column;
+ height: calc(100vh - 5rem);
+ }
+
+ &__preview {
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ height: 360px;
+ width: 55%;
+
+ margin-right: 1.5rem;
+
+ @include isMobile {
+ max-width: unset;
+ margin-right: unset;
+
+ width: 100%;
+ height: unset;
+ flex-grow: 1;
+ }
+
+ &__filename {
+ & > input {
+ margin-top: 1rem;
+ }
+ }
+
+ &__canvas {
+ box-sizing: border-box;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-grow: 1;
+ justify-content: center;
+ align-items: center;
+
+ background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")
+ left center;
+
+ border: 1px solid var(--ImageExportModal-preview-border);
+ border-radius: 12px;
+
+ overflow: hidden;
+ padding: 1rem;
+
+ & > canvas {
+ max-width: calc(100% - 2rem);
+ max-height: calc(100% - 2rem);
+
+ filter: none !important;
+
+ @include isMobile {
+ max-height: 100%;
+ }
+ }
+
+ @include isMobile {
+ margin-top: 24px;
+ max-width: unset;
+ }
+ }
+ }
+
+ &__settings {
+ display: flex;
+ flex-direction: column;
+ flex-wrap: wrap;
+ gap: 18px;
+
+ @include isMobile {
+ margin-left: unset;
+ margin-top: 1rem;
+ flex-direction: row;
+ gap: 6px 34px;
+
+ align-content: flex-start;
+ }
+
+ &__setting {
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ align-items: center;
+
+ @include isMobile {
+ flex-direction: column;
+ align-items: start;
+ justify-content: unset;
+ height: 52px;
+ }
+
+ &__label {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+
+ font-family: "Assistant";
+ font-weight: 600;
+ font-size: 1rem;
+ line-height: 150%;
+
+ & svg {
+ width: 20px;
+ height: 20px;
+ margin-left: 10px;
+ }
+ }
+
+ &__content {
+ display: flex;
+ height: 100%;
+ align-items: center;
+ }
+ }
+
+ &__buttons {
+ flex-grow: 1;
+ flex-wrap: wrap;
+ display: flex;
+ flex-direction: row;
+ gap: 11px;
+
+ align-items: flex-end;
+ align-content: flex-end;
+
+ @include isMobile {
+ padding-top: 32px;
+ flex-basis: 100%;
+ justify-content: center;
+ }
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ImageExportDialog.tsx b/packages/excalidraw/components/ImageExportDialog.tsx
new file mode 100644
index 0000000..d06f4a8
--- /dev/null
+++ b/packages/excalidraw/components/ImageExportDialog.tsx
@@ -0,0 +1,407 @@
+import React, { useEffect, useRef, useState } from "react";
+
+import type { ActionManager } from "../actions/manager";
+import type { AppClassProperties, BinaryFiles, UIAppState } from "../types";
+
+import {
+ actionExportWithDarkMode,
+ actionChangeExportBackground,
+ actionChangeExportEmbedScene,
+ actionChangeExportScale,
+ actionChangeProjectName,
+} from "../actions/actionExport";
+import { probablySupportsClipboardBlob } from "../clipboard";
+import {
+ DEFAULT_EXPORT_PADDING,
+ EXPORT_IMAGE_TYPES,
+ isFirefox,
+ EXPORT_SCALES,
+} from "../constants";
+
+import { canvasToBlob } from "../data/blob";
+import { nativeFileSystemSupported } from "../data/filesystem";
+import type { NonDeletedExcalidrawElement } from "../element/types";
+import { t } from "../i18n";
+import { isSomeElementSelected } from "../scene";
+import { exportToCanvas } from "@excalidraw/utils/export";
+
+import { copyIcon, downloadIcon, helpIcon } from "./icons";
+import { Dialog } from "./Dialog";
+import { RadioGroup } from "./RadioGroup";
+import { Switch } from "./Switch";
+import { Tooltip } from "./Tooltip";
+
+import "./ImageExportDialog.scss";
+import { FilledButton } from "./FilledButton";
+import { cloneJSON } from "../utils";
+import { prepareElementsForExport } from "../data";
+import { useCopyStatus } from "../hooks/useCopiedIndicator";
+
+const supportsContextFilters =
+ "filter" in document.createElement("canvas").getContext("2d")!;
+
+export const ErrorCanvasPreview = () => {
+ return (
+ <div>
+ <h3>{t("canvasError.cannotShowPreview")}</h3>
+ <p>
+ <span>{t("canvasError.canvasTooBig")}</span>
+ </p>
+ <em>({t("canvasError.canvasTooBigTip")})</em>
+ </div>
+ );
+};
+
+type ImageExportModalProps = {
+ appStateSnapshot: Readonly<UIAppState>;
+ elementsSnapshot: readonly NonDeletedExcalidrawElement[];
+ files: BinaryFiles;
+ actionManager: ActionManager;
+ onExportImage: AppClassProperties["onExportImage"];
+ name: string;
+};
+
+const ImageExportModal = ({
+ appStateSnapshot,
+ elementsSnapshot,
+ files,
+ actionManager,
+ onExportImage,
+ name,
+}: ImageExportModalProps) => {
+ const hasSelection = isSomeElementSelected(
+ elementsSnapshot,
+ appStateSnapshot,
+ );
+
+ const [projectName, setProjectName] = useState(name);
+ const [exportSelectionOnly, setExportSelectionOnly] = useState(hasSelection);
+ const [exportWithBackground, setExportWithBackground] = useState(
+ appStateSnapshot.exportBackground,
+ );
+ const [exportDarkMode, setExportDarkMode] = useState(
+ appStateSnapshot.exportWithDarkMode,
+ );
+ const [embedScene, setEmbedScene] = useState(
+ appStateSnapshot.exportEmbedScene,
+ );
+ const [exportScale, setExportScale] = useState(appStateSnapshot.exportScale);
+
+ const previewRef = useRef<HTMLDivElement>(null);
+ const [renderError, setRenderError] = useState<Error | null>(null);
+
+ const { onCopy, copyStatus, resetCopyStatus } = useCopyStatus();
+
+ useEffect(() => {
+ // if user changes setting right after export to clipboard, reset the status
+ // so they don't have to wait for the timeout to click the button again
+ resetCopyStatus();
+ }, [
+ projectName,
+ exportWithBackground,
+ exportDarkMode,
+ exportScale,
+ embedScene,
+ resetCopyStatus,
+ ]);
+
+ const { exportedElements, exportingFrame } = prepareElementsForExport(
+ elementsSnapshot,
+ appStateSnapshot,
+ exportSelectionOnly,
+ );
+
+ useEffect(() => {
+ const previewNode = previewRef.current;
+ if (!previewNode) {
+ return;
+ }
+ const maxWidth = previewNode.offsetWidth;
+ const maxHeight = previewNode.offsetHeight;
+ if (!maxWidth) {
+ return;
+ }
+
+ exportToCanvas({
+ elements: exportedElements,
+ appState: {
+ ...appStateSnapshot,
+ name: projectName,
+ exportBackground: exportWithBackground,
+ exportWithDarkMode: exportDarkMode,
+ exportScale,
+ exportEmbedScene: embedScene,
+ },
+ files,
+ exportPadding: DEFAULT_EXPORT_PADDING,
+ maxWidthOrHeight: Math.max(maxWidth, maxHeight),
+ exportingFrame,
+ })
+ .then((canvas) => {
+ setRenderError(null);
+ // if converting to blob fails, there's some problem that will
+ // likely prevent preview and export (e.g. canvas too big)
+ return canvasToBlob(canvas)
+ .then(() => {
+ previewNode.replaceChildren(canvas);
+ })
+ .catch((e) => {
+ if (e.name === "CANVAS_POSSIBLY_TOO_BIG") {
+ throw new Error(t("canvasError.canvasTooBig"));
+ }
+ throw e;
+ });
+ })
+ .catch((error) => {
+ console.error(error);
+ setRenderError(error);
+ });
+ }, [
+ appStateSnapshot,
+ files,
+ exportedElements,
+ exportingFrame,
+ projectName,
+ exportWithBackground,
+ exportDarkMode,
+ exportScale,
+ embedScene,
+ ]);
+
+ return (
+ <div className="ImageExportModal">
+ <h3>{t("imageExportDialog.header")}</h3>
+ <div className="ImageExportModal__preview">
+ <div className="ImageExportModal__preview__canvas" ref={previewRef}>
+ {renderError && <ErrorCanvasPreview />}
+ </div>
+ <div className="ImageExportModal__preview__filename">
+ {!nativeFileSystemSupported && (
+ <input
+ type="text"
+ className="TextInput"
+ value={projectName}
+ style={{ width: "30ch" }}
+ onChange={(event) => {
+ setProjectName(event.target.value);
+ actionManager.executeAction(
+ actionChangeProjectName,
+ "ui",
+ event.target.value,
+ );
+ }}
+ />
+ )}
+ </div>
+ </div>
+ <div className="ImageExportModal__settings">
+ <h3>{t("imageExportDialog.header")}</h3>
+ {hasSelection && (
+ <ExportSetting
+ label={t("imageExportDialog.label.onlySelected")}
+ name="exportOnlySelected"
+ >
+ <Switch
+ name="exportOnlySelected"
+ checked={exportSelectionOnly}
+ onChange={(checked) => {
+ setExportSelectionOnly(checked);
+ }}
+ />
+ </ExportSetting>
+ )}
+ <ExportSetting
+ label={t("imageExportDialog.label.withBackground")}
+ name="exportBackgroundSwitch"
+ >
+ <Switch
+ name="exportBackgroundSwitch"
+ checked={exportWithBackground}
+ onChange={(checked) => {
+ setExportWithBackground(checked);
+ actionManager.executeAction(
+ actionChangeExportBackground,
+ "ui",
+ checked,
+ );
+ }}
+ />
+ </ExportSetting>
+ {supportsContextFilters && (
+ <ExportSetting
+ label={t("imageExportDialog.label.darkMode")}
+ name="exportDarkModeSwitch"
+ >
+ <Switch
+ name="exportDarkModeSwitch"
+ checked={exportDarkMode}
+ onChange={(checked) => {
+ setExportDarkMode(checked);
+ actionManager.executeAction(
+ actionExportWithDarkMode,
+ "ui",
+ checked,
+ );
+ }}
+ />
+ </ExportSetting>
+ )}
+ <ExportSetting
+ label={t("imageExportDialog.label.embedScene")}
+ tooltip={t("imageExportDialog.tooltip.embedScene")}
+ name="exportEmbedSwitch"
+ >
+ <Switch
+ name="exportEmbedSwitch"
+ checked={embedScene}
+ onChange={(checked) => {
+ setEmbedScene(checked);
+ actionManager.executeAction(
+ actionChangeExportEmbedScene,
+ "ui",
+ checked,
+ );
+ }}
+ />
+ </ExportSetting>
+ <ExportSetting
+ label={t("imageExportDialog.label.scale")}
+ name="exportScale"
+ >
+ <RadioGroup
+ name="exportScale"
+ value={exportScale}
+ onChange={(scale) => {
+ setExportScale(scale);
+ actionManager.executeAction(actionChangeExportScale, "ui", scale);
+ }}
+ choices={EXPORT_SCALES.map((scale) => ({
+ value: scale,
+ label: `${scale}\u00d7`,
+ }))}
+ />
+ </ExportSetting>
+
+ <div className="ImageExportModal__settings__buttons">
+ <FilledButton
+ className="ImageExportModal__settings__buttons__button"
+ label={t("imageExportDialog.title.exportToPng")}
+ onClick={() =>
+ onExportImage(EXPORT_IMAGE_TYPES.png, exportedElements, {
+ exportingFrame,
+ })
+ }
+ icon={downloadIcon}
+ >
+ {t("imageExportDialog.button.exportToPng")}
+ </FilledButton>
+ <FilledButton
+ className="ImageExportModal__settings__buttons__button"
+ label={t("imageExportDialog.title.exportToSvg")}
+ onClick={() =>
+ onExportImage(EXPORT_IMAGE_TYPES.svg, exportedElements, {
+ exportingFrame,
+ })
+ }
+ icon={downloadIcon}
+ >
+ {t("imageExportDialog.button.exportToSvg")}
+ </FilledButton>
+ {(probablySupportsClipboardBlob || isFirefox) && (
+ <FilledButton
+ className="ImageExportModal__settings__buttons__button"
+ label={t("imageExportDialog.title.copyPngToClipboard")}
+ status={copyStatus}
+ onClick={async () => {
+ await onExportImage(
+ EXPORT_IMAGE_TYPES.clipboard,
+ exportedElements,
+ {
+ exportingFrame,
+ },
+ );
+ onCopy();
+ }}
+ icon={copyIcon}
+ >
+ {t("imageExportDialog.button.copyPngToClipboard")}
+ </FilledButton>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+type ExportSettingProps = {
+ label: string;
+ children: React.ReactNode;
+ tooltip?: string;
+ name?: string;
+};
+
+const ExportSetting = ({
+ label,
+ children,
+ tooltip,
+ name,
+}: ExportSettingProps) => {
+ return (
+ <div className="ImageExportModal__settings__setting" title={label}>
+ <label
+ htmlFor={name}
+ className="ImageExportModal__settings__setting__label"
+ >
+ {label}
+ {tooltip && (
+ <Tooltip label={tooltip} long={true}>
+ {helpIcon}
+ </Tooltip>
+ )}
+ </label>
+ <div className="ImageExportModal__settings__setting__content">
+ {children}
+ </div>
+ </div>
+ );
+};
+
+export const ImageExportDialog = ({
+ elements,
+ appState,
+ files,
+ actionManager,
+ onExportImage,
+ onCloseRequest,
+ name,
+}: {
+ appState: UIAppState;
+ elements: readonly NonDeletedExcalidrawElement[];
+ files: BinaryFiles;
+ actionManager: ActionManager;
+ onExportImage: AppClassProperties["onExportImage"];
+ onCloseRequest: () => void;
+ name: string;
+}) => {
+ // we need to take a snapshot so that the exported state can't be modified
+ // while the dialog is open
+ const [{ appStateSnapshot, elementsSnapshot }] = useState(() => {
+ return {
+ appStateSnapshot: cloneJSON(appState),
+ elementsSnapshot: cloneJSON(elements),
+ };
+ });
+
+ return (
+ <Dialog onCloseRequest={onCloseRequest} size="wide" title={false}>
+ <ImageExportModal
+ elementsSnapshot={elementsSnapshot}
+ appStateSnapshot={appStateSnapshot}
+ files={files}
+ actionManager={actionManager}
+ onExportImage={onExportImage}
+ name={name}
+ />
+ </Dialog>
+ );
+};
diff --git a/packages/excalidraw/components/InitializeApp.tsx b/packages/excalidraw/components/InitializeApp.tsx
new file mode 100644
index 0000000..41f90ce
--- /dev/null
+++ b/packages/excalidraw/components/InitializeApp.tsx
@@ -0,0 +1,28 @@
+import React, { useEffect, useState } from "react";
+
+import { LoadingMessage } from "./LoadingMessage";
+import type { Language } from "../i18n";
+import { defaultLang, languages, setLanguage } from "../i18n";
+import type { Theme } from "../element/types";
+
+interface Props {
+ langCode: Language["code"];
+ children: React.ReactElement;
+ theme?: Theme;
+}
+
+export const InitializeApp = (props: Props) => {
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ const updateLang = async () => {
+ await setLanguage(currentLang);
+ setLoading(false);
+ };
+ const currentLang =
+ languages.find((lang) => lang.code === props.langCode) || defaultLang;
+ updateLang();
+ }, [props.langCode]);
+
+ return loading ? <LoadingMessage theme={props.theme} /> : props.children;
+};
diff --git a/packages/excalidraw/components/InlineIcon.tsx b/packages/excalidraw/components/InlineIcon.tsx
new file mode 100644
index 0000000..75cc29d
--- /dev/null
+++ b/packages/excalidraw/components/InlineIcon.tsx
@@ -0,0 +1,15 @@
+export const InlineIcon = ({ icon }: { icon: React.ReactNode }) => {
+ return (
+ <span
+ style={{
+ width: "1em",
+ margin: "0 0.5ex 0 0.5ex",
+ display: "inline-block",
+ lineHeight: 0,
+ verticalAlign: "middle",
+ }}
+ >
+ {icon}
+ </span>
+ );
+};
diff --git a/packages/excalidraw/components/Island.scss b/packages/excalidraw/components/Island.scss
new file mode 100644
index 0000000..e9f8ebe
--- /dev/null
+++ b/packages/excalidraw/components/Island.scss
@@ -0,0 +1,16 @@
+.excalidraw {
+ .Island {
+ --padding: 0;
+ box-sizing: border-box;
+ background-color: var(--island-bg-color);
+ box-shadow: var(--shadow-island);
+ border-radius: var(--border-radius-lg);
+ padding: calc(var(--padding) * var(--space-factor));
+ position: relative;
+ transition: box-shadow 0.5s ease-in-out;
+
+ &.zen-mode {
+ box-shadow: none;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Island.tsx b/packages/excalidraw/components/Island.tsx
new file mode 100644
index 0000000..7baf307
--- /dev/null
+++ b/packages/excalidraw/components/Island.tsx
@@ -0,0 +1,23 @@
+import "./Island.scss";
+
+import React from "react";
+import clsx from "clsx";
+
+type IslandProps = {
+ children: React.ReactNode;
+ padding?: number;
+ className?: string | boolean;
+ style?: object;
+};
+
+export const Island = React.forwardRef<HTMLDivElement, IslandProps>(
+ ({ children, padding, className, style }, ref) => (
+ <div
+ className={clsx("Island", className)}
+ style={{ "--padding": padding, ...style }}
+ ref={ref}
+ >
+ {children}
+ </div>
+ ),
+);
diff --git a/packages/excalidraw/components/JSONExportDialog.tsx b/packages/excalidraw/components/JSONExportDialog.tsx
new file mode 100644
index 0000000..527ad57
--- /dev/null
+++ b/packages/excalidraw/components/JSONExportDialog.tsx
@@ -0,0 +1,136 @@
+import React from "react";
+import type { NonDeletedExcalidrawElement } from "../element/types";
+import { t } from "../i18n";
+
+import type { ExportOpts, BinaryFiles, UIAppState } from "../types";
+import { Dialog } from "./Dialog";
+import { exportToFileIcon, LinkIcon } from "./icons";
+import { ToolButton } from "./ToolButton";
+import { actionSaveFileToDisk } from "../actions/actionExport";
+import { Card } from "./Card";
+
+import "./ExportDialog.scss";
+import { nativeFileSystemSupported } from "../data/filesystem";
+import { trackEvent } from "../analytics";
+import type { ActionManager } from "../actions/manager";
+import { getFrame } from "../utils";
+
+export type ExportCB = (
+ elements: readonly NonDeletedExcalidrawElement[],
+ scale?: number,
+) => void;
+
+const JSONExportModal = ({
+ elements,
+ appState,
+ setAppState,
+ files,
+ actionManager,
+ exportOpts,
+ canvas,
+ onCloseRequest,
+}: {
+ appState: UIAppState;
+ setAppState: React.Component<any, UIAppState>["setState"];
+ files: BinaryFiles;
+ elements: readonly NonDeletedExcalidrawElement[];
+ actionManager: ActionManager;
+ onCloseRequest: () => void;
+ exportOpts: ExportOpts;
+ canvas: HTMLCanvasElement;
+}) => {
+ const { onExportToBackend } = exportOpts;
+ return (
+ <div className="ExportDialog ExportDialog--json">
+ <div className="ExportDialog-cards">
+ {exportOpts.saveFileToDisk && (
+ <Card color="lime">
+ <div className="Card-icon">{exportToFileIcon}</div>
+ <h2>{t("exportDialog.disk_title")}</h2>
+ <div className="Card-details">
+ {t("exportDialog.disk_details")}
+ {!nativeFileSystemSupported &&
+ actionManager.renderAction("changeProjectName")}
+ </div>
+ <ToolButton
+ className="Card-button"
+ type="button"
+ title={t("exportDialog.disk_button")}
+ aria-label={t("exportDialog.disk_button")}
+ showAriaLabel={true}
+ onClick={() => {
+ actionManager.executeAction(actionSaveFileToDisk, "ui");
+ }}
+ />
+ </Card>
+ )}
+ {onExportToBackend && (
+ <Card color="pink">
+ <div className="Card-icon">{LinkIcon}</div>
+ <h2>{t("exportDialog.link_title")}</h2>
+ <div className="Card-details">{t("exportDialog.link_details")}</div>
+ <ToolButton
+ className="Card-button"
+ type="button"
+ title={t("exportDialog.link_button")}
+ aria-label={t("exportDialog.link_button")}
+ showAriaLabel={true}
+ onClick={async () => {
+ try {
+ trackEvent("export", "link", `ui (${getFrame()})`);
+ await onExportToBackend(elements, appState, files);
+ onCloseRequest();
+ } catch (error: any) {
+ setAppState({ errorMessage: error.message });
+ }
+ }}
+ />
+ </Card>
+ )}
+ {exportOpts.renderCustomUI &&
+ exportOpts.renderCustomUI(elements, appState, files, canvas)}
+ </div>
+ </div>
+ );
+};
+
+export const JSONExportDialog = ({
+ elements,
+ appState,
+ files,
+ actionManager,
+ exportOpts,
+ canvas,
+ setAppState,
+}: {
+ elements: readonly NonDeletedExcalidrawElement[];
+ appState: UIAppState;
+ files: BinaryFiles;
+ actionManager: ActionManager;
+ exportOpts: ExportOpts;
+ canvas: HTMLCanvasElement;
+ setAppState: React.Component<any, UIAppState>["setState"];
+}) => {
+ const handleClose = React.useCallback(() => {
+ setAppState({ openDialog: null });
+ }, [setAppState]);
+
+ return (
+ <>
+ {appState.openDialog?.name === "jsonExport" && (
+ <Dialog onCloseRequest={handleClose} title={t("buttons.export")}>
+ <JSONExportModal
+ elements={elements}
+ appState={appState}
+ setAppState={setAppState}
+ files={files}
+ actionManager={actionManager}
+ onCloseRequest={handleClose}
+ exportOpts={exportOpts}
+ canvas={canvas}
+ />
+ </Dialog>
+ )}
+ </>
+ );
+};
diff --git a/packages/excalidraw/components/LaserPointerButton.tsx b/packages/excalidraw/components/LaserPointerButton.tsx
new file mode 100644
index 0000000..35470f6
--- /dev/null
+++ b/packages/excalidraw/components/LaserPointerButton.tsx
@@ -0,0 +1,41 @@
+import "./ToolIcon.scss";
+
+import clsx from "clsx";
+import type { ToolButtonSize } from "./ToolButton";
+import { laserPointerToolIcon } from "./icons";
+
+type LaserPointerIconProps = {
+ title?: string;
+ name?: string;
+ checked: boolean;
+ onChange?(): void;
+ isMobile?: boolean;
+};
+
+const DEFAULT_SIZE: ToolButtonSize = "small";
+
+export const LaserPointerButton = (props: LaserPointerIconProps) => {
+ return (
+ <label
+ className={clsx(
+ "ToolIcon ToolIcon__LaserPointer",
+ `ToolIcon_size_${DEFAULT_SIZE}`,
+ {
+ "is-mobile": props.isMobile,
+ },
+ )}
+ title={`${props.title}`}
+ >
+ <input
+ className="ToolIcon_type_checkbox"
+ type="checkbox"
+ name={props.name}
+ onChange={props.onChange}
+ checked={props.checked}
+ aria-label={props.title}
+ data-testid="toolbar-LaserPointer"
+ />
+ <div className="ToolIcon__icon">{laserPointerToolIcon}</div>
+ </label>
+ );
+};
diff --git a/packages/excalidraw/components/LayerUI.scss b/packages/excalidraw/components/LayerUI.scss
new file mode 100644
index 0000000..36153d7
--- /dev/null
+++ b/packages/excalidraw/components/LayerUI.scss
@@ -0,0 +1,119 @@
+@import "open-color/open-color";
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .layer-ui__wrapper.animate {
+ transition: width 0.1s ease-in-out;
+ }
+ .layer-ui__wrapper {
+ // when the rightside sidebar is docked, we need to resize the UI by its
+ // width, making the nested UI content shift to the left. To do this,
+ // we need the UI container to actually have dimensions set, but
+ // then we also need to disable pointer events else the canvas below
+ // wouldn't be interactive.
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: var(--zIndex-layerUI);
+
+ &__top-right {
+ display: flex;
+ width: 100%;
+ justify-content: flex-end;
+ gap: 0.75rem;
+ pointer-events: none !important;
+
+ & > * {
+ pointer-events: var(--ui-pointerEvents);
+ }
+ }
+
+ &__footer {
+ width: 100%;
+
+ &-right {
+ z-index: 100;
+ display: flex;
+ }
+ }
+
+ .zen-mode-transition {
+ transition: transform 0.5s ease-in-out;
+
+ :root[dir="ltr"] &.transition-left {
+ transform: translate(-999px, 0);
+ }
+
+ :root[dir="ltr"] &.transition-right {
+ transform: translate(999px, 0);
+ }
+
+ :root[dir="rtl"] &.transition-left {
+ transform: translate(999px, 0);
+ }
+
+ :root[dir="rtl"] &.transition-right {
+ transform: translate(-999px, 0);
+ }
+
+ &.layer-ui__wrapper__footer-left--transition-bottom {
+ transform: translate(0, 92px);
+ }
+ }
+
+ .disable-zen-mode {
+ padding: 10px;
+ position: absolute;
+ bottom: 0;
+ [dir="ltr"] & {
+ right: 1rem;
+ }
+ [dir="rtl"] & {
+ left: 1rem;
+ }
+ opacity: 0;
+ visibility: hidden;
+ transition: visibility 0s linear 0s, opacity 0.5s;
+
+ font-family: var(--ui-font);
+ font-size: 0.75rem;
+ font-weight: 500;
+ line-height: 1;
+
+ border-radius: var(--border-radius-lg);
+ border: 1px solid var(--default-border-color);
+ background-color: var(--island-bg-color);
+ color: var(--text-primary-color);
+
+ &:hover {
+ background-color: var(--button-hover-bg);
+ }
+ &:active {
+ border-color: var(--color-primary);
+ }
+
+ &--visible {
+ opacity: 1;
+ visibility: visible;
+ transition: visibility 0s linear 300ms, opacity 0.5s;
+ transition-delay: 0.8s;
+
+ pointer-events: var(--ui-pointerEvents);
+ }
+ }
+
+ .layer-ui__wrapper__footer-left,
+ .footer-center,
+ .layer-ui__wrapper__footer-right {
+ & > * {
+ pointer-events: var(--ui-pointerEvents);
+ }
+ }
+
+ .layer-ui__wrapper__footer-right {
+ margin-top: auto;
+ margin-bottom: auto;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/LayerUI.tsx b/packages/excalidraw/components/LayerUI.tsx
new file mode 100644
index 0000000..11914d0
--- /dev/null
+++ b/packages/excalidraw/components/LayerUI.tsx
@@ -0,0 +1,607 @@
+import clsx from "clsx";
+import React from "react";
+import type { ActionManager } from "../actions/manager";
+import { CLASSES, DEFAULT_SIDEBAR, TOOL_TYPE } from "../constants";
+import { showSelectedShapeActions } from "../element";
+import type { NonDeletedExcalidrawElement } from "../element/types";
+import type { Language } from "../i18n";
+import { t } from "../i18n";
+import { calculateScrollCenter } from "../scene";
+import type {
+ AppProps,
+ AppState,
+ ExcalidrawProps,
+ BinaryFiles,
+ UIAppState,
+ AppClassProperties,
+} from "../types";
+import { capitalizeString, isShallowEqual } from "../utils";
+import { SelectedShapeActions, ShapesSwitcher } from "./Actions";
+import { ErrorDialog } from "./ErrorDialog";
+import { ImageExportDialog } from "./ImageExportDialog";
+import { FixedSideContainer } from "./FixedSideContainer";
+import { HintViewer } from "./HintViewer";
+import { Island } from "./Island";
+import { LoadingMessage } from "./LoadingMessage";
+import { LockButton } from "./LockButton";
+import { MobileMenu } from "./MobileMenu";
+import { PasteChartDialog } from "./PasteChartDialog";
+import { Section } from "./Section";
+import { HelpDialog } from "./HelpDialog";
+import Stack from "./Stack";
+import { UserList } from "./UserList";
+import { JSONExportDialog } from "./JSONExportDialog";
+import { PenModeButton } from "./PenModeButton";
+import { trackEvent } from "../analytics";
+import { useDevice } from "./App";
+import Footer from "./footer/Footer";
+import { isSidebarDockedAtom } from "./Sidebar/Sidebar";
+import { useAtom, useAtomValue } from "../editor-jotai";
+import MainMenu from "./main-menu/MainMenu";
+import { ActiveConfirmDialog } from "./ActiveConfirmDialog";
+import { OverwriteConfirmDialog } from "./OverwriteConfirm/OverwriteConfirm";
+import { HandButton } from "./HandButton";
+import { isHandToolActive } from "../appState";
+import { TunnelsContext, useInitializeTunnels } from "../context/tunnels";
+import { LibraryIcon } from "./icons";
+import { UIAppStateContext } from "../context/ui-appState";
+import { DefaultSidebar } from "./DefaultSidebar";
+import { EyeDropper, activeEyeDropperAtom } from "./EyeDropper";
+import { mutateElement } from "../element/mutateElement";
+import { ShapeCache } from "../scene/ShapeCache";
+import Scene from "../scene/Scene";
+import { LaserPointerButton } from "./LaserPointerButton";
+import { TTDDialog } from "./TTDDialog/TTDDialog";
+import { Stats } from "./Stats";
+import { actionToggleStats } from "../actions";
+import ElementLinkDialog from "./ElementLinkDialog";
+
+import "./LayerUI.scss";
+import "./Toolbar.scss";
+
+interface LayerUIProps {
+ actionManager: ActionManager;
+ appState: UIAppState;
+ files: BinaryFiles;
+ canvas: HTMLCanvasElement;
+ setAppState: React.Component<any, AppState>["setState"];
+ elements: readonly NonDeletedExcalidrawElement[];
+ onLockToggle: () => void;
+ onHandToolToggle: () => void;
+ onPenModeToggle: AppClassProperties["togglePenMode"];
+ showExitZenModeBtn: boolean;
+ langCode: Language["code"];
+ renderTopRightUI?: ExcalidrawProps["renderTopRightUI"];
+ renderCustomStats?: ExcalidrawProps["renderCustomStats"];
+ UIOptions: AppProps["UIOptions"];
+ onExportImage: AppClassProperties["onExportImage"];
+ renderWelcomeScreen: boolean;
+ children?: React.ReactNode;
+ app: AppClassProperties;
+ isCollaborating: boolean;
+ generateLinkForSelection?: AppProps["generateLinkForSelection"];
+}
+
+const DefaultMainMenu: React.FC<{
+ UIOptions: AppProps["UIOptions"];
+}> = ({ UIOptions }) => {
+ return (
+ <MainMenu __fallback>
+ <MainMenu.DefaultItems.LoadScene />
+ <MainMenu.DefaultItems.SaveToActiveFile />
+ {/* FIXME we should to test for this inside the item itself */}
+ {UIOptions.canvasActions.export && <MainMenu.DefaultItems.Export />}
+ {/* FIXME we should to test for this inside the item itself */}
+ {UIOptions.canvasActions.saveAsImage && (
+ <MainMenu.DefaultItems.SaveAsImage />
+ )}
+ <MainMenu.DefaultItems.SearchMenu />
+ <MainMenu.DefaultItems.Help />
+ <MainMenu.DefaultItems.ClearCanvas />
+ <MainMenu.Separator />
+ <MainMenu.Group title="Excalidraw links">
+ <MainMenu.DefaultItems.Socials />
+ </MainMenu.Group>
+ <MainMenu.Separator />
+ <MainMenu.DefaultItems.ToggleTheme />
+ <MainMenu.DefaultItems.ChangeCanvasBackground />
+ </MainMenu>
+ );
+};
+
+const DefaultOverwriteConfirmDialog = () => {
+ return (
+ <OverwriteConfirmDialog __fallback>
+ <OverwriteConfirmDialog.Actions.SaveToDisk />
+ <OverwriteConfirmDialog.Actions.ExportToImage />
+ </OverwriteConfirmDialog>
+ );
+};
+
+const LayerUI = ({
+ actionManager,
+ appState,
+ files,
+ setAppState,
+ elements,
+ canvas,
+ onLockToggle,
+ onHandToolToggle,
+ onPenModeToggle,
+ showExitZenModeBtn,
+ renderTopRightUI,
+ renderCustomStats,
+ UIOptions,
+ onExportImage,
+ renderWelcomeScreen,
+ children,
+ app,
+ isCollaborating,
+ generateLinkForSelection,
+}: LayerUIProps) => {
+ const device = useDevice();
+ const tunnels = useInitializeTunnels();
+
+ const TunnelsJotaiProvider = tunnels.tunnelsJotai.Provider;
+
+ const [eyeDropperState, setEyeDropperState] = useAtom(activeEyeDropperAtom);
+
+ const renderJSONExportDialog = () => {
+ if (!UIOptions.canvasActions.export) {
+ return null;
+ }
+
+ return (
+ <JSONExportDialog
+ elements={elements}
+ appState={appState}
+ files={files}
+ actionManager={actionManager}
+ exportOpts={UIOptions.canvasActions.export}
+ canvas={canvas}
+ setAppState={setAppState}
+ />
+ );
+ };
+
+ const renderImageExportDialog = () => {
+ if (
+ !UIOptions.canvasActions.saveAsImage ||
+ appState.openDialog?.name !== "imageExport"
+ ) {
+ return null;
+ }
+
+ return (
+ <ImageExportDialog
+ elements={elements}
+ appState={appState}
+ files={files}
+ actionManager={actionManager}
+ onExportImage={onExportImage}
+ onCloseRequest={() => setAppState({ openDialog: null })}
+ name={app.getName()}
+ />
+ );
+ };
+
+ const renderCanvasActions = () => (
+ <div style={{ position: "relative" }}>
+ {/* wrapping to Fragment stops React from occasionally complaining
+ about identical Keys */}
+ <tunnels.MainMenuTunnel.Out />
+ {renderWelcomeScreen && <tunnels.WelcomeScreenMenuHintTunnel.Out />}
+ </div>
+ );
+
+ const renderSelectedShapeActions = () => (
+ <Section
+ heading="selectedShapeActions"
+ className={clsx("selected-shape-actions zen-mode-transition", {
+ "transition-left": appState.zenModeEnabled,
+ })}
+ >
+ <Island
+ className={CLASSES.SHAPE_ACTIONS_MENU}
+ padding={2}
+ style={{
+ // we want to make sure this doesn't overflow so subtracting the
+ // approximate height of hamburgerMenu + footer
+ maxHeight: `${appState.height - 166}px`,
+ }}
+ >
+ <SelectedShapeActions
+ appState={appState}
+ elementsMap={app.scene.getNonDeletedElementsMap()}
+ renderAction={actionManager.renderAction}
+ app={app}
+ />
+ </Island>
+ </Section>
+ );
+
+ const renderFixedSideContainer = () => {
+ const shouldRenderSelectedShapeActions = showSelectedShapeActions(
+ appState,
+ elements,
+ );
+
+ const shouldShowStats =
+ appState.stats.open &&
+ !appState.zenModeEnabled &&
+ !appState.viewModeEnabled &&
+ appState.openDialog?.name !== "elementLinkSelector";
+
+ return (
+ <FixedSideContainer side="top">
+ <div className="App-menu App-menu_top">
+ <Stack.Col gap={6} className={clsx("App-menu_top__left")}>
+ {renderCanvasActions()}
+ {shouldRenderSelectedShapeActions && renderSelectedShapeActions()}
+ </Stack.Col>
+ {!appState.viewModeEnabled &&
+ appState.openDialog?.name !== "elementLinkSelector" && (
+ <Section heading="shapes" className="shapes-section">
+ {(heading: React.ReactNode) => (
+ <div style={{ position: "relative" }}>
+ {renderWelcomeScreen && (
+ <tunnels.WelcomeScreenToolbarHintTunnel.Out />
+ )}
+ <Stack.Col gap={4} align="start">
+ <Stack.Row
+ gap={1}
+ className={clsx("App-toolbar-container", {
+ "zen-mode": appState.zenModeEnabled,
+ })}
+ >
+ <Island
+ padding={1}
+ className={clsx("App-toolbar", {
+ "zen-mode": appState.zenModeEnabled,
+ })}
+ >
+ <HintViewer
+ appState={appState}
+ isMobile={device.editor.isMobile}
+ device={device}
+ app={app}
+ />
+ {heading}
+ <Stack.Row gap={1}>
+ <PenModeButton
+ zenModeEnabled={appState.zenModeEnabled}
+ checked={appState.penMode}
+ onChange={() => onPenModeToggle(null)}
+ title={t("toolBar.penMode")}
+ penDetected={appState.penDetected}
+ />
+ <LockButton
+ checked={appState.activeTool.locked}
+ onChange={onLockToggle}
+ title={t("toolBar.lock")}
+ />
+
+ <div className="App-toolbar__divider" />
+
+ <HandButton
+ checked={isHandToolActive(appState)}
+ onChange={() => onHandToolToggle()}
+ title={t("toolBar.hand")}
+ isMobile
+ />
+
+ <ShapesSwitcher
+ appState={appState}
+ activeTool={appState.activeTool}
+ UIOptions={UIOptions}
+ app={app}
+ />
+ </Stack.Row>
+ </Island>
+ {isCollaborating && (
+ <Island
+ style={{
+ marginLeft: 8,
+ alignSelf: "center",
+ height: "fit-content",
+ }}
+ >
+ <LaserPointerButton
+ title={t("toolBar.laser")}
+ checked={
+ appState.activeTool.type === TOOL_TYPE.laser
+ }
+ onChange={() =>
+ app.setActiveTool({ type: TOOL_TYPE.laser })
+ }
+ isMobile
+ />
+ </Island>
+ )}
+ </Stack.Row>
+ </Stack.Col>
+ </div>
+ )}
+ </Section>
+ )}
+ <div
+ className={clsx(
+ "layer-ui__wrapper__top-right zen-mode-transition",
+ {
+ "transition-right": appState.zenModeEnabled,
+ },
+ )}
+ >
+ {appState.collaborators.size > 0 && (
+ <UserList
+ collaborators={appState.collaborators}
+ userToFollow={appState.userToFollow?.socketId || null}
+ />
+ )}
+ {renderTopRightUI?.(device.editor.isMobile, appState)}
+ {!appState.viewModeEnabled &&
+ appState.openDialog?.name !== "elementLinkSelector" &&
+ // hide button when sidebar docked
+ (!isSidebarDocked ||
+ appState.openSidebar?.name !== DEFAULT_SIDEBAR.name) && (
+ <tunnels.DefaultSidebarTriggerTunnel.Out />
+ )}
+ {shouldShowStats && (
+ <Stats
+ app={app}
+ onClose={() => {
+ actionManager.executeAction(actionToggleStats);
+ }}
+ renderCustomStats={renderCustomStats}
+ />
+ )}
+ </div>
+ </div>
+ </FixedSideContainer>
+ );
+ };
+
+ const renderSidebars = () => {
+ return (
+ <DefaultSidebar
+ __fallback
+ onDock={(docked) => {
+ trackEvent(
+ "sidebar",
+ `toggleDock (${docked ? "dock" : "undock"})`,
+ `(${device.editor.isMobile ? "mobile" : "desktop"})`,
+ );
+ }}
+ />
+ );
+ };
+
+ const isSidebarDocked = useAtomValue(isSidebarDockedAtom);
+
+ const layerUIJSX = (
+ <>
+ {/* ------------------------- tunneled UI ---------------------------- */}
+ {/* make sure we render host app components first so that we can detect
+ them first on initial render to optimize layout shift */}
+ {children}
+ {/* render component fallbacks. Can be rendered anywhere as they'll be
+ tunneled away. We only render tunneled components that actually
+ have defaults when host do not render anything. */}
+ <DefaultMainMenu UIOptions={UIOptions} />
+ <DefaultSidebar.Trigger
+ __fallback
+ icon={LibraryIcon}
+ title={capitalizeString(t("toolBar.library"))}
+ onToggle={(open) => {
+ if (open) {
+ trackEvent(
+ "sidebar",
+ `${DEFAULT_SIDEBAR.name} (open)`,
+ `button (${device.editor.isMobile ? "mobile" : "desktop"})`,
+ );
+ }
+ }}
+ tab={DEFAULT_SIDEBAR.defaultTab}
+ >
+ {t("toolBar.library")}
+ </DefaultSidebar.Trigger>
+ <DefaultOverwriteConfirmDialog />
+ {appState.openDialog?.name === "ttd" && <TTDDialog __fallback />}
+ {/* ------------------------------------------------------------------ */}
+
+ {appState.isLoading && <LoadingMessage delay={250} />}
+ {appState.errorMessage && (
+ <ErrorDialog onClose={() => setAppState({ errorMessage: null })}>
+ {appState.errorMessage}
+ </ErrorDialog>
+ )}
+ {eyeDropperState && !device.editor.isMobile && (
+ <EyeDropper
+ colorPickerType={eyeDropperState.colorPickerType}
+ onCancel={() => {
+ setEyeDropperState(null);
+ }}
+ onChange={(colorPickerType, color, selectedElements, { altKey }) => {
+ if (
+ colorPickerType !== "elementBackground" &&
+ colorPickerType !== "elementStroke"
+ ) {
+ return;
+ }
+
+ if (selectedElements.length) {
+ for (const element of selectedElements) {
+ mutateElement(
+ element,
+ {
+ [altKey && eyeDropperState.swapPreviewOnAlt
+ ? colorPickerType === "elementBackground"
+ ? "strokeColor"
+ : "backgroundColor"
+ : colorPickerType === "elementBackground"
+ ? "backgroundColor"
+ : "strokeColor"]: color,
+ },
+ false,
+ );
+ ShapeCache.delete(element);
+ }
+ Scene.getScene(selectedElements[0])?.triggerUpdate();
+ } else if (colorPickerType === "elementBackground") {
+ setAppState({
+ currentItemBackgroundColor: color,
+ });
+ } else {
+ setAppState({ currentItemStrokeColor: color });
+ }
+ }}
+ onSelect={(color, event) => {
+ setEyeDropperState((state) => {
+ return state?.keepOpenOnAlt && event.altKey ? state : null;
+ });
+ eyeDropperState?.onSelect?.(color, event);
+ }}
+ />
+ )}
+ {appState.openDialog?.name === "help" && (
+ <HelpDialog
+ onClose={() => {
+ setAppState({ openDialog: null });
+ }}
+ />
+ )}
+ <ActiveConfirmDialog />
+ {appState.openDialog?.name === "elementLinkSelector" && (
+ <ElementLinkDialog
+ sourceElementId={appState.openDialog.sourceElementId}
+ onClose={() => {
+ setAppState({
+ openDialog: null,
+ });
+ }}
+ elementsMap={app.scene.getNonDeletedElementsMap()}
+ appState={appState}
+ generateLinkForSelection={generateLinkForSelection}
+ />
+ )}
+ <tunnels.OverwriteConfirmDialogTunnel.Out />
+ {renderImageExportDialog()}
+ {renderJSONExportDialog()}
+ {appState.pasteDialog.shown && (
+ <PasteChartDialog
+ setAppState={setAppState}
+ appState={appState}
+ onClose={() =>
+ setAppState({
+ pasteDialog: { shown: false, data: null },
+ })
+ }
+ />
+ )}
+ {device.editor.isMobile && (
+ <MobileMenu
+ app={app}
+ appState={appState}
+ elements={elements}
+ actionManager={actionManager}
+ renderJSONExportDialog={renderJSONExportDialog}
+ renderImageExportDialog={renderImageExportDialog}
+ setAppState={setAppState}
+ onLockToggle={onLockToggle}
+ onHandToolToggle={onHandToolToggle}
+ onPenModeToggle={onPenModeToggle}
+ renderTopRightUI={renderTopRightUI}
+ renderCustomStats={renderCustomStats}
+ renderSidebars={renderSidebars}
+ device={device}
+ renderWelcomeScreen={renderWelcomeScreen}
+ UIOptions={UIOptions}
+ />
+ )}
+ {!device.editor.isMobile && (
+ <>
+ <div
+ className="layer-ui__wrapper"
+ style={
+ appState.openSidebar &&
+ isSidebarDocked &&
+ device.editor.canFitSidebar
+ ? { width: `calc(100% - var(--right-sidebar-width))` }
+ : {}
+ }
+ >
+ {renderWelcomeScreen && <tunnels.WelcomeScreenCenterTunnel.Out />}
+ {renderFixedSideContainer()}
+ <Footer
+ appState={appState}
+ actionManager={actionManager}
+ showExitZenModeBtn={showExitZenModeBtn}
+ renderWelcomeScreen={renderWelcomeScreen}
+ />
+ {appState.scrolledOutside && (
+ <button
+ type="button"
+ className="scroll-back-to-content"
+ onClick={() => {
+ setAppState((appState) => ({
+ ...calculateScrollCenter(elements, appState),
+ }));
+ }}
+ >
+ {t("buttons.scrollBackToContent")}
+ </button>
+ )}
+ </div>
+ {renderSidebars()}
+ </>
+ )}
+ </>
+ );
+
+ return (
+ <UIAppStateContext.Provider value={appState}>
+ <TunnelsJotaiProvider>
+ <TunnelsContext.Provider value={tunnels}>
+ {layerUIJSX}
+ </TunnelsContext.Provider>
+ </TunnelsJotaiProvider>
+ </UIAppStateContext.Provider>
+ );
+};
+
+const stripIrrelevantAppStateProps = (appState: AppState): UIAppState => {
+ const {
+ suggestedBindings,
+ startBoundElement,
+ cursorButton,
+ scrollX,
+ scrollY,
+ ...ret
+ } = appState;
+ return ret;
+};
+
+const areEqual = (prevProps: LayerUIProps, nextProps: LayerUIProps) => {
+ // short-circuit early
+ if (prevProps.children !== nextProps.children) {
+ return false;
+ }
+
+ const { canvas: _pC, appState: prevAppState, ...prev } = prevProps;
+ const { canvas: _nC, appState: nextAppState, ...next } = nextProps;
+
+ return (
+ isShallowEqual(
+ // asserting AppState because we're being passed the whole AppState
+ // but resolve to only the UI-relevant props
+ stripIrrelevantAppStateProps(prevAppState as AppState),
+ stripIrrelevantAppStateProps(nextAppState as AppState),
+ {
+ selectedElementIds: isShallowEqual,
+ selectedGroupIds: isShallowEqual,
+ },
+ ) && isShallowEqual(prev, next)
+ );
+};
+
+export default React.memo(LayerUI, areEqual);
diff --git a/packages/excalidraw/components/LibraryMenu.scss b/packages/excalidraw/components/LibraryMenu.scss
new file mode 100644
index 0000000..ac2c354
--- /dev/null
+++ b/packages/excalidraw/components/LibraryMenu.scss
@@ -0,0 +1,150 @@
+@import "open-color/open-color";
+
+.excalidraw {
+ .layer-ui__library {
+ display: flex;
+ flex-direction: column;
+
+ flex: 1 1 auto;
+ }
+
+ .library-actions-counter {
+ background-color: var(--color-primary);
+ color: var(--color-primary-light);
+ font-weight: 700;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 50%;
+ width: 1rem;
+ height: 1rem;
+ position: absolute;
+ bottom: -0.25rem;
+ right: -0.25rem;
+ font-size: 0.625rem;
+ pointer-events: none;
+ }
+
+ .layer-ui__library-message {
+ padding: 2rem;
+ min-width: 200px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ flex-grow: 1;
+ justify-content: center;
+
+ span {
+ font-size: 0.8em;
+ }
+ }
+
+ .publish-library-success {
+ .Dialog__content {
+ display: flex;
+ flex-direction: column;
+ }
+
+ &-close.ToolIcon_type_button {
+ background-color: $oc-blue-6;
+ align-self: flex-end;
+ &:hover {
+ background-color: $oc-blue-8;
+ }
+ .ToolIcon__icon {
+ width: auto;
+ font-size: 1rem;
+ color: $oc-white;
+ padding: 0 0.5rem;
+ }
+ }
+ }
+
+ .library-menu-control-buttons {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.625rem;
+ position: relative;
+
+ &--at-bottom::before {
+ content: "";
+ width: calc(100% - 1.5rem);
+ height: 1px;
+ position: absolute;
+ top: -1px;
+ background: var(--sidebar-border-color);
+ }
+ }
+
+ .library-menu-browse-button {
+ flex: 1;
+
+ height: var(--lg-button-size);
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ position: relative;
+
+ border-radius: var(--border-radius-lg);
+ background-color: var(--color-primary);
+ color: $oc-white;
+ text-align: center;
+ white-space: nowrap;
+ text-decoration: none !important;
+
+ font-weight: 600;
+ font-size: 0.75rem;
+
+ &:hover {
+ background-color: var(--color-brand-hover);
+ }
+ &:active {
+ background-color: var(--color-brand-active);
+ }
+ }
+
+ &.theme--dark {
+ .library-menu-browse-button {
+ color: var(--color-gray-100);
+ }
+ }
+
+ &.excalidraw--mobile .library-menu-browse-button {
+ height: var(--default-button-size);
+ }
+
+ .layer-ui__library .dropdown-menu {
+ width: auto;
+ top: initial;
+ right: 0;
+ left: initial;
+ bottom: 100%;
+ margin-bottom: 0.625rem;
+
+ .dropdown-menu-container {
+ width: 196px;
+ box-shadow: var(--library-dropdown-shadow);
+ border-radius: var(--border-radius-lg);
+ padding: 0.25rem 0.5rem;
+ }
+ }
+
+ .layer-ui__library .library-menu-dropdown-container {
+ position: relative;
+
+ &--in-heading {
+ padding: 0;
+ position: absolute;
+ top: 1rem;
+ right: 0.75rem;
+ z-index: 1;
+
+ .dropdown-menu {
+ top: 100%;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/LibraryMenu.tsx b/packages/excalidraw/components/LibraryMenu.tsx
new file mode 100644
index 0000000..0162d93
--- /dev/null
+++ b/packages/excalidraw/components/LibraryMenu.tsx
@@ -0,0 +1,290 @@
+import React, {
+ useState,
+ useCallback,
+ useMemo,
+ useEffect,
+ memo,
+ useRef,
+} from "react";
+import type Library from "../data/library";
+import {
+ distributeLibraryItemsOnSquareGrid,
+ libraryItemsAtom,
+} from "../data/library";
+import { t } from "../i18n";
+import { randomId } from "../random";
+import type {
+ LibraryItems,
+ LibraryItem,
+ ExcalidrawProps,
+ UIAppState,
+ AppClassProperties,
+} from "../types";
+import LibraryMenuItems from "./LibraryMenuItems";
+import { trackEvent } from "../analytics";
+import { atom, useAtom } from "../editor-jotai";
+import Spinner from "./Spinner";
+import {
+ useApp,
+ useAppProps,
+ useExcalidrawElements,
+ useExcalidrawSetAppState,
+} from "./App";
+import { getSelectedElements } from "../scene";
+import { useUIAppState } from "../context/ui-appState";
+
+import "./LibraryMenu.scss";
+import { LibraryMenuControlButtons } from "./LibraryMenuControlButtons";
+import type {
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+} from "../element/types";
+import { LIBRARY_DISABLED_TYPES } from "../constants";
+import { isShallowEqual } from "../utils";
+
+export const isLibraryMenuOpenAtom = atom(false);
+
+const LibraryMenuWrapper = ({ children }: { children: React.ReactNode }) => {
+ return <div className="layer-ui__library">{children}</div>;
+};
+
+const LibraryMenuContent = memo(
+ ({
+ onInsertLibraryItems,
+ pendingElements,
+ onAddToLibrary,
+ setAppState,
+ libraryReturnUrl,
+ library,
+ id,
+ theme,
+ selectedItems,
+ onSelectItems,
+ }: {
+ pendingElements: LibraryItem["elements"];
+ onInsertLibraryItems: (libraryItems: LibraryItems) => void;
+ onAddToLibrary: () => void;
+ setAppState: React.Component<any, UIAppState>["setState"];
+ libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
+ library: Library;
+ id: string;
+ theme: UIAppState["theme"];
+ selectedItems: LibraryItem["id"][];
+ onSelectItems: (id: LibraryItem["id"][]) => void;
+ }) => {
+ const [libraryItemsData] = useAtom(libraryItemsAtom);
+
+ const _onAddToLibrary = useCallback(
+ (elements: LibraryItem["elements"]) => {
+ const addToLibrary = async (
+ processedElements: LibraryItem["elements"],
+ libraryItems: LibraryItems,
+ ) => {
+ trackEvent("element", "addToLibrary", "ui");
+ for (const type of LIBRARY_DISABLED_TYPES) {
+ if (processedElements.some((element) => element.type === type)) {
+ return setAppState({
+ errorMessage: t(`errors.libraryElementTypeError.${type}`),
+ });
+ }
+ }
+ const nextItems: LibraryItems = [
+ {
+ status: "unpublished",
+ elements: processedElements,
+ id: randomId(),
+ created: Date.now(),
+ },
+ ...libraryItems,
+ ];
+ onAddToLibrary();
+ library.setLibrary(nextItems).catch(() => {
+ setAppState({ errorMessage: t("alerts.errorAddingToLibrary") });
+ });
+ };
+ addToLibrary(elements, libraryItemsData.libraryItems);
+ },
+ [onAddToLibrary, library, setAppState, libraryItemsData.libraryItems],
+ );
+
+ const libraryItems = useMemo(
+ () => libraryItemsData.libraryItems,
+ [libraryItemsData],
+ );
+
+ if (
+ libraryItemsData.status === "loading" &&
+ !libraryItemsData.isInitialized
+ ) {
+ return (
+ <LibraryMenuWrapper>
+ <div className="layer-ui__library-message">
+ <div>
+ <Spinner size="2em" />
+ <span>{t("labels.libraryLoadingMessage")}</span>
+ </div>
+ </div>
+ </LibraryMenuWrapper>
+ );
+ }
+
+ const showBtn =
+ libraryItemsData.libraryItems.length > 0 || pendingElements.length > 0;
+
+ return (
+ <LibraryMenuWrapper>
+ <LibraryMenuItems
+ isLoading={libraryItemsData.status === "loading"}
+ libraryItems={libraryItems}
+ onAddToLibrary={_onAddToLibrary}
+ onInsertLibraryItems={onInsertLibraryItems}
+ pendingElements={pendingElements}
+ id={id}
+ libraryReturnUrl={libraryReturnUrl}
+ theme={theme}
+ onSelectItems={onSelectItems}
+ selectedItems={selectedItems}
+ />
+ {showBtn && (
+ <LibraryMenuControlButtons
+ className="library-menu-control-buttons--at-bottom"
+ style={{ padding: "16px 12px 0 12px" }}
+ id={id}
+ libraryReturnUrl={libraryReturnUrl}
+ theme={theme}
+ />
+ )}
+ </LibraryMenuWrapper>
+ );
+ },
+);
+
+const getPendingElements = (
+ elements: readonly NonDeletedExcalidrawElement[],
+ selectedElementIds: UIAppState["selectedElementIds"],
+) => ({
+ elements,
+ pending: getSelectedElements(
+ elements,
+ { selectedElementIds },
+ {
+ includeBoundTextElement: true,
+ includeElementsInFrames: true,
+ },
+ ),
+ selectedElementIds,
+});
+
+const usePendingElementsMemo = (
+ appState: UIAppState,
+ app: AppClassProperties,
+) => {
+ const elements = useExcalidrawElements();
+ const [state, setState] = useState(() =>
+ getPendingElements(elements, appState.selectedElementIds),
+ );
+
+ const selectedElementVersions = useRef(
+ new Map<ExcalidrawElement["id"], ExcalidrawElement["version"]>(),
+ );
+
+ useEffect(() => {
+ for (const element of state.pending) {
+ selectedElementVersions.current.set(element.id, element.version);
+ }
+ }, [state.pending]);
+
+ useEffect(() => {
+ if (
+ // Only update once pointer is released.
+ // Reading directly from app.state to make it clear it's not reactive
+ // (hence, there's potential for stale state)
+ app.state.cursorButton === "up" &&
+ app.state.activeTool.type === "selection"
+ ) {
+ setState((prev) => {
+ // if selectedElementIds changed, we don't have to compare versions
+ // ---------------------------------------------------------------------
+ if (
+ !isShallowEqual(prev.selectedElementIds, appState.selectedElementIds)
+ ) {
+ selectedElementVersions.current.clear();
+ return getPendingElements(elements, appState.selectedElementIds);
+ }
+ // otherwise we need to check whether selected elements changed
+ // ---------------------------------------------------------------------
+ const elementsMap = app.scene.getNonDeletedElementsMap();
+ for (const id of Object.keys(appState.selectedElementIds)) {
+ const currVersion = elementsMap.get(id)?.version;
+ if (
+ currVersion &&
+ currVersion !== selectedElementVersions.current.get(id)
+ ) {
+ // we can't update the selectedElementVersions in here
+ // because of double render in StrictMode which would overwrite
+ // the state in the second pass with the old `prev` state.
+ // Thus, we update versions in a separate effect. May create
+ // a race condition since current effect is not fully reactive.
+ return getPendingElements(elements, appState.selectedElementIds);
+ }
+ }
+ // nothing changed
+ // ---------------------------------------------------------------------
+ return prev;
+ });
+ }
+ }, [
+ app,
+ app.state.cursorButton,
+ app.state.activeTool.type,
+ appState.selectedElementIds,
+ elements,
+ ]);
+
+ return state.pending;
+};
+
+/**
+ * This component is meant to be rendered inside <Sidebar.Tab/> inside our
+ * <DefaultSidebar/> or host apps Sidebar components.
+ */
+export const LibraryMenu = memo(() => {
+ const app = useApp();
+ const { onInsertElements } = app;
+ const appProps = useAppProps();
+ const appState = useUIAppState();
+ const setAppState = useExcalidrawSetAppState();
+ const [selectedItems, setSelectedItems] = useState<LibraryItem["id"][]>([]);
+ const memoizedLibrary = useMemo(() => app.library, [app.library]);
+ const pendingElements = usePendingElementsMemo(appState, app);
+
+ const onInsertLibraryItems = useCallback(
+ (libraryItems: LibraryItems) => {
+ onInsertElements(distributeLibraryItemsOnSquareGrid(libraryItems));
+ },
+ [onInsertElements],
+ );
+
+ const deselectItems = useCallback(() => {
+ setAppState({
+ selectedElementIds: {},
+ selectedGroupIds: {},
+ activeEmbeddable: null,
+ });
+ }, [setAppState]);
+
+ return (
+ <LibraryMenuContent
+ pendingElements={pendingElements}
+ onInsertLibraryItems={onInsertLibraryItems}
+ onAddToLibrary={deselectItems}
+ setAppState={setAppState}
+ libraryReturnUrl={appProps.libraryReturnUrl}
+ library={memoizedLibrary}
+ id={app.id}
+ theme={appState.theme}
+ selectedItems={selectedItems}
+ onSelectItems={setSelectedItems}
+ />
+ );
+});
diff --git a/packages/excalidraw/components/LibraryMenuBrowseButton.tsx b/packages/excalidraw/components/LibraryMenuBrowseButton.tsx
new file mode 100644
index 0000000..43fbedd
--- /dev/null
+++ b/packages/excalidraw/components/LibraryMenuBrowseButton.tsx
@@ -0,0 +1,31 @@
+import { VERSIONS } from "../constants";
+import { t } from "../i18n";
+import type { ExcalidrawProps, UIAppState } from "../types";
+
+const LibraryMenuBrowseButton = ({
+ theme,
+ id,
+ libraryReturnUrl,
+}: {
+ libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
+ theme: UIAppState["theme"];
+ id: string;
+}) => {
+ const referrer =
+ libraryReturnUrl || window.location.origin + window.location.pathname;
+ return (
+ <a
+ className="library-menu-browse-button"
+ href={`${import.meta.env.VITE_APP_LIBRARY_URL}?target=${
+ window.name || "_blank"
+ }&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}&version=${
+ VERSIONS.excalidrawLibrary
+ }`}
+ target="_excalidraw_libraries"
+ >
+ {t("labels.libraries")}
+ </a>
+ );
+};
+
+export default LibraryMenuBrowseButton;
diff --git a/packages/excalidraw/components/LibraryMenuControlButtons.tsx b/packages/excalidraw/components/LibraryMenuControlButtons.tsx
new file mode 100644
index 0000000..b467ca3
--- /dev/null
+++ b/packages/excalidraw/components/LibraryMenuControlButtons.tsx
@@ -0,0 +1,33 @@
+import type { ExcalidrawProps, UIAppState } from "../types";
+import LibraryMenuBrowseButton from "./LibraryMenuBrowseButton";
+import clsx from "clsx";
+
+export const LibraryMenuControlButtons = ({
+ libraryReturnUrl,
+ theme,
+ id,
+ style,
+ children,
+ className,
+}: {
+ libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
+ theme: UIAppState["theme"];
+ id: string;
+ style: React.CSSProperties;
+ children?: React.ReactNode;
+ className?: string;
+}) => {
+ return (
+ <div
+ className={clsx("library-menu-control-buttons", className)}
+ style={style}
+ >
+ <LibraryMenuBrowseButton
+ id={id}
+ libraryReturnUrl={libraryReturnUrl}
+ theme={theme}
+ />
+ {children}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/LibraryMenuHeaderContent.tsx b/packages/excalidraw/components/LibraryMenuHeaderContent.tsx
new file mode 100644
index 0000000..bec31aa
--- /dev/null
+++ b/packages/excalidraw/components/LibraryMenuHeaderContent.tsx
@@ -0,0 +1,321 @@
+import { useCallback, useState } from "react";
+import { t } from "../i18n";
+import Trans from "./Trans";
+import { useAtom } from "../editor-jotai";
+import type { LibraryItem, LibraryItems, UIAppState } from "../types";
+import { useApp, useExcalidrawSetAppState } from "./App";
+import { saveLibraryAsJSON } from "../data/json";
+import type Library from "../data/library";
+import { libraryItemsAtom } from "../data/library";
+import {
+ DotsIcon,
+ ExportIcon,
+ LoadIcon,
+ publishIcon,
+ TrashIcon,
+} from "./icons";
+import { ToolButton } from "./ToolButton";
+import { fileOpen } from "../data/filesystem";
+import { muteFSAbortError } from "../utils";
+import ConfirmDialog from "./ConfirmDialog";
+import PublishLibrary from "./PublishLibrary";
+import { Dialog } from "./Dialog";
+import DropdownMenu from "./dropdownMenu/DropdownMenu";
+import { isLibraryMenuOpenAtom } from "./LibraryMenu";
+import { useUIAppState } from "../context/ui-appState";
+import clsx from "clsx";
+import { useLibraryCache } from "../hooks/useLibraryItemSvg";
+
+const getSelectedItems = (
+ libraryItems: LibraryItems,
+ selectedItems: LibraryItem["id"][],
+) => libraryItems.filter((item) => selectedItems.includes(item.id));
+
+export const LibraryDropdownMenuButton: React.FC<{
+ setAppState: React.Component<any, UIAppState>["setState"];
+ selectedItems: LibraryItem["id"][];
+ library: Library;
+ onRemoveFromLibrary: () => void;
+ resetLibrary: () => void;
+ onSelectItems: (items: LibraryItem["id"][]) => void;
+ appState: UIAppState;
+ className?: string;
+}> = ({
+ setAppState,
+ selectedItems,
+ library,
+ onRemoveFromLibrary,
+ resetLibrary,
+ onSelectItems,
+ appState,
+ className,
+}) => {
+ const [libraryItemsData] = useAtom(libraryItemsAtom);
+ const [isLibraryMenuOpen, setIsLibraryMenuOpen] = useAtom(
+ isLibraryMenuOpenAtom,
+ );
+
+ const renderRemoveLibAlert = () => {
+ const content = selectedItems.length
+ ? t("alerts.removeItemsFromsLibrary", { count: selectedItems.length })
+ : t("alerts.resetLibrary");
+ const title = selectedItems.length
+ ? t("confirmDialog.removeItemsFromLib")
+ : t("confirmDialog.resetLibrary");
+ return (
+ <ConfirmDialog
+ onConfirm={() => {
+ if (selectedItems.length) {
+ onRemoveFromLibrary();
+ } else {
+ resetLibrary();
+ }
+ setShowRemoveLibAlert(false);
+ }}
+ onCancel={() => {
+ setShowRemoveLibAlert(false);
+ }}
+ title={title}
+ >
+ <p>{content}</p>
+ </ConfirmDialog>
+ );
+ };
+
+ const [showRemoveLibAlert, setShowRemoveLibAlert] = useState(false);
+
+ const itemsSelected = !!selectedItems.length;
+ const items = itemsSelected
+ ? libraryItemsData.libraryItems.filter((item) =>
+ selectedItems.includes(item.id),
+ )
+ : libraryItemsData.libraryItems;
+ const resetLabel = itemsSelected
+ ? t("buttons.remove")
+ : t("buttons.resetLibrary");
+
+ const [showPublishLibraryDialog, setShowPublishLibraryDialog] =
+ useState(false);
+ const [publishLibSuccess, setPublishLibSuccess] = useState<null | {
+ url: string;
+ authorName: string;
+ }>(null);
+ const renderPublishSuccess = useCallback(() => {
+ return (
+ <Dialog
+ onCloseRequest={() => setPublishLibSuccess(null)}
+ title={t("publishSuccessDialog.title")}
+ className="publish-library-success"
+ size="small"
+ >
+ <p>
+ <Trans
+ i18nKey="publishSuccessDialog.content"
+ authorName={publishLibSuccess!.authorName}
+ link={(el) => (
+ <a
+ href={publishLibSuccess?.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {el}
+ </a>
+ )}
+ />
+ </p>
+ <ToolButton
+ type="button"
+ title={t("buttons.close")}
+ aria-label={t("buttons.close")}
+ label={t("buttons.close")}
+ onClick={() => setPublishLibSuccess(null)}
+ data-testid="publish-library-success-close"
+ className="publish-library-success-close"
+ />
+ </Dialog>
+ );
+ }, [setPublishLibSuccess, publishLibSuccess]);
+
+ const onPublishLibSuccess = (
+ data: { url: string; authorName: string },
+ libraryItems: LibraryItems,
+ ) => {
+ setShowPublishLibraryDialog(false);
+ setPublishLibSuccess({ url: data.url, authorName: data.authorName });
+ const nextLibItems = libraryItems.slice();
+ nextLibItems.forEach((libItem) => {
+ if (selectedItems.includes(libItem.id)) {
+ libItem.status = "published";
+ }
+ });
+ library.setLibrary(nextLibItems);
+ };
+
+ const onLibraryImport = async () => {
+ try {
+ await library.updateLibrary({
+ libraryItems: fileOpen({
+ description: "Excalidraw library files",
+ // ToDo: Be over-permissive until https://bugs.webkit.org/show_bug.cgi?id=34442
+ // gets resolved. Else, iOS users cannot open `.excalidraw` files.
+ /*
+ extensions: [".json", ".excalidrawlib"],
+ */
+ }),
+ merge: true,
+ openLibraryMenu: true,
+ });
+ } catch (error: any) {
+ if (error?.name === "AbortError") {
+ console.warn(error);
+ return;
+ }
+ setAppState({ errorMessage: t("errors.importLibraryError") });
+ }
+ };
+
+ const onLibraryExport = async () => {
+ const libraryItems = itemsSelected
+ ? items
+ : await library.getLatestLibrary();
+ saveLibraryAsJSON(libraryItems)
+ .catch(muteFSAbortError)
+ .catch((error) => {
+ setAppState({ errorMessage: error.message });
+ });
+ };
+
+ const renderLibraryMenu = () => {
+ return (
+ <DropdownMenu open={isLibraryMenuOpen}>
+ <DropdownMenu.Trigger
+ onToggle={() => setIsLibraryMenuOpen(!isLibraryMenuOpen)}
+ >
+ {DotsIcon}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content
+ onClickOutside={() => setIsLibraryMenuOpen(false)}
+ onSelect={() => setIsLibraryMenuOpen(false)}
+ className="library-menu"
+ >
+ {!itemsSelected && (
+ <DropdownMenu.Item
+ onSelect={onLibraryImport}
+ icon={LoadIcon}
+ data-testid="lib-dropdown--load"
+ >
+ {t("buttons.load")}
+ </DropdownMenu.Item>
+ )}
+ {!!items.length && (
+ <DropdownMenu.Item
+ onSelect={onLibraryExport}
+ icon={ExportIcon}
+ data-testid="lib-dropdown--export"
+ >
+ {t("buttons.export")}
+ </DropdownMenu.Item>
+ )}
+ {!!items.length && (
+ <DropdownMenu.Item
+ onSelect={() => setShowRemoveLibAlert(true)}
+ icon={TrashIcon}
+ >
+ {resetLabel}
+ </DropdownMenu.Item>
+ )}
+ {itemsSelected && (
+ <DropdownMenu.Item
+ icon={publishIcon}
+ onSelect={() => setShowPublishLibraryDialog(true)}
+ data-testid="lib-dropdown--remove"
+ >
+ {t("buttons.publishLibrary")}
+ </DropdownMenu.Item>
+ )}
+ </DropdownMenu.Content>
+ </DropdownMenu>
+ );
+ };
+
+ return (
+ <div className={clsx("library-menu-dropdown-container", className)}>
+ {renderLibraryMenu()}
+ {selectedItems.length > 0 && (
+ <div className="library-actions-counter">{selectedItems.length}</div>
+ )}
+ {showRemoveLibAlert && renderRemoveLibAlert()}
+ {showPublishLibraryDialog && (
+ <PublishLibrary
+ onClose={() => setShowPublishLibraryDialog(false)}
+ libraryItems={getSelectedItems(
+ libraryItemsData.libraryItems,
+ selectedItems,
+ )}
+ appState={appState}
+ onSuccess={(data) =>
+ onPublishLibSuccess(data, libraryItemsData.libraryItems)
+ }
+ onError={(error) => window.alert(error)}
+ updateItemsInStorage={() =>
+ library.setLibrary(libraryItemsData.libraryItems)
+ }
+ onRemove={(id: string) =>
+ onSelectItems(selectedItems.filter((_id) => _id !== id))
+ }
+ />
+ )}
+ {publishLibSuccess && renderPublishSuccess()}
+ </div>
+ );
+};
+
+export const LibraryDropdownMenu = ({
+ selectedItems,
+ onSelectItems,
+ className,
+}: {
+ selectedItems: LibraryItem["id"][];
+ onSelectItems: (id: LibraryItem["id"][]) => void;
+ className?: string;
+}) => {
+ const { library } = useApp();
+ const { clearLibraryCache, deleteItemsFromLibraryCache } = useLibraryCache();
+ const appState = useUIAppState();
+ const setAppState = useExcalidrawSetAppState();
+
+ const [libraryItemsData] = useAtom(libraryItemsAtom);
+
+ const removeFromLibrary = async (libraryItems: LibraryItems) => {
+ const nextItems = libraryItems.filter(
+ (item) => !selectedItems.includes(item.id),
+ );
+ library.setLibrary(nextItems).catch(() => {
+ setAppState({ errorMessage: t("alerts.errorRemovingFromLibrary") });
+ });
+
+ deleteItemsFromLibraryCache(selectedItems);
+
+ onSelectItems([]);
+ };
+
+ const resetLibrary = () => {
+ library.resetLibrary();
+ clearLibraryCache();
+ };
+
+ return (
+ <LibraryDropdownMenuButton
+ appState={appState}
+ setAppState={setAppState}
+ selectedItems={selectedItems}
+ onSelectItems={onSelectItems}
+ library={library}
+ onRemoveFromLibrary={() =>
+ removeFromLibrary(libraryItemsData.libraryItems)
+ }
+ resetLibrary={resetLibrary}
+ className={className}
+ />
+ );
+};
diff --git a/packages/excalidraw/components/LibraryMenuItems.scss b/packages/excalidraw/components/LibraryMenuItems.scss
new file mode 100644
index 0000000..59cd9f1
--- /dev/null
+++ b/packages/excalidraw/components/LibraryMenuItems.scss
@@ -0,0 +1,99 @@
+@import "open-color/open-color";
+
+.excalidraw {
+ --container-padding-y: 1.5rem;
+ --container-padding-x: 0.75rem;
+
+ .library-menu-items__no-items {
+ text-align: center;
+ color: var(--color-gray-70);
+ line-height: 1.5;
+ font-size: 0.875rem;
+ width: 100%;
+
+ &__label {
+ color: var(--color-primary);
+ font-weight: 700;
+ font-size: 1.125rem;
+ margin-bottom: 0.75rem;
+ }
+ }
+
+ &.theme--dark {
+ .library-menu-items__no-items {
+ color: var(--color-gray-40);
+ }
+ }
+
+ .library-menu-items-container {
+ width: 100%;
+ display: flex;
+ flex-grow: 1;
+ flex-shrink: 1;
+ flex-basis: 0;
+ overflow-y: auto;
+ flex-direction: column;
+ height: 100%;
+ justify-content: center;
+ margin: 0;
+
+ position: relative;
+
+ & > div {
+ padding-left: 0.75rem;
+ padding-right: 0.75rem;
+ }
+
+ &__row {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 1rem;
+ }
+
+ &__items {
+ row-gap: 0.5rem;
+ padding: var(--container-padding-y) 0;
+ flex: 1;
+ overflow-y: auto;
+ overflow-x: hidden;
+ margin-bottom: 1rem;
+ }
+
+ &__header {
+ color: var(--color-primary);
+ font-size: 1.125rem;
+ font-weight: 700;
+ margin-bottom: 0.75rem;
+ width: 100%;
+ padding-right: 4rem; // due to dropdown button
+ box-sizing: border-box;
+
+ &--excal {
+ margin-top: 2rem;
+ }
+ }
+
+ &__grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr 1fr 1fr;
+ grid-gap: 1rem;
+ }
+
+ .separator {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ font-weight: 500;
+ font-size: 0.9rem;
+ margin: 0.6em 0.2em;
+ color: var(--text-primary-color);
+ }
+ }
+
+ .library-menu-items-private-library-container {
+ // so that when you toggle between pending item and no items, there's
+ // no layout shift (this is hardcoded and works only with ENG locale)
+ min-height: 3.75rem;
+ width: 100%;
+ }
+}
diff --git a/packages/excalidraw/components/LibraryMenuItems.tsx b/packages/excalidraw/components/LibraryMenuItems.tsx
new file mode 100644
index 0000000..aa2c3e6
--- /dev/null
+++ b/packages/excalidraw/components/LibraryMenuItems.tsx
@@ -0,0 +1,342 @@
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { serializeLibraryAsJSON } from "../data/json";
+import { t } from "../i18n";
+import type {
+ ExcalidrawProps,
+ LibraryItem,
+ LibraryItems,
+ UIAppState,
+} from "../types";
+import { arrayToMap } from "../utils";
+import Stack from "./Stack";
+import { MIME_TYPES } from "../constants";
+import Spinner from "./Spinner";
+import { duplicateElements } from "../element/newElement";
+import { LibraryMenuControlButtons } from "./LibraryMenuControlButtons";
+import { LibraryDropdownMenu } from "./LibraryMenuHeaderContent";
+import {
+ LibraryMenuSection,
+ LibraryMenuSectionGrid,
+} from "./LibraryMenuSection";
+import { useScrollPosition } from "../hooks/useScrollPosition";
+import { useLibraryCache } from "../hooks/useLibraryItemSvg";
+
+import "./LibraryMenuItems.scss";
+
+// using an odd number of items per batch so the rendering creates an irregular
+// pattern which looks more organic
+const ITEMS_RENDERED_PER_BATCH = 17;
+// when render outputs cached we can render many more items per batch to
+// speed it up
+const CACHED_ITEMS_RENDERED_PER_BATCH = 64;
+
+export default function LibraryMenuItems({
+ isLoading,
+ libraryItems,
+ onAddToLibrary,
+ onInsertLibraryItems,
+ pendingElements,
+ theme,
+ id,
+ libraryReturnUrl,
+ onSelectItems,
+ selectedItems,
+}: {
+ isLoading: boolean;
+ libraryItems: LibraryItems;
+ pendingElements: LibraryItem["elements"];
+ onInsertLibraryItems: (libraryItems: LibraryItems) => void;
+ onAddToLibrary: (elements: LibraryItem["elements"]) => void;
+ libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
+ theme: UIAppState["theme"];
+ id: string;
+ selectedItems: LibraryItem["id"][];
+ onSelectItems: (id: LibraryItem["id"][]) => void;
+}) {
+ const libraryContainerRef = useRef<HTMLDivElement>(null);
+ const scrollPosition = useScrollPosition<HTMLDivElement>(libraryContainerRef);
+
+ // This effect has to be called only on first render, therefore `scrollPosition` isn't in the dependency array
+ useEffect(() => {
+ if (scrollPosition > 0) {
+ libraryContainerRef.current?.scrollTo(0, scrollPosition);
+ }
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const { svgCache } = useLibraryCache();
+ const unpublishedItems = useMemo(
+ () => libraryItems.filter((item) => item.status !== "published"),
+ [libraryItems],
+ );
+
+ const publishedItems = useMemo(
+ () => libraryItems.filter((item) => item.status === "published"),
+ [libraryItems],
+ );
+
+ const showBtn = !libraryItems.length && !pendingElements.length;
+
+ const isLibraryEmpty =
+ !pendingElements.length &&
+ !unpublishedItems.length &&
+ !publishedItems.length;
+
+ const [lastSelectedItem, setLastSelectedItem] = useState<
+ LibraryItem["id"] | null
+ >(null);
+
+ const onItemSelectToggle = useCallback(
+ (id: LibraryItem["id"], event: React.MouseEvent) => {
+ const shouldSelect = !selectedItems.includes(id);
+
+ const orderedItems = [...unpublishedItems, ...publishedItems];
+
+ if (shouldSelect) {
+ if (event.shiftKey && lastSelectedItem) {
+ const rangeStart = orderedItems.findIndex(
+ (item) => item.id === lastSelectedItem,
+ );
+ const rangeEnd = orderedItems.findIndex((item) => item.id === id);
+
+ if (rangeStart === -1 || rangeEnd === -1) {
+ onSelectItems([...selectedItems, id]);
+ return;
+ }
+
+ const selectedItemsMap = arrayToMap(selectedItems);
+ const nextSelectedIds = orderedItems.reduce(
+ (acc: LibraryItem["id"][], item, idx) => {
+ if (
+ (idx >= rangeStart && idx <= rangeEnd) ||
+ selectedItemsMap.has(item.id)
+ ) {
+ acc.push(item.id);
+ }
+ return acc;
+ },
+ [],
+ );
+
+ onSelectItems(nextSelectedIds);
+ } else {
+ onSelectItems([...selectedItems, id]);
+ }
+ setLastSelectedItem(id);
+ } else {
+ setLastSelectedItem(null);
+ onSelectItems(selectedItems.filter((_id) => _id !== id));
+ }
+ },
+ [
+ lastSelectedItem,
+ onSelectItems,
+ publishedItems,
+ selectedItems,
+ unpublishedItems,
+ ],
+ );
+
+ const getInsertedElements = useCallback(
+ (id: string) => {
+ let targetElements;
+ if (selectedItems.includes(id)) {
+ targetElements = libraryItems.filter((item) =>
+ selectedItems.includes(item.id),
+ );
+ } else {
+ targetElements = libraryItems.filter((item) => item.id === id);
+ }
+ return targetElements.map((item) => {
+ return {
+ ...item,
+ // duplicate each library item before inserting on canvas to confine
+ // ids and bindings to each library item. See #6465
+ elements: duplicateElements(item.elements, { randomizeSeed: true }),
+ };
+ });
+ },
+ [libraryItems, selectedItems],
+ );
+
+ const onItemDrag = useCallback(
+ (id: LibraryItem["id"], event: React.DragEvent) => {
+ event.dataTransfer.setData(
+ MIME_TYPES.excalidrawlib,
+ serializeLibraryAsJSON(getInsertedElements(id)),
+ );
+ },
+ [getInsertedElements],
+ );
+
+ const isItemSelected = useCallback(
+ (id: LibraryItem["id"] | null) => {
+ if (!id) {
+ return false;
+ }
+
+ return selectedItems.includes(id);
+ },
+ [selectedItems],
+ );
+
+ const onAddToLibraryClick = useCallback(() => {
+ onAddToLibrary(pendingElements);
+ }, [pendingElements, onAddToLibrary]);
+
+ const onItemClick = useCallback(
+ (id: LibraryItem["id"] | null) => {
+ if (id) {
+ onInsertLibraryItems(getInsertedElements(id));
+ }
+ },
+ [getInsertedElements, onInsertLibraryItems],
+ );
+
+ const itemsRenderedPerBatch =
+ svgCache.size >= libraryItems.length
+ ? CACHED_ITEMS_RENDERED_PER_BATCH
+ : ITEMS_RENDERED_PER_BATCH;
+
+ return (
+ <div
+ className="library-menu-items-container"
+ style={
+ pendingElements.length ||
+ unpublishedItems.length ||
+ publishedItems.length
+ ? { justifyContent: "flex-start" }
+ : { borderBottom: 0 }
+ }
+ >
+ {!isLibraryEmpty && (
+ <LibraryDropdownMenu
+ selectedItems={selectedItems}
+ onSelectItems={onSelectItems}
+ className="library-menu-dropdown-container--in-heading"
+ />
+ )}
+ <Stack.Col
+ className="library-menu-items-container__items"
+ align="start"
+ gap={1}
+ style={{
+ flex: publishedItems.length > 0 ? 1 : "0 1 auto",
+ marginBottom: 0,
+ }}
+ ref={libraryContainerRef}
+ >
+ <>
+ {!isLibraryEmpty && (
+ <div className="library-menu-items-container__header">
+ {t("labels.personalLib")}
+ </div>
+ )}
+ {isLoading && (
+ <div
+ style={{
+ position: "absolute",
+ top: "var(--container-padding-y)",
+ right: "var(--container-padding-x)",
+ transform: "translateY(50%)",
+ }}
+ >
+ <Spinner />
+ </div>
+ )}
+ {!pendingElements.length && !unpublishedItems.length ? (
+ <div className="library-menu-items__no-items">
+ <div className="library-menu-items__no-items__label">
+ {t("library.noItems")}
+ </div>
+ <div className="library-menu-items__no-items__hint">
+ {publishedItems.length > 0
+ ? t("library.hint_emptyPrivateLibrary")
+ : t("library.hint_emptyLibrary")}
+ </div>
+ </div>
+ ) : (
+ <LibraryMenuSectionGrid>
+ {pendingElements.length > 0 && (
+ <LibraryMenuSection
+ itemsRenderedPerBatch={itemsRenderedPerBatch}
+ items={[{ id: null, elements: pendingElements }]}
+ onItemSelectToggle={onItemSelectToggle}
+ onItemDrag={onItemDrag}
+ onClick={onAddToLibraryClick}
+ isItemSelected={isItemSelected}
+ svgCache={svgCache}
+ />
+ )}
+ <LibraryMenuSection
+ itemsRenderedPerBatch={itemsRenderedPerBatch}
+ items={unpublishedItems}
+ onItemSelectToggle={onItemSelectToggle}
+ onItemDrag={onItemDrag}
+ onClick={onItemClick}
+ isItemSelected={isItemSelected}
+ svgCache={svgCache}
+ />
+ </LibraryMenuSectionGrid>
+ )}
+ </>
+
+ <>
+ {(publishedItems.length > 0 ||
+ pendingElements.length > 0 ||
+ unpublishedItems.length > 0) && (
+ <div className="library-menu-items-container__header library-menu-items-container__header--excal">
+ {t("labels.excalidrawLib")}
+ </div>
+ )}
+ {publishedItems.length > 0 ? (
+ <LibraryMenuSectionGrid>
+ <LibraryMenuSection
+ itemsRenderedPerBatch={itemsRenderedPerBatch}
+ items={publishedItems}
+ onItemSelectToggle={onItemSelectToggle}
+ onItemDrag={onItemDrag}
+ onClick={onItemClick}
+ isItemSelected={isItemSelected}
+ svgCache={svgCache}
+ />
+ </LibraryMenuSectionGrid>
+ ) : unpublishedItems.length > 0 ? (
+ <div
+ style={{
+ margin: "1rem 0",
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ justifyContent: "center",
+ width: "100%",
+ fontSize: ".9rem",
+ }}
+ >
+ {t("library.noItems")}
+ </div>
+ ) : null}
+ </>
+
+ {showBtn && (
+ <LibraryMenuControlButtons
+ style={{ padding: "16px 0", width: "100%" }}
+ id={id}
+ libraryReturnUrl={libraryReturnUrl}
+ theme={theme}
+ >
+ <LibraryDropdownMenu
+ selectedItems={selectedItems}
+ onSelectItems={onSelectItems}
+ />
+ </LibraryMenuControlButtons>
+ )}
+ </Stack.Col>
+ </div>
+ );
+}
diff --git a/packages/excalidraw/components/LibraryMenuSection.tsx b/packages/excalidraw/components/LibraryMenuSection.tsx
new file mode 100644
index 0000000..b07d6b1
--- /dev/null
+++ b/packages/excalidraw/components/LibraryMenuSection.tsx
@@ -0,0 +1,78 @@
+import type { ReactNode } from "react";
+import React, { memo, useEffect, useState } from "react";
+import { EmptyLibraryUnit, LibraryUnit } from "./LibraryUnit";
+import type { LibraryItem } from "../types";
+import type { ExcalidrawElement, NonDeleted } from "../element/types";
+import type { SvgCache } from "../hooks/useLibraryItemSvg";
+import { useTransition } from "../hooks/useTransition";
+
+type LibraryOrPendingItem = (
+ | LibraryItem
+ | /* pending library item */ {
+ id: null;
+ elements: readonly NonDeleted<ExcalidrawElement>[];
+ }
+)[];
+
+interface Props {
+ items: LibraryOrPendingItem;
+ onClick: (id: LibraryItem["id"] | null) => void;
+ onItemSelectToggle: (id: LibraryItem["id"], event: React.MouseEvent) => void;
+ onItemDrag: (id: LibraryItem["id"], event: React.DragEvent) => void;
+ isItemSelected: (id: LibraryItem["id"] | null) => boolean;
+ svgCache: SvgCache;
+ itemsRenderedPerBatch: number;
+}
+
+export const LibraryMenuSectionGrid = ({
+ children,
+}: {
+ children: ReactNode;
+}) => {
+ return <div className="library-menu-items-container__grid">{children}</div>;
+};
+
+export const LibraryMenuSection = memo(
+ ({
+ items,
+ onItemSelectToggle,
+ onItemDrag,
+ isItemSelected,
+ onClick,
+ svgCache,
+ itemsRenderedPerBatch,
+ }: Props) => {
+ const [, startTransition] = useTransition();
+ const [index, setIndex] = useState(0);
+
+ useEffect(() => {
+ if (index < items.length) {
+ startTransition(() => {
+ setIndex(index + itemsRenderedPerBatch);
+ });
+ }
+ }, [index, items.length, startTransition, itemsRenderedPerBatch]);
+
+ return (
+ <>
+ {items.map((item, i) => {
+ return i < index ? (
+ <LibraryUnit
+ elements={item?.elements}
+ isPending={!item?.id && !!item?.elements}
+ onClick={onClick}
+ svgCache={svgCache}
+ id={item?.id}
+ selected={isItemSelected(item.id)}
+ onToggle={onItemSelectToggle}
+ onDrag={onItemDrag}
+ key={item?.id ?? i}
+ />
+ ) : (
+ <EmptyLibraryUnit key={i} />
+ );
+ })}
+ </>
+ );
+ },
+);
diff --git a/packages/excalidraw/components/LibraryUnit.scss b/packages/excalidraw/components/LibraryUnit.scss
new file mode 100644
index 0000000..5ebe83f
--- /dev/null
+++ b/packages/excalidraw/components/LibraryUnit.scss
@@ -0,0 +1,185 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .library-unit {
+ align-items: center;
+ border: 1px solid transparent;
+ display: flex;
+ justify-content: center;
+ position: relative;
+ width: 55px;
+ height: 55px;
+ box-sizing: border-box;
+ border-radius: var(--border-radius-lg);
+
+ svg {
+ // to prevent clicks on links and such
+ pointer-events: none;
+ }
+
+ &--hover {
+ border-color: var(--color-primary);
+ }
+
+ &--selected {
+ border-color: var(--color-primary);
+ border-width: 1px;
+ }
+
+ &--skeleton {
+ opacity: 0.5;
+ background: linear-gradient(
+ -45deg,
+ var(--color-gray-10),
+ var(--color-gray-20),
+ var(--color-gray-10)
+ );
+ background-size: 200% 200%;
+ animation: library-unit__skeleton-opacity-animation 0.2s linear;
+ }
+ }
+
+ &.theme--dark .library-unit--skeleton {
+ background-image: linear-gradient(
+ -45deg,
+ var(--color-gray-100),
+ var(--color-gray-80),
+ var(--color-gray-100)
+ );
+ }
+
+ .library-unit__dragger {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ width: 100%;
+ }
+
+ .library-unit__dragger > svg {
+ filter: var(--theme-filter);
+ flex-grow: 1;
+ max-height: 100%;
+ max-width: 100%;
+ }
+
+ .library-unit__checkbox-container,
+ .library-unit__checkbox-container:hover,
+ .library-unit__checkbox-container:active {
+ align-items: center;
+ background: none;
+ border: none;
+ color: var(--icon-fill-color);
+ display: flex;
+ justify-content: center;
+ margin: 0;
+ padding: 0.5rem;
+ position: absolute;
+ left: 2rem;
+ bottom: 2rem;
+ cursor: pointer;
+
+ input {
+ cursor: pointer;
+ }
+ }
+
+ .library-unit__checkbox {
+ position: absolute;
+ top: 0.125rem;
+ right: 0.125rem;
+ margin: 0;
+
+ .Checkbox-box {
+ margin: 0;
+ width: 1rem;
+ height: 1rem;
+ border-radius: 4px;
+ background-color: var(--color-primary-light);
+ border: 1px solid var(--color-primary);
+ box-shadow: none !important;
+ padding: 2px;
+ }
+
+ &.Checkbox:hover {
+ .Checkbox-box {
+ background-color: var(--color-primary-light);
+ }
+ }
+
+ &.is-checked {
+ .Checkbox-box {
+ background-color: var(--color-primary) !important;
+
+ svg {
+ color: var(--color-primary-light);
+ }
+ }
+ }
+ }
+
+ .library-unit__removeFromLibrary > svg {
+ height: 16px;
+ width: 16px;
+ }
+
+ .library-unit__adder {
+ transform: scale(1);
+ animation: library-unit__adder-animation 1s ease-in infinite;
+
+ position: absolute;
+ width: 1.5rem;
+ height: 1.5rem;
+ background-color: var(--color-primary);
+ border-radius: var(--border-radius-md);
+
+ display: flex;
+ justify-content: center;
+ align-items: center;
+
+ pointer-events: none;
+
+ svg {
+ color: var(--color-primary-light);
+ width: 1rem;
+ height: 1rem;
+ }
+ }
+
+ .library-unit:active .library-unit__adder {
+ animation: none;
+ transform: scale(0.8);
+ }
+
+ .library-unit__active {
+ cursor: pointer;
+ }
+
+ @keyframes library-unit__adder-animation {
+ 0% {
+ transform: scale(0.85);
+ }
+
+ 50% {
+ transform: scale(1);
+ }
+
+ 100% {
+ transform: scale(0.85);
+ }
+ }
+
+ @keyframes library-unit__skeleton-opacity-animation {
+ 0% {
+ opacity: 0;
+ }
+
+ 75% {
+ opacity: 0;
+ }
+
+ 100% {
+ opacity: 0.5;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/LibraryUnit.tsx b/packages/excalidraw/components/LibraryUnit.tsx
new file mode 100644
index 0000000..71e1a00
--- /dev/null
+++ b/packages/excalidraw/components/LibraryUnit.tsx
@@ -0,0 +1,108 @@
+import clsx from "clsx";
+import { memo, useEffect, useRef, useState } from "react";
+import { useDevice } from "./App";
+import type { LibraryItem } from "../types";
+import "./LibraryUnit.scss";
+import { CheckboxItem } from "./CheckboxItem";
+import { PlusIcon } from "./icons";
+import type { SvgCache } from "../hooks/useLibraryItemSvg";
+import { useLibraryItemSvg } from "../hooks/useLibraryItemSvg";
+
+export const LibraryUnit = memo(
+ ({
+ id,
+ elements,
+ isPending,
+ onClick,
+ selected,
+ onToggle,
+ onDrag,
+ svgCache,
+ }: {
+ id: LibraryItem["id"] | /** for pending item */ null;
+ elements?: LibraryItem["elements"];
+ isPending?: boolean;
+ onClick: (id: LibraryItem["id"] | null) => void;
+ selected: boolean;
+ onToggle: (id: string, event: React.MouseEvent) => void;
+ onDrag: (id: string, event: React.DragEvent) => void;
+ svgCache: SvgCache;
+ }) => {
+ const ref = useRef<HTMLDivElement | null>(null);
+ const svg = useLibraryItemSvg(id, elements, svgCache);
+
+ useEffect(() => {
+ const node = ref.current;
+
+ if (!node) {
+ return;
+ }
+
+ if (svg) {
+ node.innerHTML = svg.outerHTML;
+ }
+
+ return () => {
+ node.innerHTML = "";
+ };
+ }, [svg]);
+
+ const [isHovered, setIsHovered] = useState(false);
+ const isMobile = useDevice().editor.isMobile;
+ const adder = isPending && (
+ <div className="library-unit__adder">{PlusIcon}</div>
+ );
+
+ return (
+ <div
+ className={clsx("library-unit", {
+ "library-unit__active": elements,
+ "library-unit--hover": elements && isHovered,
+ "library-unit--selected": selected,
+ "library-unit--skeleton": !svg,
+ })}
+ onMouseEnter={() => setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ >
+ <div
+ className={clsx("library-unit__dragger", {
+ "library-unit__pulse": !!isPending,
+ })}
+ ref={ref}
+ draggable={!!elements}
+ onClick={
+ !!elements || !!isPending
+ ? (event) => {
+ if (id && event.shiftKey) {
+ onToggle(id, event);
+ } else {
+ onClick(id);
+ }
+ }
+ : undefined
+ }
+ onDragStart={(event) => {
+ if (!id) {
+ event.preventDefault();
+ return;
+ }
+ setIsHovered(false);
+ onDrag(id, event);
+ }}
+ />
+ {adder}
+ {id && elements && (isHovered || isMobile || selected) && (
+ <CheckboxItem
+ checked={selected}
+ onChange={(checked, event) => onToggle(id, event)}
+ className="library-unit__checkbox"
+ />
+ )}
+ </div>
+ );
+ },
+);
+
+export const EmptyLibraryUnit = () => (
+ <div className="library-unit library-unit--skeleton" />
+);
diff --git a/packages/excalidraw/components/LoadingMessage.tsx b/packages/excalidraw/components/LoadingMessage.tsx
new file mode 100644
index 0000000..b007252
--- /dev/null
+++ b/packages/excalidraw/components/LoadingMessage.tsx
@@ -0,0 +1,40 @@
+import { t } from "../i18n";
+import { useState, useEffect } from "react";
+import Spinner from "./Spinner";
+import clsx from "clsx";
+import { THEME } from "../constants";
+import type { Theme } from "../element/types";
+
+export const LoadingMessage: React.FC<{ delay?: number; theme?: Theme }> = ({
+ delay,
+ theme,
+}) => {
+ const [isWaiting, setIsWaiting] = useState(!!delay);
+
+ useEffect(() => {
+ if (!delay) {
+ return;
+ }
+ const timer = setTimeout(() => {
+ setIsWaiting(false);
+ }, delay);
+ return () => clearTimeout(timer);
+ }, [delay]);
+
+ if (isWaiting) {
+ return null;
+ }
+
+ return (
+ <div
+ className={clsx("LoadingMessage", {
+ "LoadingMessage--dark": theme === THEME.DARK,
+ })}
+ >
+ <div>
+ <Spinner />
+ </div>
+ <div className="LoadingMessage-text">{t("labels.loadingScene")}</div>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/LockButton.tsx b/packages/excalidraw/components/LockButton.tsx
new file mode 100644
index 0000000..f7913d1
--- /dev/null
+++ b/packages/excalidraw/components/LockButton.tsx
@@ -0,0 +1,48 @@
+import "./ToolIcon.scss";
+
+import clsx from "clsx";
+import type { ToolButtonSize } from "./ToolButton";
+import { LockedIcon, UnlockedIcon } from "./icons";
+
+type LockIconProps = {
+ title?: string;
+ name?: string;
+ checked: boolean;
+ onChange?(): void;
+ isMobile?: boolean;
+};
+
+const DEFAULT_SIZE: ToolButtonSize = "medium";
+
+const ICONS = {
+ CHECKED: LockedIcon,
+ UNCHECKED: UnlockedIcon,
+};
+
+export const LockButton = (props: LockIconProps) => {
+ return (
+ <label
+ className={clsx(
+ "ToolIcon ToolIcon__lock",
+ `ToolIcon_size_${DEFAULT_SIZE}`,
+ {
+ "is-mobile": props.isMobile,
+ },
+ )}
+ title={`${props.title} — Q`}
+ >
+ <input
+ className="ToolIcon_type_checkbox"
+ type="checkbox"
+ name={props.name}
+ onChange={props.onChange}
+ checked={props.checked}
+ aria-label={props.title}
+ data-testid="toolbar-lock"
+ />
+ <div className="ToolIcon__icon">
+ {props.checked ? ICONS.CHECKED : ICONS.UNCHECKED}
+ </div>
+ </label>
+ );
+};
diff --git a/packages/excalidraw/components/MagicButton.tsx b/packages/excalidraw/components/MagicButton.tsx
new file mode 100644
index 0000000..eedc63b
--- /dev/null
+++ b/packages/excalidraw/components/MagicButton.tsx
@@ -0,0 +1,39 @@
+import type { JSX } from "react";
+import clsx from "clsx";
+import type { ToolButtonSize } from "./ToolButton";
+
+import "./ToolIcon.scss";
+
+const DEFAULT_SIZE: ToolButtonSize = "small";
+
+export const ElementCanvasButton = (props: {
+ title?: string;
+ icon: JSX.Element;
+ name?: string;
+ checked: boolean;
+ onChange?(): void;
+ isMobile?: boolean;
+}) => {
+ return (
+ <label
+ className={clsx(
+ "ToolIcon ToolIcon__MagicButton",
+ `ToolIcon_size_${DEFAULT_SIZE}`,
+ {
+ "is-mobile": props.isMobile,
+ },
+ )}
+ title={`${props.title}`}
+ >
+ <input
+ className="ToolIcon_type_checkbox"
+ type="checkbox"
+ name={props.name}
+ onChange={props.onChange}
+ checked={props.checked}
+ aria-label={props.title}
+ />
+ <div className="ToolIcon__icon">{props.icon}</div>
+ </label>
+ );
+};
diff --git a/packages/excalidraw/components/MobileMenu.tsx b/packages/excalidraw/components/MobileMenu.tsx
new file mode 100644
index 0000000..bef99a9
--- /dev/null
+++ b/packages/excalidraw/components/MobileMenu.tsx
@@ -0,0 +1,211 @@
+import type { JSX } from "react";
+import React from "react";
+import type {
+ AppClassProperties,
+ AppProps,
+ AppState,
+ Device,
+ ExcalidrawProps,
+ UIAppState,
+} from "../types";
+import type { ActionManager } from "../actions/manager";
+import { t } from "../i18n";
+import Stack from "./Stack";
+import { showSelectedShapeActions } from "../element";
+import type { NonDeletedExcalidrawElement } from "../element/types";
+import { FixedSideContainer } from "./FixedSideContainer";
+import { Island } from "./Island";
+import { HintViewer } from "./HintViewer";
+import { calculateScrollCenter } from "../scene";
+import { SelectedShapeActions, ShapesSwitcher } from "./Actions";
+import { Section } from "./Section";
+import { SCROLLBAR_WIDTH, SCROLLBAR_MARGIN } from "../scene/scrollbars";
+import { LockButton } from "./LockButton";
+import { PenModeButton } from "./PenModeButton";
+import { HandButton } from "./HandButton";
+import { isHandToolActive } from "../appState";
+import { useTunnels } from "../context/tunnels";
+
+type MobileMenuProps = {
+ appState: UIAppState;
+ actionManager: ActionManager;
+ renderJSONExportDialog: () => React.ReactNode;
+ renderImageExportDialog: () => React.ReactNode;
+ setAppState: React.Component<any, AppState>["setState"];
+ elements: readonly NonDeletedExcalidrawElement[];
+ onLockToggle: () => void;
+ onHandToolToggle: () => void;
+ onPenModeToggle: AppClassProperties["togglePenMode"];
+
+ renderTopRightUI?: (
+ isMobile: boolean,
+ appState: UIAppState,
+ ) => JSX.Element | null;
+ renderCustomStats?: ExcalidrawProps["renderCustomStats"];
+ renderSidebars: () => JSX.Element | null;
+ device: Device;
+ renderWelcomeScreen: boolean;
+ UIOptions: AppProps["UIOptions"];
+ app: AppClassProperties;
+};
+
+export const MobileMenu = ({
+ appState,
+ elements,
+ actionManager,
+ setAppState,
+ onLockToggle,
+ onHandToolToggle,
+ onPenModeToggle,
+
+ renderTopRightUI,
+ renderCustomStats,
+ renderSidebars,
+ device,
+ renderWelcomeScreen,
+ UIOptions,
+ app,
+}: MobileMenuProps) => {
+ const {
+ WelcomeScreenCenterTunnel,
+ MainMenuTunnel,
+ DefaultSidebarTriggerTunnel,
+ } = useTunnels();
+ const renderToolbar = () => {
+ return (
+ <FixedSideContainer side="top" className="App-top-bar">
+ {renderWelcomeScreen && <WelcomeScreenCenterTunnel.Out />}
+ <Section heading="shapes">
+ {(heading: React.ReactNode) => (
+ <Stack.Col gap={4} align="center">
+ <Stack.Row gap={1} className="App-toolbar-container">
+ <Island padding={1} className="App-toolbar App-toolbar--mobile">
+ {heading}
+ <Stack.Row gap={1}>
+ <ShapesSwitcher
+ appState={appState}
+ activeTool={appState.activeTool}
+ UIOptions={UIOptions}
+ app={app}
+ />
+ </Stack.Row>
+ </Island>
+ {renderTopRightUI && renderTopRightUI(true, appState)}
+ <div className="mobile-misc-tools-container">
+ {!appState.viewModeEnabled &&
+ appState.openDialog?.name !== "elementLinkSelector" && (
+ <DefaultSidebarTriggerTunnel.Out />
+ )}
+ <PenModeButton
+ checked={appState.penMode}
+ onChange={() => onPenModeToggle(null)}
+ title={t("toolBar.penMode")}
+ isMobile
+ penDetected={appState.penDetected}
+ />
+ <LockButton
+ checked={appState.activeTool.locked}
+ onChange={onLockToggle}
+ title={t("toolBar.lock")}
+ isMobile
+ />
+ <HandButton
+ checked={isHandToolActive(appState)}
+ onChange={() => onHandToolToggle()}
+ title={t("toolBar.hand")}
+ isMobile
+ />
+ </div>
+ </Stack.Row>
+ </Stack.Col>
+ )}
+ </Section>
+ <HintViewer
+ appState={appState}
+ isMobile={true}
+ device={device}
+ app={app}
+ />
+ </FixedSideContainer>
+ );
+ };
+
+ const renderAppToolbar = () => {
+ if (
+ appState.viewModeEnabled ||
+ appState.openDialog?.name === "elementLinkSelector"
+ ) {
+ return (
+ <div className="App-toolbar-content">
+ <MainMenuTunnel.Out />
+ </div>
+ );
+ }
+
+ return (
+ <div className="App-toolbar-content">
+ <MainMenuTunnel.Out />
+ {actionManager.renderAction("toggleEditMenu")}
+ {actionManager.renderAction(
+ appState.multiElement ? "finalize" : "duplicateSelection",
+ )}
+ {actionManager.renderAction("deleteSelectedElements")}
+ <div>
+ {actionManager.renderAction("undo")}
+ {actionManager.renderAction("redo")}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <>
+ {renderSidebars()}
+ {!appState.viewModeEnabled &&
+ appState.openDialog?.name !== "elementLinkSelector" &&
+ renderToolbar()}
+ <div
+ className="App-bottom-bar"
+ style={{
+ marginBottom: SCROLLBAR_WIDTH + SCROLLBAR_MARGIN * 2,
+ marginLeft: SCROLLBAR_WIDTH + SCROLLBAR_MARGIN * 2,
+ marginRight: SCROLLBAR_WIDTH + SCROLLBAR_MARGIN * 2,
+ }}
+ >
+ <Island padding={0}>
+ {appState.openMenu === "shape" &&
+ !appState.viewModeEnabled &&
+ appState.openDialog?.name !== "elementLinkSelector" &&
+ showSelectedShapeActions(appState, elements) ? (
+ <Section className="App-mobile-menu" heading="selectedShapeActions">
+ <SelectedShapeActions
+ appState={appState}
+ elementsMap={app.scene.getNonDeletedElementsMap()}
+ renderAction={actionManager.renderAction}
+ app={app}
+ />
+ </Section>
+ ) : null}
+ <footer className="App-toolbar">
+ {renderAppToolbar()}
+ {appState.scrolledOutside &&
+ !appState.openMenu &&
+ !appState.openSidebar && (
+ <button
+ type="button"
+ className="scroll-back-to-content"
+ onClick={() => {
+ setAppState((appState) => ({
+ ...calculateScrollCenter(elements, appState),
+ }));
+ }}
+ >
+ {t("buttons.scrollBackToContent")}
+ </button>
+ )}
+ </footer>
+ </Island>
+ </div>
+ </>
+ );
+};
diff --git a/packages/excalidraw/components/Modal.scss b/packages/excalidraw/components/Modal.scss
new file mode 100644
index 0000000..1a355e2
--- /dev/null
+++ b/packages/excalidraw/components/Modal.scss
@@ -0,0 +1,136 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ &.excalidraw-modal-container {
+ position: absolute;
+ z-index: var(--zIndex-modal);
+ }
+
+ .Modal {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: auto;
+ padding: calc(var(--space-factor) * 10);
+
+ display: flex;
+ flex-direction: column;
+
+ .Island {
+ padding: 2.5rem;
+ border: 0;
+ box-shadow: none;
+ border-radius: 0;
+ }
+
+ &.animations-disabled {
+ .Modal__background {
+ animation: none;
+ }
+
+ .Modal__content {
+ animation: none;
+ opacity: 1;
+ }
+ }
+ }
+
+ .Modal__background {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ z-index: 1;
+ background-color: rgba(#121212, 0.2);
+
+ animation: Modal__background__fade-in 0.1s linear forwards;
+ }
+
+ .Modal__content {
+ position: relative;
+ z-index: 2;
+ width: 100%;
+ max-width: var(--max-width);
+ max-height: 100%;
+
+ opacity: 0;
+ transform: translateY(10px);
+ animation: Modal__content_fade-in 0.025s ease-out 0s forwards;
+
+ position: relative;
+ overflow-y: auto;
+
+ // for modals, reset blurry bg
+ background: var(--island-bg-color);
+
+ border: 1px solid var(--dialog-border-color);
+ box-shadow: var(--modal-shadow);
+ border-radius: 0.75rem;
+ box-sizing: border-box;
+
+ &:focus {
+ outline: none;
+ }
+ }
+
+ @keyframes Modal__background__fade-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+ }
+
+ @keyframes Modal__content_fade-in {
+ from {
+ opacity: 0;
+ transform: scale(0.9);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+ }
+
+ .Modal__close {
+ color: var(--icon-fill-color);
+ margin: 0;
+ padding: 0.375rem;
+ position: absolute;
+ top: 1rem;
+ right: 1rem;
+ border: 0;
+ background-color: transparent;
+ line-height: 0;
+ cursor: pointer;
+
+ svg {
+ width: 1.5rem;
+ height: 1.5rem;
+ }
+ }
+
+ .Dialog--fullscreen {
+ .Modal {
+ padding: 0;
+ }
+
+ .Modal__content {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ max-width: 100%;
+ border: 0;
+ border-radius: 0;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Modal.tsx b/packages/excalidraw/components/Modal.tsx
new file mode 100644
index 0000000..e8fff19
--- /dev/null
+++ b/packages/excalidraw/components/Modal.tsx
@@ -0,0 +1,65 @@
+import "./Modal.scss";
+
+import { createPortal } from "react-dom";
+import clsx from "clsx";
+import { KEYS } from "../keys";
+import type { AppState } from "../types";
+import { useCreatePortalContainer } from "../hooks/useCreatePortalContainer";
+import { useRef } from "react";
+
+export const Modal: React.FC<{
+ className?: string;
+ children: React.ReactNode;
+ maxWidth?: number;
+ onCloseRequest(): void;
+ labelledBy: string;
+ theme?: AppState["theme"];
+ closeOnClickOutside?: boolean;
+}> = (props) => {
+ const { closeOnClickOutside = true } = props;
+ const modalRoot = useCreatePortalContainer({
+ className: "excalidraw-modal-container",
+ });
+
+ const animationsDisabledRef = useRef(
+ document.body.classList.contains("excalidraw-animations-disabled"),
+ );
+
+ if (!modalRoot) {
+ return null;
+ }
+
+ const handleKeydown = (event: React.KeyboardEvent) => {
+ if (event.key === KEYS.ESCAPE) {
+ event.nativeEvent.stopImmediatePropagation();
+ event.stopPropagation();
+ props.onCloseRequest();
+ }
+ };
+
+ return createPortal(
+ <div
+ className={clsx("Modal", props.className, {
+ "animations-disabled": animationsDisabledRef.current,
+ })}
+ role="dialog"
+ aria-modal="true"
+ onKeyDown={handleKeydown}
+ aria-labelledby={props.labelledBy}
+ data-prevent-outside-click
+ >
+ <div
+ className="Modal__background"
+ onClick={closeOnClickOutside ? props.onCloseRequest : undefined}
+ />
+ <div
+ className="Modal__content"
+ style={{ "--max-width": `${props.maxWidth}px` }}
+ tabIndex={0}
+ >
+ {props.children}
+ </div>
+ </div>,
+ modalRoot,
+ );
+};
diff --git a/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm.scss b/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm.scss
new file mode 100644
index 0000000..4aad0cb
--- /dev/null
+++ b/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm.scss
@@ -0,0 +1,126 @@
+@import "../../css/variables.module.scss";
+
+.excalidraw {
+ .OverwriteConfirm {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.75rem;
+ isolation: isolate;
+
+ h3 {
+ margin: 0;
+
+ font-weight: 700;
+ font-size: 1.3125rem;
+ line-height: 130%;
+ align-self: flex-start;
+
+ color: var(--text-primary-color);
+ }
+
+ &__Description {
+ box-sizing: border-box;
+
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ width: 100%;
+ gap: 1rem;
+
+ @include isMobile {
+ flex-direction: column;
+ text-align: center;
+ }
+
+ padding: 2.5rem;
+
+ background: var(--color-danger-background);
+ border-radius: 0.5rem;
+
+ font-family: "Assistant";
+ font-style: normal;
+ font-weight: 400;
+ font-size: 1rem;
+ line-height: 150%;
+
+ color: var(--color-danger-color);
+
+ &__spacer {
+ flex-grow: 1;
+ }
+
+ &__icon {
+ box-sizing: border-box;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 2.5rem;
+ background: var(--color-danger-icon-background);
+ width: 3.5rem;
+ height: 3.5rem;
+
+ padding: 0.75rem;
+
+ svg {
+ color: var(--color-danger-icon-color);
+ width: 1.5rem;
+ height: 1.5rem;
+ }
+ }
+
+ &.OverwriteConfirm__Description--color-warning {
+ background: var(--color-warning-background);
+ color: var(--color-warning-color);
+
+ .OverwriteConfirm__Description__icon {
+ background: var(--color-warning-icon-background);
+ flex: 0 0 auto;
+
+ svg {
+ color: var(--color-warning-icon-color);
+ }
+ }
+ }
+ }
+
+ &__Actions {
+ display: flex;
+ flex-direction: row;
+ align-items: stretch;
+ justify-items: stretch;
+ justify-content: center;
+ gap: 1.5rem;
+
+ @include isMobile {
+ flex-direction: column;
+ }
+
+ &__Action {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: 1.5rem;
+ gap: 0.75rem;
+ flex-basis: 50%;
+ flex-grow: 0;
+
+ &__content {
+ height: 100%;
+ font-size: 0.875rem;
+ text-align: center;
+ }
+
+ h4 {
+ font-weight: 700;
+ font-size: 1.125rem;
+ line-height: 130%;
+
+ margin: 0;
+
+ color: var(--text-primary-color);
+ }
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm.tsx b/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm.tsx
new file mode 100644
index 0000000..4bf8d67
--- /dev/null
+++ b/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm.tsx
@@ -0,0 +1,74 @@
+import React from "react";
+
+import { useTunnels } from "../../context/tunnels";
+import { useAtom } from "../../editor-jotai";
+import { Dialog } from "../Dialog";
+import { withInternalFallback } from "../hoc/withInternalFallback";
+import { overwriteConfirmStateAtom } from "./OverwriteConfirmState";
+
+import { FilledButton } from "../FilledButton";
+import { alertTriangleIcon } from "../icons";
+import { Actions, Action } from "./OverwriteConfirmActions";
+import "./OverwriteConfirm.scss";
+
+export type OverwriteConfirmDialogProps = {
+ children: React.ReactNode;
+};
+
+const OverwriteConfirmDialog = Object.assign(
+ withInternalFallback(
+ "OverwriteConfirmDialog",
+ ({ children }: OverwriteConfirmDialogProps) => {
+ const { OverwriteConfirmDialogTunnel } = useTunnels();
+ const [overwriteConfirmState, setState] = useAtom(
+ overwriteConfirmStateAtom,
+ );
+
+ if (!overwriteConfirmState.active) {
+ return null;
+ }
+
+ const handleClose = () => {
+ overwriteConfirmState.onClose();
+ setState((state) => ({ ...state, active: false }));
+ };
+
+ const handleConfirm = () => {
+ overwriteConfirmState.onConfirm();
+ setState((state) => ({ ...state, active: false }));
+ };
+
+ return (
+ <OverwriteConfirmDialogTunnel.In>
+ <Dialog onCloseRequest={handleClose} title={false} size={916}>
+ <div className="OverwriteConfirm">
+ <h3>{overwriteConfirmState.title}</h3>
+ <div
+ className={`OverwriteConfirm__Description OverwriteConfirm__Description--color-${overwriteConfirmState.color}`}
+ >
+ <div className="OverwriteConfirm__Description__icon">
+ {alertTriangleIcon}
+ </div>
+ <div>{overwriteConfirmState.description}</div>
+ <div className="OverwriteConfirm__Description__spacer"></div>
+ <FilledButton
+ color={overwriteConfirmState.color}
+ size="large"
+ label={overwriteConfirmState.actionLabel}
+ onClick={handleConfirm}
+ />
+ </div>
+ <Actions>{children}</Actions>
+ </div>
+ </Dialog>
+ </OverwriteConfirmDialogTunnel.In>
+ );
+ },
+ ),
+ {
+ Actions,
+ Action,
+ },
+);
+
+export { OverwriteConfirmDialog };
diff --git a/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirmActions.tsx b/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirmActions.tsx
new file mode 100644
index 0000000..5da0a08
--- /dev/null
+++ b/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirmActions.tsx
@@ -0,0 +1,85 @@
+import React from "react";
+import { FilledButton } from "../FilledButton";
+import { useExcalidrawActionManager, useExcalidrawSetAppState } from "../App";
+import { actionSaveFileToDisk } from "../../actions";
+import { useI18n } from "../../i18n";
+import { actionChangeExportEmbedScene } from "../../actions/actionExport";
+
+export type ActionProps = {
+ title: string;
+ children: React.ReactNode;
+ actionLabel: string;
+ onClick: () => void;
+};
+
+export const Action = ({
+ title,
+ children,
+ actionLabel,
+ onClick,
+}: ActionProps) => {
+ return (
+ <div className="OverwriteConfirm__Actions__Action">
+ <h4>{title}</h4>
+ <div className="OverwriteConfirm__Actions__Action__content">
+ {children}
+ </div>
+ <FilledButton
+ variant="outlined"
+ color="muted"
+ label={actionLabel}
+ size="large"
+ fullWidth
+ onClick={onClick}
+ />
+ </div>
+ );
+};
+
+export const ExportToImage = () => {
+ const { t } = useI18n();
+ const actionManager = useExcalidrawActionManager();
+ const setAppState = useExcalidrawSetAppState();
+
+ return (
+ <Action
+ title={t("overwriteConfirm.action.exportToImage.title")}
+ actionLabel={t("overwriteConfirm.action.exportToImage.button")}
+ onClick={() => {
+ actionManager.executeAction(actionChangeExportEmbedScene, "ui", true);
+ setAppState({ openDialog: { name: "imageExport" } });
+ }}
+ >
+ {t("overwriteConfirm.action.exportToImage.description")}
+ </Action>
+ );
+};
+
+export const SaveToDisk = () => {
+ const { t } = useI18n();
+ const actionManager = useExcalidrawActionManager();
+
+ return (
+ <Action
+ title={t("overwriteConfirm.action.saveToDisk.title")}
+ actionLabel={t("overwriteConfirm.action.saveToDisk.button")}
+ onClick={() => {
+ actionManager.executeAction(actionSaveFileToDisk, "ui");
+ }}
+ >
+ {t("overwriteConfirm.action.saveToDisk.description")}
+ </Action>
+ );
+};
+
+const Actions = Object.assign(
+ ({ children }: { children: React.ReactNode }) => {
+ return <div className="OverwriteConfirm__Actions">{children}</div>;
+ },
+ {
+ ExportToImage,
+ SaveToDisk,
+ },
+);
+
+export { Actions };
diff --git a/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirmState.ts b/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirmState.ts
new file mode 100644
index 0000000..04616aa
--- /dev/null
+++ b/packages/excalidraw/components/OverwriteConfirm/OverwriteConfirmState.ts
@@ -0,0 +1,45 @@
+import { atom, editorJotaiStore } from "../../editor-jotai";
+import type React from "react";
+
+export type OverwriteConfirmState =
+ | {
+ active: true;
+ title: string;
+ description: React.ReactNode;
+ actionLabel: string;
+ color: "danger" | "warning";
+
+ onClose: () => void;
+ onConfirm: () => void;
+ onReject: () => void;
+ }
+ | { active: false };
+
+export const overwriteConfirmStateAtom = atom<OverwriteConfirmState>({
+ active: false,
+});
+
+export async function openConfirmModal({
+ title,
+ description,
+ actionLabel,
+ color,
+}: {
+ title: string;
+ description: React.ReactNode;
+ actionLabel: string;
+ color: "danger" | "warning";
+}) {
+ return new Promise<boolean>((resolve) => {
+ editorJotaiStore.set(overwriteConfirmStateAtom, {
+ active: true,
+ onConfirm: () => resolve(true),
+ onClose: () => resolve(false),
+ onReject: () => resolve(false),
+ title,
+ description,
+ actionLabel,
+ color,
+ });
+ });
+}
diff --git a/packages/excalidraw/components/Paragraph.tsx b/packages/excalidraw/components/Paragraph.tsx
new file mode 100644
index 0000000..7b3b2ff
--- /dev/null
+++ b/packages/excalidraw/components/Paragraph.tsx
@@ -0,0 +1,10 @@
+export const Paragraph = (props: {
+ children: React.ReactNode;
+ style?: React.CSSProperties;
+}) => {
+ return (
+ <p className="excalidraw__paragraph" style={props.style}>
+ {props.children}
+ </p>
+ );
+};
diff --git a/packages/excalidraw/components/PasteChartDialog.scss b/packages/excalidraw/components/PasteChartDialog.scss
new file mode 100644
index 0000000..855b4ad
--- /dev/null
+++ b/packages/excalidraw/components/PasteChartDialog.scss
@@ -0,0 +1,46 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .PasteChartDialog {
+ @include isMobile {
+ .Island {
+ display: flex;
+ flex-direction: column;
+ }
+ }
+ .container {
+ display: flex;
+ align-items: center;
+ justify-content: space-around;
+ flex-wrap: wrap;
+ @include isMobile {
+ flex-direction: column;
+ justify-content: center;
+ }
+ }
+ .ChartPreview {
+ margin: 8px;
+ text-align: center;
+ width: 192px;
+ height: 128px;
+ border-radius: 2px;
+ padding: 1px;
+ border: 1px solid $oc-gray-4;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ div {
+ display: inline-block;
+ }
+ svg {
+ max-height: 120px;
+ max-width: 186px;
+ }
+ &:hover {
+ padding: 0;
+ border: 2px solid $oc-blue-5;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/PasteChartDialog.tsx b/packages/excalidraw/components/PasteChartDialog.tsx
new file mode 100644
index 0000000..08a5634
--- /dev/null
+++ b/packages/excalidraw/components/PasteChartDialog.tsx
@@ -0,0 +1,136 @@
+import oc from "open-color";
+import React, { useLayoutEffect, useRef, useState } from "react";
+import { trackEvent } from "../analytics";
+import type { ChartElements, Spreadsheet } from "../charts";
+import { renderSpreadsheet } from "../charts";
+import type { ChartType } from "../element/types";
+import { t } from "../i18n";
+import { exportToSvg } from "../scene/export";
+import type { UIAppState } from "../types";
+import { useApp } from "./App";
+import { Dialog } from "./Dialog";
+
+import "./PasteChartDialog.scss";
+
+type OnInsertChart = (chartType: ChartType, elements: ChartElements) => void;
+
+const ChartPreviewBtn = (props: {
+ spreadsheet: Spreadsheet | null;
+ chartType: ChartType;
+ selected: boolean;
+ onClick: OnInsertChart;
+}) => {
+ const previewRef = useRef<HTMLDivElement | null>(null);
+ const [chartElements, setChartElements] = useState<ChartElements | null>(
+ null,
+ );
+
+ useLayoutEffect(() => {
+ if (!props.spreadsheet) {
+ return;
+ }
+
+ const elements = renderSpreadsheet(
+ props.chartType,
+ props.spreadsheet,
+ 0,
+ 0,
+ );
+ setChartElements(elements);
+ let svg: SVGSVGElement;
+ const previewNode = previewRef.current!;
+
+ (async () => {
+ svg = await exportToSvg(
+ elements,
+ {
+ exportBackground: false,
+ viewBackgroundColor: oc.white,
+ },
+ null, // files
+ {
+ skipInliningFonts: true,
+ },
+ );
+ svg.querySelector(".style-fonts")?.remove();
+ previewNode.replaceChildren();
+ previewNode.appendChild(svg);
+
+ if (props.selected) {
+ (previewNode.parentNode as HTMLDivElement).focus();
+ }
+ })();
+
+ return () => {
+ previewNode.replaceChildren();
+ };
+ }, [props.spreadsheet, props.chartType, props.selected]);
+
+ return (
+ <button
+ type="button"
+ className="ChartPreview"
+ onClick={() => {
+ if (chartElements) {
+ props.onClick(props.chartType, chartElements);
+ }
+ }}
+ >
+ <div ref={previewRef} />
+ </button>
+ );
+};
+
+export const PasteChartDialog = ({
+ setAppState,
+ appState,
+ onClose,
+}: {
+ appState: UIAppState;
+ onClose: () => void;
+ setAppState: React.Component<any, UIAppState>["setState"];
+}) => {
+ const { onInsertElements } = useApp();
+ const handleClose = React.useCallback(() => {
+ if (onClose) {
+ onClose();
+ }
+ }, [onClose]);
+
+ const handleChartClick = (chartType: ChartType, elements: ChartElements) => {
+ onInsertElements(elements);
+ trackEvent("paste", "chart", chartType);
+ setAppState({
+ currentChartType: chartType,
+ pasteDialog: {
+ shown: false,
+ data: null,
+ },
+ });
+ };
+
+ return (
+ <Dialog
+ size="small"
+ onCloseRequest={handleClose}
+ title={t("labels.pasteCharts")}
+ className={"PasteChartDialog"}
+ autofocus={false}
+ >
+ <div className={"container"}>
+ <ChartPreviewBtn
+ chartType="bar"
+ spreadsheet={appState.pasteDialog.data}
+ selected={appState.currentChartType === "bar"}
+ onClick={handleChartClick}
+ />
+ <ChartPreviewBtn
+ chartType="line"
+ spreadsheet={appState.pasteDialog.data}
+ selected={appState.currentChartType === "line"}
+ onClick={handleChartClick}
+ />
+ </div>
+ </Dialog>
+ );
+};
diff --git a/packages/excalidraw/components/PenModeButton.tsx b/packages/excalidraw/components/PenModeButton.tsx
new file mode 100644
index 0000000..ca5ceb2
--- /dev/null
+++ b/packages/excalidraw/components/PenModeButton.tsx
@@ -0,0 +1,46 @@
+import "./ToolIcon.scss";
+
+import clsx from "clsx";
+import type { ToolButtonSize } from "./ToolButton";
+import { PenModeIcon } from "./icons";
+
+type PenModeIconProps = {
+ title?: string;
+ name?: string;
+ checked: boolean;
+ onChange?(): void;
+ zenModeEnabled?: boolean;
+ isMobile?: boolean;
+ penDetected: boolean;
+};
+
+const DEFAULT_SIZE: ToolButtonSize = "medium";
+
+export const PenModeButton = (props: PenModeIconProps) => {
+ if (!props.penDetected) {
+ return null;
+ }
+
+ return (
+ <label
+ className={clsx(
+ "ToolIcon ToolIcon__penMode",
+ `ToolIcon_size_${DEFAULT_SIZE}`,
+ {
+ "is-mobile": props.isMobile,
+ },
+ )}
+ title={`${props.title}`}
+ >
+ <input
+ className="ToolIcon_type_checkbox"
+ type="checkbox"
+ name={props.name}
+ onChange={props.onChange}
+ checked={props.checked}
+ aria-label={props.title}
+ />
+ <div className="ToolIcon__icon">{PenModeIcon}</div>
+ </label>
+ );
+};
diff --git a/packages/excalidraw/components/Popover.scss b/packages/excalidraw/components/Popover.scss
new file mode 100644
index 0000000..9458b50
--- /dev/null
+++ b/packages/excalidraw/components/Popover.scss
@@ -0,0 +1,8 @@
+.excalidraw {
+ .popover {
+ position: absolute;
+ z-index: 10;
+ padding: 5px 0 5px;
+ outline: none;
+ }
+}
diff --git a/packages/excalidraw/components/Popover.tsx b/packages/excalidraw/components/Popover.tsx
new file mode 100644
index 0000000..987e9fb
--- /dev/null
+++ b/packages/excalidraw/components/Popover.tsx
@@ -0,0 +1,152 @@
+import React, { useLayoutEffect, useRef, useEffect } from "react";
+import "./Popover.scss";
+import { unstable_batchedUpdates } from "react-dom";
+import { queryFocusableElements } from "../utils";
+import { KEYS } from "../keys";
+
+type Props = {
+ top?: number;
+ left?: number;
+ children?: React.ReactNode;
+ onCloseRequest?(event: PointerEvent): void;
+ fitInViewport?: boolean;
+ offsetLeft?: number;
+ offsetTop?: number;
+ viewportWidth?: number;
+ viewportHeight?: number;
+};
+
+export const Popover = ({
+ children,
+ left,
+ top,
+ onCloseRequest,
+ fitInViewport = false,
+ offsetLeft = 0,
+ offsetTop = 0,
+ viewportWidth = window.innerWidth,
+ viewportHeight = window.innerHeight,
+}: Props) => {
+ const popoverRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const container = popoverRef.current;
+
+ if (!container) {
+ return;
+ }
+
+ // focus popover only if the caller didn't focus on something else nested
+ // within the popover, which should take precedence. Fixes cases
+ // like color picker listening to keydown events on containers nested
+ // in the popover.
+ if (!container.contains(document.activeElement)) {
+ container.focus();
+ }
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === KEYS.TAB) {
+ const focusableElements = queryFocusableElements(container);
+ const { activeElement } = document;
+ const currentIndex = focusableElements.findIndex(
+ (element) => element === activeElement,
+ );
+
+ if (activeElement === container) {
+ if (event.shiftKey) {
+ focusableElements[focusableElements.length - 1]?.focus();
+ } else {
+ focusableElements[0].focus();
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ } else if (currentIndex === 0 && event.shiftKey) {
+ focusableElements[focusableElements.length - 1]?.focus();
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ } else if (
+ currentIndex === focusableElements.length - 1 &&
+ !event.shiftKey
+ ) {
+ focusableElements[0]?.focus();
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ }
+ };
+
+ container.addEventListener("keydown", handleKeyDown);
+
+ return () => container.removeEventListener("keydown", handleKeyDown);
+ }, []);
+
+ const lastInitializedPosRef = useRef<{ top: number; left: number } | null>(
+ null,
+ );
+
+ // ensure the popover doesn't overflow the viewport
+ useLayoutEffect(() => {
+ if (fitInViewport && popoverRef.current && top != null && left != null) {
+ const container = popoverRef.current;
+ const { width, height } = container.getBoundingClientRect();
+
+ // hack for StrictMode so this effect only runs once for
+ // the same top/left position, otherwise
+ // we'd potentically reposition twice (once for viewport overflow)
+ // and once for top/left position afterwards
+ if (
+ lastInitializedPosRef.current?.top === top &&
+ lastInitializedPosRef.current?.left === left
+ ) {
+ return;
+ }
+ lastInitializedPosRef.current = { top, left };
+
+ if (width >= viewportWidth) {
+ container.style.width = `${viewportWidth}px`;
+ container.style.left = "0px";
+ container.style.overflowX = "scroll";
+ } else if (left + width - offsetLeft > viewportWidth) {
+ container.style.left = `${viewportWidth - width - 10}px`;
+ } else {
+ container.style.left = `${left}px`;
+ }
+
+ if (height >= viewportHeight) {
+ container.style.height = `${viewportHeight - 20}px`;
+ container.style.top = "10px";
+ container.style.overflowY = "scroll";
+ } else if (top + height - offsetTop > viewportHeight) {
+ container.style.top = `${viewportHeight - height}px`;
+ } else {
+ container.style.top = `${top}px`;
+ }
+ }
+ }, [
+ top,
+ left,
+ fitInViewport,
+ viewportWidth,
+ viewportHeight,
+ offsetLeft,
+ offsetTop,
+ ]);
+
+ useEffect(() => {
+ if (onCloseRequest) {
+ const handler = (event: PointerEvent) => {
+ if (!popoverRef.current?.contains(event.target as Node)) {
+ unstable_batchedUpdates(() => onCloseRequest(event));
+ }
+ };
+ document.addEventListener("pointerdown", handler, false);
+ return () => document.removeEventListener("pointerdown", handler, false);
+ }
+ }, [onCloseRequest]);
+
+ return (
+ <div className="popover" ref={popoverRef} tabIndex={-1}>
+ {children}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ProjectName.scss b/packages/excalidraw/components/ProjectName.scss
new file mode 100644
index 0000000..18bee26
--- /dev/null
+++ b/packages/excalidraw/components/ProjectName.scss
@@ -0,0 +1,25 @@
+.ProjectName {
+ margin: auto;
+ display: flex;
+ align-items: center;
+
+ .TextInput {
+ height: calc(1rem - 3px);
+ width: 200px;
+ overflow: hidden;
+ text-align: center;
+ margin-left: 8px;
+ text-overflow: ellipsis;
+
+ &--readonly {
+ background: none;
+ border: none;
+ &:hover {
+ background: none;
+ }
+ width: auto;
+ max-width: 200px;
+ padding-left: 2px;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ProjectName.tsx b/packages/excalidraw/components/ProjectName.tsx
new file mode 100644
index 0000000..5929617
--- /dev/null
+++ b/packages/excalidraw/components/ProjectName.tsx
@@ -0,0 +1,57 @@
+import "./TextInput.scss";
+
+import React, { useState } from "react";
+import { focusNearestParent } from "../utils";
+
+import "./ProjectName.scss";
+import { useExcalidrawContainer } from "./App";
+import { KEYS } from "../keys";
+
+type Props = {
+ value: string;
+ onChange: (value: string) => void;
+ label: string;
+ ignoreFocus?: boolean;
+};
+
+export const ProjectName = (props: Props) => {
+ const { id } = useExcalidrawContainer();
+ const [fileName, setFileName] = useState<string>(props.value);
+
+ const handleBlur = (event: any) => {
+ if (!props.ignoreFocus) {
+ focusNearestParent(event.target);
+ }
+ const value = event.target.value;
+ if (value !== props.value) {
+ props.onChange(value);
+ }
+ };
+
+ const handleKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {
+ if (event.key === KEYS.ENTER) {
+ event.preventDefault();
+ if (event.nativeEvent.isComposing || event.keyCode === 229) {
+ return;
+ }
+ event.currentTarget.blur();
+ }
+ };
+
+ return (
+ <div className="ProjectName">
+ <label className="ProjectName-label" htmlFor="filename">
+ {`${props.label}:`}
+ </label>
+ <input
+ type="text"
+ className="TextInput"
+ onBlur={handleBlur}
+ onKeyDown={handleKeyDown}
+ id={`${id}-filename`}
+ value={fileName}
+ onChange={(event) => setFileName(event.target.value)}
+ />
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/PropertiesPopover.tsx b/packages/excalidraw/components/PropertiesPopover.tsx
new file mode 100644
index 0000000..455af11
--- /dev/null
+++ b/packages/excalidraw/components/PropertiesPopover.tsx
@@ -0,0 +1,96 @@
+import React, { type ReactNode } from "react";
+import clsx from "clsx";
+import * as Popover from "@radix-ui/react-popover";
+
+import { useDevice } from "./App";
+import { Island } from "./Island";
+import { isInteractive } from "../utils";
+
+interface PropertiesPopoverProps {
+ className?: string;
+ container: HTMLDivElement | null;
+ children: ReactNode;
+ style?: object;
+ onClose: () => void;
+ onKeyDown?: React.KeyboardEventHandler<HTMLDivElement>;
+ onPointerLeave?: React.PointerEventHandler<HTMLDivElement>;
+ onFocusOutside?: Popover.PopoverContentProps["onFocusOutside"];
+ onPointerDownOutside?: Popover.PopoverContentProps["onPointerDownOutside"];
+}
+
+export const PropertiesPopover = React.forwardRef<
+ HTMLDivElement,
+ PropertiesPopoverProps
+>(
+ (
+ {
+ className,
+ container,
+ children,
+ style,
+ onClose,
+ onKeyDown,
+ onFocusOutside,
+ onPointerLeave,
+ onPointerDownOutside,
+ },
+ ref,
+ ) => {
+ const device = useDevice();
+
+ return (
+ <Popover.Portal container={container}>
+ <Popover.Content
+ ref={ref}
+ className={clsx("focus-visible-none", className)}
+ data-prevent-outside-click
+ side={
+ device.editor.isMobile && !device.viewport.isLandscape
+ ? "bottom"
+ : "right"
+ }
+ align={
+ device.editor.isMobile && !device.viewport.isLandscape
+ ? "center"
+ : "start"
+ }
+ alignOffset={-16}
+ sideOffset={20}
+ style={{
+ zIndex: "var(--zIndex-popup)",
+ }}
+ onPointerLeave={onPointerLeave}
+ onKeyDown={onKeyDown}
+ onFocusOutside={onFocusOutside}
+ onPointerDownOutside={onPointerDownOutside}
+ onCloseAutoFocus={(e) => {
+ e.stopPropagation();
+ // prevents focusing the trigger
+ e.preventDefault();
+
+ // return focus to excalidraw container unless
+ // user focuses an interactive element, such as a button, or
+ // enters the text editor by clicking on canvas with the text tool
+ if (container && !isInteractive(document.activeElement)) {
+ container.focus();
+ }
+
+ onClose();
+ }}
+ >
+ <Island padding={3} style={style}>
+ {children}
+ </Island>
+ <Popover.Arrow
+ width={20}
+ height={10}
+ style={{
+ fill: "var(--popup-bg-color)",
+ filter: "drop-shadow(rgba(0, 0, 0, 0.05) 0px 3px 2px)",
+ }}
+ />
+ </Popover.Content>
+ </Popover.Portal>
+ );
+ },
+);
diff --git a/packages/excalidraw/components/PublishLibrary.scss b/packages/excalidraw/components/PublishLibrary.scss
new file mode 100644
index 0000000..fdcacf1
--- /dev/null
+++ b/packages/excalidraw/components/PublishLibrary.scss
@@ -0,0 +1,172 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .publish-library {
+ &__fields {
+ display: flex;
+ flex-direction: column;
+
+ label {
+ padding: 1em 0;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ span {
+ font-weight: 500;
+ font-size: 1rem;
+ color: $oc-gray-6;
+ }
+ input,
+ textarea {
+ width: 70%;
+ padding: 0.6em;
+ font-family: var(--ui-font);
+ }
+
+ .required {
+ color: $oc-red-8;
+ margin: 0.2rem;
+ }
+ }
+ }
+
+ &__buttons {
+ display: flex;
+ padding: 0.2rem 0;
+ justify-content: flex-end;
+ gap: 0.5rem;
+
+ .ToolIcon__icon {
+ min-width: 2.5rem;
+ width: auto;
+ font-size: 1rem;
+ }
+
+ .ToolIcon_type_button {
+ margin-left: 1rem;
+ padding: 0 0.5rem;
+ }
+
+ &--confirm.ToolIcon_type_button {
+ background-color: $oc-blue-6;
+
+ &:hover {
+ background-color: $oc-blue-8;
+ }
+ }
+
+ &--cancel.ToolIcon_type_button {
+ background-color: $oc-gray-5;
+ &:hover {
+ background-color: $oc-gray-6;
+ }
+ }
+
+ .ToolIcon__icon {
+ color: $oc-white;
+ .Spinner {
+ --spinner-color: #fff;
+ svg {
+ padding: 0.5rem;
+ }
+ }
+ }
+ }
+
+ .selected-library-items {
+ display: flex;
+ flex-wrap: wrap;
+
+ .single-library-item-wrapper {
+ width: 9rem;
+ }
+ }
+
+ &-warning {
+ color: $oc-red-6;
+ }
+
+ &-note {
+ padding: 1em 0;
+ font-style: italic;
+ font-size: 14px;
+ display: block;
+ }
+ }
+
+ .single-library-item {
+ position: relative;
+
+ &-status {
+ position: absolute;
+ top: 0.3rem;
+ left: 0.3rem;
+ font-size: 0.7rem;
+ color: $oc-red-7;
+ background: rgba(255, 255, 255, 0.9);
+ padding: 0.1rem 0.2rem;
+ border-radius: 0.2rem;
+ }
+
+ &__svg {
+ background-color: $oc-white;
+ padding: 0.3rem;
+ width: 7.5rem;
+ height: 7.5rem;
+ border: 1px solid var(--button-gray-2);
+ svg {
+ width: 100%;
+ height: 100%;
+ }
+ }
+
+ .ToolIcon__icon {
+ background-color: $oc-white;
+ width: auto;
+ height: auto;
+ margin: 0 0.5rem;
+ }
+ .ToolIcon,
+ .ToolIcon_type_button:hover {
+ background-color: white;
+ }
+ .required,
+ .error {
+ color: $oc-red-8;
+ font-weight: 700;
+ font-size: 1rem;
+ margin: 0.2rem;
+ }
+ .error {
+ font-weight: 500;
+ margin: 0;
+ padding: 0.3em 0;
+ }
+
+ &--remove {
+ position: absolute;
+ top: 0.2rem;
+ right: 1rem;
+
+ .ToolIcon__icon {
+ margin: 0;
+ }
+ .ToolIcon__icon {
+ background-color: $oc-red-6;
+ &:hover {
+ background-color: $oc-red-7;
+ }
+ &:active {
+ background-color: $oc-red-8;
+ }
+ }
+ svg {
+ color: $oc-white;
+ padding: 0.26rem;
+ border-radius: 0.3em;
+ width: 1rem;
+ height: 1rem;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/PublishLibrary.tsx b/packages/excalidraw/components/PublishLibrary.tsx
new file mode 100644
index 0000000..fe68f88
--- /dev/null
+++ b/packages/excalidraw/components/PublishLibrary.tsx
@@ -0,0 +1,540 @@
+import type { ReactNode } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import OpenColor from "open-color";
+
+import { Dialog } from "./Dialog";
+import { t } from "../i18n";
+import Trans from "./Trans";
+
+import type { LibraryItems, LibraryItem, UIAppState } from "../types";
+import { exportToCanvas, exportToSvg } from "@excalidraw/utils/export";
+import {
+ EDITOR_LS_KEYS,
+ EXPORT_DATA_TYPES,
+ EXPORT_SOURCE,
+ MIME_TYPES,
+ VERSIONS,
+} from "../constants";
+import type { ExportedLibraryData } from "../data/types";
+import { canvasToBlob, resizeImageFile } from "../data/blob";
+import { chunk } from "../utils";
+import DialogActionButton from "./DialogActionButton";
+import { CloseIcon } from "./icons";
+import { ToolButton } from "./ToolButton";
+import { EditorLocalStorage } from "../data/EditorLocalStorage";
+
+import "./PublishLibrary.scss";
+
+interface PublishLibraryDataParams {
+ authorName: string;
+ githubHandle: string;
+ name: string;
+ description: string;
+ twitterHandle: string;
+ website: string;
+}
+
+const generatePreviewImage = async (libraryItems: LibraryItems) => {
+ const MAX_ITEMS_PER_ROW = 6;
+ const BOX_SIZE = 128;
+ const BOX_PADDING = Math.round(BOX_SIZE / 16);
+ const BORDER_WIDTH = Math.max(Math.round(BOX_SIZE / 64), 2);
+
+ const rows = chunk(libraryItems, MAX_ITEMS_PER_ROW);
+
+ const canvas = document.createElement("canvas");
+
+ canvas.width =
+ rows[0].length * BOX_SIZE +
+ (rows[0].length + 1) * (BOX_PADDING * 2) -
+ BOX_PADDING * 2;
+ canvas.height =
+ rows.length * BOX_SIZE +
+ (rows.length + 1) * (BOX_PADDING * 2) -
+ BOX_PADDING * 2;
+
+ const ctx = canvas.getContext("2d")!;
+
+ ctx.fillStyle = OpenColor.white;
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ // draw items
+ // ---------------------------------------------------------------------------
+ for (const [index, item] of libraryItems.entries()) {
+ const itemCanvas = await exportToCanvas({
+ elements: item.elements,
+ files: null,
+ maxWidthOrHeight: BOX_SIZE,
+ });
+
+ const { width, height } = itemCanvas;
+
+ // draw item
+ // -------------------------------------------------------------------------
+ const rowOffset =
+ Math.floor(index / MAX_ITEMS_PER_ROW) * (BOX_SIZE + BOX_PADDING * 2);
+ const colOffset =
+ (index % MAX_ITEMS_PER_ROW) * (BOX_SIZE + BOX_PADDING * 2);
+
+ ctx.drawImage(
+ itemCanvas,
+ colOffset + (BOX_SIZE - width) / 2 + BOX_PADDING,
+ rowOffset + (BOX_SIZE - height) / 2 + BOX_PADDING,
+ );
+
+ // draw item border
+ // -------------------------------------------------------------------------
+ ctx.lineWidth = BORDER_WIDTH;
+ ctx.strokeStyle = OpenColor.gray[4];
+ ctx.strokeRect(
+ colOffset + BOX_PADDING / 2,
+ rowOffset + BOX_PADDING / 2,
+ BOX_SIZE + BOX_PADDING,
+ BOX_SIZE + BOX_PADDING,
+ );
+ }
+
+ return await resizeImageFile(
+ new File([await canvasToBlob(canvas)], "preview", { type: MIME_TYPES.png }),
+ {
+ outputType: MIME_TYPES.jpg,
+ maxWidthOrHeight: 5000,
+ },
+ );
+};
+
+const SingleLibraryItem = ({
+ libItem,
+ appState,
+ index,
+ onChange,
+ onRemove,
+}: {
+ libItem: LibraryItem;
+ appState: UIAppState;
+ index: number;
+ onChange: (val: string, index: number) => void;
+ onRemove: (id: string) => void;
+}) => {
+ const svgRef = useRef<HTMLDivElement | null>(null);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ useEffect(() => {
+ const node = svgRef.current;
+ if (!node) {
+ return;
+ }
+ (async () => {
+ const svg = await exportToSvg({
+ elements: libItem.elements,
+ appState: {
+ ...appState,
+ viewBackgroundColor: OpenColor.white,
+ exportBackground: true,
+ },
+ files: null,
+ skipInliningFonts: true,
+ });
+ node.innerHTML = svg.outerHTML;
+ })();
+ }, [libItem.elements, appState]);
+
+ return (
+ <div className="single-library-item">
+ {libItem.status === "published" && (
+ <span className="single-library-item-status">
+ {t("labels.statusPublished")}
+ </span>
+ )}
+ <div ref={svgRef} className="single-library-item__svg" />
+ <ToolButton
+ aria-label={t("buttons.remove")}
+ type="button"
+ icon={CloseIcon}
+ className="single-library-item--remove"
+ onClick={onRemove.bind(null, libItem.id)}
+ title={t("buttons.remove")}
+ />
+ <div
+ style={{
+ display: "flex",
+ margin: "0.8rem 0",
+ width: "100%",
+ fontSize: "14px",
+ fontWeight: 500,
+ flexDirection: "column",
+ }}
+ >
+ <label
+ style={{
+ display: "flex",
+ justifyContent: "space-between",
+ flexDirection: "column",
+ }}
+ >
+ <div style={{ padding: "0.5em 0" }}>
+ <span style={{ fontWeight: 500, color: OpenColor.gray[6] }}>
+ {t("publishDialog.itemName")}
+ </span>
+ <span aria-hidden="true" className="required">
+ *
+ </span>
+ </div>
+ <input
+ type="text"
+ ref={inputRef}
+ style={{ width: "80%", padding: "0.2rem" }}
+ defaultValue={libItem.name}
+ placeholder="Item name"
+ onChange={(event) => {
+ onChange(event.target.value, index);
+ }}
+ />
+ </label>
+ <span className="error">{libItem.error}</span>
+ </div>
+ </div>
+ );
+};
+
+const PublishLibrary = ({
+ onClose,
+ libraryItems,
+ appState,
+ onSuccess,
+ onError,
+ updateItemsInStorage,
+ onRemove,
+}: {
+ onClose: () => void;
+ libraryItems: LibraryItems;
+ appState: UIAppState;
+ onSuccess: (data: {
+ url: string;
+ authorName: string;
+ items: LibraryItems;
+ }) => void;
+
+ onError: (error: Error) => void;
+ updateItemsInStorage: (items: LibraryItems) => void;
+ onRemove: (id: string) => void;
+}) => {
+ const [libraryData, setLibraryData] = useState<PublishLibraryDataParams>({
+ authorName: "",
+ githubHandle: "",
+ name: "",
+ description: "",
+ twitterHandle: "",
+ website: "",
+ });
+
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ useEffect(() => {
+ const data = EditorLocalStorage.get<PublishLibraryDataParams>(
+ EDITOR_LS_KEYS.PUBLISH_LIBRARY,
+ );
+ if (data) {
+ setLibraryData(data);
+ }
+ }, []);
+
+ const [clonedLibItems, setClonedLibItems] = useState<LibraryItems>(
+ libraryItems.slice(),
+ );
+
+ useEffect(() => {
+ setClonedLibItems(libraryItems.slice());
+ }, [libraryItems]);
+
+ const onInputChange = (event: any) => {
+ setLibraryData({
+ ...libraryData,
+ [event.target.name]: event.target.value,
+ });
+ };
+
+ const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ setIsSubmitting(true);
+ const erroredLibItems: LibraryItem[] = [];
+ let isError = false;
+ clonedLibItems.forEach((libItem) => {
+ let error = "";
+ if (!libItem.name) {
+ error = t("publishDialog.errors.required");
+ isError = true;
+ }
+ erroredLibItems.push({ ...libItem, error });
+ });
+
+ if (isError) {
+ setClonedLibItems(erroredLibItems);
+ setIsSubmitting(false);
+ return;
+ }
+
+ const previewImage = await generatePreviewImage(clonedLibItems);
+
+ const libContent: ExportedLibraryData = {
+ type: EXPORT_DATA_TYPES.excalidrawLibrary,
+ version: VERSIONS.excalidrawLibrary,
+ source: EXPORT_SOURCE,
+ libraryItems: clonedLibItems,
+ };
+ const content = JSON.stringify(libContent, null, 2);
+ const lib = new Blob([content], { type: "application/json" });
+
+ const formData = new FormData();
+ formData.append("excalidrawLib", lib);
+ formData.append("previewImage", previewImage);
+ formData.append("previewImageType", previewImage.type);
+ formData.append("title", libraryData.name);
+ formData.append("authorName", libraryData.authorName);
+ formData.append("githubHandle", libraryData.githubHandle);
+ formData.append("name", libraryData.name);
+ formData.append("description", libraryData.description);
+ formData.append("twitterHandle", libraryData.twitterHandle);
+ formData.append("website", libraryData.website);
+
+ fetch(`${import.meta.env.VITE_APP_LIBRARY_BACKEND}/submit`, {
+ method: "post",
+ body: formData,
+ })
+ .then(
+ (response) => {
+ if (response.ok) {
+ return response.json().then(({ url }) => {
+ // flush data from local storage
+ EditorLocalStorage.delete(EDITOR_LS_KEYS.PUBLISH_LIBRARY);
+ onSuccess({
+ url,
+ authorName: libraryData.authorName,
+ items: clonedLibItems,
+ });
+ });
+ }
+ return response
+ .json()
+ .catch(() => {
+ throw new Error(response.statusText || "something went wrong");
+ })
+ .then((error) => {
+ throw new Error(
+ error.message || response.statusText || "something went wrong",
+ );
+ });
+ },
+ (err) => {
+ console.error(err);
+ onError(err);
+ setIsSubmitting(false);
+ },
+ )
+ .catch((err) => {
+ console.error(err);
+ onError(err);
+ setIsSubmitting(false);
+ });
+ };
+
+ const renderLibraryItems = () => {
+ const items: ReactNode[] = [];
+ clonedLibItems.forEach((libItem, index) => {
+ items.push(
+ <div className="single-library-item-wrapper" key={index}>
+ <SingleLibraryItem
+ libItem={libItem}
+ appState={appState}
+ index={index}
+ onChange={(val, index) => {
+ const items = clonedLibItems.slice();
+ items[index].name = val;
+ setClonedLibItems(items);
+ }}
+ onRemove={onRemove}
+ />
+ </div>,
+ );
+ });
+ return <div className="selected-library-items">{items}</div>;
+ };
+
+ const onDialogClose = useCallback(() => {
+ updateItemsInStorage(clonedLibItems);
+ EditorLocalStorage.set(EDITOR_LS_KEYS.PUBLISH_LIBRARY, libraryData);
+ onClose();
+ }, [clonedLibItems, onClose, updateItemsInStorage, libraryData]);
+
+ const shouldRenderForm = !!libraryItems.length;
+
+ const containsPublishedItems = libraryItems.some(
+ (item) => item.status === "published",
+ );
+
+ return (
+ <Dialog
+ onCloseRequest={onDialogClose}
+ title={t("publishDialog.title")}
+ className="publish-library"
+ >
+ {shouldRenderForm ? (
+ <form onSubmit={onSubmit}>
+ <div className="publish-library-note">
+ <Trans
+ i18nKey="publishDialog.noteDescription"
+ link={(el) => (
+ <a
+ href="https://libraries.excalidraw.com"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {el}
+ </a>
+ )}
+ />
+ </div>
+ <span className="publish-library-note">
+ <Trans
+ i18nKey="publishDialog.noteGuidelines"
+ link={(el) => (
+ <a
+ href="https://github.com/excalidraw/excalidraw-libraries#guidelines"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {el}
+ </a>
+ )}
+ />
+ </span>
+
+ <div className="publish-library-note">
+ {t("publishDialog.noteItems")}
+ </div>
+ {containsPublishedItems && (
+ <span className="publish-library-note publish-library-warning">
+ {t("publishDialog.republishWarning")}
+ </span>
+ )}
+ {renderLibraryItems()}
+ <div className="publish-library__fields">
+ <label>
+ <div>
+ <span>{t("publishDialog.libraryName")}</span>
+ <span aria-hidden="true" className="required">
+ *
+ </span>
+ </div>
+ <input
+ type="text"
+ name="name"
+ required
+ value={libraryData.name}
+ onChange={onInputChange}
+ placeholder={t("publishDialog.placeholder.libraryName")}
+ />
+ </label>
+ <label style={{ alignItems: "flex-start" }}>
+ <div>
+ <span>{t("publishDialog.libraryDesc")}</span>
+ <span aria-hidden="true" className="required">
+ *
+ </span>
+ </div>
+ <textarea
+ name="description"
+ rows={4}
+ required
+ value={libraryData.description}
+ onChange={onInputChange}
+ placeholder={t("publishDialog.placeholder.libraryDesc")}
+ />
+ </label>
+ <label>
+ <div>
+ <span>{t("publishDialog.authorName")}</span>
+ <span aria-hidden="true" className="required">
+ *
+ </span>
+ </div>
+ <input
+ type="text"
+ name="authorName"
+ required
+ value={libraryData.authorName}
+ onChange={onInputChange}
+ placeholder={t("publishDialog.placeholder.authorName")}
+ />
+ </label>
+ <label>
+ <span>{t("publishDialog.githubUsername")}</span>
+ <input
+ type="text"
+ name="githubHandle"
+ value={libraryData.githubHandle}
+ onChange={onInputChange}
+ placeholder={t("publishDialog.placeholder.githubHandle")}
+ />
+ </label>
+ <label>
+ <span>{t("publishDialog.twitterUsername")}</span>
+ <input
+ type="text"
+ name="twitterHandle"
+ value={libraryData.twitterHandle}
+ onChange={onInputChange}
+ placeholder={t("publishDialog.placeholder.twitterHandle")}
+ />
+ </label>
+ <label>
+ <span>{t("publishDialog.website")}</span>
+ <input
+ type="text"
+ name="website"
+ pattern="https?://.+"
+ title={t("publishDialog.errors.website")}
+ value={libraryData.website}
+ onChange={onInputChange}
+ placeholder={t("publishDialog.placeholder.website")}
+ />
+ </label>
+ <span className="publish-library-note">
+ <Trans
+ i18nKey="publishDialog.noteLicense"
+ link={(el) => (
+ <a
+ href="https://github.com/excalidraw/excalidraw-libraries/blob/main/LICENSE"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {el}
+ </a>
+ )}
+ />
+ </span>
+ </div>
+ <div className="publish-library__buttons">
+ <DialogActionButton
+ label={t("buttons.cancel")}
+ onClick={onDialogClose}
+ data-testid="cancel-clear-canvas-button"
+ />
+ <DialogActionButton
+ type="submit"
+ label={t("buttons.submit")}
+ actionType="primary"
+ isLoading={isSubmitting}
+ />
+ </div>
+ </form>
+ ) : (
+ <p style={{ padding: "1em", textAlign: "center", fontWeight: 500 }}>
+ {t("publishDialog.atleastOneLibItem")}
+ </p>
+ )}
+ </Dialog>
+ );
+};
+
+export default PublishLibrary;
diff --git a/packages/excalidraw/components/QuickSearch.scss b/packages/excalidraw/components/QuickSearch.scss
new file mode 100644
index 0000000..face6d1
--- /dev/null
+++ b/packages/excalidraw/components/QuickSearch.scss
@@ -0,0 +1,48 @@
+.excalidraw {
+ --list-border-color: var(--color-gray-20);
+
+ .QuickSearch__wrapper {
+ position: relative;
+ height: 2.6rem; // added +0.1 due to Safari
+ border-bottom: 1px solid var(--list-border-color);
+
+ svg {
+ position: absolute;
+ top: 47.5%; // 50% is not exactly in the center of the input
+ transform: translateY(-50%);
+ left: 0.75rem;
+ width: 1.25rem;
+ height: 1.25rem;
+ color: var(--color-gray-40);
+ z-index: 1;
+ }
+ }
+
+ &.theme--dark {
+ --list-border-color: var(--color-gray-80);
+
+ .QuickSearch__wrapper {
+ border-bottom: none;
+ }
+ }
+
+ .QuickSearch__input {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ box-sizing: border-box;
+ border: 0 !important;
+ font-size: 0.875rem;
+ padding-left: 2.5rem !important;
+ padding-right: 0.75rem !important;
+
+ &::placeholder {
+ color: var(--color-gray-40);
+ }
+
+ &:focus {
+ box-shadow: none !important;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/QuickSearch.tsx b/packages/excalidraw/components/QuickSearch.tsx
new file mode 100644
index 0000000..c7ec78b
--- /dev/null
+++ b/packages/excalidraw/components/QuickSearch.tsx
@@ -0,0 +1,28 @@
+import clsx from "clsx";
+import React from "react";
+import { searchIcon } from "./icons";
+
+import "./QuickSearch.scss";
+
+interface QuickSearchProps {
+ className?: string;
+ placeholder: string;
+ onChange: (term: string) => void;
+}
+
+export const QuickSearch = React.forwardRef<HTMLInputElement, QuickSearchProps>(
+ ({ className, placeholder, onChange }, ref) => {
+ return (
+ <div className={clsx("QuickSearch__wrapper", className)}>
+ {searchIcon}
+ <input
+ ref={ref}
+ className="QuickSearch__input"
+ type="text"
+ placeholder={placeholder}
+ onChange={(e) => onChange(e.target.value.trim().toLowerCase())}
+ />
+ </div>
+ );
+ },
+);
diff --git a/packages/excalidraw/components/RadioGroup.scss b/packages/excalidraw/components/RadioGroup.scss
new file mode 100644
index 0000000..76ee20a
--- /dev/null
+++ b/packages/excalidraw/components/RadioGroup.scss
@@ -0,0 +1,91 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ --RadioGroup-background: var(--island-bg-color);
+ --RadioGroup-border: var(--color-surface-high);
+
+ --RadioGroup-choice-color-off: var(--color-primary);
+ --RadioGroup-choice-color-off-hover: var(--color-brand-hover);
+ --RadioGroup-choice-background-off: var(--island-bg-color);
+ --RadioGroup-choice-background-off-active: var(--color-surface-high);
+
+ --RadioGroup-choice-color-on: var(--color-surface-lowest);
+ --RadioGroup-choice-background-on: var(--color-primary);
+ --RadioGroup-choice-background-on-hover: var(--color-brand-hover);
+ --RadioGroup-choice-background-on-active: var(--color-brand-active);
+
+ .RadioGroup {
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: row;
+ align-items: flex-start;
+
+ padding: 3px;
+ border-radius: 10px;
+
+ background: var(--RadioGroup-background);
+ border: 1px solid var(--RadioGroup-border);
+
+ &__choice {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 24px;
+
+ color: var(--RadioGroup-choice-color-off);
+ background: var(--RadioGroup-choice-background-off);
+
+ border-radius: 8px;
+
+ font-family: "Assistant";
+ font-style: normal;
+ font-weight: 600;
+ font-size: 0.75rem;
+ line-height: 100%;
+ user-select: none;
+ letter-spacing: 0.4px;
+
+ transition: all 75ms ease-out;
+
+ &:hover {
+ color: var(--RadioGroup-choice-color-off-hover);
+ }
+
+ &:active {
+ background: var(--RadioGroup-choice-background-off-active);
+ }
+
+ &.active {
+ color: var(--RadioGroup-choice-color-on);
+ background: var(--RadioGroup-choice-background-on);
+
+ &:hover {
+ background: var(--RadioGroup-choice-background-on-hover);
+ }
+
+ &:active {
+ background: var(--RadioGroup-choice-background-on-active);
+ }
+ }
+
+ & input {
+ z-index: 1;
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+
+ border-radius: 8px;
+
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ appearance: none;
+
+ cursor: pointer;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/RadioGroup.tsx b/packages/excalidraw/components/RadioGroup.tsx
new file mode 100644
index 0000000..64d4d58
--- /dev/null
+++ b/packages/excalidraw/components/RadioGroup.tsx
@@ -0,0 +1,45 @@
+import clsx from "clsx";
+import "./RadioGroup.scss";
+
+export type RadioGroupChoice<T> = {
+ value: T;
+ label: React.ReactNode;
+ ariaLabel?: string;
+};
+
+export type RadioGroupProps<T> = {
+ choices: RadioGroupChoice<T>[];
+ value: T;
+ onChange: (value: T) => void;
+ name: string;
+};
+
+export const RadioGroup = function <T>({
+ onChange,
+ value,
+ choices,
+ name,
+}: RadioGroupProps<T>) {
+ return (
+ <div className="RadioGroup">
+ {choices.map((choice) => (
+ <div
+ className={clsx("RadioGroup__choice", {
+ active: choice.value === value,
+ })}
+ key={String(choice.value)}
+ title={choice.ariaLabel}
+ >
+ <input
+ name={name}
+ type="radio"
+ checked={choice.value === value}
+ onChange={() => onChange(choice.value)}
+ aria-label={choice.ariaLabel}
+ />
+ {choice.label}
+ </div>
+ ))}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/Range.scss b/packages/excalidraw/components/Range.scss
new file mode 100644
index 0000000..01cb916
--- /dev/null
+++ b/packages/excalidraw/components/Range.scss
@@ -0,0 +1,56 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ --slider-thumb-size: 16px;
+
+ .range-wrapper {
+ position: relative;
+ padding-top: 10px;
+ padding-bottom: 30px;
+ }
+
+ .range-input {
+ width: 100%;
+ height: 4px;
+ -webkit-appearance: none;
+ background: var(--color-slider-track);
+ border-radius: 2px;
+ outline: none;
+ }
+
+ .range-input::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: var(--slider-thumb-size);
+ height: var(--slider-thumb-size);
+ background: var(--color-slider-thumb);
+ border-radius: 50%;
+ cursor: pointer;
+ border: none;
+ }
+
+ .range-input::-moz-range-thumb {
+ width: var(--slider-thumb-size);
+ height: var(--slider-thumb-size);
+ background: var(--color-slider-thumb);
+ border-radius: 50%;
+ cursor: pointer;
+ border: none;
+ }
+
+ .value-bubble {
+ position: absolute;
+ bottom: 0;
+ transform: translateX(-50%);
+ font-size: 12px;
+ color: var(--text-primary-color);
+ }
+
+ .zero-label {
+ position: absolute;
+ bottom: 0;
+ left: 4px;
+ font-size: 12px;
+ color: var(--text-primary-color);
+ }
+}
diff --git a/packages/excalidraw/components/Range.tsx b/packages/excalidraw/components/Range.tsx
new file mode 100644
index 0000000..cd1869c
--- /dev/null
+++ b/packages/excalidraw/components/Range.tsx
@@ -0,0 +1,65 @@
+import React, { useEffect } from "react";
+import { getFormValue } from "../actions/actionProperties";
+import { t } from "../i18n";
+import "./Range.scss";
+
+export type RangeProps = {
+ updateData: (value: number) => void;
+ appState: any;
+ elements: any;
+ testId?: string;
+};
+
+export const Range = ({
+ updateData,
+ appState,
+ elements,
+ testId,
+}: RangeProps) => {
+ const rangeRef = React.useRef<HTMLInputElement>(null);
+ const valueRef = React.useRef<HTMLDivElement>(null);
+ const value = getFormValue(
+ elements,
+ appState,
+ (element) => element.opacity,
+ true,
+ appState.currentItemOpacity,
+ );
+ useEffect(() => {
+ if (rangeRef.current && valueRef.current) {
+ const rangeElement = rangeRef.current;
+ const valueElement = valueRef.current;
+ const inputWidth = rangeElement.offsetWidth;
+ const thumbWidth = 15; // 15 is the width of the thumb
+ const position =
+ (value / 100) * (inputWidth - thumbWidth) + thumbWidth / 2;
+ valueElement.style.left = `${position}px`;
+ rangeElement.style.background = `linear-gradient(to right, var(--color-slider-track) 0%, var(--color-slider-track) ${value}%, var(--button-bg) ${value}%, var(--button-bg) 100%)`;
+ }
+ }, [value]);
+
+ return (
+ <label className="control-label">
+ {t("labels.opacity")}
+ <div className="range-wrapper">
+ <input
+ ref={rangeRef}
+ type="range"
+ min="0"
+ max="100"
+ step="10"
+ onChange={(event) => {
+ updateData(+event.target.value);
+ }}
+ value={value}
+ className="range-input"
+ data-testid={testId}
+ />
+ <div className="value-bubble" ref={valueRef}>
+ {value !== 0 ? value : null}
+ </div>
+ <div className="zero-label">0</div>
+ </div>
+ </label>
+ );
+};
diff --git a/packages/excalidraw/components/SVGLayer.scss b/packages/excalidraw/components/SVGLayer.scss
new file mode 100644
index 0000000..1ab5a63
--- /dev/null
+++ b/packages/excalidraw/components/SVGLayer.scss
@@ -0,0 +1,24 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .SVGLayer {
+ pointer-events: none;
+ width: 100vw;
+ height: 100vh;
+ position: fixed;
+ top: 0;
+ left: 0;
+
+ z-index: var(--zIndex-svgLayer);
+
+ & svg {
+ image-rendering: auto;
+ overflow: visible;
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ top: 0;
+ left: 0;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/SVGLayer.tsx b/packages/excalidraw/components/SVGLayer.tsx
new file mode 100644
index 0000000..667b89a
--- /dev/null
+++ b/packages/excalidraw/components/SVGLayer.tsx
@@ -0,0 +1,33 @@
+import { useEffect, useRef } from "react";
+import type { Trail } from "../animated-trail";
+
+import "./SVGLayer.scss";
+
+type SVGLayerProps = {
+ trails: Trail[];
+};
+
+export const SVGLayer = ({ trails }: SVGLayerProps) => {
+ const svgRef = useRef<SVGSVGElement | null>(null);
+
+ useEffect(() => {
+ if (svgRef.current) {
+ for (const trail of trails) {
+ trail.start(svgRef.current);
+ }
+ }
+
+ return () => {
+ for (const trail of trails) {
+ trail.stop();
+ }
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, trails);
+
+ return (
+ <div className="SVGLayer">
+ <svg ref={svgRef} />
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ScrollableList.scss b/packages/excalidraw/components/ScrollableList.scss
new file mode 100644
index 0000000..a2bda4a
--- /dev/null
+++ b/packages/excalidraw/components/ScrollableList.scss
@@ -0,0 +1,21 @@
+.excalidraw {
+ .ScrollableList__wrapper {
+ position: static !important;
+ border: none;
+ font-size: 0.875rem;
+ overflow-y: auto;
+
+ & > .empty,
+ & > .hint {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding: 0.5rem;
+ font-size: 0.75rem;
+ color: var(--color-gray-60);
+ overflow: hidden;
+ text-align: center;
+ line-height: 150%;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ScrollableList.tsx b/packages/excalidraw/components/ScrollableList.tsx
new file mode 100644
index 0000000..60ca1ad
--- /dev/null
+++ b/packages/excalidraw/components/ScrollableList.tsx
@@ -0,0 +1,24 @@
+import clsx from "clsx";
+import { Children } from "react";
+
+import "./ScrollableList.scss";
+
+interface ScrollableListProps {
+ className?: string;
+ placeholder: string;
+ children: React.ReactNode;
+}
+
+export const ScrollableList = ({
+ className,
+ placeholder,
+ children,
+}: ScrollableListProps) => {
+ const isEmpty = !Children.count(children);
+
+ return (
+ <div className={clsx("ScrollableList__wrapper", className)} role="menu">
+ {isEmpty ? <div className="empty">{placeholder}</div> : children}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/SearchMenu.scss b/packages/excalidraw/components/SearchMenu.scss
new file mode 100644
index 0000000..1f47f98
--- /dev/null
+++ b/packages/excalidraw/components/SearchMenu.scss
@@ -0,0 +1,110 @@
+@import "open-color/open-color";
+
+.excalidraw {
+ .layer-ui__search {
+ flex: 1 0 auto;
+ display: flex;
+ flex-direction: column;
+ padding: 8px 0 0 0;
+ }
+
+ .layer-ui__search-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 0 0.75rem;
+ .ExcTextField {
+ flex: 1 0 auto;
+ }
+
+ .ExcTextField__input {
+ background-color: #f5f5f9;
+ @at-root .excalidraw.theme--dark#{&} {
+ background-color: #31303b;
+ }
+
+ border-radius: var(--border-radius-md);
+ border: 0;
+
+ input::placeholder {
+ font-size: 0.9rem;
+ }
+ }
+ }
+
+ .layer-ui__search-count {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 8px 8px 0 8px;
+ margin: 0 0.75rem 0.25rem 0.75rem;
+ font-size: 0.8em;
+
+ .result-nav {
+ display: flex;
+
+ .result-nav-btn {
+ width: 36px;
+ height: 36px;
+ --button-border: transparent;
+
+ &:active {
+ background-color: var(--color-surface-high);
+ }
+
+ &:first-child {
+ margin-right: 4px;
+ }
+ }
+ }
+ }
+
+ .layer-ui__search-result-container {
+ overflow-y: auto;
+ flex: 1 1 0;
+ display: flex;
+ flex-direction: column;
+
+ gap: 0.125rem;
+ }
+
+ .layer-ui__result-item {
+ display: flex;
+ align-items: center;
+ min-height: 2rem;
+ flex: 0 0 auto;
+ padding: 0.25rem 0.75rem;
+ cursor: pointer;
+ border: 1px solid transparent;
+ outline: none;
+
+ margin: 0 0.75rem;
+ border-radius: var(--border-radius-md);
+
+ .text-icon {
+ width: 1rem;
+ height: 1rem;
+ margin-right: 0.75rem;
+ }
+
+ .preview-text {
+ flex: 1;
+ max-height: 48px;
+ line-height: 24px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ word-break: break-all;
+ }
+
+ &:hover {
+ background-color: var(--color-surface-high);
+ }
+ &:active {
+ border-color: var(--color-primary);
+ }
+
+ &.active {
+ background-color: var(--color-surface-high);
+ }
+ }
+}
diff --git a/packages/excalidraw/components/SearchMenu.tsx b/packages/excalidraw/components/SearchMenu.tsx
new file mode 100644
index 0000000..873de5a
--- /dev/null
+++ b/packages/excalidraw/components/SearchMenu.tsx
@@ -0,0 +1,713 @@
+import { Fragment, memo, useEffect, useRef, useState } from "react";
+import { collapseDownIcon, upIcon, searchIcon } from "./icons";
+import { TextField } from "./TextField";
+import { Button } from "./Button";
+import { useApp, useExcalidrawSetAppState } from "./App";
+import debounce from "lodash.debounce";
+import type { AppClassProperties } from "../types";
+import { isTextElement, newTextElement } from "../element";
+import type { ExcalidrawTextElement } from "../element/types";
+import { addEventListener, getFontString } from "../utils";
+import { KEYS } from "../keys";
+import clsx from "clsx";
+import { atom, useAtom } from "../editor-jotai";
+import { t } from "../i18n";
+import { isElementCompletelyInViewport } from "../element/sizeHelpers";
+import { randomInteger } from "../random";
+import { CLASSES, EVENT } from "../constants";
+import { useStable } from "../hooks/useStable";
+
+import "./SearchMenu.scss";
+import { round } from "@excalidraw/math";
+import { measureText } from "../element/textMeasurements";
+
+const searchQueryAtom = atom<string>("");
+export const searchItemInFocusAtom = atom<number | null>(null);
+
+const SEARCH_DEBOUNCE = 350;
+
+type SearchMatchItem = {
+ textElement: ExcalidrawTextElement;
+ searchQuery: SearchQuery;
+ index: number;
+ preview: {
+ indexInSearchQuery: number;
+ previewText: string;
+ moreBefore: boolean;
+ moreAfter: boolean;
+ };
+ matchedLines: {
+ offsetX: number;
+ offsetY: number;
+ width: number;
+ height: number;
+ }[];
+};
+
+type SearchMatches = {
+ nonce: number | null;
+ items: SearchMatchItem[];
+};
+
+type SearchQuery = string & { _brand: "SearchQuery" };
+
+export const SearchMenu = () => {
+ const app = useApp();
+ const setAppState = useExcalidrawSetAppState();
+
+ const searchInputRef = useRef<HTMLInputElement>(null);
+
+ const [inputValue, setInputValue] = useAtom(searchQueryAtom);
+ const searchQuery = inputValue.trim() as SearchQuery;
+
+ const [isSearching, setIsSearching] = useState(false);
+
+ const [searchMatches, setSearchMatches] = useState<SearchMatches>({
+ nonce: null,
+ items: [],
+ });
+ const searchedQueryRef = useRef<SearchQuery | null>(null);
+ const lastSceneNonceRef = useRef<number | undefined>(undefined);
+
+ const [focusIndex, setFocusIndex] = useAtom(searchItemInFocusAtom);
+ const elementsMap = app.scene.getNonDeletedElementsMap();
+
+ useEffect(() => {
+ if (isSearching) {
+ return;
+ }
+ if (
+ searchQuery !== searchedQueryRef.current ||
+ app.scene.getSceneNonce() !== lastSceneNonceRef.current
+ ) {
+ searchedQueryRef.current = null;
+ handleSearch(searchQuery, app, (matchItems, index) => {
+ setSearchMatches({
+ nonce: randomInteger(),
+ items: matchItems,
+ });
+ searchedQueryRef.current = searchQuery;
+ lastSceneNonceRef.current = app.scene.getSceneNonce();
+ setAppState({
+ searchMatches: matchItems.map((searchMatch) => ({
+ id: searchMatch.textElement.id,
+ focus: false,
+ matchedLines: searchMatch.matchedLines,
+ })),
+ });
+ });
+ }
+ }, [
+ isSearching,
+ searchQuery,
+ elementsMap,
+ app,
+ setAppState,
+ setFocusIndex,
+ lastSceneNonceRef,
+ ]);
+
+ const goToNextItem = () => {
+ if (searchMatches.items.length > 0) {
+ setFocusIndex((focusIndex) => {
+ if (focusIndex === null) {
+ return 0;
+ }
+
+ return (focusIndex + 1) % searchMatches.items.length;
+ });
+ }
+ };
+
+ const goToPreviousItem = () => {
+ if (searchMatches.items.length > 0) {
+ setFocusIndex((focusIndex) => {
+ if (focusIndex === null) {
+ return 0;
+ }
+
+ return focusIndex - 1 < 0
+ ? searchMatches.items.length - 1
+ : focusIndex - 1;
+ });
+ }
+ };
+
+ useEffect(() => {
+ setAppState((state) => {
+ return {
+ searchMatches: state.searchMatches.map((match, index) => {
+ if (index === focusIndex) {
+ return { ...match, focus: true };
+ }
+ return { ...match, focus: false };
+ }),
+ };
+ });
+ }, [focusIndex, setAppState]);
+
+ useEffect(() => {
+ if (searchMatches.items.length > 0 && focusIndex !== null) {
+ const match = searchMatches.items[focusIndex];
+
+ if (match) {
+ const zoomValue = app.state.zoom.value;
+
+ const matchAsElement = newTextElement({
+ text: match.searchQuery,
+ x: match.textElement.x + (match.matchedLines[0]?.offsetX ?? 0),
+ y: match.textElement.y + (match.matchedLines[0]?.offsetY ?? 0),
+ width: match.matchedLines[0]?.width,
+ height: match.matchedLines[0]?.height,
+ fontSize: match.textElement.fontSize,
+ fontFamily: match.textElement.fontFamily,
+ });
+
+ const FONT_SIZE_LEGIBILITY_THRESHOLD = 14;
+
+ const fontSize = match.textElement.fontSize;
+ const isTextTiny =
+ fontSize * zoomValue < FONT_SIZE_LEGIBILITY_THRESHOLD;
+
+ if (
+ !isElementCompletelyInViewport(
+ [matchAsElement],
+ app.canvas.width / window.devicePixelRatio,
+ app.canvas.height / window.devicePixelRatio,
+ {
+ offsetLeft: app.state.offsetLeft,
+ offsetTop: app.state.offsetTop,
+ scrollX: app.state.scrollX,
+ scrollY: app.state.scrollY,
+ zoom: app.state.zoom,
+ },
+ app.scene.getNonDeletedElementsMap(),
+ app.getEditorUIOffsets(),
+ ) ||
+ isTextTiny
+ ) {
+ let zoomOptions: Parameters<AppClassProperties["scrollToContent"]>[1];
+
+ if (isTextTiny) {
+ if (fontSize >= FONT_SIZE_LEGIBILITY_THRESHOLD) {
+ zoomOptions = { fitToContent: true };
+ } else {
+ zoomOptions = {
+ fitToViewport: true,
+ // calculate zoom level to make the fontSize ~equal to FONT_SIZE_THRESHOLD, rounded to nearest 10%
+ maxZoom: round(FONT_SIZE_LEGIBILITY_THRESHOLD / fontSize, 1),
+ };
+ }
+ } else {
+ zoomOptions = { fitToContent: true };
+ }
+
+ app.scrollToContent(matchAsElement, {
+ animate: true,
+ duration: 300,
+ ...zoomOptions,
+ canvasOffsets: app.getEditorUIOffsets(),
+ });
+ }
+ }
+ }
+ }, [focusIndex, searchMatches, app]);
+
+ useEffect(() => {
+ return () => {
+ setFocusIndex(null);
+ searchedQueryRef.current = null;
+ lastSceneNonceRef.current = undefined;
+ setAppState({
+ searchMatches: [],
+ });
+ setIsSearching(false);
+ };
+ }, [setAppState, setFocusIndex]);
+
+ const stableState = useStable({
+ goToNextItem,
+ goToPreviousItem,
+ searchMatches,
+ });
+
+ useEffect(() => {
+ const eventHandler = (event: KeyboardEvent) => {
+ if (
+ event.key === KEYS.ESCAPE &&
+ !app.state.openDialog &&
+ !app.state.openPopup
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ setAppState({
+ openSidebar: null,
+ });
+ return;
+ }
+
+ if (event[KEYS.CTRL_OR_CMD] && event.key === KEYS.F) {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (!searchInputRef.current?.matches(":focus")) {
+ if (app.state.openDialog) {
+ setAppState({
+ openDialog: null,
+ });
+ }
+ searchInputRef.current?.focus();
+ searchInputRef.current?.select();
+ } else {
+ setAppState({
+ openSidebar: null,
+ });
+ }
+ }
+
+ if (
+ event.target instanceof HTMLElement &&
+ event.target.closest(".layer-ui__search")
+ ) {
+ if (stableState.searchMatches.items.length) {
+ if (event.key === KEYS.ENTER) {
+ event.stopPropagation();
+ stableState.goToNextItem();
+ }
+
+ if (event.key === KEYS.ARROW_UP) {
+ event.stopPropagation();
+ stableState.goToPreviousItem();
+ } else if (event.key === KEYS.ARROW_DOWN) {
+ event.stopPropagation();
+ stableState.goToNextItem();
+ }
+ }
+ }
+ };
+
+ // `capture` needed to prevent firing on initial open from App.tsx,
+ // as well as to handle events before App ones
+ return addEventListener(window, EVENT.KEYDOWN, eventHandler, {
+ capture: true,
+ passive: false,
+ });
+ }, [setAppState, stableState, app]);
+
+ const matchCount = `${searchMatches.items.length} ${
+ searchMatches.items.length === 1
+ ? t("search.singleResult")
+ : t("search.multipleResults")
+ }`;
+
+ return (
+ <div className="layer-ui__search">
+ <div className="layer-ui__search-header">
+ <TextField
+ className={CLASSES.SEARCH_MENU_INPUT_WRAPPER}
+ value={inputValue}
+ ref={searchInputRef}
+ placeholder={t("search.placeholder")}
+ icon={searchIcon}
+ onChange={(value) => {
+ setInputValue(value);
+ setIsSearching(true);
+ const searchQuery = value.trim() as SearchQuery;
+ handleSearch(searchQuery, app, (matchItems, index) => {
+ setSearchMatches({
+ nonce: randomInteger(),
+ items: matchItems,
+ });
+ setFocusIndex(index);
+ searchedQueryRef.current = searchQuery;
+ lastSceneNonceRef.current = app.scene.getSceneNonce();
+ setAppState({
+ searchMatches: matchItems.map((searchMatch) => ({
+ id: searchMatch.textElement.id,
+ focus: false,
+ matchedLines: searchMatch.matchedLines,
+ })),
+ });
+
+ setIsSearching(false);
+ });
+ }}
+ selectOnRender
+ />
+ </div>
+
+ <div className="layer-ui__search-count">
+ {searchMatches.items.length > 0 && (
+ <>
+ {focusIndex !== null && focusIndex > -1 ? (
+ <div>
+ {focusIndex + 1} / {matchCount}
+ </div>
+ ) : (
+ <div>{matchCount}</div>
+ )}
+ <div className="result-nav">
+ <Button
+ onSelect={() => {
+ goToNextItem();
+ }}
+ className="result-nav-btn"
+ >
+ {collapseDownIcon}
+ </Button>
+ <Button
+ onSelect={() => {
+ goToPreviousItem();
+ }}
+ className="result-nav-btn"
+ >
+ {upIcon}
+ </Button>
+ </div>
+ </>
+ )}
+
+ {searchMatches.items.length === 0 &&
+ searchQuery &&
+ searchedQueryRef.current && (
+ <div style={{ margin: "1rem auto" }}>{t("search.noMatch")}</div>
+ )}
+ </div>
+
+ <MatchList
+ matches={searchMatches}
+ onItemClick={setFocusIndex}
+ focusIndex={focusIndex}
+ searchQuery={searchQuery}
+ />
+ </div>
+ );
+};
+
+const ListItem = (props: {
+ preview: SearchMatchItem["preview"];
+ searchQuery: SearchQuery;
+ highlighted: boolean;
+ onClick?: () => void;
+}) => {
+ const preview = [
+ props.preview.moreBefore ? "..." : "",
+ props.preview.previewText.slice(0, props.preview.indexInSearchQuery),
+ props.preview.previewText.slice(
+ props.preview.indexInSearchQuery,
+ props.preview.indexInSearchQuery + props.searchQuery.length,
+ ),
+ props.preview.previewText.slice(
+ props.preview.indexInSearchQuery + props.searchQuery.length,
+ ),
+ props.preview.moreAfter ? "..." : "",
+ ];
+
+ return (
+ <div
+ tabIndex={-1}
+ className={clsx("layer-ui__result-item", {
+ active: props.highlighted,
+ })}
+ onClick={props.onClick}
+ ref={(ref) => {
+ if (props.highlighted) {
+ ref?.scrollIntoView({ behavior: "auto", block: "nearest" });
+ }
+ }}
+ >
+ <div className="preview-text">
+ {preview.flatMap((text, idx) => (
+ <Fragment key={idx}>{idx === 2 ? <b>{text}</b> : text}</Fragment>
+ ))}
+ </div>
+ </div>
+ );
+};
+
+interface MatchListProps {
+ matches: SearchMatches;
+ onItemClick: (index: number) => void;
+ focusIndex: number | null;
+ searchQuery: SearchQuery;
+}
+
+const MatchListBase = (props: MatchListProps) => {
+ return (
+ <div className="layer-ui__search-result-container">
+ {props.matches.items.map((searchMatch, index) => (
+ <ListItem
+ key={searchMatch.textElement.id + searchMatch.index}
+ searchQuery={props.searchQuery}
+ preview={searchMatch.preview}
+ highlighted={index === props.focusIndex}
+ onClick={() => props.onItemClick(index)}
+ />
+ ))}
+ </div>
+ );
+};
+
+const areEqual = (prevProps: MatchListProps, nextProps: MatchListProps) => {
+ return (
+ prevProps.matches.nonce === nextProps.matches.nonce &&
+ prevProps.focusIndex === nextProps.focusIndex
+ );
+};
+
+const MatchList = memo(MatchListBase, areEqual);
+
+const getMatchPreview = (
+ text: string,
+ index: number,
+ searchQuery: SearchQuery,
+) => {
+ const WORDS_BEFORE = 2;
+ const WORDS_AFTER = 5;
+
+ const substrBeforeQuery = text.slice(0, index);
+ const wordsBeforeQuery = substrBeforeQuery.split(/\s+/);
+ // text = "small", query = "mall", not complete before
+ // text = "small", query = "smal", complete before
+ const isQueryCompleteBefore = substrBeforeQuery.endsWith(" ");
+ const startWordIndex =
+ wordsBeforeQuery.length -
+ WORDS_BEFORE -
+ 1 -
+ (isQueryCompleteBefore ? 0 : 1);
+ let wordsBeforeAsString =
+ wordsBeforeQuery.slice(startWordIndex <= 0 ? 0 : startWordIndex).join(" ") +
+ (isQueryCompleteBefore ? " " : "");
+
+ const MAX_ALLOWED_CHARS = 20;
+
+ wordsBeforeAsString =
+ wordsBeforeAsString.length > MAX_ALLOWED_CHARS
+ ? wordsBeforeAsString.slice(-MAX_ALLOWED_CHARS)
+ : wordsBeforeAsString;
+
+ const substrAfterQuery = text.slice(index + searchQuery.length);
+ const wordsAfter = substrAfterQuery.split(/\s+/);
+ // text = "small", query = "mall", complete after
+ // text = "small", query = "smal", not complete after
+ const isQueryCompleteAfter = !substrAfterQuery.startsWith(" ");
+ const numberOfWordsToTake = isQueryCompleteAfter
+ ? WORDS_AFTER + 1
+ : WORDS_AFTER;
+ const wordsAfterAsString =
+ (isQueryCompleteAfter ? "" : " ") +
+ wordsAfter.slice(0, numberOfWordsToTake).join(" ");
+
+ return {
+ indexInSearchQuery: wordsBeforeAsString.length,
+ previewText: wordsBeforeAsString + searchQuery + wordsAfterAsString,
+ moreBefore: startWordIndex > 0,
+ moreAfter: wordsAfter.length > numberOfWordsToTake,
+ };
+};
+
+const normalizeWrappedText = (
+ wrappedText: string,
+ originalText: string,
+): string => {
+ const wrappedLines = wrappedText.split("\n");
+ const normalizedLines: string[] = [];
+ let originalIndex = 0;
+
+ for (let i = 0; i < wrappedLines.length; i++) {
+ let currentLine = wrappedLines[i];
+ const nextLine = wrappedLines[i + 1];
+
+ if (nextLine) {
+ const nextLineIndexInOriginal = originalText.indexOf(
+ nextLine,
+ originalIndex,
+ );
+
+ if (nextLineIndexInOriginal > currentLine.length + originalIndex) {
+ let j = nextLineIndexInOriginal - (currentLine.length + originalIndex);
+
+ while (j > 0) {
+ currentLine += " ";
+ j--;
+ }
+ }
+ }
+
+ normalizedLines.push(currentLine);
+ originalIndex = originalIndex + currentLine.length;
+ }
+
+ return normalizedLines.join("\n");
+};
+
+const getMatchedLines = (
+ textElement: ExcalidrawTextElement,
+ searchQuery: SearchQuery,
+ index: number,
+) => {
+ const normalizedText = normalizeWrappedText(
+ textElement.text,
+ textElement.originalText,
+ );
+
+ const lines = normalizedText.split("\n");
+
+ const lineIndexRanges = [];
+ let currentIndex = 0;
+ let lineNumber = 0;
+
+ for (const line of lines) {
+ const startIndex = currentIndex;
+ const endIndex = startIndex + line.length - 1;
+
+ lineIndexRanges.push({
+ line,
+ startIndex,
+ endIndex,
+ lineNumber,
+ });
+
+ // Move to the next line's start index
+ currentIndex = endIndex + 1;
+ lineNumber++;
+ }
+
+ let startIndex = index;
+ let remainingQuery = textElement.originalText.slice(
+ index,
+ index + searchQuery.length,
+ );
+ const matchedLines: {
+ offsetX: number;
+ offsetY: number;
+ width: number;
+ height: number;
+ }[] = [];
+
+ for (const lineIndexRange of lineIndexRanges) {
+ if (remainingQuery === "") {
+ break;
+ }
+
+ if (
+ startIndex >= lineIndexRange.startIndex &&
+ startIndex <= lineIndexRange.endIndex
+ ) {
+ const matchCapacity = lineIndexRange.endIndex + 1 - startIndex;
+ const textToStart = lineIndexRange.line.slice(
+ 0,
+ startIndex - lineIndexRange.startIndex,
+ );
+
+ const matchedWord = remainingQuery.slice(0, matchCapacity);
+ remainingQuery = remainingQuery.slice(matchCapacity);
+
+ const offset = measureText(
+ textToStart,
+ getFontString(textElement),
+ textElement.lineHeight,
+ );
+
+ // measureText returns a non-zero width for the empty string
+ // which is not what we're after here, hence the check and the correction
+ if (textToStart === "") {
+ offset.width = 0;
+ }
+
+ if (textElement.textAlign !== "left" && lineIndexRange.line.length > 0) {
+ const lineLength = measureText(
+ lineIndexRange.line,
+ getFontString(textElement),
+ textElement.lineHeight,
+ );
+
+ const spaceToStart =
+ textElement.textAlign === "center"
+ ? (textElement.width - lineLength.width) / 2
+ : textElement.width - lineLength.width;
+ offset.width += spaceToStart;
+ }
+
+ const { width, height } = measureText(
+ matchedWord,
+ getFontString(textElement),
+ textElement.lineHeight,
+ );
+
+ const offsetX = offset.width;
+ const offsetY = lineIndexRange.lineNumber * offset.height;
+
+ matchedLines.push({
+ offsetX,
+ offsetY,
+ width,
+ height,
+ });
+
+ startIndex += matchCapacity;
+ }
+ }
+
+ return matchedLines;
+};
+
+const escapeSpecialCharacters = (string: string) => {
+ return string.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&");
+};
+
+const handleSearch = debounce(
+ (
+ searchQuery: SearchQuery,
+ app: AppClassProperties,
+ cb: (matchItems: SearchMatchItem[], focusIndex: number | null) => void,
+ ) => {
+ if (!searchQuery || searchQuery === "") {
+ cb([], null);
+ return;
+ }
+
+ const elements = app.scene.getNonDeletedElements();
+ const texts = elements.filter((el) =>
+ isTextElement(el),
+ ) as ExcalidrawTextElement[];
+
+ texts.sort((a, b) => a.y - b.y);
+
+ const matchItems: SearchMatchItem[] = [];
+
+ const regex = new RegExp(escapeSpecialCharacters(searchQuery), "gi");
+
+ for (const textEl of texts) {
+ let match = null;
+ const text = textEl.originalText;
+
+ while ((match = regex.exec(text)) !== null) {
+ const preview = getMatchPreview(text, match.index, searchQuery);
+ const matchedLines = getMatchedLines(textEl, searchQuery, match.index);
+
+ if (matchedLines.length > 0) {
+ matchItems.push({
+ textElement: textEl,
+ searchQuery,
+ preview,
+ index: match.index,
+ matchedLines,
+ });
+ }
+ }
+ }
+
+ const visibleIds = new Set(
+ app.visibleElements.map((visibleElement) => visibleElement.id),
+ );
+
+ const focusIndex =
+ matchItems.findIndex((matchItem) =>
+ visibleIds.has(matchItem.textElement.id),
+ ) ?? null;
+
+ cb(matchItems, focusIndex);
+ },
+ SEARCH_DEBOUNCE,
+);
diff --git a/packages/excalidraw/components/Section.tsx b/packages/excalidraw/components/Section.tsx
new file mode 100644
index 0000000..8cd0aaa
--- /dev/null
+++ b/packages/excalidraw/components/Section.tsx
@@ -0,0 +1,28 @@
+import React from "react";
+import { t } from "../i18n";
+import { useExcalidrawContainer } from "./App";
+
+export const Section: React.FC<{
+ heading: "canvasActions" | "selectedShapeActions" | "shapes";
+ children?: React.ReactNode | ((heading: React.ReactNode) => React.ReactNode);
+ className?: string;
+}> = ({ heading, children, ...props }) => {
+ const { id } = useExcalidrawContainer();
+ const header = (
+ <h2 className="visually-hidden" id={`${id}-${heading}-title`}>
+ {t(`headings.${heading}`)}
+ </h2>
+ );
+ return (
+ <section {...props} aria-labelledby={`${id}-${heading}-title`}>
+ {typeof children === "function" ? (
+ children(header)
+ ) : (
+ <>
+ {header}
+ {children}
+ </>
+ )}
+ </section>
+ );
+};
diff --git a/packages/excalidraw/components/ShareableLinkDialog.scss b/packages/excalidraw/components/ShareableLinkDialog.scss
new file mode 100644
index 0000000..2bdaaf0
--- /dev/null
+++ b/packages/excalidraw/components/ShareableLinkDialog.scss
@@ -0,0 +1,91 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .ShareableLinkDialog {
+ display: flex;
+ flex-direction: column;
+ gap: 1.5rem;
+
+ color: var(--text-primary-color);
+
+ ::selection {
+ background: var(--color-primary-light-darker);
+ }
+
+ h3 {
+ font-family: "Assistant";
+ font-weight: 700;
+ font-size: 1.313rem;
+ line-height: 130%;
+
+ margin: 0;
+ }
+
+ &__popover {
+ @keyframes ShareableLinkDialog__popover__scaleIn {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+ }
+
+ box-sizing: border-box;
+ z-index: 100;
+
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ align-items: flex-start;
+ padding: 0.125rem 0.5rem;
+ gap: 0.125rem;
+
+ height: 1.125rem;
+
+ border: none;
+ border-radius: 0.6875rem;
+
+ font-family: "Assistant";
+ font-style: normal;
+ font-weight: 600;
+ font-size: 0.75rem;
+ line-height: 110%;
+
+ background: var(--color-success);
+ color: var(--color-success-text);
+
+ & > svg {
+ width: 0.875rem;
+ height: 0.875rem;
+ }
+
+ transform-origin: var(--radix-popover-content-transform-origin);
+ animation: ShareableLinkDialog__popover__scaleIn 150ms ease-out;
+ }
+
+ &__linkRow {
+ display: flex;
+ flex-direction: row;
+ align-items: flex-end;
+ gap: 0.75rem;
+ }
+
+ &__description {
+ border-top: 1px solid var(--color-gray-20);
+
+ padding: 0.5rem 0.5rem 0;
+ font-weight: 400;
+ font-size: 0.75rem;
+ line-height: 150%;
+
+ & p {
+ margin: 0;
+ }
+
+ & p + p {
+ margin-top: 1em;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/ShareableLinkDialog.tsx b/packages/excalidraw/components/ShareableLinkDialog.tsx
new file mode 100644
index 0000000..987c7bf
--- /dev/null
+++ b/packages/excalidraw/components/ShareableLinkDialog.tsx
@@ -0,0 +1,80 @@
+import { useRef, useState } from "react";
+
+import { copyTextToSystemClipboard } from "../clipboard";
+import { useI18n } from "../i18n";
+
+import { Dialog } from "./Dialog";
+import { TextField } from "./TextField";
+import { FilledButton } from "./FilledButton";
+import { useCopyStatus } from "../hooks/useCopiedIndicator";
+import { copyIcon } from "./icons";
+
+import "./ShareableLinkDialog.scss";
+
+export type ShareableLinkDialogProps = {
+ link: string;
+
+ onCloseRequest: () => void;
+ setErrorMessage: (error: string) => void;
+};
+
+export const ShareableLinkDialog = ({
+ link,
+ onCloseRequest,
+ setErrorMessage,
+}: ShareableLinkDialogProps) => {
+ const { t } = useI18n();
+ const [, setJustCopied] = useState(false);
+ const timerRef = useRef<number>(0);
+ const ref = useRef<HTMLInputElement>(null);
+
+ const copyRoomLink = async () => {
+ try {
+ await copyTextToSystemClipboard(link);
+ } catch (e) {
+ setErrorMessage(t("errors.copyToSystemClipboardFailed"));
+ }
+ setJustCopied(true);
+
+ if (timerRef.current) {
+ window.clearTimeout(timerRef.current);
+ }
+
+ timerRef.current = window.setTimeout(() => {
+ setJustCopied(false);
+ }, 3000);
+
+ ref.current?.select();
+ };
+ const { onCopy, copyStatus } = useCopyStatus();
+ return (
+ <Dialog onCloseRequest={onCloseRequest} title={false} size="small">
+ <div className="ShareableLinkDialog">
+ <h3>Shareable link</h3>
+ <div className="ShareableLinkDialog__linkRow">
+ <TextField
+ ref={ref}
+ label="Link"
+ readonly
+ fullWidth
+ value={link}
+ selectOnRender
+ />
+ <FilledButton
+ size="large"
+ label={t("buttons.copyLink")}
+ icon={copyIcon}
+ status={copyStatus}
+ onClick={() => {
+ onCopy();
+ copyRoomLink();
+ }}
+ />
+ </div>
+ <div className="ShareableLinkDialog__description">
+ 🔒 {t("alerts.uploadedSecurly")}
+ </div>
+ </div>
+ </Dialog>
+ );
+};
diff --git a/packages/excalidraw/components/Sidebar/Sidebar.scss b/packages/excalidraw/components/Sidebar/Sidebar.scss
new file mode 100644
index 0000000..c7776d1
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/Sidebar.scss
@@ -0,0 +1,176 @@
+@import "open-color/open-color";
+@import "../../css/variables.module.scss";
+
+.excalidraw {
+ .sidebar {
+ display: flex;
+ flex-direction: column;
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ right: 0;
+ z-index: 5;
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+
+ background-color: var(--sidebar-bg-color);
+ box-shadow: var(--sidebar-shadow);
+
+ pointer-events: var(--ui-pointerEvents);
+
+ :root[dir="rtl"] & {
+ left: 0;
+ right: auto;
+ }
+
+ &--docked {
+ box-shadow: none;
+ }
+
+ overflow: hidden;
+ border-radius: 0;
+ width: calc(var(--right-sidebar-width) - var(--space-factor) * 2);
+
+ border-left: 1px solid var(--sidebar-border-color);
+
+ :root[dir="rtl"] & {
+ border-right: 1px solid var(--sidebar-border-color);
+ border-left: 0;
+ }
+ }
+
+ // ---------------------------- sidebar header ------------------------------
+
+ .sidebar__header {
+ box-sizing: border-box;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ width: 100%;
+ padding: 1rem 0.75rem;
+ position: relative;
+
+ &::after {
+ content: "";
+ width: calc(100% - 1.5rem);
+ height: 1px;
+ background: var(--sidebar-border-color);
+ position: absolute;
+ bottom: -1px;
+ }
+ }
+
+ .sidebar__header__buttons {
+ gap: 0;
+ display: flex;
+ align-items: center;
+ margin-left: auto;
+
+ button {
+ @include outlineButtonStyles;
+ --button-bg: transparent;
+ border: 0 !important;
+
+ width: var(--lg-button-size);
+ height: var(--lg-button-size);
+ padding: 0;
+
+ svg {
+ width: var(--lg-icon-size);
+ height: var(--lg-icon-size);
+ }
+
+ &:hover {
+ background: var(--button-hover-bg, var(--island-bg-color));
+ }
+ }
+
+ .sidebar__dock.selected {
+ svg {
+ stroke: var(--color-primary);
+ fill: var(--color-primary);
+ }
+ }
+ }
+
+ // ---------------------------- sidebar tabs ------------------------------
+
+ .sidebar-tabs-root {
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ padding: 1rem 0;
+
+ [role="tabpanel"] {
+ flex: 1;
+ outline: none;
+
+ flex: 1 1 auto;
+ display: flex;
+ flex-direction: column;
+ outline: none;
+ }
+
+ [role="tabpanel"][data-state="inactive"] {
+ display: none !important;
+ }
+
+ [role="tablist"] {
+ display: grid;
+ gap: 1rem;
+ grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
+ }
+ }
+
+ .sidebar-tabs-root > .sidebar__header {
+ padding-top: 0;
+ padding-bottom: 1rem;
+ }
+
+ .sidebar-tab-trigger {
+ --button-width: auto;
+ --button-bg: transparent;
+ --button-hover-bg: transparent;
+ --button-active-bg: var(--color-primary);
+ --button-hover-color: var(--color-primary);
+ --button-hover-border: var(--color-primary);
+
+ &[data-state="active"] {
+ --button-bg: var(--color-primary);
+ --button-hover-bg: var(--color-primary-darker);
+ --button-hover-color: var(--color-icon-white);
+ --button-border: var(--color-primary);
+ color: var(--color-icon-white);
+ }
+ }
+
+ // ---------------------------- default sidebar ------------------------------
+
+ .default-sidebar {
+ display: flex;
+ flex-direction: column;
+
+ .sidebar-triggers {
+ $padding: 2px;
+ $border: 1px;
+ display: flex;
+ gap: 0;
+ padding: $padding;
+ // offset by padding + border to vertically center the list with sibling
+ // buttons (both from top and bototm, due to flex layout)
+ margin-top: -#{$padding + $border};
+ margin-bottom: -#{$padding + $border};
+ border: $border solid var(--sidebar-border-color);
+ background: var(--default-bg-color);
+ border-radius: 0.625rem;
+
+ .sidebar-tab-trigger {
+ height: var(--lg-button-size);
+ width: var(--lg-button-size);
+
+ border: none;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Sidebar/Sidebar.test.tsx b/packages/excalidraw/components/Sidebar/Sidebar.test.tsx
new file mode 100644
index 0000000..b61529d
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/Sidebar.test.tsx
@@ -0,0 +1,393 @@
+import React from "react";
+import { DEFAULT_SIDEBAR } from "../../constants";
+import { Excalidraw, Sidebar } from "../../index";
+import {
+ act,
+ fireEvent,
+ queryAllByTestId,
+ queryByTestId,
+ render,
+ waitFor,
+ withExcalidrawDimensions,
+} from "../../tests/test-utils";
+import { vi } from "vitest";
+import {
+ assertExcalidrawWithSidebar,
+ assertSidebarDockButton,
+} from "./siderbar.test.helpers";
+
+const toggleSidebar = (
+ ...args: Parameters<typeof window.h.app.toggleSidebar>
+): Promise<boolean> => {
+ return act(() => {
+ return window.h.app.toggleSidebar(...args);
+ });
+};
+
+describe("Sidebar", () => {
+ describe("General behavior", () => {
+ it("should render custom sidebar", async () => {
+ const { container } = await render(
+ <Excalidraw
+ initialData={{ appState: { openSidebar: { name: "customSidebar" } } }}
+ >
+ <Sidebar name="customSidebar">
+ <div id="test-sidebar-content">42</div>
+ </Sidebar>
+ </Excalidraw>,
+ );
+
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).not.toBe(null);
+ });
+
+ it("should render only one sidebar and prefer the custom one", async () => {
+ const { container } = await render(
+ <Excalidraw
+ initialData={{ appState: { openSidebar: { name: "customSidebar" } } }}
+ >
+ <Sidebar name="customSidebar">
+ <div id="test-sidebar-content">42</div>
+ </Sidebar>
+ </Excalidraw>,
+ );
+
+ await waitFor(() => {
+ // make sure the custom sidebar is rendered
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).not.toBe(null);
+
+ // make sure only one sidebar is rendered
+ const sidebars = container.querySelectorAll(".sidebar");
+ expect(sidebars.length).toBe(1);
+ });
+ });
+
+ it("should toggle sidebar using excalidrawAPI.toggleSidebar()", async () => {
+ const { container } = await render(
+ <Excalidraw>
+ <Sidebar name="customSidebar">
+ <div id="test-sidebar-content">42</div>
+ </Sidebar>
+ </Excalidraw>,
+ );
+
+ // sidebar isn't rendered initially
+ // -------------------------------------------------------------------------
+ await waitFor(() => {
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).toBe(null);
+ });
+
+ // toggle sidebar on
+ // -------------------------------------------------------------------------
+ expect(await toggleSidebar({ name: "customSidebar" })).toBe(true);
+
+ await waitFor(() => {
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).not.toBe(null);
+ });
+
+ // toggle sidebar off
+ // -------------------------------------------------------------------------
+ expect(await toggleSidebar({ name: "customSidebar" })).toBe(false);
+
+ await waitFor(() => {
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).toBe(null);
+ });
+
+ // force-toggle sidebar off (=> still hidden)
+ // -------------------------------------------------------------------------
+ expect(await toggleSidebar({ name: "customSidebar", force: false })).toBe(
+ false,
+ );
+
+ await waitFor(() => {
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).toBe(null);
+ });
+
+ // force-toggle sidebar on
+ // -------------------------------------------------------------------------
+ expect(await toggleSidebar({ name: "customSidebar", force: true })).toBe(
+ true,
+ );
+ expect(await toggleSidebar({ name: "customSidebar", force: true })).toBe(
+ true,
+ );
+
+ await waitFor(() => {
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).not.toBe(null);
+ });
+
+ // toggle library (= hide custom sidebar)
+ // -------------------------------------------------------------------------
+ expect(await toggleSidebar({ name: DEFAULT_SIDEBAR.name })).toBe(true);
+
+ await waitFor(() => {
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).toBe(null);
+
+ // make sure only one sidebar is rendered
+ const sidebars = container.querySelectorAll(".sidebar");
+ expect(sidebars.length).toBe(1);
+ });
+
+ // closing sidebar using `{ name: null }`
+ // -------------------------------------------------------------------------
+ expect(await toggleSidebar({ name: "customSidebar" })).toBe(true);
+ await waitFor(() => {
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).not.toBe(null);
+ });
+
+ expect(await toggleSidebar({ name: null })).toBe(false);
+ await waitFor(() => {
+ const node = container.querySelector("#test-sidebar-content");
+ expect(node).toBe(null);
+ });
+ });
+ });
+
+ describe("<Sidebar.Header/>", () => {
+ it("should render custom sidebar header", async () => {
+ const { container } = await render(
+ <Excalidraw
+ initialData={{ appState: { openSidebar: { name: "customSidebar" } } }}
+ >
+ <Sidebar name="customSidebar">
+ <Sidebar.Header>
+ <div id="test-sidebar-header-content">42</div>
+ </Sidebar.Header>
+ </Sidebar>
+ </Excalidraw>,
+ );
+
+ const node = container.querySelector("#test-sidebar-header-content");
+ expect(node).not.toBe(null);
+ // make sure we don't render the default fallback header,
+ // just the custom one
+ expect(queryAllByTestId(container, "sidebar-header").length).toBe(1);
+ });
+
+ it("should not render <Sidebar.Header> for custom sidebars by default", async () => {
+ const CustomExcalidraw = () => {
+ return (
+ <Excalidraw
+ initialData={{
+ appState: { openSidebar: { name: "customSidebar" } },
+ }}
+ >
+ <Sidebar name="customSidebar" className="test-sidebar">
+ hello
+ </Sidebar>
+ </Excalidraw>
+ );
+ };
+
+ const { container } = await render(<CustomExcalidraw />);
+
+ const sidebar = container.querySelector<HTMLElement>(".test-sidebar");
+ expect(sidebar).not.toBe(null);
+ const closeButton = queryByTestId(sidebar!, "sidebar-close");
+ expect(closeButton).toBe(null);
+ });
+
+ it("<Sidebar.Header> should render close button", async () => {
+ const onStateChange = vi.fn();
+ const CustomExcalidraw = () => {
+ return (
+ <Excalidraw
+ initialData={{
+ appState: { openSidebar: { name: "customSidebar" } },
+ }}
+ >
+ <Sidebar
+ name="customSidebar"
+ className="test-sidebar"
+ onStateChange={onStateChange}
+ >
+ <Sidebar.Header />
+ </Sidebar>
+ </Excalidraw>
+ );
+ };
+
+ const { container } = await render(<CustomExcalidraw />);
+
+ // initial open
+ expect(onStateChange).toHaveBeenCalledWith({ name: "customSidebar" });
+
+ const sidebar = container.querySelector<HTMLElement>(".test-sidebar");
+ expect(sidebar).not.toBe(null);
+ const closeButton = queryByTestId(sidebar!, "sidebar-close")!;
+ expect(closeButton).not.toBe(null);
+
+ fireEvent.click(closeButton);
+ await waitFor(() => {
+ expect(container.querySelector<HTMLElement>(".test-sidebar")).toBe(
+ null,
+ );
+ expect(onStateChange).toHaveBeenCalledWith(null);
+ });
+ });
+ });
+
+ describe("Docking behavior", () => {
+ it("shouldn't be user-dockable if `onDock` not supplied", async () => {
+ await assertExcalidrawWithSidebar(
+ <Sidebar name="customSidebar">
+ <Sidebar.Header />
+ </Sidebar>,
+ "customSidebar",
+ async () => {
+ await assertSidebarDockButton(false);
+ },
+ );
+ });
+
+ it("shouldn't be user-dockable if `onDock` not supplied & `docked={true}`", async () => {
+ await assertExcalidrawWithSidebar(
+ <Sidebar name="customSidebar" docked={true}>
+ <Sidebar.Header />
+ </Sidebar>,
+ "customSidebar",
+ async () => {
+ await assertSidebarDockButton(false);
+ },
+ );
+ });
+
+ it("shouldn't be user-dockable if `onDock` not supplied & docked={false}`", async () => {
+ await assertExcalidrawWithSidebar(
+ <Sidebar name="customSidebar" docked={false}>
+ <Sidebar.Header />
+ </Sidebar>,
+ "customSidebar",
+ async () => {
+ await assertSidebarDockButton(false);
+ },
+ );
+ });
+
+ it("should be user-dockable when both `onDock` and `docked` supplied", async () => {
+ await render(
+ <Excalidraw
+ initialData={{ appState: { openSidebar: { name: "customSidebar" } } }}
+ >
+ <Sidebar
+ name="customSidebar"
+ className="test-sidebar"
+ onDock={() => {}}
+ docked
+ >
+ <Sidebar.Header />
+ </Sidebar>
+ </Excalidraw>,
+ );
+
+ await withExcalidrawDimensions(
+ { width: 1920, height: 1080 },
+ async () => {
+ await assertSidebarDockButton(true);
+ },
+ );
+ });
+
+ it("shouldn't be user-dockable when only `onDock` supplied w/o `docked`", async () => {
+ // we expect warnings in this test and don't want to pollute stdout
+ const mock = jest.spyOn(console, "warn").mockImplementation(() => {});
+
+ await render(
+ <Excalidraw
+ initialData={{ appState: { openSidebar: { name: "customSidebar" } } }}
+ >
+ <Sidebar
+ name="customSidebar"
+ className="test-sidebar"
+ onDock={() => {}}
+ >
+ <Sidebar.Header />
+ </Sidebar>
+ </Excalidraw>,
+ );
+
+ await withExcalidrawDimensions(
+ { width: 1920, height: 1080 },
+ async () => {
+ await assertSidebarDockButton(false);
+ },
+ );
+
+ mock.mockRestore();
+ });
+ });
+
+ describe("Sidebar.tab", () => {
+ it("should toggle sidebars tabs correctly", async () => {
+ const { container } = await render(
+ <Excalidraw>
+ <Sidebar name="custom" docked>
+ <Sidebar.Tabs>
+ <Sidebar.Tab tab="library">Library</Sidebar.Tab>
+ <Sidebar.Tab tab="comments">Comments</Sidebar.Tab>
+ </Sidebar.Tabs>
+ </Sidebar>
+ </Excalidraw>,
+ );
+
+ await withExcalidrawDimensions(
+ { width: 1920, height: 1080 },
+ async () => {
+ expect(
+ container.querySelector<HTMLElement>(
+ "[role=tabpanel][data-testid=library]",
+ ),
+ ).toBeNull();
+
+ // open library sidebar
+ expect(await toggleSidebar({ name: "custom", tab: "library" })).toBe(
+ true,
+ );
+ expect(
+ container.querySelector<HTMLElement>(
+ "[role=tabpanel][data-testid=library]",
+ ),
+ ).not.toBeNull();
+
+ // switch to comments tab
+ expect(await toggleSidebar({ name: "custom", tab: "comments" })).toBe(
+ true,
+ );
+ expect(
+ container.querySelector<HTMLElement>(
+ "[role=tabpanel][data-testid=comments]",
+ ),
+ ).not.toBeNull();
+
+ // toggle sidebar closed
+ expect(await toggleSidebar({ name: "custom", tab: "comments" })).toBe(
+ false,
+ );
+ expect(
+ container.querySelector<HTMLElement>(
+ "[role=tabpanel][data-testid=comments]",
+ ),
+ ).toBeNull();
+
+ // toggle sidebar open
+ expect(await toggleSidebar({ name: "custom", tab: "comments" })).toBe(
+ true,
+ );
+ expect(
+ container.querySelector<HTMLElement>(
+ "[role=tabpanel][data-testid=comments]",
+ ),
+ ).not.toBeNull();
+ },
+ );
+ });
+ });
+});
diff --git a/packages/excalidraw/components/Sidebar/Sidebar.tsx b/packages/excalidraw/components/Sidebar/Sidebar.tsx
new file mode 100644
index 0000000..7c747d2
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/Sidebar.tsx
@@ -0,0 +1,213 @@
+import React, {
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ forwardRef,
+ useImperativeHandle,
+ useCallback,
+} from "react";
+import { Island } from "../Island";
+import { atom, useSetAtom } from "../../editor-jotai";
+import type { SidebarProps, SidebarPropsContextValue } from "./common";
+import { SidebarPropsContext } from "./common";
+import { SidebarHeader } from "./SidebarHeader";
+import clsx from "clsx";
+import { useDevice, useExcalidrawSetAppState } from "../App";
+import { updateObject } from "../../utils";
+import { KEYS } from "../../keys";
+import { EVENT } from "../../constants";
+import { SidebarTrigger } from "./SidebarTrigger";
+import { SidebarTabTriggers } from "./SidebarTabTriggers";
+import { SidebarTabTrigger } from "./SidebarTabTrigger";
+import { SidebarTabs } from "./SidebarTabs";
+import { SidebarTab } from "./SidebarTab";
+import { useUIAppState } from "../../context/ui-appState";
+import { useOutsideClick } from "../../hooks/useOutsideClick";
+
+import "./Sidebar.scss";
+
+/**
+ * Flags whether the currently rendered Sidebar is docked or not, for use
+ * in upstream components that need to act on this (e.g. LayerUI to shift the
+ * UI). We use an atom because of potential host app sidebars (for the default
+ * sidebar we could just read from appState.defaultSidebarDockedPreference).
+ *
+ * Since we can only render one Sidebar at a time, we can use a simple flag.
+ */
+export const isSidebarDockedAtom = atom(false);
+
+export const SidebarInner = forwardRef(
+ (
+ {
+ name,
+ children,
+ onDock,
+ docked,
+ className,
+ ...rest
+ }: SidebarProps & Omit<React.RefAttributes<HTMLDivElement>, "onSelect">,
+ ref: React.ForwardedRef<HTMLDivElement>,
+ ) => {
+ if (import.meta.env.DEV && onDock && docked == null) {
+ console.warn(
+ "Sidebar: `docked` must be set when `onDock` is supplied for the sidebar to be user-dockable. To hide this message, either pass `docked` or remove `onDock`",
+ );
+ }
+
+ const setAppState = useExcalidrawSetAppState();
+
+ const setIsSidebarDockedAtom = useSetAtom(isSidebarDockedAtom);
+
+ useLayoutEffect(() => {
+ setIsSidebarDockedAtom(!!docked);
+ return () => {
+ setIsSidebarDockedAtom(false);
+ };
+ }, [setIsSidebarDockedAtom, docked]);
+
+ const headerPropsRef = useRef<SidebarPropsContextValue>(
+ {} as SidebarPropsContextValue,
+ );
+ headerPropsRef.current.onCloseRequest = () => {
+ setAppState({ openSidebar: null });
+ };
+ headerPropsRef.current.onDock = (isDocked) => onDock?.(isDocked);
+ // renew the ref object if the following props change since we want to
+ // rerender. We can't pass down as component props manually because
+ // the <Sidebar.Header/> can be rendered upstream.
+ headerPropsRef.current = updateObject(headerPropsRef.current, {
+ docked,
+ // explicit prop to rerender on update
+ shouldRenderDockButton: !!onDock && docked != null,
+ });
+
+ const islandRef = useRef<HTMLDivElement>(null);
+
+ useImperativeHandle(ref, () => {
+ return islandRef.current!;
+ });
+
+ const device = useDevice();
+
+ const closeLibrary = useCallback(() => {
+ const isDialogOpen = !!document.querySelector(".Dialog");
+
+ // Prevent closing if any dialog is open
+ if (isDialogOpen) {
+ return;
+ }
+ setAppState({ openSidebar: null });
+ }, [setAppState]);
+
+ useOutsideClick(
+ islandRef,
+ useCallback(
+ (event) => {
+ // If click on the library icon, do nothing so that LibraryButton
+ // can toggle library menu
+ if ((event.target as Element).closest(".sidebar-trigger")) {
+ return;
+ }
+ if (!docked || !device.editor.canFitSidebar) {
+ closeLibrary();
+ }
+ },
+ [closeLibrary, docked, device.editor.canFitSidebar],
+ ),
+ );
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (
+ event.key === KEYS.ESCAPE &&
+ (!docked || !device.editor.canFitSidebar)
+ ) {
+ closeLibrary();
+ }
+ };
+ document.addEventListener(EVENT.KEYDOWN, handleKeyDown);
+ return () => {
+ document.removeEventListener(EVENT.KEYDOWN, handleKeyDown);
+ };
+ }, [closeLibrary, docked, device.editor.canFitSidebar]);
+
+ return (
+ <Island
+ {...rest}
+ className={clsx("sidebar", { "sidebar--docked": docked }, className)}
+ ref={islandRef}
+ >
+ <SidebarPropsContext.Provider value={headerPropsRef.current}>
+ {children}
+ </SidebarPropsContext.Provider>
+ </Island>
+ );
+ },
+);
+SidebarInner.displayName = "SidebarInner";
+
+export const Sidebar = Object.assign(
+ forwardRef((props: SidebarProps, ref: React.ForwardedRef<HTMLDivElement>) => {
+ const appState = useUIAppState();
+
+ const { onStateChange } = props;
+
+ const refPrevOpenSidebar = useRef(appState.openSidebar);
+ useEffect(() => {
+ if (
+ // closing sidebar
+ ((!appState.openSidebar &&
+ refPrevOpenSidebar?.current?.name === props.name) ||
+ // opening current sidebar
+ (appState.openSidebar?.name === props.name &&
+ refPrevOpenSidebar?.current?.name !== props.name) ||
+ // switching tabs or switching to a different sidebar
+ refPrevOpenSidebar.current?.name === props.name) &&
+ appState.openSidebar !== refPrevOpenSidebar.current
+ ) {
+ onStateChange?.(
+ appState.openSidebar?.name !== props.name
+ ? null
+ : appState.openSidebar,
+ );
+ }
+ refPrevOpenSidebar.current = appState.openSidebar;
+ }, [appState.openSidebar, onStateChange, props.name]);
+
+ const [mounted, setMounted] = useState(false);
+ useLayoutEffect(() => {
+ setMounted(true);
+ return () => setMounted(false);
+ }, []);
+
+ // We want to render in the next tick (hence `mounted` flag) so that it's
+ // guaranteed to happen after unmount of the previous sidebar (in case the
+ // previous sidebar is mounted after the next one). This is necessary to
+ // prevent flicker of subcomponents that support fallbacks
+ // (e.g. SidebarHeader). This is because we're using flags to determine
+ // whether prefer the fallback component or not (otherwise both will render
+ // initially), and the flag won't be reset in time if the unmount order
+ // it not correct.
+ //
+ // Alternative, and more general solution would be to namespace the fallback
+ // HoC so that state is not shared between subcomponents when the wrapping
+ // component is of the same type (e.g. Sidebar -> SidebarHeader).
+ const shouldRender = mounted && appState.openSidebar?.name === props.name;
+
+ if (!shouldRender) {
+ return null;
+ }
+
+ return <SidebarInner {...props} ref={ref} key={props.name} />;
+ }),
+ {
+ Header: SidebarHeader,
+ TabTriggers: SidebarTabTriggers,
+ TabTrigger: SidebarTabTrigger,
+ Tabs: SidebarTabs,
+ Tab: SidebarTab,
+ Trigger: SidebarTrigger,
+ },
+);
+Sidebar.displayName = "Sidebar";
diff --git a/packages/excalidraw/components/Sidebar/SidebarHeader.tsx b/packages/excalidraw/components/Sidebar/SidebarHeader.tsx
new file mode 100644
index 0000000..6d046ab
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/SidebarHeader.tsx
@@ -0,0 +1,57 @@
+import clsx from "clsx";
+import { useContext } from "react";
+import { t } from "../../i18n";
+import { useDevice } from "../App";
+import { SidebarPropsContext } from "./common";
+import { CloseIcon, PinIcon } from "../icons";
+import { Tooltip } from "../Tooltip";
+import { Button } from "../Button";
+
+export const SidebarHeader = ({
+ children,
+ className,
+}: {
+ children?: React.ReactNode;
+ className?: string;
+}) => {
+ const device = useDevice();
+ const props = useContext(SidebarPropsContext);
+
+ const renderDockButton = !!(
+ device.editor.canFitSidebar && props.shouldRenderDockButton
+ );
+
+ return (
+ <div
+ className={clsx("sidebar__header", className)}
+ data-testid="sidebar-header"
+ >
+ {children}
+ <div className="sidebar__header__buttons">
+ {renderDockButton && (
+ <Tooltip label={t("labels.sidebarLock")}>
+ <Button
+ onSelect={() => props.onDock?.(!props.docked)}
+ selected={!!props.docked}
+ className="sidebar__dock"
+ data-testid="sidebar-dock"
+ aria-label={t("labels.sidebarLock")}
+ >
+ {PinIcon}
+ </Button>
+ </Tooltip>
+ )}
+ <Button
+ data-testid="sidebar-close"
+ className="sidebar__close"
+ onSelect={props.onCloseRequest}
+ aria-label={t("buttons.close")}
+ >
+ {CloseIcon}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+SidebarHeader.displayName = "SidebarHeader";
diff --git a/packages/excalidraw/components/Sidebar/SidebarTab.tsx b/packages/excalidraw/components/Sidebar/SidebarTab.tsx
new file mode 100644
index 0000000..6fddab0
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/SidebarTab.tsx
@@ -0,0 +1,18 @@
+import * as RadixTabs from "@radix-ui/react-tabs";
+import type { SidebarTabName } from "../../types";
+
+export const SidebarTab = ({
+ tab,
+ children,
+ ...rest
+}: {
+ tab: SidebarTabName;
+ children: React.ReactNode;
+} & React.HTMLAttributes<HTMLDivElement>) => {
+ return (
+ <RadixTabs.Content {...rest} value={tab} data-testid={tab}>
+ {children}
+ </RadixTabs.Content>
+ );
+};
+SidebarTab.displayName = "SidebarTab";
diff --git a/packages/excalidraw/components/Sidebar/SidebarTabTrigger.tsx b/packages/excalidraw/components/Sidebar/SidebarTabTrigger.tsx
new file mode 100644
index 0000000..8509ef2
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/SidebarTabTrigger.tsx
@@ -0,0 +1,26 @@
+import * as RadixTabs from "@radix-ui/react-tabs";
+import type { SidebarTabName } from "../../types";
+
+export const SidebarTabTrigger = ({
+ children,
+ tab,
+ onSelect,
+ ...rest
+}: {
+ children: React.ReactNode;
+ tab: SidebarTabName;
+ onSelect?: React.ReactEventHandler<HTMLButtonElement> | undefined;
+} & Omit<React.HTMLAttributes<HTMLButtonElement>, "onSelect">) => {
+ return (
+ <RadixTabs.Trigger value={tab} asChild onSelect={onSelect}>
+ <button
+ type={"button"}
+ className={`excalidraw-button sidebar-tab-trigger`}
+ {...rest}
+ >
+ {children}
+ </button>
+ </RadixTabs.Trigger>
+ );
+};
+SidebarTabTrigger.displayName = "SidebarTabTrigger";
diff --git a/packages/excalidraw/components/Sidebar/SidebarTabTriggers.tsx b/packages/excalidraw/components/Sidebar/SidebarTabTriggers.tsx
new file mode 100644
index 0000000..0be187b
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/SidebarTabTriggers.tsx
@@ -0,0 +1,16 @@
+import * as RadixTabs from "@radix-ui/react-tabs";
+
+export const SidebarTabTriggers = ({
+ children,
+ ...rest
+}: { children: React.ReactNode } & Omit<
+ React.RefAttributes<HTMLDivElement>,
+ "onSelect"
+>) => {
+ return (
+ <RadixTabs.List className="sidebar-triggers" {...rest}>
+ {children}
+ </RadixTabs.List>
+ );
+};
+SidebarTabTriggers.displayName = "SidebarTabTriggers";
diff --git a/packages/excalidraw/components/Sidebar/SidebarTabs.tsx b/packages/excalidraw/components/Sidebar/SidebarTabs.tsx
new file mode 100644
index 0000000..a681b5e
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/SidebarTabs.tsx
@@ -0,0 +1,36 @@
+import * as RadixTabs from "@radix-ui/react-tabs";
+import { useUIAppState } from "../../context/ui-appState";
+import { useExcalidrawSetAppState } from "../App";
+
+export const SidebarTabs = ({
+ children,
+ ...rest
+}: {
+ children: React.ReactNode;
+} & Omit<React.RefAttributes<HTMLDivElement>, "onSelect">) => {
+ const appState = useUIAppState();
+ const setAppState = useExcalidrawSetAppState();
+
+ if (!appState.openSidebar) {
+ return null;
+ }
+
+ const { name } = appState.openSidebar;
+
+ return (
+ <RadixTabs.Root
+ className="sidebar-tabs-root"
+ value={appState.openSidebar.tab}
+ onValueChange={(tab) =>
+ setAppState((state) => ({
+ ...state,
+ openSidebar: { ...state.openSidebar, name, tab },
+ }))
+ }
+ {...rest}
+ >
+ {children}
+ </RadixTabs.Root>
+ );
+};
+SidebarTabs.displayName = "SidebarTabs";
diff --git a/packages/excalidraw/components/Sidebar/SidebarTrigger.scss b/packages/excalidraw/components/Sidebar/SidebarTrigger.scss
new file mode 100644
index 0000000..5b003cd
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/SidebarTrigger.scss
@@ -0,0 +1,38 @@
+@import "../../css/variables.module.scss";
+
+.excalidraw {
+ .sidebar-trigger {
+ @include outlineButtonStyles;
+ @include filledButtonOnCanvas;
+
+ width: auto;
+ height: var(--lg-button-size);
+
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+
+ line-height: 0;
+
+ font-size: 0.75rem;
+ letter-spacing: 0.4px;
+
+ svg {
+ width: var(--lg-icon-size);
+ height: var(--lg-icon-size);
+ }
+
+ &__label-element {
+ align-self: flex-start;
+ }
+ }
+
+ .default-sidebar-trigger .sidebar-trigger__label {
+ display: block;
+ white-space: nowrap;
+ }
+
+ &.excalidraw--mobile .default-sidebar-trigger .sidebar-trigger__label {
+ display: none;
+ }
+}
diff --git a/packages/excalidraw/components/Sidebar/SidebarTrigger.tsx b/packages/excalidraw/components/Sidebar/SidebarTrigger.tsx
new file mode 100644
index 0000000..a26e52d
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/SidebarTrigger.tsx
@@ -0,0 +1,45 @@
+import { useExcalidrawSetAppState } from "../App";
+import type { SidebarTriggerProps } from "./common";
+import { useUIAppState } from "../../context/ui-appState";
+import clsx from "clsx";
+
+import "./SidebarTrigger.scss";
+
+export const SidebarTrigger = ({
+ name,
+ tab,
+ icon,
+ title,
+ children,
+ onToggle,
+ className,
+ style,
+}: SidebarTriggerProps) => {
+ const setAppState = useExcalidrawSetAppState();
+ const appState = useUIAppState();
+
+ return (
+ <label title={title} className="sidebar-trigger__label-element">
+ <input
+ className="ToolIcon_type_checkbox"
+ type="checkbox"
+ onChange={(event) => {
+ document
+ .querySelector(".layer-ui__wrapper")
+ ?.classList.remove("animate");
+ const isOpen = event.target.checked;
+ setAppState({ openSidebar: isOpen ? { name, tab } : null });
+ onToggle?.(isOpen);
+ }}
+ checked={appState.openSidebar?.name === name}
+ aria-label={title}
+ aria-keyshortcuts="0"
+ />
+ <div className={clsx("sidebar-trigger", className)} style={style}>
+ {icon && <div>{icon}</div>}
+ {children && <div className="sidebar-trigger__label">{children}</div>}
+ </div>
+ </label>
+ );
+};
+SidebarTrigger.displayName = "SidebarTrigger";
diff --git a/packages/excalidraw/components/Sidebar/common.ts b/packages/excalidraw/components/Sidebar/common.ts
new file mode 100644
index 0000000..35c0c8b
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/common.ts
@@ -0,0 +1,42 @@
+import type { JSX } from "react";
+import React from "react";
+import type { AppState, SidebarName, SidebarTabName } from "../../types";
+
+export type SidebarTriggerProps = {
+ name: SidebarName;
+ tab?: SidebarTabName;
+ icon?: JSX.Element;
+ children?: React.ReactNode;
+ title?: string;
+ className?: string;
+ onToggle?: (open: boolean) => void;
+ style?: React.CSSProperties;
+};
+
+export type SidebarProps<P = {}> = {
+ name: SidebarName;
+ children: React.ReactNode;
+ /**
+ * Called on sidebar open/close or tab change.
+ */
+ onStateChange?: (state: AppState["openSidebar"]) => void;
+ /**
+ * supply alongside `docked` prop in order to make the Sidebar user-dockable
+ */
+ onDock?: (docked: boolean) => void;
+ docked?: boolean;
+ className?: string;
+ // NOTE sidebars we use internally inside the editor must have this flag set.
+ // It indicates that this sidebar should have lower precedence over host
+ // sidebars, if both are open.
+ /** @private internal */
+ __fallback?: boolean;
+} & P;
+
+export type SidebarPropsContextValue = Pick<
+ SidebarProps,
+ "onDock" | "docked"
+> & { onCloseRequest: () => void; shouldRenderDockButton: boolean };
+
+export const SidebarPropsContext =
+ React.createContext<SidebarPropsContextValue>({} as SidebarPropsContextValue);
diff --git a/packages/excalidraw/components/Sidebar/siderbar.test.helpers.tsx b/packages/excalidraw/components/Sidebar/siderbar.test.helpers.tsx
new file mode 100644
index 0000000..c2a3743
--- /dev/null
+++ b/packages/excalidraw/components/Sidebar/siderbar.test.helpers.tsx
@@ -0,0 +1,42 @@
+import React from "react";
+import { Excalidraw } from "../..";
+import {
+ GlobalTestState,
+ queryByTestId,
+ render,
+ withExcalidrawDimensions,
+} from "../../tests/test-utils";
+
+export const assertSidebarDockButton = async <T extends boolean>(
+ hasDockButton: T,
+): Promise<
+ T extends false
+ ? { dockButton: null; sidebar: HTMLElement }
+ : { dockButton: HTMLElement; sidebar: HTMLElement }
+> => {
+ const sidebar =
+ GlobalTestState.renderResult.container.querySelector<HTMLElement>(
+ ".sidebar",
+ );
+ expect(sidebar).not.toBe(null);
+ const dockButton = queryByTestId(sidebar!, "sidebar-dock");
+ if (hasDockButton) {
+ expect(dockButton).not.toBe(null);
+ return { dockButton: dockButton!, sidebar: sidebar! } as any;
+ }
+ expect(dockButton).toBe(null);
+ return { dockButton: null, sidebar: sidebar! } as any;
+};
+
+export const assertExcalidrawWithSidebar = async (
+ sidebar: React.ReactNode,
+ name: string,
+ test: () => void,
+) => {
+ await render(
+ <Excalidraw initialData={{ appState: { openSidebar: { name } } }}>
+ {sidebar}
+ </Excalidraw>,
+ );
+ await withExcalidrawDimensions({ width: 1920, height: 1080 }, test);
+};
diff --git a/packages/excalidraw/components/Spinner.scss b/packages/excalidraw/components/Spinner.scss
new file mode 100644
index 0000000..e2d90f8
--- /dev/null
+++ b/packages/excalidraw/components/Spinner.scss
@@ -0,0 +1,49 @@
+@import "open-color/open-color.scss";
+
+$duration: 1.6s;
+
+.excalidraw {
+ .Spinner {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ margin-left: auto;
+ margin-right: auto;
+
+ --spinner-color: var(--icon-fill-color);
+
+ svg {
+ animation: rotate $duration linear infinite;
+ animation-delay: var(--spinner-delay);
+ transform-origin: center center;
+ }
+
+ circle {
+ stroke: var(--spinner-color);
+ animation: dash $duration linear 0s infinite;
+ stroke-linecap: round;
+ }
+ }
+
+ @keyframes rotate {
+ 100% {
+ transform: rotate(360deg);
+ }
+ }
+
+ @keyframes dash {
+ 0% {
+ stroke-dasharray: 1, 300;
+ stroke-dashoffset: 0;
+ }
+ 50% {
+ stroke-dasharray: 150, 300;
+ stroke-dashoffset: -200;
+ }
+ 100% {
+ stroke-dasharray: 1, 300;
+ stroke-dashoffset: -280;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Spinner.tsx b/packages/excalidraw/components/Spinner.tsx
new file mode 100644
index 0000000..e8050ca
--- /dev/null
+++ b/packages/excalidraw/components/Spinner.tsx
@@ -0,0 +1,43 @@
+import React from "react";
+
+import "./Spinner.scss";
+
+const Spinner = ({
+ size = "1em",
+ circleWidth = 8,
+ synchronized = false,
+ className = "",
+}: {
+ size?: string | number;
+ circleWidth?: number;
+ synchronized?: boolean;
+ className?: string;
+}) => {
+ const mountTime = React.useRef(Date.now());
+ const mountDelay = -(mountTime.current % 1600);
+
+ return (
+ <div className={`Spinner ${className}`}>
+ <svg
+ viewBox="0 0 100 100"
+ style={{
+ width: size,
+ height: size,
+ // fix for remounting causing spinner flicker
+ ["--spinner-delay" as any]: synchronized ? `${mountDelay}ms` : 0,
+ }}
+ >
+ <circle
+ cx="50"
+ cy="50"
+ r={50 - circleWidth / 2}
+ strokeWidth={circleWidth}
+ fill="none"
+ strokeMiterlimit="10"
+ />
+ </svg>
+ </div>
+ );
+};
+
+export default Spinner;
diff --git a/packages/excalidraw/components/Stack.scss b/packages/excalidraw/components/Stack.scss
new file mode 100644
index 0000000..dc5df76
--- /dev/null
+++ b/packages/excalidraw/components/Stack.scss
@@ -0,0 +1,19 @@
+.excalidraw {
+ .Stack {
+ --gap: 0;
+ display: grid;
+ gap: calc(var(--space-factor) * var(--gap));
+ }
+
+ .Stack_vertical {
+ grid-template-columns: auto;
+ grid-auto-flow: row;
+ grid-auto-rows: min-content;
+ }
+
+ .Stack_horizontal {
+ grid-template-rows: auto;
+ grid-auto-flow: column;
+ grid-auto-columns: min-content;
+ }
+}
diff --git a/packages/excalidraw/components/Stack.tsx b/packages/excalidraw/components/Stack.tsx
new file mode 100644
index 0000000..f45d471
--- /dev/null
+++ b/packages/excalidraw/components/Stack.tsx
@@ -0,0 +1,62 @@
+import "./Stack.scss";
+
+import React, { forwardRef } from "react";
+import clsx from "clsx";
+
+type StackProps = {
+ children: React.ReactNode;
+ gap?: number;
+ align?: "start" | "center" | "end" | "baseline";
+ justifyContent?: "center" | "space-around" | "space-between";
+ className?: string | boolean;
+ style?: React.CSSProperties;
+};
+
+const RowStack = forwardRef(
+ (
+ { children, gap, align, justifyContent, className, style }: StackProps,
+ ref: React.ForwardedRef<HTMLDivElement>,
+ ) => {
+ return (
+ <div
+ className={clsx("Stack Stack_horizontal", className)}
+ style={{
+ "--gap": gap,
+ alignItems: align,
+ justifyContent,
+ ...style,
+ }}
+ ref={ref}
+ >
+ {children}
+ </div>
+ );
+ },
+);
+
+const ColStack = forwardRef(
+ (
+ { children, gap, align, justifyContent, className, style }: StackProps,
+ ref: React.ForwardedRef<HTMLDivElement>,
+ ) => {
+ return (
+ <div
+ className={clsx("Stack Stack_vertical", className)}
+ style={{
+ "--gap": gap,
+ justifyItems: align,
+ justifyContent,
+ ...style,
+ }}
+ ref={ref}
+ >
+ {children}
+ </div>
+ );
+ },
+);
+
+export default {
+ Row: RowStack,
+ Col: ColStack,
+};
diff --git a/packages/excalidraw/components/Stats/Angle.tsx b/packages/excalidraw/components/Stats/Angle.tsx
new file mode 100644
index 0000000..409476a
--- /dev/null
+++ b/packages/excalidraw/components/Stats/Angle.tsx
@@ -0,0 +1,95 @@
+import { mutateElement } from "../../element/mutateElement";
+import { getBoundTextElement } from "../../element/textElement";
+import { isArrowElement, isElbowArrow } from "../../element/typeChecks";
+import type { ExcalidrawElement } from "../../element/types";
+import { angleIcon } from "../icons";
+import DragInput from "./DragInput";
+import type { DragInputCallbackType } from "./DragInput";
+import { getStepSizedValue, isPropertyEditable, updateBindings } from "./utils";
+import type Scene from "../../scene/Scene";
+import type { AppState } from "../../types";
+import type { Degrees } from "@excalidraw/math";
+import { degreesToRadians, radiansToDegrees } from "@excalidraw/math";
+
+interface AngleProps {
+ element: ExcalidrawElement;
+ scene: Scene;
+ appState: AppState;
+ property: "angle";
+}
+
+const STEP_SIZE = 15;
+
+const handleDegreeChange: DragInputCallbackType<AngleProps["property"]> = ({
+ accumulatedChange,
+ originalElements,
+ shouldChangeByStepSize,
+ nextValue,
+ scene,
+}) => {
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const elements = scene.getNonDeletedElements();
+ const origElement = originalElements[0];
+ if (origElement && !isElbowArrow(origElement)) {
+ const latestElement = elementsMap.get(origElement.id);
+ if (!latestElement) {
+ return;
+ }
+
+ if (nextValue !== undefined) {
+ const nextAngle = degreesToRadians(nextValue as Degrees);
+ mutateElement(latestElement, {
+ angle: nextAngle,
+ });
+ updateBindings(latestElement, elementsMap, elements, scene);
+
+ const boundTextElement = getBoundTextElement(latestElement, elementsMap);
+ if (boundTextElement && !isArrowElement(latestElement)) {
+ mutateElement(boundTextElement, { angle: nextAngle });
+ }
+
+ return;
+ }
+
+ const originalAngleInDegrees =
+ Math.round(radiansToDegrees(origElement.angle) * 100) / 100;
+ const changeInDegrees = Math.round(accumulatedChange);
+ let nextAngleInDegrees = (originalAngleInDegrees + changeInDegrees) % 360;
+ if (shouldChangeByStepSize) {
+ nextAngleInDegrees = getStepSizedValue(nextAngleInDegrees, STEP_SIZE);
+ }
+
+ nextAngleInDegrees =
+ nextAngleInDegrees < 0 ? nextAngleInDegrees + 360 : nextAngleInDegrees;
+
+ const nextAngle = degreesToRadians(nextAngleInDegrees as Degrees);
+
+ mutateElement(latestElement, {
+ angle: nextAngle,
+ });
+ updateBindings(latestElement, elementsMap, elements, scene);
+
+ const boundTextElement = getBoundTextElement(latestElement, elementsMap);
+ if (boundTextElement && !isArrowElement(latestElement)) {
+ mutateElement(boundTextElement, { angle: nextAngle });
+ }
+ }
+};
+
+const Angle = ({ element, scene, appState, property }: AngleProps) => {
+ return (
+ <DragInput
+ label="A"
+ icon={angleIcon}
+ value={Math.round((radiansToDegrees(element.angle) % 360) * 100) / 100}
+ elements={[element]}
+ dragInputCallback={handleDegreeChange}
+ editable={isPropertyEditable(element, "angle")}
+ scene={scene}
+ appState={appState}
+ property={property}
+ />
+ );
+};
+
+export default Angle;
diff --git a/packages/excalidraw/components/Stats/CanvasGrid.tsx b/packages/excalidraw/components/Stats/CanvasGrid.tsx
new file mode 100644
index 0000000..a08f709
--- /dev/null
+++ b/packages/excalidraw/components/Stats/CanvasGrid.tsx
@@ -0,0 +1,67 @@
+import StatsDragInput from "./DragInput";
+import type Scene from "../../scene/Scene";
+import type { AppState } from "../../types";
+import { getStepSizedValue } from "./utils";
+import { getNormalizedGridStep } from "../../scene";
+
+interface PositionProps {
+ property: "gridStep";
+ scene: Scene;
+ appState: AppState;
+ setAppState: React.Component<any, AppState>["setState"];
+}
+
+const STEP_SIZE = 5;
+
+const CanvasGrid = ({
+ property,
+ scene,
+ appState,
+ setAppState,
+}: PositionProps) => {
+ return (
+ <StatsDragInput
+ label="Grid step"
+ sensitivity={8}
+ elements={[]}
+ dragInputCallback={({
+ nextValue,
+ instantChange,
+ shouldChangeByStepSize,
+ setInputValue,
+ }) => {
+ setAppState((state) => {
+ let nextGridStep;
+
+ if (nextValue) {
+ nextGridStep = nextValue;
+ } else if (instantChange) {
+ nextGridStep = shouldChangeByStepSize
+ ? getStepSizedValue(
+ state.gridStep + STEP_SIZE * Math.sign(instantChange),
+ STEP_SIZE,
+ )
+ : state.gridStep + instantChange;
+ }
+
+ if (!nextGridStep) {
+ setInputValue(state.gridStep);
+ return null;
+ }
+
+ nextGridStep = getNormalizedGridStep(nextGridStep);
+ setInputValue(nextGridStep);
+ return {
+ gridStep: nextGridStep,
+ };
+ });
+ }}
+ scene={scene}
+ value={appState.gridStep}
+ property={property}
+ appState={appState}
+ />
+ );
+};
+
+export default CanvasGrid;
diff --git a/packages/excalidraw/components/Stats/Collapsible.tsx b/packages/excalidraw/components/Stats/Collapsible.tsx
new file mode 100644
index 0000000..13d476d
--- /dev/null
+++ b/packages/excalidraw/components/Stats/Collapsible.tsx
@@ -0,0 +1,46 @@
+import { InlineIcon } from "../InlineIcon";
+import { collapseDownIcon, collapseUpIcon } from "../icons";
+
+interface CollapsibleProps {
+ label: React.ReactNode;
+ // having it controlled so that the state is managed outside
+ // this is to keep the user's previous choice even when the
+ // Collapsible is unmounted
+ open: boolean;
+ openTrigger: () => void;
+ children: React.ReactNode;
+ className?: string;
+}
+
+const Collapsible = ({
+ label,
+ open,
+ openTrigger,
+ children,
+ className,
+}: CollapsibleProps) => {
+ return (
+ <>
+ <div
+ style={{
+ cursor: "pointer",
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ }}
+ className={className}
+ onClick={openTrigger}
+ >
+ {label}
+ <InlineIcon icon={open ? collapseUpIcon : collapseDownIcon} />
+ </div>
+ {open && (
+ <div style={{ display: "flex", flexDirection: "column" }}>
+ {children}
+ </div>
+ )}
+ </>
+ );
+};
+
+export default Collapsible;
diff --git a/packages/excalidraw/components/Stats/Dimension.tsx b/packages/excalidraw/components/Stats/Dimension.tsx
new file mode 100644
index 0000000..ce096d2
--- /dev/null
+++ b/packages/excalidraw/components/Stats/Dimension.tsx
@@ -0,0 +1,272 @@
+import type { ExcalidrawElement } from "../../element/types";
+import DragInput from "./DragInput";
+import type { DragInputCallbackType } from "./DragInput";
+import { getStepSizedValue, isPropertyEditable } from "./utils";
+import { MIN_WIDTH_OR_HEIGHT } from "../../constants";
+import { resizeSingleElement } from "../../element/resizeElements";
+import type Scene from "../../scene/Scene";
+import type { AppState } from "../../types";
+import { isImageElement } from "../../element/typeChecks";
+import {
+ MINIMAL_CROP_SIZE,
+ getUncroppedWidthAndHeight,
+} from "../../element/cropElement";
+import { mutateElement } from "../../element/mutateElement";
+import { clamp, round } from "@excalidraw/math";
+
+interface DimensionDragInputProps {
+ property: "width" | "height";
+ element: ExcalidrawElement;
+ scene: Scene;
+ appState: AppState;
+}
+
+const STEP_SIZE = 10;
+const _shouldKeepAspectRatio = (element: ExcalidrawElement) => {
+ return element.type === "image";
+};
+
+const handleDimensionChange: DragInputCallbackType<
+ DimensionDragInputProps["property"]
+> = ({
+ accumulatedChange,
+ originalElements,
+ originalElementsMap,
+ shouldKeepAspectRatio,
+ shouldChangeByStepSize,
+ nextValue,
+ property,
+ originalAppState,
+ instantChange,
+ scene,
+}) => {
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const origElement = originalElements[0];
+ const latestElement = elementsMap.get(origElement.id);
+ if (origElement && latestElement) {
+ const keepAspectRatio =
+ shouldKeepAspectRatio || _shouldKeepAspectRatio(origElement);
+ const aspectRatio = origElement.width / origElement.height;
+
+ if (originalAppState.croppingElementId === origElement.id) {
+ const element = elementsMap.get(origElement.id);
+
+ if (!element || !isImageElement(element) || !element.crop) {
+ return;
+ }
+
+ const crop = element.crop;
+ let nextCrop = { ...crop };
+
+ const isFlippedByX = element.scale[0] === -1;
+ const isFlippedByY = element.scale[1] === -1;
+
+ const { width: uncroppedWidth, height: uncroppedHeight } =
+ getUncroppedWidthAndHeight(element);
+
+ const naturalToUncroppedWidthRatio = crop.naturalWidth / uncroppedWidth;
+ const naturalToUncroppedHeightRatio =
+ crop.naturalHeight / uncroppedHeight;
+
+ const MAX_POSSIBLE_WIDTH = isFlippedByX
+ ? crop.width + crop.x
+ : crop.naturalWidth - crop.x;
+
+ const MAX_POSSIBLE_HEIGHT = isFlippedByY
+ ? crop.height + crop.y
+ : crop.naturalHeight - crop.y;
+
+ const MIN_WIDTH = MINIMAL_CROP_SIZE * naturalToUncroppedWidthRatio;
+ const MIN_HEIGHT = MINIMAL_CROP_SIZE * naturalToUncroppedHeightRatio;
+
+ if (nextValue !== undefined) {
+ if (property === "width") {
+ const nextValueInNatural = nextValue * naturalToUncroppedWidthRatio;
+
+ const nextCropWidth = clamp(
+ nextValueInNatural,
+ MIN_WIDTH,
+ MAX_POSSIBLE_WIDTH,
+ );
+
+ nextCrop = {
+ ...nextCrop,
+ width: nextCropWidth,
+ x: isFlippedByX ? crop.x + crop.width - nextCropWidth : crop.x,
+ };
+ } else if (property === "height") {
+ const nextValueInNatural = nextValue * naturalToUncroppedHeightRatio;
+ const nextCropHeight = clamp(
+ nextValueInNatural,
+ MIN_HEIGHT,
+ MAX_POSSIBLE_HEIGHT,
+ );
+
+ nextCrop = {
+ ...nextCrop,
+ height: nextCropHeight,
+ y: isFlippedByY ? crop.y + crop.height - nextCropHeight : crop.y,
+ };
+ }
+
+ mutateElement(element, {
+ crop: nextCrop,
+ width: nextCrop.width / (crop.naturalWidth / uncroppedWidth),
+ height: nextCrop.height / (crop.naturalHeight / uncroppedHeight),
+ });
+ return;
+ }
+
+ const changeInWidth = property === "width" ? instantChange : 0;
+ const changeInHeight = property === "height" ? instantChange : 0;
+
+ const nextCropWidth = clamp(
+ crop.width + changeInWidth,
+ MIN_WIDTH,
+ MAX_POSSIBLE_WIDTH,
+ );
+
+ const nextCropHeight = clamp(
+ crop.height + changeInHeight,
+ MIN_WIDTH,
+ MAX_POSSIBLE_HEIGHT,
+ );
+
+ nextCrop = {
+ ...crop,
+ x: isFlippedByX ? crop.x + crop.width - nextCropWidth : crop.x,
+ y: isFlippedByY ? crop.y + crop.height - nextCropHeight : crop.y,
+ width: nextCropWidth,
+ height: nextCropHeight,
+ };
+
+ mutateElement(element, {
+ crop: nextCrop,
+ width: nextCrop.width / (crop.naturalWidth / uncroppedWidth),
+ height: nextCrop.height / (crop.naturalHeight / uncroppedHeight),
+ });
+
+ return;
+ }
+
+ if (nextValue !== undefined) {
+ const nextWidth = Math.max(
+ property === "width"
+ ? nextValue
+ : keepAspectRatio
+ ? nextValue * aspectRatio
+ : origElement.width,
+ MIN_WIDTH_OR_HEIGHT,
+ );
+ const nextHeight = Math.max(
+ property === "height"
+ ? nextValue
+ : keepAspectRatio
+ ? nextValue / aspectRatio
+ : origElement.height,
+ MIN_WIDTH_OR_HEIGHT,
+ );
+
+ resizeSingleElement(
+ nextWidth,
+ nextHeight,
+ latestElement,
+ origElement,
+ elementsMap,
+ originalElementsMap,
+ property === "width" ? "e" : "s",
+ {
+ shouldMaintainAspectRatio: keepAspectRatio,
+ },
+ );
+
+ return;
+ }
+ const changeInWidth = property === "width" ? accumulatedChange : 0;
+ const changeInHeight = property === "height" ? accumulatedChange : 0;
+
+ let nextWidth = Math.max(0, origElement.width + changeInWidth);
+ if (property === "width") {
+ if (shouldChangeByStepSize) {
+ nextWidth = getStepSizedValue(nextWidth, STEP_SIZE);
+ } else {
+ nextWidth = Math.round(nextWidth);
+ }
+ }
+
+ let nextHeight = Math.max(0, origElement.height + changeInHeight);
+ if (property === "height") {
+ if (shouldChangeByStepSize) {
+ nextHeight = getStepSizedValue(nextHeight, STEP_SIZE);
+ } else {
+ nextHeight = Math.round(nextHeight);
+ }
+ }
+
+ if (keepAspectRatio) {
+ if (property === "width") {
+ nextHeight = Math.round((nextWidth / aspectRatio) * 100) / 100;
+ } else {
+ nextWidth = Math.round(nextHeight * aspectRatio * 100) / 100;
+ }
+ }
+
+ nextHeight = Math.max(MIN_WIDTH_OR_HEIGHT, nextHeight);
+ nextWidth = Math.max(MIN_WIDTH_OR_HEIGHT, nextWidth);
+
+ resizeSingleElement(
+ nextWidth,
+ nextHeight,
+ latestElement,
+ origElement,
+ elementsMap,
+ originalElementsMap,
+ property === "width" ? "e" : "s",
+ {
+ shouldMaintainAspectRatio: keepAspectRatio,
+ },
+ );
+ }
+};
+
+const DimensionDragInput = ({
+ property,
+ element,
+ scene,
+ appState,
+}: DimensionDragInputProps) => {
+ let value = round(property === "width" ? element.width : element.height, 2);
+
+ if (
+ appState.croppingElementId &&
+ appState.croppingElementId === element.id &&
+ isImageElement(element) &&
+ element.crop
+ ) {
+ const { width: uncroppedWidth, height: uncroppedHeight } =
+ getUncroppedWidthAndHeight(element);
+ if (property === "width") {
+ const ratio = uncroppedWidth / element.crop.naturalWidth;
+ value = round(element.crop.width * ratio, 2);
+ }
+ if (property === "height") {
+ const ratio = uncroppedHeight / element.crop.naturalHeight;
+ value = round(element.crop.height * ratio, 2);
+ }
+ }
+
+ return (
+ <DragInput
+ label={property === "width" ? "W" : "H"}
+ elements={[element]}
+ dragInputCallback={handleDimensionChange}
+ value={value}
+ editable={isPropertyEditable(element, property)}
+ scene={scene}
+ appState={appState}
+ property={property}
+ />
+ );
+};
+
+export default DimensionDragInput;
diff --git a/packages/excalidraw/components/Stats/DragInput.scss b/packages/excalidraw/components/Stats/DragInput.scss
new file mode 100644
index 0000000..76b9d14
--- /dev/null
+++ b/packages/excalidraw/components/Stats/DragInput.scss
@@ -0,0 +1,76 @@
+.excalidraw {
+ .drag-input-container {
+ display: flex;
+ width: 100%;
+
+ &:focus-within {
+ box-shadow: 0 0 0 1px var(--color-primary-darkest);
+ border-radius: var(--border-radius-md);
+ }
+ }
+
+ .disabled {
+ opacity: 0.5;
+ pointer-events: none;
+ }
+
+ .drag-input-label {
+ flex-shrink: 0;
+ border: 1px solid var(--default-border-color);
+ border-right: 0;
+ padding: 0 0.5rem 0 0.75rem;
+ min-width: 1rem;
+ height: 2rem;
+ box-sizing: border-box;
+ color: var(--popup-text-color);
+
+ :root[dir="ltr"] & {
+ border-radius: var(--border-radius-md) 0 0 var(--border-radius-md);
+ }
+
+ :root[dir="rtl"] & {
+ border-radius: 0 var(--border-radius-md) var(--border-radius-md) 0;
+ border-right: 1px solid var(--default-border-color);
+ border-left: 0;
+ }
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ }
+
+ .drag-input {
+ box-sizing: border-box;
+ width: 100%;
+ margin: 0;
+ font-size: 0.875rem;
+ font-family: inherit;
+ background-color: transparent;
+ color: var(--text-primary-color);
+ border: 0;
+ outline: none;
+ height: 2rem;
+ border: 1px solid var(--default-border-color);
+ border-left: 0;
+ letter-spacing: 0.4px;
+
+ :root[dir="ltr"] & {
+ border-radius: 0 var(--border-radius-md) var(--border-radius-md) 0;
+ }
+
+ :root[dir="rtl"] & {
+ border-radius: var(--border-radius-md) 0 0 var(--border-radius-md);
+ border-left: 1px solid var(--default-border-color);
+ border-right: 0;
+ }
+
+ padding: 0.5rem;
+ padding-left: 0.25rem;
+ appearance: none;
+
+ &:focus-visible {
+ box-shadow: none;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Stats/DragInput.tsx b/packages/excalidraw/components/Stats/DragInput.tsx
new file mode 100644
index 0000000..82d6419
--- /dev/null
+++ b/packages/excalidraw/components/Stats/DragInput.tsx
@@ -0,0 +1,355 @@
+import { useEffect, useRef, useState } from "react";
+import { EVENT } from "../../constants";
+import { KEYS } from "../../keys";
+import type { ElementsMap, ExcalidrawElement } from "../../element/types";
+import { deepCopyElement } from "../../element/newElement";
+import clsx from "clsx";
+import { useApp } from "../App";
+import { InlineIcon } from "../InlineIcon";
+import type { StatsInputProperty } from "./utils";
+import { SMALLEST_DELTA } from "./utils";
+import { CaptureUpdateAction } from "../../store";
+import type Scene from "../../scene/Scene";
+
+import "./DragInput.scss";
+import type { AppState } from "../../types";
+import { cloneJSON } from "../../utils";
+
+export type DragInputCallbackType<
+ P extends StatsInputProperty,
+ E = ExcalidrawElement,
+> = (props: {
+ accumulatedChange: number;
+ instantChange: number;
+ originalElements: readonly E[];
+ originalElementsMap: ElementsMap;
+ shouldKeepAspectRatio: boolean;
+ shouldChangeByStepSize: boolean;
+ scene: Scene;
+ nextValue?: number;
+ property: P;
+ originalAppState: AppState;
+ setInputValue: (value: number) => void;
+}) => void;
+
+interface StatsDragInputProps<
+ T extends StatsInputProperty,
+ E = ExcalidrawElement,
+> {
+ label: string | React.ReactNode;
+ icon?: React.ReactNode;
+ value: number | "Mixed";
+ elements: readonly E[];
+ editable?: boolean;
+ shouldKeepAspectRatio?: boolean;
+ dragInputCallback: DragInputCallbackType<T, E>;
+ property: T;
+ scene: Scene;
+ appState: AppState;
+ /** how many px you need to drag to get 1 unit change */
+ sensitivity?: number;
+}
+
+const StatsDragInput = <
+ T extends StatsInputProperty,
+ E extends ExcalidrawElement = ExcalidrawElement,
+>({
+ label,
+ icon,
+ dragInputCallback,
+ value,
+ elements,
+ editable = true,
+ shouldKeepAspectRatio,
+ property,
+ scene,
+ appState,
+ sensitivity = 1,
+}: StatsDragInputProps<T, E>) => {
+ const app = useApp();
+ const inputRef = useRef<HTMLInputElement>(null);
+ const labelRef = useRef<HTMLDivElement>(null);
+
+ const [inputValue, setInputValue] = useState(value.toString());
+
+ const stateRef = useRef<{
+ originalAppState: AppState;
+ originalElements: readonly E[];
+ lastUpdatedValue: string;
+ updatePending: boolean;
+ }>(null!);
+ if (!stateRef.current) {
+ stateRef.current = {
+ originalAppState: cloneJSON(appState),
+ originalElements: elements,
+ lastUpdatedValue: inputValue,
+ updatePending: false,
+ };
+ }
+
+ useEffect(() => {
+ const inputValue = value.toString();
+ setInputValue(inputValue);
+ stateRef.current.lastUpdatedValue = inputValue;
+ }, [value]);
+
+ const handleInputValue = (
+ updatedValue: string,
+ elements: readonly E[],
+ appState: AppState,
+ ) => {
+ if (!stateRef.current.updatePending) {
+ return false;
+ }
+ stateRef.current.updatePending = false;
+
+ const parsed = Number(updatedValue);
+ if (isNaN(parsed)) {
+ setInputValue(value.toString());
+ return;
+ }
+
+ const rounded = Number(parsed.toFixed(2));
+ const original = Number(value);
+
+ // only update when
+ // 1. original was "Mixed" and we have a new value
+ // 2. original was not "Mixed" and the difference between a new value and previous value is greater
+ // than the smallest delta allowed, which is 0.01
+ // reason: idempotent to avoid unnecessary
+ if (isNaN(original) || Math.abs(rounded - original) >= SMALLEST_DELTA) {
+ stateRef.current.lastUpdatedValue = updatedValue;
+ dragInputCallback({
+ accumulatedChange: 0,
+ instantChange: 0,
+ originalElements: elements,
+ originalElementsMap: app.scene.getNonDeletedElementsMap(),
+ shouldKeepAspectRatio: shouldKeepAspectRatio!!,
+ shouldChangeByStepSize: false,
+ scene,
+ nextValue: rounded,
+ property,
+ originalAppState: appState,
+ setInputValue: (value) => setInputValue(String(value)),
+ });
+ app.syncActionResult({
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+ }
+ };
+
+ const callbacksRef = useRef<
+ Partial<{
+ handleInputValue: typeof handleInputValue;
+ onPointerUp: (event: PointerEvent) => void;
+ onPointerMove: (event: PointerEvent) => void;
+ }>
+ >({});
+ callbacksRef.current.handleInputValue = handleInputValue;
+
+ // make sure that clicking on canvas (which umounts the component)
+ // updates current input value (blur isn't triggered)
+ useEffect(() => {
+ const input = inputRef.current;
+ const callbacks = callbacksRef.current;
+ return () => {
+ const nextValue = input?.value;
+ if (nextValue) {
+ callbacks.handleInputValue?.(
+ nextValue,
+ stateRef.current.originalElements,
+ stateRef.current.originalAppState,
+ );
+ }
+
+ // generally not needed, but in case `pointerup` doesn't fire and
+ // we don't remove the listeners that way, we should at least remove
+ // on unmount
+ window.removeEventListener(
+ EVENT.POINTER_MOVE,
+ callbacks.onPointerMove!,
+ false,
+ );
+ window.removeEventListener(
+ EVENT.POINTER_UP,
+ callbacks.onPointerUp!,
+ false,
+ );
+ };
+ }, [
+ // we need to track change of `editable` state as mount/unmount
+ // because react doesn't trigger `blur` when a an input is blurred due
+ // to being disabled (https://github.com/facebook/react/issues/9142).
+ // As such, if we keep rendering disabled inputs, then change in selection
+ // to an element that has a given property as non-editable would not trigger
+ // blur/unmount and wouldn't update the value.
+ editable,
+ ]);
+
+ if (!editable) {
+ return null;
+ }
+
+ return (
+ <div
+ className={clsx("drag-input-container", !editable && "disabled")}
+ data-testid={label}
+ >
+ <div
+ className="drag-input-label"
+ ref={labelRef}
+ onPointerDown={(event) => {
+ if (inputRef.current && editable) {
+ document.body.classList.add("excalidraw-cursor-resize");
+
+ let startValue = Number(inputRef.current.value);
+ if (isNaN(startValue)) {
+ startValue = 0;
+ }
+
+ let lastPointer: {
+ x: number;
+ y: number;
+ } | null = null;
+
+ let originalElementsMap: Map<string, ExcalidrawElement> | null =
+ app.scene
+ .getNonDeletedElements()
+ .reduce((acc: ElementsMap, element) => {
+ acc.set(element.id, deepCopyElement(element));
+ return acc;
+ }, new Map());
+
+ let originalElements: readonly E[] | null = elements.map(
+ (element) => originalElementsMap!.get(element.id) as E,
+ );
+
+ const originalAppState: AppState = cloneJSON(appState);
+
+ let accumulatedChange = 0;
+ let stepChange = 0;
+
+ const onPointerMove = (event: PointerEvent) => {
+ if (
+ lastPointer &&
+ originalElementsMap !== null &&
+ originalElements !== null
+ ) {
+ const instantChange = event.clientX - lastPointer.x;
+
+ if (instantChange !== 0) {
+ stepChange += instantChange;
+
+ if (Math.abs(stepChange) >= sensitivity) {
+ stepChange =
+ Math.sign(stepChange) *
+ Math.floor(Math.abs(stepChange) / sensitivity);
+
+ accumulatedChange += stepChange;
+
+ dragInputCallback({
+ accumulatedChange,
+ instantChange: stepChange,
+ originalElements,
+ originalElementsMap,
+ shouldKeepAspectRatio: shouldKeepAspectRatio!!,
+ shouldChangeByStepSize: event.shiftKey,
+ property,
+ scene,
+ originalAppState,
+ setInputValue: (value) => setInputValue(String(value)),
+ });
+
+ stepChange = 0;
+ }
+ }
+ }
+
+ lastPointer = {
+ x: event.clientX,
+ y: event.clientY,
+ };
+ };
+
+ const onPointerUp = () => {
+ window.removeEventListener(
+ EVENT.POINTER_MOVE,
+ onPointerMove,
+ false,
+ );
+
+ app.syncActionResult({
+ captureUpdate: CaptureUpdateAction.IMMEDIATELY,
+ });
+
+ lastPointer = null;
+ accumulatedChange = 0;
+ stepChange = 0;
+ originalElements = null;
+ originalElementsMap = null;
+
+ document.body.classList.remove("excalidraw-cursor-resize");
+
+ window.removeEventListener(EVENT.POINTER_UP, onPointerUp, false);
+ };
+
+ callbacksRef.current.onPointerMove = onPointerMove;
+ callbacksRef.current.onPointerUp = onPointerUp;
+
+ window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, false);
+ window.addEventListener(EVENT.POINTER_UP, onPointerUp, false);
+ }
+ }}
+ onPointerEnter={() => {
+ if (labelRef.current) {
+ labelRef.current.style.cursor = "ew-resize";
+ }
+ }}
+ >
+ {icon ? <InlineIcon icon={icon} /> : label}
+ </div>
+ <input
+ className="drag-input"
+ autoComplete="off"
+ spellCheck="false"
+ onKeyDown={(event) => {
+ if (editable) {
+ const eventTarget = event.target;
+ if (
+ eventTarget instanceof HTMLInputElement &&
+ event.key === KEYS.ENTER
+ ) {
+ handleInputValue(eventTarget.value, elements, appState);
+ app.focusContainer();
+ }
+ }
+ }}
+ ref={inputRef}
+ value={inputValue}
+ onChange={(event) => {
+ stateRef.current.updatePending = true;
+ setInputValue(event.target.value);
+ }}
+ onFocus={(event) => {
+ event.target.select();
+ stateRef.current.originalElements = elements;
+ stateRef.current.originalAppState = cloneJSON(appState);
+ }}
+ onBlur={(event) => {
+ if (!inputValue) {
+ setInputValue(value.toString());
+ } else if (editable) {
+ handleInputValue(
+ event.target.value,
+ stateRef.current.originalElements,
+ stateRef.current.originalAppState,
+ );
+ }
+ }}
+ disabled={!editable}
+ />
+ </div>
+ );
+};
+
+export default StatsDragInput;
diff --git a/packages/excalidraw/components/Stats/FontSize.tsx b/packages/excalidraw/components/Stats/FontSize.tsx
new file mode 100644
index 0000000..13dc6db
--- /dev/null
+++ b/packages/excalidraw/components/Stats/FontSize.tsx
@@ -0,0 +1,99 @@
+import type {
+ ExcalidrawElement,
+ ExcalidrawTextElement,
+} from "../../element/types";
+import StatsDragInput from "./DragInput";
+import type { DragInputCallbackType } from "./DragInput";
+import { mutateElement } from "../../element/mutateElement";
+import { getStepSizedValue } from "./utils";
+import { fontSizeIcon } from "../icons";
+import type Scene from "../../scene/Scene";
+import type { AppState } from "../../types";
+import { isTextElement, redrawTextBoundingBox } from "../../element";
+import { hasBoundTextElement } from "../../element/typeChecks";
+import { getBoundTextElement } from "../../element/textElement";
+
+interface FontSizeProps {
+ element: ExcalidrawElement;
+ scene: Scene;
+ appState: AppState;
+ property: "fontSize";
+}
+
+const MIN_FONT_SIZE = 4;
+const STEP_SIZE = 4;
+
+const handleFontSizeChange: DragInputCallbackType<
+ FontSizeProps["property"],
+ ExcalidrawTextElement
+> = ({
+ accumulatedChange,
+ originalElements,
+ shouldChangeByStepSize,
+ nextValue,
+ scene,
+}) => {
+ const elementsMap = scene.getNonDeletedElementsMap();
+
+ const origElement = originalElements[0];
+ if (origElement) {
+ const latestElement = elementsMap.get(origElement.id);
+ if (!latestElement || !isTextElement(latestElement)) {
+ return;
+ }
+
+ let nextFontSize;
+
+ if (nextValue !== undefined) {
+ nextFontSize = Math.max(Math.round(nextValue), MIN_FONT_SIZE);
+ } else if (origElement.type === "text") {
+ const originalFontSize = Math.round(origElement.fontSize);
+ const changeInFontSize = Math.round(accumulatedChange);
+ nextFontSize = Math.max(
+ originalFontSize + changeInFontSize,
+ MIN_FONT_SIZE,
+ );
+ if (shouldChangeByStepSize) {
+ nextFontSize = getStepSizedValue(nextFontSize, STEP_SIZE);
+ }
+ }
+
+ if (nextFontSize) {
+ mutateElement(latestElement, {
+ fontSize: nextFontSize,
+ });
+ redrawTextBoundingBox(
+ latestElement,
+ scene.getContainerElement(latestElement),
+ scene.getNonDeletedElementsMap(),
+ );
+ }
+ }
+};
+
+const FontSize = ({ element, scene, appState, property }: FontSizeProps) => {
+ const _element = isTextElement(element)
+ ? element
+ : hasBoundTextElement(element)
+ ? getBoundTextElement(element, scene.getNonDeletedElementsMap())
+ : null;
+
+ if (!_element) {
+ return null;
+ }
+
+ return (
+ <StatsDragInput
+ label="F"
+ value={Math.round(_element.fontSize * 10) / 10}
+ elements={[_element]}
+ dragInputCallback={handleFontSizeChange}
+ icon={fontSizeIcon}
+ appState={appState}
+ scene={scene}
+ property={property}
+ />
+ );
+};
+
+export default FontSize;
diff --git a/packages/excalidraw/components/Stats/MultiAngle.tsx b/packages/excalidraw/components/Stats/MultiAngle.tsx
new file mode 100644
index 0000000..d9a7882
--- /dev/null
+++ b/packages/excalidraw/components/Stats/MultiAngle.tsx
@@ -0,0 +1,136 @@
+import { mutateElement } from "../../element/mutateElement";
+import { getBoundTextElement } from "../../element/textElement";
+import { isArrowElement } from "../../element/typeChecks";
+import type { ExcalidrawElement } from "../../element/types";
+import { isInGroup } from "../../groups";
+import type Scene from "../../scene/Scene";
+import { angleIcon } from "../icons";
+import DragInput from "./DragInput";
+import type { DragInputCallbackType } from "./DragInput";
+import { getStepSizedValue, isPropertyEditable } from "./utils";
+import type { AppState } from "../../types";
+import type { Degrees } from "@excalidraw/math";
+import { degreesToRadians, radiansToDegrees } from "@excalidraw/math";
+
+interface MultiAngleProps {
+ elements: readonly ExcalidrawElement[];
+ scene: Scene;
+ appState: AppState;
+ property: "angle";
+}
+
+const STEP_SIZE = 15;
+
+const handleDegreeChange: DragInputCallbackType<
+ MultiAngleProps["property"]
+> = ({
+ accumulatedChange,
+ originalElements,
+ shouldChangeByStepSize,
+ nextValue,
+ property,
+ scene,
+}) => {
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const editableLatestIndividualElements = originalElements
+ .map((el) => elementsMap.get(el.id))
+ .filter((el) => el && !isInGroup(el) && isPropertyEditable(el, property));
+ const editableOriginalIndividualElements = originalElements.filter(
+ (el) => !isInGroup(el) && isPropertyEditable(el, property),
+ );
+
+ if (nextValue !== undefined) {
+ const nextAngle = degreesToRadians(nextValue as Degrees);
+
+ for (const element of editableLatestIndividualElements) {
+ if (!element) {
+ continue;
+ }
+ mutateElement(
+ element,
+ {
+ angle: nextAngle,
+ },
+ false,
+ );
+
+ const boundTextElement = getBoundTextElement(element, elementsMap);
+ if (boundTextElement && !isArrowElement(element)) {
+ mutateElement(boundTextElement, { angle: nextAngle }, false);
+ }
+ }
+
+ scene.triggerUpdate();
+
+ return;
+ }
+
+ for (let i = 0; i < editableLatestIndividualElements.length; i++) {
+ const latestElement = editableLatestIndividualElements[i];
+ if (!latestElement) {
+ continue;
+ }
+ const originalElement = editableOriginalIndividualElements[i];
+ const originalAngleInDegrees =
+ Math.round(radiansToDegrees(originalElement.angle) * 100) / 100;
+ const changeInDegrees = Math.round(accumulatedChange);
+ let nextAngleInDegrees = (originalAngleInDegrees + changeInDegrees) % 360;
+ if (shouldChangeByStepSize) {
+ nextAngleInDegrees = getStepSizedValue(nextAngleInDegrees, STEP_SIZE);
+ }
+
+ nextAngleInDegrees =
+ nextAngleInDegrees < 0 ? nextAngleInDegrees + 360 : nextAngleInDegrees;
+
+ const nextAngle = degreesToRadians(nextAngleInDegrees as Degrees);
+
+ mutateElement(
+ latestElement,
+ {
+ angle: nextAngle,
+ },
+ false,
+ );
+
+ const boundTextElement = getBoundTextElement(latestElement, elementsMap);
+ if (boundTextElement && !isArrowElement(latestElement)) {
+ mutateElement(boundTextElement, { angle: nextAngle }, false);
+ }
+ }
+ scene.triggerUpdate();
+};
+
+const MultiAngle = ({
+ elements,
+ scene,
+ appState,
+ property,
+}: MultiAngleProps) => {
+ const editableLatestIndividualElements = elements.filter(
+ (el) => !isInGroup(el) && isPropertyEditable(el, "angle"),
+ );
+ const angles = editableLatestIndividualElements.map(
+ (el) => Math.round((radiansToDegrees(el.angle) % 360) * 100) / 100,
+ );
+ const value = new Set(angles).size === 1 ? angles[0] : "Mixed";
+
+ const editable = editableLatestIndividualElements.some((el) =>
+ isPropertyEditable(el, "angle"),
+ );
+
+ return (
+ <DragInput
+ label="A"
+ icon={angleIcon}
+ value={value}
+ elements={elements}
+ dragInputCallback={handleDegreeChange}
+ editable={editable}
+ appState={appState}
+ scene={scene}
+ property={property}
+ />
+ );
+};
+
+export default MultiAngle;
diff --git a/packages/excalidraw/components/Stats/MultiDimension.tsx b/packages/excalidraw/components/Stats/MultiDimension.tsx
new file mode 100644
index 0000000..04f1937
--- /dev/null
+++ b/packages/excalidraw/components/Stats/MultiDimension.tsx
@@ -0,0 +1,401 @@
+import { useMemo } from "react";
+import { getCommonBounds, isTextElement } from "../../element";
+import { updateBoundElements } from "../../element/binding";
+import { mutateElement } from "../../element/mutateElement";
+import {
+ rescalePointsInElement,
+ resizeSingleElement,
+} from "../../element/resizeElements";
+import {
+ getBoundTextElement,
+ handleBindTextResize,
+} from "../../element/textElement";
+import type {
+ ElementsMap,
+ ExcalidrawElement,
+ NonDeletedSceneElementsMap,
+} from "../../element/types";
+import type Scene from "../../scene/Scene";
+import type { AppState } from "../../types";
+import DragInput from "./DragInput";
+import type { DragInputCallbackType } from "./DragInput";
+import { getAtomicUnits, getStepSizedValue, isPropertyEditable } from "./utils";
+import { getElementsInAtomicUnit } from "./utils";
+import type { AtomicUnit } from "./utils";
+import { MIN_WIDTH_OR_HEIGHT } from "../../constants";
+import { pointFrom, type GlobalPoint } from "@excalidraw/math";
+
+interface MultiDimensionProps {
+ property: "width" | "height";
+ elements: readonly ExcalidrawElement[];
+ elementsMap: NonDeletedSceneElementsMap;
+ atomicUnits: AtomicUnit[];
+ scene: Scene;
+ appState: AppState;
+}
+
+const STEP_SIZE = 10;
+
+const getResizedUpdates = (
+ anchorX: number,
+ anchorY: number,
+ scale: number,
+ origElement: ExcalidrawElement,
+) => {
+ const offsetX = origElement.x - anchorX;
+ const offsetY = origElement.y - anchorY;
+ const nextWidth = origElement.width * scale;
+ const nextHeight = origElement.height * scale;
+ const x = anchorX + offsetX * scale;
+ const y = anchorY + offsetY * scale;
+
+ return {
+ width: nextWidth,
+ height: nextHeight,
+ x,
+ y,
+ ...rescalePointsInElement(origElement, nextWidth, nextHeight, false),
+ ...(isTextElement(origElement)
+ ? { fontSize: origElement.fontSize * scale }
+ : {}),
+ };
+};
+
+const resizeElementInGroup = (
+ anchorX: number,
+ anchorY: number,
+ property: MultiDimensionProps["property"],
+ scale: number,
+ latestElement: ExcalidrawElement,
+ origElement: ExcalidrawElement,
+ elementsMap: NonDeletedSceneElementsMap,
+ originalElementsMap: ElementsMap,
+) => {
+ const updates = getResizedUpdates(anchorX, anchorY, scale, origElement);
+
+ mutateElement(latestElement, updates, false);
+ const boundTextElement = getBoundTextElement(
+ origElement,
+ originalElementsMap,
+ );
+ if (boundTextElement) {
+ const newFontSize = boundTextElement.fontSize * scale;
+ updateBoundElements(latestElement, elementsMap, {
+ newSize: { width: updates.width, height: updates.height },
+ });
+ const latestBoundTextElement = elementsMap.get(boundTextElement.id);
+ if (latestBoundTextElement && isTextElement(latestBoundTextElement)) {
+ mutateElement(
+ latestBoundTextElement,
+ {
+ fontSize: newFontSize,
+ },
+ false,
+ );
+ handleBindTextResize(
+ latestElement,
+ elementsMap,
+ property === "width" ? "e" : "s",
+ true,
+ );
+ }
+ }
+};
+
+const resizeGroup = (
+ nextWidth: number,
+ nextHeight: number,
+ initialHeight: number,
+ aspectRatio: number,
+ anchor: GlobalPoint,
+ property: MultiDimensionProps["property"],
+ latestElements: ExcalidrawElement[],
+ originalElements: ExcalidrawElement[],
+ elementsMap: NonDeletedSceneElementsMap,
+ originalElementsMap: ElementsMap,
+) => {
+ // keep aspect ratio for groups
+ if (property === "width") {
+ nextHeight = Math.round((nextWidth / aspectRatio) * 100) / 100;
+ } else {
+ nextWidth = Math.round(nextHeight * aspectRatio * 100) / 100;
+ }
+
+ const scale = nextHeight / initialHeight;
+
+ for (let i = 0; i < originalElements.length; i++) {
+ const origElement = originalElements[i];
+ const latestElement = latestElements[i];
+
+ resizeElementInGroup(
+ anchor[0],
+ anchor[1],
+ property,
+ scale,
+ latestElement,
+ origElement,
+ elementsMap,
+ originalElementsMap,
+ );
+ }
+};
+
+const handleDimensionChange: DragInputCallbackType<
+ MultiDimensionProps["property"]
+> = ({
+ accumulatedChange,
+ originalElements,
+ originalElementsMap,
+ originalAppState,
+ shouldChangeByStepSize,
+ nextValue,
+ scene,
+ property,
+}) => {
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const atomicUnits = getAtomicUnits(originalElements, originalAppState);
+ if (nextValue !== undefined) {
+ for (const atomicUnit of atomicUnits) {
+ const elementsInUnit = getElementsInAtomicUnit(
+ atomicUnit,
+ elementsMap,
+ originalElementsMap,
+ );
+
+ if (elementsInUnit.length > 1) {
+ const latestElements = elementsInUnit.map((el) => el.latest!);
+ const originalElements = elementsInUnit.map((el) => el.original!);
+ const [x1, y1, x2, y2] = getCommonBounds(originalElements);
+ const initialWidth = x2 - x1;
+ const initialHeight = y2 - y1;
+ const aspectRatio = initialWidth / initialHeight;
+ const nextWidth = Math.max(
+ MIN_WIDTH_OR_HEIGHT,
+ property === "width" ? Math.max(0, nextValue) : initialWidth,
+ );
+ const nextHeight = Math.max(
+ MIN_WIDTH_OR_HEIGHT,
+ property === "height" ? Math.max(0, nextValue) : initialHeight,
+ );
+
+ resizeGroup(
+ nextWidth,
+ nextHeight,
+ initialHeight,
+ aspectRatio,
+ pointFrom(x1, y1),
+ property,
+ latestElements,
+ originalElements,
+ elementsMap,
+ originalElementsMap,
+ );
+ } else {
+ const [el] = elementsInUnit;
+ const latestElement = el?.latest;
+ const origElement = el?.original;
+
+ if (
+ latestElement &&
+ origElement &&
+ isPropertyEditable(latestElement, property)
+ ) {
+ let nextWidth =
+ property === "width" ? Math.max(0, nextValue) : latestElement.width;
+ if (property === "width") {
+ if (shouldChangeByStepSize) {
+ nextWidth = getStepSizedValue(nextWidth, STEP_SIZE);
+ } else {
+ nextWidth = Math.round(nextWidth);
+ }
+ }
+
+ let nextHeight =
+ property === "height"
+ ? Math.max(0, nextValue)
+ : latestElement.height;
+ if (property === "height") {
+ if (shouldChangeByStepSize) {
+ nextHeight = getStepSizedValue(nextHeight, STEP_SIZE);
+ } else {
+ nextHeight = Math.round(nextHeight);
+ }
+ }
+
+ nextWidth = Math.max(MIN_WIDTH_OR_HEIGHT, nextWidth);
+ nextHeight = Math.max(MIN_WIDTH_OR_HEIGHT, nextHeight);
+
+ resizeSingleElement(
+ nextWidth,
+ nextHeight,
+ latestElement,
+ origElement,
+ elementsMap,
+ originalElementsMap,
+ property === "width" ? "e" : "s",
+ {
+ shouldInformMutation: false,
+ },
+ );
+ }
+ }
+ }
+
+ scene.triggerUpdate();
+
+ return;
+ }
+
+ const changeInWidth = property === "width" ? accumulatedChange : 0;
+ const changeInHeight = property === "height" ? accumulatedChange : 0;
+
+ for (const atomicUnit of atomicUnits) {
+ const elementsInUnit = getElementsInAtomicUnit(
+ atomicUnit,
+ elementsMap,
+ originalElementsMap,
+ );
+
+ if (elementsInUnit.length > 1) {
+ const latestElements = elementsInUnit.map((el) => el.latest!);
+ const originalElements = elementsInUnit.map((el) => el.original!);
+
+ const [x1, y1, x2, y2] = getCommonBounds(originalElements);
+ const initialWidth = x2 - x1;
+ const initialHeight = y2 - y1;
+ const aspectRatio = initialWidth / initialHeight;
+ let nextWidth = Math.max(0, initialWidth + changeInWidth);
+ if (property === "width") {
+ if (shouldChangeByStepSize) {
+ nextWidth = getStepSizedValue(nextWidth, STEP_SIZE);
+ } else {
+ nextWidth = Math.round(nextWidth);
+ }
+ }
+
+ let nextHeight = Math.max(0, initialHeight + changeInHeight);
+ if (property === "height") {
+ if (shouldChangeByStepSize) {
+ nextHeight = getStepSizedValue(nextHeight, STEP_SIZE);
+ } else {
+ nextHeight = Math.round(nextHeight);
+ }
+ }
+
+ nextWidth = Math.max(MIN_WIDTH_OR_HEIGHT, nextWidth);
+ nextHeight = Math.max(MIN_WIDTH_OR_HEIGHT, nextHeight);
+
+ resizeGroup(
+ nextWidth,
+ nextHeight,
+ initialHeight,
+ aspectRatio,
+ pointFrom(x1, y1),
+ property,
+ latestElements,
+ originalElements,
+ elementsMap,
+ originalElementsMap,
+ );
+ } else {
+ const [el] = elementsInUnit;
+ const latestElement = el?.latest;
+ const origElement = el?.original;
+
+ if (
+ latestElement &&
+ origElement &&
+ isPropertyEditable(latestElement, property)
+ ) {
+ let nextWidth = Math.max(0, origElement.width + changeInWidth);
+ if (property === "width") {
+ if (shouldChangeByStepSize) {
+ nextWidth = getStepSizedValue(nextWidth, STEP_SIZE);
+ } else {
+ nextWidth = Math.round(nextWidth);
+ }
+ }
+
+ let nextHeight = Math.max(0, origElement.height + changeInHeight);
+ if (property === "height") {
+ if (shouldChangeByStepSize) {
+ nextHeight = getStepSizedValue(nextHeight, STEP_SIZE);
+ } else {
+ nextHeight = Math.round(nextHeight);
+ }
+ }
+
+ nextWidth = Math.max(MIN_WIDTH_OR_HEIGHT, nextWidth);
+ nextHeight = Math.max(MIN_WIDTH_OR_HEIGHT, nextHeight);
+
+ resizeSingleElement(
+ nextWidth,
+ nextHeight,
+ latestElement,
+ origElement,
+ elementsMap,
+ originalElementsMap,
+ property === "width" ? "e" : "s",
+ {
+ shouldInformMutation: false,
+ },
+ );
+ }
+ }
+ }
+
+ scene.triggerUpdate();
+};
+
+const MultiDimension = ({
+ property,
+ elements,
+ elementsMap,
+ atomicUnits,
+ scene,
+ appState,
+}: MultiDimensionProps) => {
+ const sizes = useMemo(
+ () =>
+ atomicUnits.map((atomicUnit) => {
+ const elementsInUnit = getElementsInAtomicUnit(atomicUnit, elementsMap);
+
+ if (elementsInUnit.length > 1) {
+ const [x1, y1, x2, y2] = getCommonBounds(
+ elementsInUnit.map((el) => el.latest),
+ );
+ return (
+ Math.round((property === "width" ? x2 - x1 : y2 - y1) * 100) / 100
+ );
+ }
+ const [el] = elementsInUnit;
+
+ return (
+ Math.round(
+ (property === "width" ? el.latest.width : el.latest.height) * 100,
+ ) / 100
+ );
+ }),
+ [elementsMap, atomicUnits, property],
+ );
+
+ const value =
+ new Set(sizes).size === 1 ? Math.round(sizes[0] * 100) / 100 : "Mixed";
+
+ const editable = sizes.length > 0;
+
+ return (
+ <DragInput
+ label={property === "width" ? "W" : "H"}
+ elements={elements}
+ dragInputCallback={handleDimensionChange}
+ value={value}
+ editable={editable}
+ appState={appState}
+ property={property}
+ scene={scene}
+ />
+ );
+};
+
+export default MultiDimension;
diff --git a/packages/excalidraw/components/Stats/MultiFontSize.tsx b/packages/excalidraw/components/Stats/MultiFontSize.tsx
new file mode 100644
index 0000000..419bbbc
--- /dev/null
+++ b/packages/excalidraw/components/Stats/MultiFontSize.tsx
@@ -0,0 +1,164 @@
+import { isTextElement, redrawTextBoundingBox } from "../../element";
+import { mutateElement } from "../../element/mutateElement";
+import { hasBoundTextElement } from "../../element/typeChecks";
+import type {
+ ExcalidrawElement,
+ ExcalidrawTextElement,
+ NonDeletedSceneElementsMap,
+} from "../../element/types";
+import { isInGroup } from "../../groups";
+import type Scene from "../../scene/Scene";
+import { fontSizeIcon } from "../icons";
+import StatsDragInput from "./DragInput";
+import type { DragInputCallbackType } from "./DragInput";
+import { getStepSizedValue } from "./utils";
+import type { AppState } from "../../types";
+import { getBoundTextElement } from "../../element/textElement";
+
+interface MultiFontSizeProps {
+ elements: readonly ExcalidrawElement[];
+ scene: Scene;
+ elementsMap: NonDeletedSceneElementsMap;
+ appState: AppState;
+ property: "fontSize";
+}
+
+const MIN_FONT_SIZE = 4;
+const STEP_SIZE = 4;
+
+const getApplicableTextElements = (
+ elements: readonly (ExcalidrawElement | undefined)[],
+ elementsMap: NonDeletedSceneElementsMap,
+) =>
+ elements.reduce(
+ (acc: ExcalidrawTextElement[], el) => {
+ if (!el || isInGroup(el)) {
+ return acc;
+ }
+ if (isTextElement(el)) {
+ acc.push(el);
+ return acc;
+ }
+ if (hasBoundTextElement(el)) {
+ const boundTextElement = getBoundTextElement(el, elementsMap);
+ if (boundTextElement) {
+ acc.push(boundTextElement);
+ return acc;
+ }
+ }
+
+ return acc;
+ },
+
+ [],
+ );
+
+const handleFontSizeChange: DragInputCallbackType<
+ MultiFontSizeProps["property"],
+ ExcalidrawTextElement
+> = ({
+ accumulatedChange,
+ originalElements,
+ shouldChangeByStepSize,
+ nextValue,
+ scene,
+}) => {
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const latestTextElements = originalElements.map((el) =>
+ elementsMap.get(el.id),
+ ) as ExcalidrawTextElement[];
+
+ let nextFontSize;
+
+ if (nextValue) {
+ nextFontSize = Math.max(Math.round(nextValue), MIN_FONT_SIZE);
+
+ for (const textElement of latestTextElements) {
+ mutateElement(
+ textElement,
+ {
+ fontSize: nextFontSize,
+ },
+ false,
+ );
+
+ redrawTextBoundingBox(
+ textElement,
+ scene.getContainerElement(textElement),
+ elementsMap,
+ false,
+ );
+ }
+
+ scene.triggerUpdate();
+ } else {
+ const originalTextElements = originalElements as ExcalidrawTextElement[];
+
+ for (let i = 0; i < latestTextElements.length; i++) {
+ const latestElement = latestTextElements[i];
+ const originalElement = originalTextElements[i];
+
+ const originalFontSize = Math.round(originalElement.fontSize);
+ const changeInFontSize = Math.round(accumulatedChange);
+ let nextFontSize = Math.max(
+ originalFontSize + changeInFontSize,
+ MIN_FONT_SIZE,
+ );
+ if (shouldChangeByStepSize) {
+ nextFontSize = getStepSizedValue(nextFontSize, STEP_SIZE);
+ }
+ mutateElement(
+ latestElement,
+ {
+ fontSize: nextFontSize,
+ },
+ false,
+ );
+
+ redrawTextBoundingBox(
+ latestElement,
+ scene.getContainerElement(latestElement),
+ elementsMap,
+ false,
+ );
+ }
+
+ scene.triggerUpdate();
+ }
+};
+
+const MultiFontSize = ({
+ elements,
+ scene,
+ appState,
+ property,
+ elementsMap,
+}: MultiFontSizeProps) => {
+ const latestTextElements = getApplicableTextElements(elements, elementsMap);
+
+ if (!latestTextElements.length) {
+ return null;
+ }
+
+ const fontSizes = latestTextElements.map(
+ (textEl) => Math.round(textEl.fontSize * 10) / 10,
+ );
+ const value = new Set(fontSizes).size === 1 ? fontSizes[0] : "Mixed";
+ const editable = fontSizes.length > 0;
+
+ return (
+ <StatsDragInput
+ label="F"
+ icon={fontSizeIcon}
+ elements={latestTextElements}
+ dragInputCallback={handleFontSizeChange}
+ value={value}
+ editable={editable}
+ scene={scene}
+ property={property}
+ appState={appState}
+ />
+ );
+};
+
+export default MultiFontSize;
diff --git a/packages/excalidraw/components/Stats/MultiPosition.tsx b/packages/excalidraw/components/Stats/MultiPosition.tsx
new file mode 100644
index 0000000..8a29aa6
--- /dev/null
+++ b/packages/excalidraw/components/Stats/MultiPosition.tsx
@@ -0,0 +1,270 @@
+import type {
+ ElementsMap,
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+ NonDeletedSceneElementsMap,
+} from "../../element/types";
+import type Scene from "../../scene/Scene";
+import StatsDragInput from "./DragInput";
+import type { DragInputCallbackType } from "./DragInput";
+import { getAtomicUnits, getStepSizedValue, isPropertyEditable } from "./utils";
+import { getCommonBounds, isTextElement } from "../../element";
+import { useMemo } from "react";
+import { getElementsInAtomicUnit, moveElement } from "./utils";
+import type { AtomicUnit } from "./utils";
+import type { AppState } from "../../types";
+import { pointFrom, pointRotateRads } from "@excalidraw/math";
+
+interface MultiPositionProps {
+ property: "x" | "y";
+ elements: readonly ExcalidrawElement[];
+ elementsMap: ElementsMap;
+ atomicUnits: AtomicUnit[];
+ scene: Scene;
+ appState: AppState;
+}
+
+const STEP_SIZE = 10;
+
+const moveElements = (
+ property: MultiPositionProps["property"],
+ changeInTopX: number,
+ changeInTopY: number,
+ elements: readonly ExcalidrawElement[],
+ originalElements: readonly ExcalidrawElement[],
+ elementsMap: NonDeletedSceneElementsMap,
+ originalElementsMap: ElementsMap,
+ scene: Scene,
+) => {
+ for (let i = 0; i < elements.length; i++) {
+ const origElement = originalElements[i];
+
+ const [cx, cy] = [
+ origElement.x + origElement.width / 2,
+ origElement.y + origElement.height / 2,
+ ];
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(origElement.x, origElement.y),
+ pointFrom(cx, cy),
+ origElement.angle,
+ );
+
+ const newTopLeftX =
+ property === "x" ? Math.round(topLeftX + changeInTopX) : topLeftX;
+
+ const newTopLeftY =
+ property === "y" ? Math.round(topLeftY + changeInTopY) : topLeftY;
+
+ moveElement(
+ newTopLeftX,
+ newTopLeftY,
+ origElement,
+ elementsMap,
+ elements,
+ scene,
+ originalElementsMap,
+ false,
+ );
+ }
+};
+
+const moveGroupTo = (
+ nextX: number,
+ nextY: number,
+ originalElements: ExcalidrawElement[],
+ elementsMap: NonDeletedSceneElementsMap,
+ elements: readonly NonDeletedExcalidrawElement[],
+ originalElementsMap: ElementsMap,
+ scene: Scene,
+) => {
+ const [x1, y1, ,] = getCommonBounds(originalElements);
+ const offsetX = nextX - x1;
+ const offsetY = nextY - y1;
+
+ for (let i = 0; i < originalElements.length; i++) {
+ const origElement = originalElements[i];
+
+ const latestElement = elementsMap.get(origElement.id);
+ if (!latestElement) {
+ continue;
+ }
+
+ // bound texts are moved with their containers
+ if (!isTextElement(latestElement) || !latestElement.containerId) {
+ const [cx, cy] = [
+ latestElement.x + latestElement.width / 2,
+ latestElement.y + latestElement.height / 2,
+ ];
+
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(latestElement.x, latestElement.y),
+ pointFrom(cx, cy),
+ latestElement.angle,
+ );
+
+ moveElement(
+ topLeftX + offsetX,
+ topLeftY + offsetY,
+ origElement,
+ elementsMap,
+ elements,
+ scene,
+ originalElementsMap,
+ false,
+ );
+ }
+ }
+};
+
+const handlePositionChange: DragInputCallbackType<
+ MultiPositionProps["property"]
+> = ({
+ accumulatedChange,
+ originalElements,
+ originalElementsMap,
+ shouldChangeByStepSize,
+ nextValue,
+ property,
+ scene,
+ originalAppState,
+}) => {
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const elements = scene.getNonDeletedElements();
+
+ if (nextValue !== undefined) {
+ for (const atomicUnit of getAtomicUnits(
+ originalElements,
+ originalAppState,
+ )) {
+ const elementsInUnit = getElementsInAtomicUnit(
+ atomicUnit,
+ elementsMap,
+ originalElementsMap,
+ );
+
+ if (elementsInUnit.length > 1) {
+ const [x1, y1, ,] = getCommonBounds(
+ elementsInUnit.map((el) => el.latest!),
+ );
+ const newTopLeftX = property === "x" ? nextValue : x1;
+ const newTopLeftY = property === "y" ? nextValue : y1;
+
+ moveGroupTo(
+ newTopLeftX,
+ newTopLeftY,
+ elementsInUnit.map((el) => el.original),
+ elementsMap,
+ elements,
+ originalElementsMap,
+ scene,
+ );
+ } else {
+ const origElement = elementsInUnit[0]?.original;
+ const latestElement = elementsInUnit[0]?.latest;
+ if (
+ origElement &&
+ latestElement &&
+ isPropertyEditable(latestElement, property)
+ ) {
+ const [cx, cy] = [
+ origElement.x + origElement.width / 2,
+ origElement.y + origElement.height / 2,
+ ];
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(origElement.x, origElement.y),
+ pointFrom(cx, cy),
+ origElement.angle,
+ );
+
+ const newTopLeftX = property === "x" ? nextValue : topLeftX;
+ const newTopLeftY = property === "y" ? nextValue : topLeftY;
+ moveElement(
+ newTopLeftX,
+ newTopLeftY,
+ origElement,
+ elementsMap,
+ elements,
+ scene,
+ originalElementsMap,
+ false,
+ );
+ }
+ }
+ }
+
+ scene.triggerUpdate();
+ return;
+ }
+
+ const change = shouldChangeByStepSize
+ ? getStepSizedValue(accumulatedChange, STEP_SIZE)
+ : accumulatedChange;
+
+ const changeInTopX = property === "x" ? change : 0;
+ const changeInTopY = property === "y" ? change : 0;
+
+ moveElements(
+ property,
+ changeInTopX,
+ changeInTopY,
+ originalElements,
+ originalElements,
+ elementsMap,
+ originalElementsMap,
+ scene,
+ );
+
+ scene.triggerUpdate();
+};
+
+const MultiPosition = ({
+ property,
+ elements,
+ elementsMap,
+ atomicUnits,
+ scene,
+ appState,
+}: MultiPositionProps) => {
+ const positions = useMemo(
+ () =>
+ atomicUnits.map((atomicUnit) => {
+ const elementsInUnit = Object.keys(atomicUnit)
+ .map((id) => elementsMap.get(id))
+ .filter((el) => el !== undefined) as ExcalidrawElement[];
+
+ // we're dealing with a group
+ if (elementsInUnit.length > 1) {
+ const [x1, y1] = getCommonBounds(elementsInUnit);
+ return Math.round((property === "x" ? x1 : y1) * 100) / 100;
+ }
+
+ const [el] = elementsInUnit;
+ const [cx, cy] = [el.x + el.width / 2, el.y + el.height / 2];
+
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(el.x, el.y),
+ pointFrom(cx, cy),
+ el.angle,
+ );
+
+ return Math.round((property === "x" ? topLeftX : topLeftY) * 100) / 100;
+ }),
+ [atomicUnits, elementsMap, property],
+ );
+
+ const value = new Set(positions).size === 1 ? positions[0] : "Mixed";
+
+ return (
+ <StatsDragInput
+ label={property === "x" ? "X" : "Y"}
+ elements={elements}
+ dragInputCallback={handlePositionChange}
+ value={value}
+ property={property}
+ scene={scene}
+ appState={appState}
+ />
+ );
+};
+
+export default MultiPosition;
diff --git a/packages/excalidraw/components/Stats/Position.tsx b/packages/excalidraw/components/Stats/Position.tsx
new file mode 100644
index 0000000..038e58e
--- /dev/null
+++ b/packages/excalidraw/components/Stats/Position.tsx
@@ -0,0 +1,214 @@
+import type { ElementsMap, ExcalidrawElement } from "../../element/types";
+import StatsDragInput from "./DragInput";
+import type { DragInputCallbackType } from "./DragInput";
+import { getStepSizedValue, moveElement } from "./utils";
+import type Scene from "../../scene/Scene";
+import type { AppState } from "../../types";
+import { clamp, pointFrom, pointRotateRads, round } from "@excalidraw/math";
+import { isImageElement } from "../../element/typeChecks";
+import {
+ getFlipAdjustedCropPosition,
+ getUncroppedWidthAndHeight,
+} from "../../element/cropElement";
+import { mutateElement } from "../../element/mutateElement";
+
+interface PositionProps {
+ property: "x" | "y";
+ element: ExcalidrawElement;
+ elementsMap: ElementsMap;
+ scene: Scene;
+ appState: AppState;
+}
+
+const STEP_SIZE = 10;
+
+const handlePositionChange: DragInputCallbackType<"x" | "y"> = ({
+ accumulatedChange,
+ instantChange,
+ originalElements,
+ originalElementsMap,
+ shouldChangeByStepSize,
+ nextValue,
+ property,
+ scene,
+ originalAppState,
+}) => {
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const elements = scene.getNonDeletedElements();
+ const origElement = originalElements[0];
+ const [cx, cy] = [
+ origElement.x + origElement.width / 2,
+ origElement.y + origElement.height / 2,
+ ];
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(origElement.x, origElement.y),
+ pointFrom(cx, cy),
+ origElement.angle,
+ );
+
+ if (originalAppState.croppingElementId === origElement.id) {
+ const element = elementsMap.get(origElement.id);
+
+ if (!element || !isImageElement(element) || !element.crop) {
+ return;
+ }
+
+ const crop = element.crop;
+ let nextCrop = crop;
+ const isFlippedByX = element.scale[0] === -1;
+ const isFlippedByY = element.scale[1] === -1;
+ const { width: uncroppedWidth, height: uncroppedHeight } =
+ getUncroppedWidthAndHeight(element);
+
+ if (nextValue !== undefined) {
+ if (property === "x") {
+ const nextValueInNatural =
+ nextValue * (crop.naturalWidth / uncroppedWidth);
+
+ if (isFlippedByX) {
+ nextCrop = {
+ ...crop,
+ x: clamp(
+ crop.naturalWidth - nextValueInNatural - crop.width,
+ 0,
+ crop.naturalWidth - crop.width,
+ ),
+ };
+ } else {
+ nextCrop = {
+ ...crop,
+ x: clamp(
+ nextValue * (crop.naturalWidth / uncroppedWidth),
+ 0,
+ crop.naturalWidth - crop.width,
+ ),
+ };
+ }
+ }
+
+ if (property === "y") {
+ nextCrop = {
+ ...crop,
+ y: clamp(
+ nextValue * (crop.naturalHeight / uncroppedHeight),
+ 0,
+ crop.naturalHeight - crop.height,
+ ),
+ };
+ }
+
+ mutateElement(element, {
+ crop: nextCrop,
+ });
+
+ return;
+ }
+
+ const changeInX =
+ (property === "x" ? instantChange : 0) * (isFlippedByX ? -1 : 1);
+ const changeInY =
+ (property === "y" ? instantChange : 0) * (isFlippedByY ? -1 : 1);
+
+ nextCrop = {
+ ...crop,
+ x: clamp(crop.x + changeInX, 0, crop.naturalWidth - crop.width),
+ y: clamp(crop.y + changeInY, 0, crop.naturalHeight - crop.height),
+ };
+
+ mutateElement(element, {
+ crop: nextCrop,
+ });
+
+ return;
+ }
+
+ if (nextValue !== undefined) {
+ const newTopLeftX = property === "x" ? nextValue : topLeftX;
+ const newTopLeftY = property === "y" ? nextValue : topLeftY;
+ moveElement(
+ newTopLeftX,
+ newTopLeftY,
+ origElement,
+ elementsMap,
+ elements,
+ scene,
+ originalElementsMap,
+ );
+ return;
+ }
+
+ const changeInTopX = property === "x" ? accumulatedChange : 0;
+ const changeInTopY = property === "y" ? accumulatedChange : 0;
+
+ const newTopLeftX =
+ property === "x"
+ ? Math.round(
+ shouldChangeByStepSize
+ ? getStepSizedValue(origElement.x + changeInTopX, STEP_SIZE)
+ : topLeftX + changeInTopX,
+ )
+ : topLeftX;
+
+ const newTopLeftY =
+ property === "y"
+ ? Math.round(
+ shouldChangeByStepSize
+ ? getStepSizedValue(origElement.y + changeInTopY, STEP_SIZE)
+ : topLeftY + changeInTopY,
+ )
+ : topLeftY;
+
+ moveElement(
+ newTopLeftX,
+ newTopLeftY,
+ origElement,
+ elementsMap,
+ elements,
+ scene,
+ originalElementsMap,
+ );
+};
+
+const Position = ({
+ property,
+ element,
+ elementsMap,
+ scene,
+ appState,
+}: PositionProps) => {
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(element.x, element.y),
+ pointFrom(element.x + element.width / 2, element.y + element.height / 2),
+ element.angle,
+ );
+ let value = round(property === "x" ? topLeftX : topLeftY, 2);
+
+ if (
+ appState.croppingElementId === element.id &&
+ isImageElement(element) &&
+ element.crop
+ ) {
+ const flipAdjustedPosition = getFlipAdjustedCropPosition(element);
+
+ if (flipAdjustedPosition) {
+ value = round(
+ property === "x" ? flipAdjustedPosition.x : flipAdjustedPosition.y,
+ 2,
+ );
+ }
+ }
+
+ return (
+ <StatsDragInput
+ label={property === "x" ? "X" : "Y"}
+ elements={[element]}
+ dragInputCallback={handlePositionChange}
+ scene={scene}
+ value={value}
+ property={property}
+ appState={appState}
+ />
+ );
+};
+
+export default Position;
diff --git a/packages/excalidraw/components/Stats/Stats.scss b/packages/excalidraw/components/Stats/Stats.scss
new file mode 100644
index 0000000..106ecf3
--- /dev/null
+++ b/packages/excalidraw/components/Stats/Stats.scss
@@ -0,0 +1,72 @@
+.exc-stats {
+ width: 204px;
+ position: absolute;
+ top: 60px;
+ font-size: 12px;
+ z-index: var(--zIndex-layerUI);
+ pointer-events: var(--ui-pointerEvents);
+
+ :root[dir="rtl"] & {
+ left: 12px;
+ right: initial;
+ }
+
+ h2 {
+ font-size: 1.5em;
+ margin-block-start: 0.83em;
+ margin-block-end: 0.83em;
+ font-weight: bold;
+ }
+ h3 {
+ white-space: nowrap;
+ font-size: 1.17em;
+ margin: 0;
+ font-weight: bold;
+ }
+
+ &__rows {
+ display: flex;
+ flex-direction: column;
+ gap: 0.3125rem;
+ }
+
+ &__row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+
+ display: grid;
+ gap: 4px;
+
+ div + div {
+ text-align: right;
+ }
+ }
+
+ &__row--heading {
+ text-align: center;
+ font-weight: bold;
+ margin: 0.25rem 0;
+ }
+
+ .title {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 12px;
+
+ h2 {
+ margin: 0;
+ }
+ }
+
+ .close {
+ height: 16px;
+ width: 16px;
+ cursor: pointer;
+ svg {
+ width: 100%;
+ height: 100%;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Stats/index.tsx b/packages/excalidraw/components/Stats/index.tsx
new file mode 100644
index 0000000..2ccd93c
--- /dev/null
+++ b/packages/excalidraw/components/Stats/index.tsx
@@ -0,0 +1,434 @@
+import { useEffect, useMemo, useState, memo } from "react";
+import { getCommonBounds } from "../../element/bounds";
+import type { NonDeletedExcalidrawElement } from "../../element/types";
+import { t } from "../../i18n";
+import type {
+ AppClassProperties,
+ AppState,
+ ExcalidrawProps,
+} from "../../types";
+import { CloseIcon } from "../icons";
+import { Island } from "../Island";
+import throttle from "lodash.throttle";
+import Dimension from "./Dimension";
+import Angle from "./Angle";
+import FontSize from "./FontSize";
+import MultiDimension from "./MultiDimension";
+import { elementsAreInSameGroup } from "../../groups";
+import MultiAngle from "./MultiAngle";
+import MultiFontSize from "./MultiFontSize";
+import Position from "./Position";
+import MultiPosition from "./MultiPosition";
+import Collapsible from "./Collapsible";
+import { useExcalidrawAppState, useExcalidrawSetAppState } from "../App";
+import { getAtomicUnits } from "./utils";
+import { STATS_PANELS } from "../../constants";
+import { isElbowArrow, isImageElement } from "../../element/typeChecks";
+import CanvasGrid from "./CanvasGrid";
+import clsx from "clsx";
+
+import "./Stats.scss";
+import { isGridModeEnabled } from "../../snapping";
+import { getUncroppedWidthAndHeight } from "../../element/cropElement";
+import { round } from "@excalidraw/math";
+import { frameAndChildrenSelectedTogether } from "../../frame";
+
+interface StatsProps {
+ app: AppClassProperties;
+ onClose: () => void;
+ renderCustomStats: ExcalidrawProps["renderCustomStats"];
+}
+
+const STATS_TIMEOUT = 50;
+
+export const Stats = (props: StatsProps) => {
+ const appState = useExcalidrawAppState();
+ const sceneNonce = props.app.scene.getSceneNonce() || 1;
+ const selectedElements = props.app.scene.getSelectedElements({
+ selectedElementIds: appState.selectedElementIds,
+ includeBoundTextElement: false,
+ });
+ const gridModeEnabled = isGridModeEnabled(props.app);
+
+ return (
+ <StatsInner
+ {...props}
+ appState={appState}
+ sceneNonce={sceneNonce}
+ selectedElements={selectedElements}
+ gridModeEnabled={gridModeEnabled}
+ />
+ );
+};
+
+const StatsRow = ({
+ children,
+ columns = 1,
+ heading,
+ style,
+ ...rest
+}: {
+ children: React.ReactNode;
+ columns?: number;
+ heading?: boolean;
+ style?: React.CSSProperties;
+} & React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={clsx("exc-stats__row", { "exc-stats__row--heading": heading })}
+ style={{
+ gridTemplateColumns: `repeat(${columns}, 1fr)`,
+ ...style,
+ }}
+ {...rest}
+ >
+ {children}
+ </div>
+);
+StatsRow.displayName = "StatsRow";
+
+const StatsRows = ({
+ children,
+ order,
+ style,
+ ...rest
+}: {
+ children: React.ReactNode;
+ order?: number;
+ style?: React.CSSProperties;
+} & React.HTMLAttributes<HTMLDivElement>) => (
+ <div className="exc-stats__rows" style={{ order, ...style }} {...rest}>
+ {children}
+ </div>
+);
+StatsRows.displayName = "StatsRows";
+
+Stats.StatsRow = StatsRow;
+Stats.StatsRows = StatsRows;
+
+export const StatsInner = memo(
+ ({
+ app,
+ onClose,
+ renderCustomStats,
+ selectedElements,
+ appState,
+ sceneNonce,
+ gridModeEnabled,
+ }: StatsProps & {
+ sceneNonce: number;
+ selectedElements: readonly NonDeletedExcalidrawElement[];
+ appState: AppState;
+ gridModeEnabled: boolean;
+ }) => {
+ const scene = app.scene;
+ const elements = scene.getNonDeletedElements();
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const setAppState = useExcalidrawSetAppState();
+
+ const singleElement =
+ selectedElements.length === 1 ? selectedElements[0] : null;
+
+ const multipleElements =
+ selectedElements.length > 1 ? selectedElements : null;
+
+ const cropMode =
+ appState.croppingElementId && isImageElement(singleElement);
+
+ const unCroppedDimension = cropMode
+ ? getUncroppedWidthAndHeight(singleElement)
+ : null;
+
+ const [sceneDimension, setSceneDimension] = useState<{
+ width: number;
+ height: number;
+ }>({
+ width: 0,
+ height: 0,
+ });
+
+ const throttledSetSceneDimension = useMemo(
+ () =>
+ throttle((elements: readonly NonDeletedExcalidrawElement[]) => {
+ const boundingBox = getCommonBounds(elements);
+ setSceneDimension({
+ width: Math.round(boundingBox[2]) - Math.round(boundingBox[0]),
+ height: Math.round(boundingBox[3]) - Math.round(boundingBox[1]),
+ });
+ }, STATS_TIMEOUT),
+ [],
+ );
+
+ useEffect(() => {
+ throttledSetSceneDimension(elements);
+ }, [sceneNonce, elements, throttledSetSceneDimension]);
+
+ useEffect(
+ () => () => throttledSetSceneDimension.cancel(),
+ [throttledSetSceneDimension],
+ );
+
+ const atomicUnits = useMemo(() => {
+ return getAtomicUnits(selectedElements, appState);
+ }, [selectedElements, appState]);
+
+ const _frameAndChildrenSelectedTogether = useMemo(() => {
+ return frameAndChildrenSelectedTogether(selectedElements);
+ }, [selectedElements]);
+
+ return (
+ <div className="exc-stats">
+ <Island padding={3}>
+ <div className="title">
+ <h2>{t("stats.title")}</h2>
+ <div className="close" onClick={onClose}>
+ {CloseIcon}
+ </div>
+ </div>
+
+ <Collapsible
+ label={<h3>{t("stats.generalStats")}</h3>}
+ open={!!(appState.stats.panels & STATS_PANELS.generalStats)}
+ openTrigger={() =>
+ setAppState((state) => {
+ return {
+ stats: {
+ open: true,
+ panels: state.stats.panels ^ STATS_PANELS.generalStats,
+ },
+ };
+ })
+ }
+ >
+ <StatsRows>
+ <StatsRow heading>{t("stats.scene")}</StatsRow>
+ <StatsRow columns={2}>
+ <div>{t("stats.shapes")}</div>
+ <div>{elements.length}</div>
+ </StatsRow>
+ <StatsRow columns={2}>
+ <div>{t("stats.width")}</div>
+ <div>{sceneDimension.width}</div>
+ </StatsRow>
+ <StatsRow columns={2}>
+ <div>{t("stats.height")}</div>
+ <div>{sceneDimension.height}</div>
+ </StatsRow>
+ {gridModeEnabled && (
+ <>
+ <StatsRow heading>Canvas</StatsRow>
+ <StatsRow>
+ <CanvasGrid
+ property="gridStep"
+ scene={scene}
+ appState={appState}
+ setAppState={setAppState}
+ />
+ </StatsRow>
+ </>
+ )}
+ </StatsRows>
+
+ {renderCustomStats?.(elements, appState)}
+ </Collapsible>
+
+ {!_frameAndChildrenSelectedTogether && selectedElements.length > 0 && (
+ <div
+ id="elementStats"
+ style={{
+ marginTop: 12,
+ }}
+ >
+ <Collapsible
+ label={<h3>{t("stats.elementProperties")}</h3>}
+ open={
+ !!(appState.stats.panels & STATS_PANELS.elementProperties)
+ }
+ openTrigger={() =>
+ setAppState((state) => {
+ return {
+ stats: {
+ open: true,
+ panels:
+ state.stats.panels ^ STATS_PANELS.elementProperties,
+ },
+ };
+ })
+ }
+ >
+ <StatsRows>
+ {singleElement && (
+ <>
+ {cropMode && (
+ <StatsRow heading>
+ {t("labels.unCroppedDimension")}
+ </StatsRow>
+ )}
+
+ {appState.croppingElementId &&
+ isImageElement(singleElement) &&
+ unCroppedDimension && (
+ <StatsRow columns={2}>
+ <div>{t("stats.width")}</div>
+ <div>{round(unCroppedDimension.width, 2)}</div>
+ </StatsRow>
+ )}
+
+ {appState.croppingElementId &&
+ isImageElement(singleElement) &&
+ unCroppedDimension && (
+ <StatsRow columns={2}>
+ <div>{t("stats.height")}</div>
+ <div>{round(unCroppedDimension.height, 2)}</div>
+ </StatsRow>
+ )}
+
+ <StatsRow heading data-testid="stats-element-type">
+ {appState.croppingElementId
+ ? t("labels.imageCropping")
+ : t(`element.${singleElement.type}`)}
+ </StatsRow>
+
+ <StatsRow>
+ <Position
+ element={singleElement}
+ property="x"
+ elementsMap={elementsMap}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ <StatsRow>
+ <Position
+ element={singleElement}
+ property="y"
+ elementsMap={elementsMap}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ <StatsRow>
+ <Dimension
+ property="width"
+ element={singleElement}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ <StatsRow>
+ <Dimension
+ property="height"
+ element={singleElement}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ {!isElbowArrow(singleElement) && (
+ <StatsRow>
+ <Angle
+ property="angle"
+ element={singleElement}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ )}
+ <StatsRow>
+ <FontSize
+ property="fontSize"
+ element={singleElement}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ </>
+ )}
+
+ {multipleElements && (
+ <>
+ {elementsAreInSameGroup(multipleElements) && (
+ <StatsRow heading>{t("element.group")}</StatsRow>
+ )}
+
+ <StatsRow columns={2} style={{ margin: "0.3125rem 0" }}>
+ <div>{t("stats.shapes")}</div>
+ <div>{selectedElements.length}</div>
+ </StatsRow>
+
+ <StatsRow>
+ <MultiPosition
+ property="x"
+ elements={multipleElements}
+ elementsMap={elementsMap}
+ atomicUnits={atomicUnits}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ <StatsRow>
+ <MultiPosition
+ property="y"
+ elements={multipleElements}
+ elementsMap={elementsMap}
+ atomicUnits={atomicUnits}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ <StatsRow>
+ <MultiDimension
+ property="width"
+ elements={multipleElements}
+ elementsMap={elementsMap}
+ atomicUnits={atomicUnits}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ <StatsRow>
+ <MultiDimension
+ property="height"
+ elements={multipleElements}
+ elementsMap={elementsMap}
+ atomicUnits={atomicUnits}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ <StatsRow>
+ <MultiAngle
+ property="angle"
+ elements={multipleElements}
+ scene={scene}
+ appState={appState}
+ />
+ </StatsRow>
+ <StatsRow>
+ <MultiFontSize
+ property="fontSize"
+ elements={multipleElements}
+ scene={scene}
+ appState={appState}
+ elementsMap={elementsMap}
+ />
+ </StatsRow>
+ </>
+ )}
+ </StatsRows>
+ </Collapsible>
+ </div>
+ )}
+ </Island>
+ </div>
+ );
+ },
+ (prev, next) => {
+ return (
+ prev.sceneNonce === next.sceneNonce &&
+ prev.selectedElements === next.selectedElements &&
+ prev.appState.stats.panels === next.appState.stats.panels &&
+ prev.gridModeEnabled === next.gridModeEnabled &&
+ prev.appState.gridStep === next.appState.gridStep &&
+ prev.appState.croppingElementId === next.appState.croppingElementId
+ );
+ },
+);
diff --git a/packages/excalidraw/components/Stats/stats.test.tsx b/packages/excalidraw/components/Stats/stats.test.tsx
new file mode 100644
index 0000000..49d6a62
--- /dev/null
+++ b/packages/excalidraw/components/Stats/stats.test.tsx
@@ -0,0 +1,724 @@
+import React from "react";
+import { act, fireEvent, queryByTestId } from "@testing-library/react";
+import { Keyboard, Pointer, UI } from "../../tests/helpers/ui";
+import { getStepSizedValue } from "./utils";
+import {
+ GlobalTestState,
+ mockBoundingClientRect,
+ render,
+ restoreOriginalGetBoundingClientRect,
+} from "../../tests/test-utils";
+import * as StaticScene from "../../renderer/staticScene";
+import { vi } from "vitest";
+import { reseed } from "../../random";
+import { setDateTimeForTests } from "../../utils";
+import { Excalidraw, mutateElement } from "../..";
+import { t } from "../../i18n";
+import type {
+ ExcalidrawElement,
+ ExcalidrawLinearElement,
+ ExcalidrawTextElement,
+} from "../../element/types";
+import { getTextEditor, updateTextEditor } from "../../tests/queries/dom";
+import { getCommonBounds, isTextElement } from "../../element";
+import { API } from "../../tests/helpers/api";
+import { actionGroup } from "../../actions";
+import { isInGroup } from "../../groups";
+import type { Degrees } from "@excalidraw/math";
+import { degreesToRadians, pointFrom, pointRotateRads } from "@excalidraw/math";
+
+const { h } = window;
+const mouse = new Pointer("mouse");
+const renderStaticScene = vi.spyOn(StaticScene, "renderStaticScene");
+let stats: HTMLElement | null = null;
+let elementStats: HTMLElement | null | undefined = null;
+
+const testInputProperty = (
+ element: ExcalidrawElement,
+ property: "x" | "y" | "width" | "height" | "angle" | "fontSize",
+ label: string,
+ initialValue: number,
+ nextValue: number,
+) => {
+ const input = UI.queryStatsProperty(label)?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(input).toBeDefined();
+ expect(input.value).toBe(initialValue.toString());
+ UI.updateInput(input, String(nextValue));
+ if (property === "angle") {
+ expect(element[property]).toBe(
+ degreesToRadians(Number(nextValue) as Degrees),
+ );
+ } else if (property === "fontSize" && isTextElement(element)) {
+ expect(element[property]).toBe(Number(nextValue));
+ } else if (property !== "fontSize") {
+ expect(element[property]).toBe(Number(nextValue));
+ }
+};
+
+describe("step sized value", () => {
+ it("should return edge values correctly", () => {
+ const steps = [10, 15, 20, 25, 30];
+ const values = [10, 15, 20, 25, 30];
+
+ steps.forEach((step, idx) => {
+ expect(getStepSizedValue(values[idx], step)).toEqual(values[idx]);
+ });
+ });
+
+ it("step sized value lies in the middle", () => {
+ let stepSize = 15;
+ let values = [7.5, 9, 12, 14.99, 15, 22.49];
+
+ values.forEach((value) => {
+ expect(getStepSizedValue(value, stepSize)).toEqual(15);
+ });
+
+ stepSize = 10;
+ values = [-5, 4.99, 0, 1.23];
+ values.forEach((value) => {
+ expect(getStepSizedValue(value, stepSize)).toEqual(0);
+ });
+ });
+});
+
+describe("binding with linear elements", () => {
+ beforeEach(async () => {
+ localStorage.clear();
+ renderStaticScene.mockClear();
+ reseed(19);
+ setDateTimeForTests("201933152653");
+
+ await render(<Excalidraw handleKeyboardGlobally={true} />);
+
+ API.setElements([]);
+
+ fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
+ button: 2,
+ clientX: 1,
+ clientY: 1,
+ });
+ const contextMenu = UI.queryContextMenu();
+ fireEvent.click(queryByTestId(contextMenu!, "stats")!);
+ stats = UI.queryStats();
+
+ UI.clickTool("rectangle");
+ mouse.down();
+ mouse.up(200, 100);
+
+ UI.clickTool("arrow");
+ mouse.down(5, 0);
+ mouse.up(300, 50);
+
+ elementStats = stats?.querySelector("#elementStats");
+ });
+
+ beforeAll(() => {
+ mockBoundingClientRect();
+ });
+
+ afterAll(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("should remain bound to linear element on small position change", async () => {
+ const linear = h.elements[1] as ExcalidrawLinearElement;
+ const inputX = UI.queryStatsProperty("X")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+
+ expect(linear.startBinding).not.toBe(null);
+ expect(inputX).not.toBeNull();
+ UI.updateInput(inputX, String("204"));
+ expect(linear.startBinding).not.toBe(null);
+ });
+
+ it("should remain bound to linear element on small angle change", async () => {
+ const linear = h.elements[1] as ExcalidrawLinearElement;
+ const inputAngle = UI.queryStatsProperty("A")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+
+ expect(linear.startBinding).not.toBe(null);
+ UI.updateInput(inputAngle, String("1"));
+ expect(linear.startBinding).not.toBe(null);
+ });
+
+ it("should unbind linear element on large position change", async () => {
+ const linear = h.elements[1] as ExcalidrawLinearElement;
+ const inputX = UI.queryStatsProperty("X")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+
+ expect(linear.startBinding).not.toBe(null);
+ expect(inputX).not.toBeNull();
+ UI.updateInput(inputX, String("254"));
+ expect(linear.startBinding).toBe(null);
+ });
+
+ it("should remain bound to linear element on small angle change", async () => {
+ const linear = h.elements[1] as ExcalidrawLinearElement;
+ const inputAngle = UI.queryStatsProperty("A")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+
+ expect(linear.startBinding).not.toBe(null);
+ UI.updateInput(inputAngle, String("45"));
+ expect(linear.startBinding).toBe(null);
+ });
+});
+
+// single element
+describe("stats for a generic element", () => {
+ beforeEach(async () => {
+ localStorage.clear();
+ renderStaticScene.mockClear();
+ reseed(7);
+ setDateTimeForTests("201933152653");
+
+ await render(<Excalidraw handleKeyboardGlobally={true} />);
+
+ API.setElements([]);
+
+ fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
+ button: 2,
+ clientX: 1,
+ clientY: 1,
+ });
+ const contextMenu = UI.queryContextMenu();
+ fireEvent.click(queryByTestId(contextMenu!, "stats")!);
+ stats = UI.queryStats();
+
+ UI.clickTool("rectangle");
+ mouse.down();
+ mouse.up(200, 100);
+ elementStats = stats?.querySelector("#elementStats");
+ });
+
+ beforeAll(() => {
+ mockBoundingClientRect();
+ });
+
+ afterAll(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("should open stats", () => {
+ expect(stats).toBeDefined();
+ expect(elementStats).toBeDefined();
+
+ // title
+ const title = elementStats?.querySelector("h3");
+ expect(title?.lastChild?.nodeValue)?.toBe(t("stats.elementProperties"));
+
+ // element type
+ const elementType = queryByTestId(elementStats!, "stats-element-type");
+ expect(elementType).toBeDefined();
+ expect(elementType?.lastChild?.nodeValue).toBe(t("element.rectangle"));
+
+ // properties
+ ["X", "Y", "W", "H", "A"].forEach((label) => () => {
+ expect(
+ stats!.querySelector?.(`.drag-input-container[data-testid="${label}"]`),
+ ).toBeDefined();
+ });
+ });
+
+ it("should be able to edit all properties for a general element", () => {
+ const rectangle = h.elements[0];
+ const initialX = rectangle.x;
+ const initialY = rectangle.y;
+
+ testInputProperty(rectangle, "width", "W", 200, 100);
+ testInputProperty(rectangle, "height", "H", 100, 200);
+ testInputProperty(rectangle, "x", "X", initialX, 230);
+ testInputProperty(rectangle, "y", "Y", initialY, 220);
+ testInputProperty(rectangle, "angle", "A", 0, 45);
+ });
+
+ it("should keep only two decimal places", () => {
+ const rectangle = h.elements[0];
+ const rectangleId = rectangle.id;
+
+ const input = UI.queryStatsProperty("W")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(input).toBeDefined();
+ expect(input.value).toBe(rectangle.width.toString());
+ UI.updateInput(input, "123.123");
+ expect(h.elements.length).toBe(1);
+ expect(rectangle.id).toBe(rectangleId);
+ expect(input.value).toBe("123.12");
+ expect(rectangle.width).toBe(123.12);
+
+ UI.updateInput(input, "88.98766");
+ expect(input.value).toBe("88.99");
+ expect(rectangle.width).toBe(88.99);
+ });
+
+ it("should update input x and y when angle is changed", () => {
+ const rectangle = h.elements[0];
+ const [cx, cy] = [
+ rectangle.x + rectangle.width / 2,
+ rectangle.y + rectangle.height / 2,
+ ];
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(rectangle.x, rectangle.y),
+ pointFrom(cx, cy),
+ rectangle.angle,
+ );
+
+ const xInput = UI.queryStatsProperty("X")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+
+ const yInput = UI.queryStatsProperty("Y")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+
+ expect(xInput.value).toBe(topLeftX.toString());
+ expect(yInput.value).toBe(topLeftY.toString());
+
+ testInputProperty(rectangle, "angle", "A", 0, 45);
+
+ let [newTopLeftX, newTopLeftY] = pointRotateRads(
+ pointFrom(rectangle.x, rectangle.y),
+ pointFrom(cx, cy),
+ rectangle.angle,
+ );
+
+ expect(newTopLeftX.toString()).not.toEqual(xInput.value);
+ expect(newTopLeftY.toString()).not.toEqual(yInput.value);
+
+ testInputProperty(rectangle, "angle", "A", 45, 66);
+
+ [newTopLeftX, newTopLeftY] = pointRotateRads(
+ pointFrom(rectangle.x, rectangle.y),
+ pointFrom(cx, cy),
+ rectangle.angle,
+ );
+ expect(newTopLeftX.toString()).not.toEqual(xInput.value);
+ expect(newTopLeftY.toString()).not.toEqual(yInput.value);
+ });
+
+ it("should fix top left corner when width or height is changed", () => {
+ const rectangle = h.elements[0];
+
+ testInputProperty(rectangle, "angle", "A", 0, 45);
+ let [cx, cy] = [
+ rectangle.x + rectangle.width / 2,
+ rectangle.y + rectangle.height / 2,
+ ];
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(rectangle.x, rectangle.y),
+ pointFrom(cx, cy),
+ rectangle.angle,
+ );
+ testInputProperty(rectangle, "width", "W", rectangle.width, 400);
+ [cx, cy] = [
+ rectangle.x + rectangle.width / 2,
+ rectangle.y + rectangle.height / 2,
+ ];
+ let [currentTopLeftX, currentTopLeftY] = pointRotateRads(
+ pointFrom(rectangle.x, rectangle.y),
+ pointFrom(cx, cy),
+ rectangle.angle,
+ );
+ expect(currentTopLeftX).toBeCloseTo(topLeftX, 4);
+ expect(currentTopLeftY).toBeCloseTo(topLeftY, 4);
+
+ testInputProperty(rectangle, "height", "H", rectangle.height, 400);
+ [cx, cy] = [
+ rectangle.x + rectangle.width / 2,
+ rectangle.y + rectangle.height / 2,
+ ];
+ [currentTopLeftX, currentTopLeftY] = pointRotateRads(
+ pointFrom(rectangle.x, rectangle.y),
+ pointFrom(cx, cy),
+ rectangle.angle,
+ );
+
+ expect(currentTopLeftX).toBeCloseTo(topLeftX, 4);
+ expect(currentTopLeftY).toBeCloseTo(topLeftY, 4);
+ });
+});
+
+describe("stats for a non-generic element", () => {
+ beforeEach(async () => {
+ localStorage.clear();
+ renderStaticScene.mockClear();
+ reseed(7);
+ setDateTimeForTests("201933152653");
+
+ await render(<Excalidraw handleKeyboardGlobally={true} />);
+
+ API.setElements([]);
+
+ fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
+ button: 2,
+ clientX: 1,
+ clientY: 1,
+ });
+ const contextMenu = UI.queryContextMenu();
+ fireEvent.click(queryByTestId(contextMenu!, "stats")!);
+ stats = UI.queryStats();
+ });
+
+ beforeAll(() => {
+ mockBoundingClientRect();
+ });
+
+ afterAll(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("text element", async () => {
+ UI.clickTool("text");
+ mouse.clickAt(20, 30);
+ const textEditorSelector = ".excalidraw-textEditorContainer > textarea";
+ const editor = await getTextEditor(textEditorSelector, true);
+ updateTextEditor(editor, "Hello!");
+ act(() => {
+ editor.blur();
+ });
+
+ const text = h.elements[0] as ExcalidrawTextElement;
+ mouse.clickOn(text);
+
+ elementStats = stats?.querySelector("#elementStats");
+
+ // can change font size
+ const input = UI.queryStatsProperty("F")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(input).toBeDefined();
+ expect(input.value).toBe(text.fontSize.toString());
+ UI.updateInput(input, "36");
+ expect(text.fontSize).toBe(36);
+
+ // cannot change width or height
+ const width = UI.queryStatsProperty("W")?.querySelector(".drag-input");
+ expect(width).toBeUndefined();
+ const height = UI.queryStatsProperty("H")?.querySelector(".drag-input");
+ expect(height).toBeUndefined();
+
+ // min font size is 4
+ UI.updateInput(input, "0");
+ expect(text.fontSize).not.toBe(0);
+ expect(text.fontSize).toBe(4);
+ });
+
+ it("frame element", () => {
+ const frame = API.createElement({
+ id: "id0",
+ type: "frame",
+ x: 150,
+ width: 150,
+ });
+ API.setElements([frame]);
+ API.setAppState({
+ selectedElementIds: {
+ [frame.id]: true,
+ },
+ });
+
+ elementStats = stats?.querySelector("#elementStats");
+
+ expect(elementStats).toBeDefined();
+
+ // cannot change angle
+ const angle = UI.queryStatsProperty("A")?.querySelector(".drag-input");
+ expect(angle).toBeUndefined();
+
+ // can change width or height
+ testInputProperty(frame, "width", "W", frame.width, 250);
+ testInputProperty(frame, "height", "H", frame.height, 500);
+ });
+
+ it("image element", () => {
+ const image = API.createElement({ type: "image", width: 200, height: 100 });
+ API.setElements([image]);
+ mouse.clickOn(image);
+ API.setAppState({
+ selectedElementIds: {
+ [image.id]: true,
+ },
+ });
+ elementStats = stats?.querySelector("#elementStats");
+ expect(elementStats).toBeDefined();
+ const widthToHeight = image.width / image.height;
+
+ // when width or height is changed, the aspect ratio is preserved
+ testInputProperty(image, "width", "W", image.width, 400);
+ expect(image.width).toBe(400);
+ expect(image.width / image.height).toBe(widthToHeight);
+
+ testInputProperty(image, "height", "H", image.height, 80);
+ expect(image.height).toBe(80);
+ expect(image.width / image.height).toBe(widthToHeight);
+ });
+
+ it("should display fontSize for bound text", () => {
+ const container = API.createElement({
+ type: "rectangle",
+ width: 200,
+ height: 100,
+ });
+ const text = API.createElement({
+ type: "text",
+ width: 200,
+ height: 100,
+ containerId: container.id,
+ fontSize: 20,
+ });
+ mutateElement(container, {
+ boundElements: [{ type: "text", id: text.id }],
+ });
+ API.setElements([container, text]);
+
+ API.setSelectedElements([container]);
+ const fontSize = UI.queryStatsProperty("F")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(fontSize).toBeDefined();
+
+ UI.updateInput(fontSize, "40");
+
+ expect(text.fontSize).toBe(40);
+ });
+});
+
+// multiple elements
+describe("stats for multiple elements", () => {
+ beforeEach(async () => {
+ mouse.reset();
+ localStorage.clear();
+ renderStaticScene.mockClear();
+ reseed(7);
+ setDateTimeForTests("201933152653");
+
+ await render(<Excalidraw handleKeyboardGlobally={true} />);
+
+ API.setElements([]);
+
+ fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
+ button: 2,
+ clientX: 1,
+ clientY: 1,
+ });
+ const contextMenu = UI.queryContextMenu();
+ fireEvent.click(queryByTestId(contextMenu!, "stats")!);
+ stats = UI.queryStats();
+ });
+
+ beforeAll(() => {
+ mockBoundingClientRect();
+ });
+
+ afterAll(() => {
+ restoreOriginalGetBoundingClientRect();
+ });
+
+ it("should display MIXED for elements with different values", () => {
+ UI.clickTool("rectangle");
+ mouse.down();
+ mouse.up(200, 100);
+
+ UI.clickTool("ellipse");
+ mouse.down(50, 50);
+ mouse.up(100, 100);
+
+ UI.clickTool("diamond");
+ mouse.down(-100, -100);
+ mouse.up(125, 145);
+
+ API.setAppState({
+ selectedElementIds: h.elements.reduce((acc, el) => {
+ acc[el.id] = true;
+ return acc;
+ }, {} as Record<string, true>),
+ });
+
+ elementStats = stats?.querySelector("#elementStats");
+
+ const width = UI.queryStatsProperty("W")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(width?.value).toBe("Mixed");
+ const height = UI.queryStatsProperty("H")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(height?.value).toBe("Mixed");
+ const angle = UI.queryStatsProperty("A")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(angle.value).toBe("0");
+
+ UI.updateInput(width, "250");
+ h.elements.forEach((el) => {
+ expect(el.width).toBe(250);
+ });
+
+ UI.updateInput(height, "450");
+ h.elements.forEach((el) => {
+ expect(el.height).toBe(450);
+ });
+ });
+
+ it("should display a property when one of the elements is editable for that property", async () => {
+ // text, rectangle, frame
+ UI.clickTool("text");
+ mouse.clickAt(20, 30);
+ const textEditorSelector = ".excalidraw-textEditorContainer > textarea";
+ const editor = await getTextEditor(textEditorSelector, true);
+ updateTextEditor(editor, "Hello!");
+ act(() => {
+ editor.blur();
+ });
+
+ UI.clickTool("rectangle");
+ mouse.down();
+ mouse.up(200, 100);
+
+ const frame = API.createElement({
+ type: "frame",
+ x: 150,
+ width: 150,
+ });
+
+ API.setElements([...h.elements, frame]);
+
+ const text = h.elements.find((el) => el.type === "text");
+ const rectangle = h.elements.find((el) => el.type === "rectangle");
+
+ API.setAppState({
+ selectedElementIds: h.elements.reduce((acc, el) => {
+ acc[el.id] = true;
+ return acc;
+ }, {} as Record<string, true>),
+ });
+
+ elementStats = stats?.querySelector("#elementStats");
+
+ const width = UI.queryStatsProperty("W")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(width).toBeDefined();
+ expect(width.value).toBe("Mixed");
+
+ const height = UI.queryStatsProperty("H")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(height).toBeDefined();
+ expect(height.value).toBe("Mixed");
+
+ const angle = UI.queryStatsProperty("A")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(angle).toBeDefined();
+ expect(angle.value).toBe("0");
+
+ const fontSize = UI.queryStatsProperty("F")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(fontSize).toBeDefined();
+
+ // changing width does not affect text
+ UI.updateInput(width, "200");
+
+ expect(rectangle?.width).toBe(200);
+ expect(frame.width).toBe(200);
+ expect(text?.width).not.toBe(200);
+
+ UI.updateInput(angle, "40");
+
+ const angleInRadian = degreesToRadians(40 as Degrees);
+ expect(rectangle?.angle).toBeCloseTo(angleInRadian, 4);
+ expect(text?.angle).toBeCloseTo(angleInRadian, 4);
+ expect(frame.angle).toBe(0);
+ });
+
+ it("should treat groups as single units", () => {
+ const createAndSelectGroup = () => {
+ UI.clickTool("rectangle");
+ mouse.down();
+ mouse.up(100, 100);
+
+ UI.clickTool("rectangle");
+ mouse.down(0, 0);
+ mouse.up(100, 100);
+
+ mouse.reset();
+ Keyboard.withModifierKeys({ shift: true }, () => {
+ mouse.click();
+ });
+
+ API.executeAction(actionGroup);
+ };
+
+ createAndSelectGroup();
+
+ const elementsInGroup = h.elements.filter((el) => isInGroup(el));
+ let [x1, y1, x2, y2] = getCommonBounds(elementsInGroup);
+
+ elementStats = stats?.querySelector("#elementStats");
+
+ const x = UI.queryStatsProperty("X")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+
+ expect(x).toBeDefined();
+ expect(Number(x.value)).toBe(x1);
+
+ UI.updateInput(x, "300");
+
+ expect(h.elements[0].x).toBe(300);
+ expect(h.elements[1].x).toBe(400);
+ expect(x.value).toBe("300");
+
+ const y = UI.queryStatsProperty("Y")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+
+ expect(y).toBeDefined();
+ expect(Number(y.value)).toBe(y1);
+
+ UI.updateInput(y, "200");
+
+ expect(h.elements[0].y).toBe(200);
+ expect(h.elements[1].y).toBe(300);
+ expect(y.value).toBe("200");
+
+ const width = UI.queryStatsProperty("W")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(width).toBeDefined();
+ expect(Number(width.value)).toBe(200);
+
+ const height = UI.queryStatsProperty("H")?.querySelector(
+ ".drag-input",
+ ) as HTMLInputElement;
+ expect(height).toBeDefined();
+ expect(Number(height.value)).toBe(200);
+
+ UI.updateInput(width, "400");
+
+ [x1, y1, x2, y2] = getCommonBounds(elementsInGroup);
+ let newGroupWidth = x2 - x1;
+
+ expect(newGroupWidth).toBeCloseTo(400, 4);
+
+ UI.updateInput(width, "300");
+
+ [x1, y1, x2, y2] = getCommonBounds(elementsInGroup);
+ newGroupWidth = x2 - x1;
+ expect(newGroupWidth).toBeCloseTo(300, 4);
+
+ UI.updateInput(height, "500");
+
+ [x1, y1, x2, y2] = getCommonBounds(elementsInGroup);
+ const newGroupHeight = y2 - y1;
+ expect(newGroupHeight).toBeCloseTo(500, 4);
+ });
+});
diff --git a/packages/excalidraw/components/Stats/utils.ts b/packages/excalidraw/components/Stats/utils.ts
new file mode 100644
index 0000000..61555ba
--- /dev/null
+++ b/packages/excalidraw/components/Stats/utils.ts
@@ -0,0 +1,219 @@
+import type { Radians } from "@excalidraw/math";
+import { pointFrom, pointRotateRads } from "@excalidraw/math";
+import {
+ bindOrUnbindLinearElements,
+ updateBoundElements,
+} from "../../element/binding";
+import { mutateElement } from "../../element/mutateElement";
+import { getBoundTextElement } from "../../element/textElement";
+import {
+ isFrameLikeElement,
+ isLinearElement,
+ isTextElement,
+} from "../../element/typeChecks";
+import type {
+ ElementsMap,
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+ NonDeletedSceneElementsMap,
+} from "../../element/types";
+import {
+ getSelectedGroupIds,
+ getElementsInGroup,
+ isInGroup,
+} from "../../groups";
+import type Scene from "../../scene/Scene";
+import type { AppState } from "../../types";
+
+export type StatsInputProperty =
+ | "x"
+ | "y"
+ | "width"
+ | "height"
+ | "angle"
+ | "fontSize"
+ | "gridStep";
+
+export const SMALLEST_DELTA = 0.01;
+
+export const isPropertyEditable = (
+ element: ExcalidrawElement,
+ property: keyof ExcalidrawElement,
+) => {
+ if (property === "height" && isTextElement(element)) {
+ return false;
+ }
+ if (property === "width" && isTextElement(element)) {
+ return false;
+ }
+ if (property === "angle" && isFrameLikeElement(element)) {
+ return false;
+ }
+ return true;
+};
+
+export const getStepSizedValue = (value: number, stepSize: number) => {
+ const v = value + stepSize / 2;
+ return v - (v % stepSize);
+};
+
+export type AtomicUnit = Record<string, true>;
+export const getElementsInAtomicUnit = (
+ atomicUnit: AtomicUnit,
+ elementsMap: ElementsMap,
+ originalElementsMap?: ElementsMap,
+) => {
+ return Object.keys(atomicUnit)
+ .map((id) => ({
+ original: (originalElementsMap ?? elementsMap).get(id),
+ latest: elementsMap.get(id),
+ }))
+ .filter((el) => el.original !== undefined && el.latest !== undefined) as {
+ original: NonDeletedExcalidrawElement;
+ latest: NonDeletedExcalidrawElement;
+ }[];
+};
+
+export const newOrigin = (
+ x1: number,
+ y1: number,
+ w1: number,
+ h1: number,
+ w2: number,
+ h2: number,
+ angle: number,
+) => {
+ /**
+ * The formula below is the result of solving
+ * rotate(x1, y1, cx1, cy1, angle) = rotate(x2, y2, cx2, cy2, angle)
+ * where rotate is the function defined in math.ts
+ *
+ * This is so that the new origin (x2, y2),
+ * when rotated against the new center (cx2, cy2),
+ * coincides with (x1, y1) rotated against (cx1, cy1)
+ *
+ * The reason for doing this computation is so the element's top left corner
+ * on the canvas remains fixed after any changes in its dimension.
+ */
+
+ return {
+ x:
+ x1 +
+ (w1 - w2) / 2 +
+ ((w2 - w1) / 2) * Math.cos(angle) +
+ ((h1 - h2) / 2) * Math.sin(angle),
+ y:
+ y1 +
+ (h1 - h2) / 2 +
+ ((w2 - w1) / 2) * Math.sin(angle) +
+ ((h2 - h1) / 2) * Math.cos(angle),
+ };
+};
+
+export const moveElement = (
+ newTopLeftX: number,
+ newTopLeftY: number,
+ originalElement: ExcalidrawElement,
+ elementsMap: NonDeletedSceneElementsMap,
+ elements: readonly NonDeletedExcalidrawElement[],
+ scene: Scene,
+ originalElementsMap: ElementsMap,
+ shouldInformMutation = true,
+) => {
+ const latestElement = elementsMap.get(originalElement.id);
+ if (!latestElement) {
+ return;
+ }
+ const [cx, cy] = [
+ originalElement.x + originalElement.width / 2,
+ originalElement.y + originalElement.height / 2,
+ ];
+ const [topLeftX, topLeftY] = pointRotateRads(
+ pointFrom(originalElement.x, originalElement.y),
+ pointFrom(cx, cy),
+ originalElement.angle,
+ );
+
+ const changeInX = newTopLeftX - topLeftX;
+ const changeInY = newTopLeftY - topLeftY;
+
+ const [x, y] = pointRotateRads(
+ pointFrom(newTopLeftX, newTopLeftY),
+ pointFrom(cx + changeInX, cy + changeInY),
+ -originalElement.angle as Radians,
+ );
+
+ mutateElement(
+ latestElement,
+ {
+ x,
+ y,
+ },
+ shouldInformMutation,
+ );
+ updateBindings(latestElement, elementsMap, elements, scene);
+
+ const boundTextElement = getBoundTextElement(
+ originalElement,
+ originalElementsMap,
+ );
+ if (boundTextElement) {
+ const latestBoundTextElement = elementsMap.get(boundTextElement.id);
+ latestBoundTextElement &&
+ mutateElement(
+ latestBoundTextElement,
+ {
+ x: boundTextElement.x + changeInX,
+ y: boundTextElement.y + changeInY,
+ },
+ shouldInformMutation,
+ );
+ }
+};
+
+export const getAtomicUnits = (
+ targetElements: readonly ExcalidrawElement[],
+ appState: AppState,
+) => {
+ const selectedGroupIds = getSelectedGroupIds(appState);
+ const _atomicUnits = selectedGroupIds.map((gid) => {
+ return getElementsInGroup(targetElements, gid).reduce((acc, el) => {
+ acc[el.id] = true;
+ return acc;
+ }, {} as AtomicUnit);
+ });
+ targetElements
+ .filter((el) => !isInGroup(el))
+ .forEach((el) => {
+ _atomicUnits.push({
+ [el.id]: true,
+ });
+ });
+ return _atomicUnits;
+};
+
+export const updateBindings = (
+ latestElement: ExcalidrawElement,
+ elementsMap: NonDeletedSceneElementsMap,
+ elements: readonly NonDeletedExcalidrawElement[],
+ scene: Scene,
+ options?: {
+ simultaneouslyUpdated?: readonly ExcalidrawElement[];
+ newSize?: { width: number; height: number };
+ zoom?: AppState["zoom"];
+ },
+) => {
+ if (isLinearElement(latestElement)) {
+ bindOrUnbindLinearElements(
+ [latestElement],
+ elementsMap,
+ elements,
+ scene,
+ true,
+ [],
+ options?.zoom,
+ );
+ } else {
+ updateBoundElements(latestElement, elementsMap, options);
+ }
+};
diff --git a/packages/excalidraw/components/Switch.scss b/packages/excalidraw/components/Switch.scss
new file mode 100644
index 0000000..894f806
--- /dev/null
+++ b/packages/excalidraw/components/Switch.scss
@@ -0,0 +1,118 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ --Switch-disabled-color: var(--color-border-outline);
+ --Switch-disabled-toggled-background: var(--color-border-outline-variant);
+ --Switch-disabled-border: var(--color-border-outline-variant);
+ --Switch-track-background: var(--island-bg-color);
+ --Switch-thumb-background: var(--color-on-surface);
+ --Switch-hover-background: var(--color-brand-hover);
+ --Switch-active-background: var(--color-brand-active);
+
+ .Switch {
+ position: relative;
+ box-sizing: border-box;
+
+ width: 40px;
+ height: 20px;
+ border-radius: 12px;
+
+ transition-property: background, border;
+ transition-duration: 150ms;
+ transition-timing-function: ease-out;
+
+ background: var(--Switch-track-background);
+ border: 1px solid var(--Switch-disabled-color);
+
+ &:hover {
+ background: var(--Switch-track-background);
+ border: 1px solid var(--Switch-hover-background);
+ }
+
+ &:active {
+ border: 1px solid var(--Switch-active-background);
+ }
+
+ &.toggled {
+ background: var(--color-primary);
+ border: 1px solid var(--color-primary);
+
+ &:hover {
+ background: var(--color-primary-darker);
+ border: 1px solid var(--color-primary-darker);
+ }
+ }
+
+ &.disabled {
+ background: var(--Switch-track-background);
+ border: 1px solid var(--Switch-disabled-border);
+
+ &.toggled {
+ background: var(--Switch-disabled-toggled-background);
+ border: 1px solid var(--Switch-disabled-toggled-background);
+ }
+ }
+
+ &:before {
+ content: "";
+ box-sizing: border-box;
+ display: block;
+ pointer-events: none;
+ position: absolute;
+
+ border-radius: 100%;
+ transition: all 150ms ease-out;
+
+ width: 10px;
+ height: 10px;
+ top: 4px;
+ left: 4px;
+
+ background: var(--Switch-thumb-background);
+ }
+
+ &:active:before {
+ width: 12px;
+ }
+
+ &.toggled:before {
+ width: 14px;
+ height: 14px;
+ left: 22px;
+ top: 2px;
+
+ background: var(--Switch-track-background);
+ }
+
+ &.toggled:active:before {
+ width: 16px;
+ left: 20px;
+ }
+
+ &.disabled:before {
+ background: var(--Switch-disabled-color);
+ }
+
+ &.disabled.toggled:before {
+ background: var(--Switch-disabled-color);
+ }
+
+ & input {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+
+ border-radius: 12px;
+
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ appearance: none;
+
+ cursor: pointer;
+
+ &:disabled {
+ cursor: unset;
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Switch.tsx b/packages/excalidraw/components/Switch.tsx
new file mode 100644
index 0000000..431c644
--- /dev/null
+++ b/packages/excalidraw/components/Switch.tsx
@@ -0,0 +1,38 @@
+import clsx from "clsx";
+
+import "./Switch.scss";
+
+export type SwitchProps = {
+ name: string;
+ checked: boolean;
+ title?: string;
+ onChange: (value: boolean) => void;
+ disabled?: boolean;
+};
+
+export const Switch = ({
+ title,
+ name,
+ checked,
+ onChange,
+ disabled = false,
+}: SwitchProps) => {
+ return (
+ <div className={clsx("Switch", { toggled: checked, disabled })}>
+ <input
+ name={name}
+ id={name}
+ title={title}
+ type="checkbox"
+ checked={checked}
+ disabled={disabled}
+ onChange={() => onChange(!checked)}
+ onKeyDown={(event) => {
+ if (event.key === " ") {
+ onChange(!checked);
+ }
+ }}
+ />
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.scss b/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.scss
new file mode 100644
index 0000000..2a9a40b
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.scss
@@ -0,0 +1,10 @@
+.excalidraw {
+ .dialog-mermaid {
+ &-title {
+ margin-block: 0.25rem;
+ font-size: 1.25rem;
+ font-weight: 700;
+ padding-inline: 2.5rem;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx b/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx
new file mode 100644
index 0000000..83fb91d
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx
@@ -0,0 +1,132 @@
+import { useState, useRef, useEffect, useDeferredValue } from "react";
+import type { BinaryFiles } from "../../types";
+import { useApp } from "../App";
+import type { NonDeletedExcalidrawElement } from "../../element/types";
+import { ArrowRightIcon } from "../icons";
+import "./MermaidToExcalidraw.scss";
+import { t } from "../../i18n";
+import Trans from "../Trans";
+import type { MermaidToExcalidrawLibProps } from "./common";
+import {
+ convertMermaidToExcalidraw,
+ insertToEditor,
+ saveMermaidDataToStorage,
+} from "./common";
+import { TTDDialogPanels } from "./TTDDialogPanels";
+import { TTDDialogPanel } from "./TTDDialogPanel";
+import { TTDDialogInput } from "./TTDDialogInput";
+import { TTDDialogOutput } from "./TTDDialogOutput";
+import { EditorLocalStorage } from "../../data/EditorLocalStorage";
+import { EDITOR_LS_KEYS } from "../../constants";
+import { debounce, isDevEnv } from "../../utils";
+import { TTDDialogSubmitShortcut } from "./TTDDialogSubmitShortcut";
+
+const MERMAID_EXAMPLE =
+ "flowchart TD\n A[Christmas] -->|Get money| B(Go shopping)\n B --> C{Let me think}\n C -->|One| D[Laptop]\n C -->|Two| E[iPhone]\n C -->|Three| F[Car]";
+
+const debouncedSaveMermaidDefinition = debounce(saveMermaidDataToStorage, 300);
+
+const MermaidToExcalidraw = ({
+ mermaidToExcalidrawLib,
+}: {
+ mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
+}) => {
+ const [text, setText] = useState(
+ () =>
+ EditorLocalStorage.get<string>(EDITOR_LS_KEYS.MERMAID_TO_EXCALIDRAW) ||
+ MERMAID_EXAMPLE,
+ );
+ const deferredText = useDeferredValue(text.trim());
+ const [error, setError] = useState<Error | null>(null);
+
+ const canvasRef = useRef<HTMLDivElement>(null);
+ const data = useRef<{
+ elements: readonly NonDeletedExcalidrawElement[];
+ files: BinaryFiles | null;
+ }>({ elements: [], files: null });
+
+ const app = useApp();
+
+ useEffect(() => {
+ convertMermaidToExcalidraw({
+ canvasRef,
+ data,
+ mermaidToExcalidrawLib,
+ setError,
+ mermaidDefinition: deferredText,
+ }).catch((err) => {
+ if (isDevEnv()) {
+ console.error("Failed to parse mermaid definition", err);
+ }
+ });
+
+ debouncedSaveMermaidDefinition(deferredText);
+ }, [deferredText, mermaidToExcalidrawLib]);
+
+ useEffect(
+ () => () => {
+ debouncedSaveMermaidDefinition.flush();
+ },
+ [],
+ );
+
+ const onInsertToEditor = () => {
+ insertToEditor({
+ app,
+ data,
+ text,
+ shouldSaveMermaidDataToStorage: true,
+ });
+ };
+
+ return (
+ <>
+ <div className="ttd-dialog-desc">
+ <Trans
+ i18nKey="mermaid.description"
+ flowchartLink={(el) => (
+ <a href="https://mermaid.js.org/syntax/flowchart.html">{el}</a>
+ )}
+ sequenceLink={(el) => (
+ <a href="https://mermaid.js.org/syntax/sequenceDiagram.html">
+ {el}
+ </a>
+ )}
+ classLink={(el) => (
+ <a href="https://mermaid.js.org/syntax/classDiagram.html">{el}</a>
+ )}
+ />
+ </div>
+ <TTDDialogPanels>
+ <TTDDialogPanel label={t("mermaid.syntax")}>
+ <TTDDialogInput
+ input={text}
+ placeholder={"Write Mermaid diagram defintion here..."}
+ onChange={(event) => setText(event.target.value)}
+ onKeyboardSubmit={() => {
+ onInsertToEditor();
+ }}
+ />
+ </TTDDialogPanel>
+ <TTDDialogPanel
+ label={t("mermaid.preview")}
+ panelAction={{
+ action: () => {
+ onInsertToEditor();
+ },
+ label: t("mermaid.button"),
+ icon: ArrowRightIcon,
+ }}
+ renderSubmitShortcut={() => <TTDDialogSubmitShortcut />}
+ >
+ <TTDDialogOutput
+ canvasRef={canvasRef}
+ loaded={mermaidToExcalidrawLib.loaded}
+ error={error}
+ />
+ </TTDDialogPanel>
+ </TTDDialogPanels>
+ </>
+ );
+};
+export default MermaidToExcalidraw;
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialog.scss b/packages/excalidraw/components/TTDDialog/TTDDialog.scss
new file mode 100644
index 0000000..37ec336
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialog.scss
@@ -0,0 +1,315 @@
+@import "../../css/variables.module.scss";
+
+$verticalBreakpoint: 861px;
+
+.excalidraw {
+ .Modal.Dialog.ttd-dialog {
+ padding: 1.25rem;
+
+ &.Dialog--fullscreen {
+ margin-top: 0;
+ }
+
+ .Island {
+ padding-inline: 0 !important;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ box-shadow: none;
+ }
+
+ .Modal__content {
+ height: auto;
+ max-height: 100%;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ max-height: 750px;
+ height: 100%;
+ }
+ }
+
+ .Dialog__content {
+ flex: 1 1 auto;
+ }
+ }
+
+ .ttd-dialog-desc {
+ font-size: 15px;
+ font-style: italic;
+ font-weight: 500;
+ margin-bottom: 1.5rem;
+ }
+
+ .ttd-dialog-tabs-root {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .ttd-dialog-tab-trigger {
+ color: var(--color-on-surface);
+ font-size: 0.875rem;
+ margin: 0;
+ padding: 0 1rem;
+ background-color: transparent;
+ border: 0;
+ height: 2.875rem;
+ font-weight: 600;
+ font-family: inherit;
+ letter-spacing: 0.4px;
+
+ &[data-state="active"] {
+ border-bottom: 2px solid var(--color-primary);
+ }
+ }
+
+ .ttd-dialog-triggers {
+ border-bottom: 1px solid var(--color-surface-high);
+ margin-bottom: 1.5rem;
+ padding-inline: 2.5rem;
+ }
+
+ .ttd-dialog-content {
+ padding-inline: 2.5rem;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+
+ &[hidden] {
+ display: none;
+ }
+ }
+
+ .ttd-dialog-input {
+ width: auto;
+ height: 10rem;
+ resize: none;
+ border-radius: var(--border-radius-lg);
+ border: 1px solid var(--dialog-border-color);
+ white-space: pre-wrap;
+ padding: 0.85rem;
+ box-sizing: border-box;
+ font-family: monospace;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ width: 100%;
+ height: 100%;
+ }
+ }
+
+ .ttd-dialog-output-wrapper {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0.85rem;
+ box-sizing: border-box;
+ flex-grow: 1;
+ position: relative;
+
+ background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")
+ left center;
+ border-radius: var(--border-radius-lg);
+ border: 1px solid var(--dialog-border-color);
+
+ height: 400px;
+ width: auto;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ width: 100%;
+ // acts as min-height
+ height: 200px;
+ }
+
+ canvas {
+ max-width: 100%;
+ max-height: 100%;
+ }
+ }
+
+ .ttd-dialog-output-canvas-container {
+ display: flex;
+ width: 100%;
+ height: 100%;
+ align-items: center;
+ justify-content: center;
+ flex-grow: 1;
+ }
+
+ .ttd-dialog-output-error {
+ color: red;
+ font-weight: 700;
+ font-size: 30px;
+ word-break: break-word;
+ overflow: auto;
+ max-height: 100%;
+ height: 100%;
+ width: 100%;
+ text-align: center;
+ position: absolute;
+ z-index: 10;
+
+ p {
+ font-weight: 500;
+ font-family: Cascadia;
+ text-align: left;
+ white-space: pre-wrap;
+ font-size: 0.875rem;
+ padding: 0 10px;
+ }
+ }
+
+ .ttd-dialog-panels {
+ height: 100%;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 4rem;
+ }
+ }
+
+ .ttd-dialog-panel {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+
+ &__header {
+ display: flex;
+ margin: 0px 4px 4px 4px;
+ align-items: center;
+ gap: 1rem;
+
+ label {
+ font-size: 14px;
+ font-style: normal;
+ font-weight: 600;
+ }
+ }
+
+ &:first-child {
+ .ttd-dialog-panel-button-container:not(.invisible) {
+ margin-bottom: 4rem;
+ }
+ }
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ .ttd-dialog-panel-button-container:not(.invisible) {
+ margin-bottom: 0.5rem !important;
+ }
+ }
+
+ textarea {
+ height: 100%;
+ resize: none;
+ border-radius: var(--border-radius-lg);
+ border: 1px solid var(--dialog-border-color);
+ white-space: pre-wrap;
+ padding: 0.85rem;
+ box-sizing: border-box;
+ width: 100%;
+ font-family: monospace;
+
+ @media screen and (max-width: $verticalBreakpoint) {
+ width: auto;
+ height: 10rem;
+ }
+ }
+ }
+
+ .ttd-dialog-panel-button-container {
+ margin-top: 1rem;
+ margin-bottom: 0.5rem;
+
+ &.invisible {
+ .ttd-dialog-panel-button {
+ display: none;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ display: block;
+ visibility: hidden;
+ }
+ }
+ }
+ }
+
+ .ttd-dialog-panel-button {
+ &.excalidraw-button {
+ font-family: inherit;
+ font-weight: 600;
+ height: 2.5rem;
+
+ font-size: 12px;
+ color: $oc-white;
+ background-color: var(--color-primary);
+ width: 100%;
+
+ &:hover {
+ background-color: var(--color-primary-darker);
+ }
+ &:active {
+ background-color: var(--color-primary-darkest);
+ }
+
+ &:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+
+ &:hover {
+ background-color: var(--color-primary);
+ }
+ }
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ width: auto;
+ min-width: 7.5rem;
+ }
+
+ @at-root .excalidraw.theme--dark#{&} {
+ color: var(--color-gray-100);
+ }
+ }
+
+ position: relative;
+
+ div {
+ display: contents;
+
+ &.invisible {
+ visibility: hidden;
+ }
+
+ &.Spinner {
+ display: flex !important;
+ position: absolute;
+ inset: 0;
+
+ --spinner-color: white;
+
+ @at-root .excalidraw.theme--dark#{&} {
+ --spinner-color: var(--color-gray-100);
+ }
+ }
+
+ span {
+ padding-left: 0.5rem;
+ display: flex;
+ }
+ }
+ }
+
+ .ttd-dialog-submit-shortcut {
+ margin-inline-start: 0.5rem;
+ font-size: 0.625rem;
+ opacity: 0.6;
+ display: flex;
+ gap: 0.125rem;
+
+ &__key {
+ border: 1px solid gray;
+ padding: 2px 3px;
+ border-radius: 4px;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialog.tsx b/packages/excalidraw/components/TTDDialog/TTDDialog.tsx
new file mode 100644
index 0000000..c77dfbf
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialog.tsx
@@ -0,0 +1,394 @@
+import { Dialog } from "../Dialog";
+import { useApp, useExcalidrawSetAppState } from "../App";
+import MermaidToExcalidraw from "./MermaidToExcalidraw";
+import TTDDialogTabs from "./TTDDialogTabs";
+import type { ChangeEventHandler } from "react";
+import { useEffect, useRef, useState } from "react";
+import { useUIAppState } from "../../context/ui-appState";
+import { withInternalFallback } from "../hoc/withInternalFallback";
+import { TTDDialogTabTriggers } from "./TTDDialogTabTriggers";
+import { TTDDialogTabTrigger } from "./TTDDialogTabTrigger";
+import { TTDDialogTab } from "./TTDDialogTab";
+import { t } from "../../i18n";
+import { TTDDialogInput } from "./TTDDialogInput";
+import { TTDDialogOutput } from "./TTDDialogOutput";
+import { TTDDialogPanel } from "./TTDDialogPanel";
+import { TTDDialogPanels } from "./TTDDialogPanels";
+import type { MermaidToExcalidrawLibProps } from "./common";
+import {
+ convertMermaidToExcalidraw,
+ insertToEditor,
+ saveMermaidDataToStorage,
+} from "./common";
+import type { NonDeletedExcalidrawElement } from "../../element/types";
+import type { BinaryFiles } from "../../types";
+import { ArrowRightIcon } from "../icons";
+
+import "./TTDDialog.scss";
+import { atom, useAtom } from "../../editor-jotai";
+import { trackEvent } from "../../analytics";
+import { InlineIcon } from "../InlineIcon";
+import { TTDDialogSubmitShortcut } from "./TTDDialogSubmitShortcut";
+import { isFiniteNumber } from "@excalidraw/math";
+
+const MIN_PROMPT_LENGTH = 3;
+const MAX_PROMPT_LENGTH = 1000;
+
+const rateLimitsAtom = atom<{
+ rateLimit: number;
+ rateLimitRemaining: number;
+} | null>(null);
+
+const ttdGenerationAtom = atom<{
+ generatedResponse: string | null;
+ prompt: string | null;
+} | null>(null);
+
+type OnTestSubmitRetValue = {
+ rateLimit?: number | null;
+ rateLimitRemaining?: number | null;
+} & (
+ | { generatedResponse: string | undefined; error?: null | undefined }
+ | {
+ error: Error;
+ generatedResponse?: null | undefined;
+ }
+);
+
+export const TTDDialog = (
+ props:
+ | {
+ onTextSubmit(value: string): Promise<OnTestSubmitRetValue>;
+ }
+ | { __fallback: true },
+) => {
+ const appState = useUIAppState();
+
+ if (appState.openDialog?.name !== "ttd") {
+ return null;
+ }
+
+ return <TTDDialogBase {...props} tab={appState.openDialog.tab} />;
+};
+
+/**
+ * Text to diagram (TTD) dialog
+ */
+export const TTDDialogBase = withInternalFallback(
+ "TTDDialogBase",
+ ({
+ tab,
+ ...rest
+ }: {
+ tab: "text-to-diagram" | "mermaid";
+ } & (
+ | {
+ onTextSubmit(value: string): Promise<OnTestSubmitRetValue>;
+ }
+ | { __fallback: true }
+ )) => {
+ const app = useApp();
+ const setAppState = useExcalidrawSetAppState();
+
+ const someRandomDivRef = useRef<HTMLDivElement>(null);
+
+ const [ttdGeneration, setTtdGeneration] = useAtom(ttdGenerationAtom);
+
+ const [text, setText] = useState(ttdGeneration?.prompt ?? "");
+
+ const prompt = text.trim();
+
+ const handleTextChange: ChangeEventHandler<HTMLTextAreaElement> = (
+ event,
+ ) => {
+ setText(event.target.value);
+ setTtdGeneration((s) => ({
+ generatedResponse: s?.generatedResponse ?? null,
+ prompt: event.target.value,
+ }));
+ };
+
+ const [onTextSubmitInProgess, setOnTextSubmitInProgess] = useState(false);
+ const [rateLimits, setRateLimits] = useAtom(rateLimitsAtom);
+
+ const onGenerate = async () => {
+ if (
+ prompt.length > MAX_PROMPT_LENGTH ||
+ prompt.length < MIN_PROMPT_LENGTH ||
+ onTextSubmitInProgess ||
+ rateLimits?.rateLimitRemaining === 0 ||
+ // means this is not a text-to-diagram dialog (needed for TS only)
+ "__fallback" in rest
+ ) {
+ if (prompt.length < MIN_PROMPT_LENGTH) {
+ setError(
+ new Error(
+ `Prompt is too short (min ${MIN_PROMPT_LENGTH} characters)`,
+ ),
+ );
+ }
+ if (prompt.length > MAX_PROMPT_LENGTH) {
+ setError(
+ new Error(
+ `Prompt is too long (max ${MAX_PROMPT_LENGTH} characters)`,
+ ),
+ );
+ }
+
+ return;
+ }
+
+ try {
+ setOnTextSubmitInProgess(true);
+
+ trackEvent("ai", "generate", "ttd");
+
+ const { generatedResponse, error, rateLimit, rateLimitRemaining } =
+ await rest.onTextSubmit(prompt);
+
+ if (typeof generatedResponse === "string") {
+ setTtdGeneration((s) => ({
+ generatedResponse,
+ prompt: s?.prompt ?? null,
+ }));
+ }
+
+ if (isFiniteNumber(rateLimit) && isFiniteNumber(rateLimitRemaining)) {
+ setRateLimits({ rateLimit, rateLimitRemaining });
+ }
+
+ if (error) {
+ setError(error);
+ return;
+ }
+ if (!generatedResponse) {
+ setError(new Error("Generation failed"));
+ return;
+ }
+
+ try {
+ await convertMermaidToExcalidraw({
+ canvasRef: someRandomDivRef,
+ data,
+ mermaidToExcalidrawLib,
+ setError,
+ mermaidDefinition: generatedResponse,
+ });
+ trackEvent("ai", "mermaid parse success", "ttd");
+ } catch (error: any) {
+ console.info(
+ `%cTTD mermaid render errror: ${error.message}`,
+ "color: red",
+ );
+ console.info(
+ `>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nTTD mermaid definition render errror: ${error.message}`,
+ "color: yellow",
+ );
+ trackEvent("ai", "mermaid parse failed", "ttd");
+ setError(
+ new Error(
+ "Generated an invalid diagram :(. You may also try a different prompt.",
+ ),
+ );
+ }
+ } catch (error: any) {
+ let message: string | undefined = error.message;
+ if (!message || message === "Failed to fetch") {
+ message = "Request failed";
+ }
+ setError(new Error(message));
+ } finally {
+ setOnTextSubmitInProgess(false);
+ }
+ };
+
+ const refOnGenerate = useRef(onGenerate);
+ refOnGenerate.current = onGenerate;
+
+ const [mermaidToExcalidrawLib, setMermaidToExcalidrawLib] =
+ useState<MermaidToExcalidrawLibProps>({
+ loaded: false,
+ api: import("@excalidraw/mermaid-to-excalidraw"),
+ });
+
+ useEffect(() => {
+ const fn = async () => {
+ await mermaidToExcalidrawLib.api;
+ setMermaidToExcalidrawLib((prev) => ({ ...prev, loaded: true }));
+ };
+ fn();
+ }, [mermaidToExcalidrawLib.api]);
+
+ const data = useRef<{
+ elements: readonly NonDeletedExcalidrawElement[];
+ files: BinaryFiles | null;
+ }>({ elements: [], files: null });
+
+ const [error, setError] = useState<Error | null>(null);
+
+ return (
+ <Dialog
+ className="ttd-dialog"
+ onCloseRequest={() => {
+ app.setOpenDialog(null);
+ }}
+ size={1200}
+ title={false}
+ {...rest}
+ autofocus={false}
+ >
+ <TTDDialogTabs dialog="ttd" tab={tab}>
+ {"__fallback" in rest && rest.__fallback ? (
+ <p className="dialog-mermaid-title">{t("mermaid.title")}</p>
+ ) : (
+ <TTDDialogTabTriggers>
+ <TTDDialogTabTrigger tab="text-to-diagram">
+ <div style={{ display: "flex", alignItems: "center" }}>
+ {t("labels.textToDiagram")}
+ <div
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ padding: "1px 6px",
+ marginLeft: "10px",
+ fontSize: 10,
+ borderRadius: "12px",
+ background: "var(--color-promo)",
+ color: "var(--color-surface-lowest)",
+ }}
+ >
+ AI Beta
+ </div>
+ </div>
+ </TTDDialogTabTrigger>
+ <TTDDialogTabTrigger tab="mermaid">Mermaid</TTDDialogTabTrigger>
+ </TTDDialogTabTriggers>
+ )}
+
+ <TTDDialogTab className="ttd-dialog-content" tab="mermaid">
+ <MermaidToExcalidraw
+ mermaidToExcalidrawLib={mermaidToExcalidrawLib}
+ />
+ </TTDDialogTab>
+ {!("__fallback" in rest) && (
+ <TTDDialogTab className="ttd-dialog-content" tab="text-to-diagram">
+ <div className="ttd-dialog-desc">
+ Currently we use Mermaid as a middle step, so you'll get best
+ results if you describe a diagram, workflow, flow chart, and
+ similar.
+ </div>
+ <TTDDialogPanels>
+ <TTDDialogPanel
+ label={t("labels.prompt")}
+ panelAction={{
+ action: onGenerate,
+ label: "Generate",
+ icon: ArrowRightIcon,
+ }}
+ onTextSubmitInProgess={onTextSubmitInProgess}
+ panelActionDisabled={
+ prompt.length > MAX_PROMPT_LENGTH ||
+ rateLimits?.rateLimitRemaining === 0
+ }
+ renderTopRight={() => {
+ if (!rateLimits) {
+ return null;
+ }
+
+ return (
+ <div
+ className="ttd-dialog-rate-limit"
+ style={{
+ fontSize: 12,
+ marginLeft: "auto",
+ color:
+ rateLimits.rateLimitRemaining === 0
+ ? "var(--color-danger)"
+ : undefined,
+ }}
+ >
+ {rateLimits.rateLimitRemaining} requests left today
+ </div>
+ );
+ }}
+ renderSubmitShortcut={() => <TTDDialogSubmitShortcut />}
+ renderBottomRight={() => {
+ if (typeof ttdGeneration?.generatedResponse === "string") {
+ return (
+ <div
+ className="excalidraw-link"
+ style={{ marginLeft: "auto", fontSize: 14 }}
+ onClick={() => {
+ if (
+ typeof ttdGeneration?.generatedResponse ===
+ "string"
+ ) {
+ saveMermaidDataToStorage(
+ ttdGeneration.generatedResponse,
+ );
+ setAppState({
+ openDialog: { name: "ttd", tab: "mermaid" },
+ });
+ }
+ }}
+ >
+ View as Mermaid
+ <InlineIcon icon={ArrowRightIcon} />
+ </div>
+ );
+ }
+ const ratio = prompt.length / MAX_PROMPT_LENGTH;
+ if (ratio > 0.8) {
+ return (
+ <div
+ style={{
+ marginLeft: "auto",
+ fontSize: 12,
+ fontFamily: "monospace",
+ color:
+ ratio > 1 ? "var(--color-danger)" : undefined,
+ }}
+ >
+ Length: {prompt.length}/{MAX_PROMPT_LENGTH}
+ </div>
+ );
+ }
+
+ return null;
+ }}
+ >
+ <TTDDialogInput
+ onChange={handleTextChange}
+ input={text}
+ placeholder={"Describe what you want to see..."}
+ onKeyboardSubmit={() => {
+ refOnGenerate.current();
+ }}
+ />
+ </TTDDialogPanel>
+ <TTDDialogPanel
+ label="Preview"
+ panelAction={{
+ action: () => {
+ console.info("Panel action clicked");
+ insertToEditor({ app, data });
+ },
+ label: "Insert",
+ icon: ArrowRightIcon,
+ }}
+ >
+ <TTDDialogOutput
+ canvasRef={someRandomDivRef}
+ error={error}
+ loaded={mermaidToExcalidrawLib.loaded}
+ />
+ </TTDDialogPanel>
+ </TTDDialogPanels>
+ </TTDDialogTab>
+ )}
+ </TTDDialogTabs>
+ </Dialog>
+ );
+ },
+);
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogInput.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogInput.tsx
new file mode 100644
index 0000000..e11d0dc
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogInput.tsx
@@ -0,0 +1,53 @@
+import type { ChangeEventHandler } from "react";
+import { useEffect, useRef } from "react";
+import { EVENT } from "../../constants";
+import { KEYS } from "../../keys";
+
+interface TTDDialogInputProps {
+ input: string;
+ placeholder: string;
+ onChange: ChangeEventHandler<HTMLTextAreaElement>;
+ onKeyboardSubmit?: () => void;
+}
+
+export const TTDDialogInput = ({
+ input,
+ placeholder,
+ onChange,
+ onKeyboardSubmit,
+}: TTDDialogInputProps) => {
+ const ref = useRef<HTMLTextAreaElement>(null);
+
+ const callbackRef = useRef(onKeyboardSubmit);
+ callbackRef.current = onKeyboardSubmit;
+
+ useEffect(() => {
+ if (!callbackRef.current) {
+ return;
+ }
+ const textarea = ref.current;
+ if (textarea) {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event[KEYS.CTRL_OR_CMD] && event.key === KEYS.ENTER) {
+ event.preventDefault();
+ callbackRef.current?.();
+ }
+ };
+ textarea.addEventListener(EVENT.KEYDOWN, handleKeyDown);
+ return () => {
+ textarea.removeEventListener(EVENT.KEYDOWN, handleKeyDown);
+ };
+ }
+ }, []);
+
+ return (
+ <textarea
+ className="ttd-dialog-input"
+ onChange={onChange}
+ value={input}
+ placeholder={placeholder}
+ autoFocus
+ ref={ref}
+ />
+ );
+};
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogOutput.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogOutput.tsx
new file mode 100644
index 0000000..084a67f
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogOutput.tsx
@@ -0,0 +1,39 @@
+import Spinner from "../Spinner";
+
+const ErrorComp = ({ error }: { error: string }) => {
+ return (
+ <div
+ data-testid="ttd-dialog-output-error"
+ className="ttd-dialog-output-error"
+ >
+ Error! <p>{error}</p>
+ </div>
+ );
+};
+
+interface TTDDialogOutputProps {
+ error: Error | null;
+ canvasRef: React.RefObject<HTMLDivElement | null>;
+ loaded: boolean;
+}
+
+export const TTDDialogOutput = ({
+ error,
+ canvasRef,
+ loaded,
+}: TTDDialogOutputProps) => {
+ return (
+ <div className="ttd-dialog-output-wrapper">
+ {error && <ErrorComp error={error.message} />}
+ {loaded ? (
+ <div
+ ref={canvasRef}
+ style={{ opacity: error ? "0.15" : 1 }}
+ className="ttd-dialog-output-canvas-container"
+ />
+ ) : (
+ <Spinner size="2rem" />
+ )}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogPanel.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogPanel.tsx
new file mode 100644
index 0000000..0a78e49
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogPanel.tsx
@@ -0,0 +1,63 @@
+import type { ReactNode } from "react";
+import { Button } from "../Button";
+import clsx from "clsx";
+import Spinner from "../Spinner";
+
+interface TTDDialogPanelProps {
+ label: string;
+ children: ReactNode;
+ panelAction?: {
+ label: string;
+ action: () => void;
+ icon?: ReactNode;
+ };
+ panelActionDisabled?: boolean;
+ onTextSubmitInProgess?: boolean;
+ renderTopRight?: () => ReactNode;
+ renderSubmitShortcut?: () => ReactNode;
+ renderBottomRight?: () => ReactNode;
+}
+
+export const TTDDialogPanel = ({
+ label,
+ children,
+ panelAction,
+ panelActionDisabled = false,
+ onTextSubmitInProgess,
+ renderTopRight,
+ renderSubmitShortcut,
+ renderBottomRight,
+}: TTDDialogPanelProps) => {
+ return (
+ <div className="ttd-dialog-panel">
+ <div className="ttd-dialog-panel__header">
+ <label>{label}</label>
+ {renderTopRight?.()}
+ </div>
+
+ {children}
+ <div
+ className={clsx("ttd-dialog-panel-button-container", {
+ invisible: !panelAction,
+ })}
+ style={{ display: "flex", alignItems: "center" }}
+ >
+ <Button
+ className="ttd-dialog-panel-button"
+ onSelect={panelAction ? panelAction.action : () => {}}
+ disabled={panelActionDisabled || onTextSubmitInProgess}
+ >
+ <div className={clsx({ invisible: onTextSubmitInProgess })}>
+ {panelAction?.label}
+ {panelAction?.icon && <span>{panelAction.icon}</span>}
+ </div>
+ {onTextSubmitInProgess && <Spinner />}
+ </Button>
+ {!panelActionDisabled &&
+ !onTextSubmitInProgess &&
+ renderSubmitShortcut?.()}
+ {renderBottomRight?.()}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogPanels.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogPanels.tsx
new file mode 100644
index 0000000..0e5e2b5
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogPanels.tsx
@@ -0,0 +1,5 @@
+import type { ReactNode } from "react";
+
+export const TTDDialogPanels = ({ children }: { children: ReactNode }) => {
+ return <div className="ttd-dialog-panels">{children}</div>;
+};
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogSubmitShortcut.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogSubmitShortcut.tsx
new file mode 100644
index 0000000..a8831e3
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogSubmitShortcut.tsx
@@ -0,0 +1,14 @@
+import { getShortcutKey } from "../../utils";
+
+export const TTDDialogSubmitShortcut = () => {
+ return (
+ <div className="ttd-dialog-submit-shortcut">
+ <div className="ttd-dialog-submit-shortcut__key">
+ {getShortcutKey("CtrlOrCmd")}
+ </div>
+ <div className="ttd-dialog-submit-shortcut__key">
+ {getShortcutKey("Enter")}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogTab.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogTab.tsx
new file mode 100644
index 0000000..b9758f1
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogTab.tsx
@@ -0,0 +1,17 @@
+import * as RadixTabs from "@radix-ui/react-tabs";
+
+export const TTDDialogTab = ({
+ tab,
+ children,
+ ...rest
+}: {
+ tab: string;
+ children: React.ReactNode;
+} & React.HTMLAttributes<HTMLDivElement>) => {
+ return (
+ <RadixTabs.Content {...rest} value={tab}>
+ {children}
+ </RadixTabs.Content>
+ );
+};
+TTDDialogTab.displayName = "TTDDialogTab";
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogTabTrigger.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogTabTrigger.tsx
new file mode 100644
index 0000000..ec975ff
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogTabTrigger.tsx
@@ -0,0 +1,21 @@
+import * as RadixTabs from "@radix-ui/react-tabs";
+
+export const TTDDialogTabTrigger = ({
+ children,
+ tab,
+ onSelect,
+ ...rest
+}: {
+ children: React.ReactNode;
+ tab: string;
+ onSelect?: React.ReactEventHandler<HTMLButtonElement> | undefined;
+} & Omit<React.HTMLAttributes<HTMLButtonElement>, "onSelect">) => {
+ return (
+ <RadixTabs.Trigger value={tab} asChild onSelect={onSelect}>
+ <button type="button" className="ttd-dialog-tab-trigger" {...rest}>
+ {children}
+ </button>
+ </RadixTabs.Trigger>
+ );
+};
+TTDDialogTabTrigger.displayName = "TTDDialogTabTrigger";
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogTabTriggers.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogTabTriggers.tsx
new file mode 100644
index 0000000..509c746
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogTabTriggers.tsx
@@ -0,0 +1,13 @@
+import * as RadixTabs from "@radix-ui/react-tabs";
+
+export const TTDDialogTabTriggers = ({
+ children,
+ ...rest
+}: { children: React.ReactNode } & React.HTMLAttributes<HTMLDivElement>) => {
+ return (
+ <RadixTabs.List className="ttd-dialog-triggers" {...rest}>
+ {children}
+ </RadixTabs.List>
+ );
+};
+TTDDialogTabTriggers.displayName = "TTDDialogTabTriggers";
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogTabs.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogTabs.tsx
new file mode 100644
index 0000000..439f928
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogTabs.tsx
@@ -0,0 +1,55 @@
+import * as RadixTabs from "@radix-ui/react-tabs";
+import type { ReactNode } from "react";
+import { useRef } from "react";
+import { useExcalidrawSetAppState } from "../App";
+import { isMemberOf } from "../../utils";
+
+const TTDDialogTabs = (
+ props: {
+ children: ReactNode;
+ } & { dialog: "ttd"; tab: "text-to-diagram" | "mermaid" },
+) => {
+ const setAppState = useExcalidrawSetAppState();
+
+ const rootRef = useRef<HTMLDivElement>(null);
+ const minHeightRef = useRef<number>(0);
+
+ return (
+ <RadixTabs.Root
+ ref={rootRef}
+ className="ttd-dialog-tabs-root"
+ value={props.tab}
+ onValueChange={(
+ // at least in test enviros, `tab` can be `undefined`
+ tab: string | undefined,
+ ) => {
+ if (!tab) {
+ return;
+ }
+ const modalContentNode =
+ rootRef.current?.closest<HTMLElement>(".Modal__content");
+ if (modalContentNode) {
+ const currHeight = modalContentNode.offsetHeight || 0;
+ if (currHeight > minHeightRef.current) {
+ minHeightRef.current = currHeight;
+ modalContentNode.style.minHeight = `min(${minHeightRef.current}px, 100%)`;
+ }
+ }
+ if (
+ props.dialog === "ttd" &&
+ isMemberOf(["text-to-diagram", "mermaid"], tab)
+ ) {
+ setAppState({
+ openDialog: { name: props.dialog, tab },
+ });
+ }
+ }}
+ >
+ {props.children}
+ </RadixTabs.Root>
+ );
+};
+
+TTDDialogTabs.displayName = "TTDDialogTabs";
+
+export default TTDDialogTabs;
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogTrigger.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogTrigger.tsx
new file mode 100644
index 0000000..a73f31a
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogTrigger.tsx
@@ -0,0 +1,35 @@
+import type { JSX } from "react";
+import type { ReactNode } from "react";
+import { useTunnels } from "../../context/tunnels";
+import DropdownMenu from "../dropdownMenu/DropdownMenu";
+import { useExcalidrawSetAppState } from "../App";
+import { brainIcon } from "../icons";
+import { t } from "../../i18n";
+import { trackEvent } from "../../analytics";
+
+export const TTDDialogTrigger = ({
+ children,
+ icon,
+}: {
+ children?: ReactNode;
+ icon?: JSX.Element;
+}) => {
+ const { TTDDialogTriggerTunnel } = useTunnels();
+ const setAppState = useExcalidrawSetAppState();
+
+ return (
+ <TTDDialogTriggerTunnel.In>
+ <DropdownMenu.Item
+ onSelect={() => {
+ trackEvent("ai", "dialog open", "ttd");
+ setAppState({ openDialog: { name: "ttd", tab: "text-to-diagram" } });
+ }}
+ icon={icon ?? brainIcon}
+ >
+ {children ?? t("labels.textToDiagram")}
+ <DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>
+ </DropdownMenu.Item>
+ </TTDDialogTriggerTunnel.In>
+ );
+};
+TTDDialogTrigger.displayName = "TTDDialogTrigger";
diff --git a/packages/excalidraw/components/TTDDialog/common.ts b/packages/excalidraw/components/TTDDialog/common.ts
new file mode 100644
index 0000000..4191126
--- /dev/null
+++ b/packages/excalidraw/components/TTDDialog/common.ts
@@ -0,0 +1,161 @@
+import type { MermaidConfig } from "@excalidraw/mermaid-to-excalidraw";
+import type { MermaidToExcalidrawResult } from "@excalidraw/mermaid-to-excalidraw/dist/interfaces";
+import { DEFAULT_EXPORT_PADDING, EDITOR_LS_KEYS } from "../../constants";
+import { convertToExcalidrawElements, exportToCanvas } from "../../index";
+import type { NonDeletedExcalidrawElement } from "../../element/types";
+import type { AppClassProperties, BinaryFiles } from "../../types";
+import { canvasToBlob } from "../../data/blob";
+import { EditorLocalStorage } from "../../data/EditorLocalStorage";
+import { t } from "../../i18n";
+
+const resetPreview = ({
+ canvasRef,
+ setError,
+}: {
+ canvasRef: React.RefObject<HTMLDivElement | null>;
+ setError: (error: Error | null) => void;
+}) => {
+ const canvasNode = canvasRef.current;
+
+ if (!canvasNode) {
+ return;
+ }
+ const parent = canvasNode.parentElement;
+ if (!parent) {
+ return;
+ }
+ parent.style.background = "";
+ setError(null);
+ canvasNode.replaceChildren();
+};
+
+export interface MermaidToExcalidrawLibProps {
+ loaded: boolean;
+ api: Promise<{
+ parseMermaidToExcalidraw: (
+ definition: string,
+ config?: MermaidConfig,
+ ) => Promise<MermaidToExcalidrawResult>;
+ }>;
+}
+
+interface ConvertMermaidToExcalidrawFormatProps {
+ canvasRef: React.RefObject<HTMLDivElement | null>;
+ mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
+ mermaidDefinition: string;
+ setError: (error: Error | null) => void;
+ data: React.MutableRefObject<{
+ elements: readonly NonDeletedExcalidrawElement[];
+ files: BinaryFiles | null;
+ }>;
+}
+
+export const convertMermaidToExcalidraw = async ({
+ canvasRef,
+ mermaidToExcalidrawLib,
+ mermaidDefinition,
+ setError,
+ data,
+}: ConvertMermaidToExcalidrawFormatProps) => {
+ const canvasNode = canvasRef.current;
+ const parent = canvasNode?.parentElement;
+
+ if (!canvasNode || !parent) {
+ return;
+ }
+
+ if (!mermaidDefinition) {
+ resetPreview({ canvasRef, setError });
+ return;
+ }
+
+ try {
+ const api = await mermaidToExcalidrawLib.api;
+
+ let ret;
+ try {
+ ret = await api.parseMermaidToExcalidraw(mermaidDefinition);
+ } catch (err: any) {
+ ret = await api.parseMermaidToExcalidraw(
+ mermaidDefinition.replace(/"/g, "'"),
+ );
+ }
+ const { elements, files } = ret;
+ setError(null);
+
+ data.current = {
+ elements: convertToExcalidrawElements(elements, {
+ regenerateIds: true,
+ }),
+ files,
+ };
+
+ const canvas = await exportToCanvas({
+ elements: data.current.elements,
+ files: data.current.files,
+ exportPadding: DEFAULT_EXPORT_PADDING,
+ maxWidthOrHeight:
+ Math.max(parent.offsetWidth, parent.offsetHeight) *
+ window.devicePixelRatio,
+ });
+ // if converting to blob fails, there's some problem that will
+ // likely prevent preview and export (e.g. canvas too big)
+ try {
+ await canvasToBlob(canvas);
+ } catch (e: any) {
+ if (e.name === "CANVAS_POSSIBLY_TOO_BIG") {
+ throw new Error(t("canvasError.canvasTooBig"));
+ }
+ throw e;
+ }
+ parent.style.background = "var(--default-bg-color)";
+ canvasNode.replaceChildren(canvas);
+ } catch (err: any) {
+ parent.style.background = "var(--default-bg-color)";
+ if (mermaidDefinition) {
+ setError(err);
+ }
+
+ throw err;
+ }
+};
+
+export const saveMermaidDataToStorage = (mermaidDefinition: string) => {
+ EditorLocalStorage.set(
+ EDITOR_LS_KEYS.MERMAID_TO_EXCALIDRAW,
+ mermaidDefinition,
+ );
+};
+
+export const insertToEditor = ({
+ app,
+ data,
+ text,
+ shouldSaveMermaidDataToStorage,
+}: {
+ app: AppClassProperties;
+ data: React.MutableRefObject<{
+ elements: readonly NonDeletedExcalidrawElement[];
+ files: BinaryFiles | null;
+ }>;
+ text?: string;
+ shouldSaveMermaidDataToStorage?: boolean;
+}) => {
+ const { elements: newElements, files } = data.current;
+
+ if (!newElements.length) {
+ return;
+ }
+
+ app.addElementsFromPasteOrLibrary({
+ elements: newElements,
+ files,
+ position: "center",
+ fitToContent: true,
+ });
+ app.setOpenDialog(null);
+
+ if (shouldSaveMermaidDataToStorage && text) {
+ saveMermaidDataToStorage(text);
+ }
+};
diff --git a/packages/excalidraw/components/TextField.scss b/packages/excalidraw/components/TextField.scss
new file mode 100644
index 0000000..c46cd2f
--- /dev/null
+++ b/packages/excalidraw/components/TextField.scss
@@ -0,0 +1,123 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ --ExcTextField--color: var(--color-on-surface);
+ --ExcTextField--label-color: var(--color-on-surface);
+ --ExcTextField--background: var(--color-surface-low);
+ --ExcTextField--readonly--background: var(--color-surface-high);
+ --ExcTextField--readonly--color: var(--color-on-surface);
+ --ExcTextField--border: var(--color-gray-20);
+ --ExcTextField--readonly--border: var(--color-border-outline-variant);
+ --ExcTextField--border-hover: var(--color-brand-hover);
+ --ExcTextField--border-active: var(--color-brand-active);
+ --ExcTextField--placeholder: var(--color-border-outline-variant);
+
+ .ExcTextField {
+ position: relative;
+
+ svg {
+ position: absolute;
+ top: 50%; // 50% is not exactly in the center of the input
+ transform: translateY(-50%);
+ left: 0.75rem;
+ width: 1.25rem;
+ height: 1.25rem;
+ color: var(--color-gray-40);
+ z-index: 1;
+ }
+
+ &--fullWidth {
+ width: 100%;
+ flex-grow: 1;
+ }
+
+ &__label {
+ font-family: "Assistant";
+ font-style: normal;
+ font-weight: 600;
+ font-size: 0.875rem;
+ line-height: 150%;
+
+ color: var(--ExcTextField--label-color);
+
+ margin-bottom: 0.25rem;
+ user-select: none;
+ }
+
+ &__input {
+ box-sizing: border-box;
+
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+
+ height: 3rem;
+
+ background: var(--ExcTextField--background);
+ border: 1px solid var(--ExcTextField--border);
+ border-radius: 0.5rem;
+
+ padding: 0 0.75rem;
+
+ &:not(&--readonly) {
+ &:hover {
+ border-color: var(--ExcTextField--border-hover);
+ }
+
+ &:active,
+ &:focus-within {
+ border-color: var(--ExcTextField--border-active);
+ }
+ }
+
+ & input {
+ display: flex;
+ align-items: center;
+
+ border: none;
+ outline: none;
+ padding: 0;
+ margin: 0;
+
+ height: 1.5rem;
+
+ color: var(--ExcTextField--color);
+
+ font-family: "Assistant";
+ font-style: normal;
+ font-weight: 400;
+ font-size: 1rem;
+ line-height: 150%;
+ text-overflow: ellipsis;
+
+ background: transparent;
+
+ width: 100%;
+
+ &:not(:focus) {
+ &:hover {
+ background-color: initial;
+ }
+ }
+
+ &:focus {
+ outline: initial;
+ box-shadow: initial;
+ }
+ }
+
+ &--readonly {
+ background: var(--ExcTextField--readonly--background);
+ border-color: var(--ExcTextField--readonly--border);
+
+ & input {
+ color: var(--ExcTextField--readonly--color);
+ }
+ }
+ }
+
+ &--hasIcon .ExcTextField__input {
+ padding-left: 2.5rem;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/TextField.tsx b/packages/excalidraw/components/TextField.tsx
new file mode 100644
index 0000000..c5bdc82
--- /dev/null
+++ b/packages/excalidraw/components/TextField.tsx
@@ -0,0 +1,112 @@
+import type { KeyboardEvent } from "react";
+import {
+ forwardRef,
+ useRef,
+ useImperativeHandle,
+ useLayoutEffect,
+ useState,
+} from "react";
+import clsx from "clsx";
+
+import "./TextField.scss";
+import { Button } from "./Button";
+import { eyeIcon, eyeClosedIcon } from "./icons";
+
+type TextFieldProps = {
+ onChange?: (value: string) => void;
+ onClick?: () => void;
+ onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;
+
+ readonly?: boolean;
+ fullWidth?: boolean;
+ selectOnRender?: boolean;
+
+ icon?: React.ReactNode;
+ label?: string;
+ className?: string;
+ placeholder?: string;
+ isRedacted?: boolean;
+} & ({ value: string } | { defaultValue: string });
+
+export const TextField = forwardRef<HTMLInputElement, TextFieldProps>(
+ (
+ {
+ onChange,
+ label,
+ fullWidth,
+ placeholder,
+ readonly,
+ selectOnRender,
+ onKeyDown,
+ isRedacted = false,
+ icon,
+ className,
+ ...rest
+ },
+ ref,
+ ) => {
+ const innerRef = useRef<HTMLInputElement | null>(null);
+
+ useImperativeHandle(ref, () => innerRef.current!);
+
+ useLayoutEffect(() => {
+ if (selectOnRender) {
+ // focusing first is needed because vitest/jsdom
+ innerRef.current?.focus();
+ innerRef.current?.select();
+ }
+ }, [selectOnRender]);
+
+ const [isTemporarilyUnredacted, setIsTemporarilyUnredacted] =
+ useState<boolean>(false);
+
+ return (
+ <div
+ className={clsx("ExcTextField", className, {
+ "ExcTextField--fullWidth": fullWidth,
+ "ExcTextField--hasIcon": !!icon,
+ })}
+ onClick={() => {
+ innerRef.current?.focus();
+ }}
+ >
+ {icon}
+ {label && <div className="ExcTextField__label">{label}</div>}
+ <div
+ className={clsx("ExcTextField__input", {
+ "ExcTextField__input--readonly": readonly,
+ })}
+ >
+ <input
+ className={clsx({
+ "is-redacted":
+ "value" in rest &&
+ rest.value &&
+ isRedacted &&
+ !isTemporarilyUnredacted,
+ })}
+ readOnly={readonly}
+ value={"value" in rest ? rest.value : undefined}
+ defaultValue={
+ "defaultValue" in rest ? rest.defaultValue : undefined
+ }
+ placeholder={placeholder}
+ ref={innerRef}
+ onChange={(event) => onChange?.(event.target.value)}
+ onKeyDown={onKeyDown}
+ />
+ {isRedacted && (
+ <Button
+ onSelect={() =>
+ setIsTemporarilyUnredacted(!isTemporarilyUnredacted)
+ }
+ style={{ border: 0, userSelect: "none" }}
+ >
+ {isTemporarilyUnredacted ? eyeClosedIcon : eyeIcon}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+ },
+);
diff --git a/packages/excalidraw/components/TextInput.scss b/packages/excalidraw/components/TextInput.scss
new file mode 100644
index 0000000..60a03ca
--- /dev/null
+++ b/packages/excalidraw/components/TextInput.scss
@@ -0,0 +1,7 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .TextInput {
+ display: inline-block;
+ }
+}
diff --git a/packages/excalidraw/components/Toast.scss b/packages/excalidraw/components/Toast.scss
new file mode 100644
index 0000000..853871f
--- /dev/null
+++ b/packages/excalidraw/components/Toast.scss
@@ -0,0 +1,49 @@
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .Toast {
+ $closeButtonSize: 1.2rem;
+ $closeButtonPadding: 0.4rem;
+
+ animation: fade-in 0.5s;
+ background-color: var(--button-gray-1);
+ border-radius: 4px;
+ bottom: 10px;
+ box-sizing: border-box;
+ cursor: default;
+ left: 50%;
+ margin-left: -150px;
+ padding: 4px 0;
+ position: absolute;
+ text-align: center;
+ width: 300px;
+ z-index: 999999;
+
+ .Toast__message {
+ padding: 0 $closeButtonSize + ($closeButtonPadding);
+ color: var(--popup-text-color);
+ white-space: pre-wrap;
+ }
+
+ .close {
+ position: absolute;
+ top: 0;
+ right: 0;
+ padding: $closeButtonPadding;
+
+ .ToolIcon__icon {
+ width: $closeButtonSize;
+ height: $closeButtonSize;
+ }
+ }
+ }
+
+ @keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Toast.tsx b/packages/excalidraw/components/Toast.tsx
new file mode 100644
index 0000000..d99c9f6
--- /dev/null
+++ b/packages/excalidraw/components/Toast.tsx
@@ -0,0 +1,63 @@
+import type { CSSProperties } from "react";
+import { useCallback, useEffect, useRef } from "react";
+import { CloseIcon } from "./icons";
+import "./Toast.scss";
+import { ToolButton } from "./ToolButton";
+
+const DEFAULT_TOAST_TIMEOUT = 5000;
+
+export const Toast = ({
+ message,
+ onClose,
+ closable = false,
+ // To prevent autoclose, pass duration as Infinity
+ duration = DEFAULT_TOAST_TIMEOUT,
+ style,
+}: {
+ message: string;
+ onClose: () => void;
+ closable?: boolean;
+ duration?: number;
+ style?: CSSProperties;
+}) => {
+ const timerRef = useRef<number>(0);
+ const shouldAutoClose = duration !== Infinity;
+ const scheduleTimeout = useCallback(() => {
+ if (!shouldAutoClose) {
+ return;
+ }
+ timerRef.current = window.setTimeout(() => onClose(), duration);
+ }, [onClose, duration, shouldAutoClose]);
+
+ useEffect(() => {
+ if (!shouldAutoClose) {
+ return;
+ }
+ scheduleTimeout();
+ return () => clearTimeout(timerRef.current);
+ }, [scheduleTimeout, message, duration, shouldAutoClose]);
+
+ const onMouseEnter = shouldAutoClose
+ ? () => clearTimeout(timerRef?.current)
+ : undefined;
+ const onMouseLeave = shouldAutoClose ? scheduleTimeout : undefined;
+ return (
+ <div
+ className="Toast"
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
+ style={style}
+ >
+ <p className="Toast__message">{message}</p>
+ {closable && (
+ <ToolButton
+ icon={CloseIcon}
+ aria-label="close"
+ type="icon"
+ onClick={onClose}
+ className="close"
+ />
+ )}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/ToolButton.tsx b/packages/excalidraw/components/ToolButton.tsx
new file mode 100644
index 0000000..09b0b6c
--- /dev/null
+++ b/packages/excalidraw/components/ToolButton.tsx
@@ -0,0 +1,206 @@
+import "./ToolIcon.scss";
+
+import type { CSSProperties } from "react";
+import React, { useEffect, useRef, useState } from "react";
+import clsx from "clsx";
+import { useExcalidrawContainer } from "./App";
+import { AbortError } from "../errors";
+import Spinner from "./Spinner";
+import type { PointerType } from "../element/types";
+import { isPromiseLike } from "../utils";
+
+export type ToolButtonSize = "small" | "medium";
+
+type ToolButtonBaseProps = {
+ icon?: React.ReactNode;
+ "aria-label": string;
+ "aria-keyshortcuts"?: string;
+ "data-testid"?: string;
+ label?: string;
+ title?: string;
+ name?: string;
+ id?: string;
+ size?: ToolButtonSize;
+ keyBindingLabel?: string | null;
+ showAriaLabel?: boolean;
+ hidden?: boolean;
+ visible?: boolean;
+ selected?: boolean;
+ disabled?: boolean;
+ className?: string;
+ style?: CSSProperties;
+ isLoading?: boolean;
+};
+
+type ToolButtonProps =
+ | (ToolButtonBaseProps & {
+ type: "button";
+ children?: React.ReactNode;
+ onClick?(event: React.MouseEvent): void;
+ })
+ | (ToolButtonBaseProps & {
+ type: "submit";
+ children?: React.ReactNode;
+ onClick?(event: React.MouseEvent): void;
+ })
+ | (ToolButtonBaseProps & {
+ type: "icon";
+ children?: React.ReactNode;
+ onClick?(): void;
+ })
+ | (ToolButtonBaseProps & {
+ type: "radio";
+ checked: boolean;
+ onChange?(data: { pointerType: PointerType | null }): void;
+ onPointerDown?(data: { pointerType: PointerType }): void;
+ });
+
+export const ToolButton = React.forwardRef(
+ (
+ {
+ size = "medium",
+ visible = true,
+ className = "",
+ ...props
+ }: ToolButtonProps,
+ ref,
+ ) => {
+ const { id: excalId } = useExcalidrawContainer();
+ const innerRef = React.useRef(null);
+ React.useImperativeHandle(ref, () => innerRef.current);
+ const sizeCn = `ToolIcon_size_${size}`;
+
+ const [isLoading, setIsLoading] = useState(false);
+
+ const isMountedRef = useRef(true);
+
+ const onClick = async (event: React.MouseEvent) => {
+ const ret = "onClick" in props && props.onClick?.(event);
+
+ if (isPromiseLike(ret)) {
+ try {
+ setIsLoading(true);
+ await ret;
+ } catch (error: any) {
+ if (!(error instanceof AbortError)) {
+ throw error;
+ } else {
+ console.warn(error);
+ }
+ } finally {
+ if (isMountedRef.current) {
+ setIsLoading(false);
+ }
+ }
+ }
+ };
+
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ };
+ }, []);
+
+ const lastPointerTypeRef = useRef<PointerType | null>(null);
+
+ if (
+ props.type === "button" ||
+ props.type === "icon" ||
+ props.type === "submit"
+ ) {
+ const type = (props.type === "icon" ? "button" : props.type) as
+ | "button"
+ | "submit";
+ return (
+ <button
+ className={clsx(
+ "ToolIcon_type_button",
+ sizeCn,
+ className,
+ visible && !props.hidden
+ ? "ToolIcon_type_button--show"
+ : "ToolIcon_type_button--hide",
+ {
+ ToolIcon: !props.hidden,
+ "ToolIcon--selected": props.selected,
+ "ToolIcon--plain": props.type === "icon",
+ },
+ )}
+ style={props.style}
+ data-testid={props["data-testid"]}
+ hidden={props.hidden}
+ title={props.title}
+ aria-label={props["aria-label"]}
+ type={type}
+ onClick={onClick}
+ ref={innerRef}
+ disabled={isLoading || props.isLoading || !!props.disabled}
+ >
+ {(props.icon || props.label) && (
+ <div
+ className="ToolIcon__icon"
+ aria-hidden="true"
+ aria-disabled={!!props.disabled}
+ >
+ {props.icon || props.label}
+ {props.keyBindingLabel && (
+ <span className="ToolIcon__keybinding">
+ {props.keyBindingLabel}
+ </span>
+ )}
+ {props.isLoading && <Spinner />}
+ </div>
+ )}
+ {props.showAriaLabel && (
+ <div className="ToolIcon__label">
+ {props["aria-label"]} {isLoading && <Spinner />}
+ </div>
+ )}
+ {props.children}
+ </button>
+ );
+ }
+
+ return (
+ <label
+ className={clsx("ToolIcon", className)}
+ title={props.title}
+ onPointerDown={(event) => {
+ lastPointerTypeRef.current = event.pointerType || null;
+ props.onPointerDown?.({ pointerType: event.pointerType || null });
+ }}
+ onPointerUp={() => {
+ requestAnimationFrame(() => {
+ lastPointerTypeRef.current = null;
+ });
+ }}
+ >
+ <input
+ className={`ToolIcon_type_radio ${sizeCn}`}
+ type="radio"
+ name={props.name}
+ aria-label={props["aria-label"]}
+ aria-keyshortcuts={props["aria-keyshortcuts"]}
+ data-testid={props["data-testid"]}
+ id={`${excalId}-${props.id}`}
+ onChange={() => {
+ props.onChange?.({ pointerType: lastPointerTypeRef.current });
+ }}
+ checked={props.checked}
+ ref={innerRef}
+ />
+ <div className="ToolIcon__icon">
+ {props.icon}
+ {props.keyBindingLabel && (
+ <span className="ToolIcon__keybinding">
+ {props.keyBindingLabel}
+ </span>
+ )}
+ </div>
+ </label>
+ );
+ },
+);
+
+ToolButton.displayName = "ToolButton";
diff --git a/packages/excalidraw/components/ToolIcon.scss b/packages/excalidraw/components/ToolIcon.scss
new file mode 100644
index 0000000..dfba270
--- /dev/null
+++ b/packages/excalidraw/components/ToolIcon.scss
@@ -0,0 +1,199 @@
+@import "open-color/open-color.scss";
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .ToolIcon {
+ border-radius: var(--border-radius-lg);
+ display: inline-flex;
+ align-items: center;
+ position: relative;
+ cursor: pointer;
+ -webkit-tap-highlight-color: transparent;
+ user-select: none;
+
+ &__hidden {
+ display: none !important;
+ }
+
+ @include toolbarButtonColorStates;
+ }
+
+ .ToolIcon--plain {
+ background-color: transparent;
+ .ToolIcon__icon {
+ width: 2rem;
+ height: 2rem;
+ }
+ }
+
+ .ToolIcon_type_radio,
+ .ToolIcon_type_checkbox {
+ position: absolute;
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ .ToolIcon__icon {
+ box-sizing: border-box;
+ width: var(--default-button-size);
+ height: var(--default-button-size);
+ color: var(--icon-fill-color);
+
+ display: flex;
+ justify-content: center;
+ align-items: center;
+
+ border-radius: var(--border-radius-lg);
+
+ & + .ToolIcon__label {
+ margin-inline-start: 0;
+ }
+
+ svg {
+ position: relative;
+ width: var(--default-icon-size);
+ height: var(--default-icon-size);
+ color: var(--icon-fill-color);
+ }
+ }
+
+ .ToolIcon__label {
+ display: flex;
+ align-items: center;
+ color: var(--icon-fill-color);
+ font-family: var(--ui-font);
+ margin: 0 0.8em;
+ text-overflow: ellipsis;
+
+ .Spinner {
+ margin-left: 0.6em;
+ }
+ }
+
+ .ToolIcon_size_small .ToolIcon__icon {
+ width: 2rem;
+ height: 2rem;
+ font-size: 0.8em;
+ }
+
+ .ToolIcon_type_button,
+ .Modal .ToolIcon_type_button {
+ padding: 0;
+ border: none;
+ margin: 0;
+ font-size: inherit;
+ background-color: initial;
+
+ &:focus-visible {
+ box-shadow: 0 0 0 2px var(--focus-highlight-color);
+ }
+
+ &.ToolIcon--selected {
+ background-color: var(--button-gray-2);
+
+ &:active {
+ background-color: var(--button-gray-3);
+ }
+ }
+
+ &:active {
+ background-color: var(--button-gray-3);
+ }
+
+ &:disabled {
+ cursor: default;
+
+ &:active,
+ &:focus-visible,
+ &:hover {
+ background-color: initial;
+ border: none;
+ box-shadow: none;
+ }
+
+ svg {
+ color: var(--color-disabled);
+ }
+ }
+
+ &--show {
+ visibility: visible;
+ }
+
+ &--hide {
+ display: none !important;
+ }
+ }
+
+ .ToolIcon_type_floating {
+ background-color: transparent;
+
+ &:hover {
+ background-color: transparent;
+ }
+
+ &:active {
+ background-color: transparent;
+ }
+
+ .ToolIcon__icon {
+ background-color: var(--button-gray-1);
+ &:hover {
+ background-color: var(--button-gray-2);
+ }
+ &:active {
+ background-color: var(--button-gray-3);
+ }
+
+ width: 2rem;
+ height: 2rem;
+ }
+ }
+
+ .ToolIcon__keybinding {
+ position: absolute;
+ bottom: 2px;
+ right: 3px;
+ font-size: 0.625rem;
+ color: var(--keybinding-color);
+ font-family: var(--ui-font);
+ user-select: none;
+ }
+
+ .unlocked-icon {
+ :root[dir="ltr"] & {
+ left: 2px;
+ }
+
+ :root[dir="rtl"] & {
+ right: 2px;
+ }
+ }
+
+ .App-toolbar-container {
+ .ToolIcon__icon {
+ width: var(--lg-button-size);
+ height: var(--lg-button-size);
+
+ @media screen and (max-width: 450px) {
+ width: 1.8rem;
+ height: 1.8rem;
+ }
+ @media screen and (max-width: 379px) {
+ width: 1.5rem;
+ height: 1.5rem;
+ }
+
+ svg {
+ width: var(--lg-icon-size);
+ height: var(--lg-icon-size);
+ }
+ }
+
+ .ToolIcon__LaserPointer .ToolIcon__icon,
+ .ToolIcon__MagicButton .ToolIcon__icon {
+ width: var(--default-button-size);
+ height: var(--default-button-size);
+ }
+ }
+}
diff --git a/packages/excalidraw/components/Toolbar.scss b/packages/excalidraw/components/Toolbar.scss
new file mode 100644
index 0000000..1565120
--- /dev/null
+++ b/packages/excalidraw/components/Toolbar.scss
@@ -0,0 +1,50 @@
+@import "open-color/open-color.scss";
+@import "../css/variables.module.scss";
+
+.excalidraw {
+ .App-toolbar {
+ &.zen-mode {
+ .ToolIcon__keybinding,
+ .HintViewer {
+ display: none;
+ }
+ }
+
+ &__divider {
+ width: 1px;
+ height: 1.5rem;
+ align-self: center;
+ background-color: var(--default-border-color);
+ margin: 0 0.25rem;
+
+ @include isMobile {
+ margin: 0;
+ }
+ }
+ }
+
+ .App-toolbar__extra-tools-trigger {
+ box-shadow: none;
+ border: 0;
+ background-color: transparent;
+
+ &:active {
+ background-color: var(--button-hover-bg);
+ box-shadow: 0 0 0 1px
+ var(--button-active-border, var(--color-primary-darkest)) inset;
+ }
+
+ &--selected,
+ &--selected:hover {
+ background: var(--color-primary-light);
+ color: var(--color-primary);
+ }
+ }
+
+ .App-toolbar__extra-tools-dropdown {
+ margin-top: 0.375rem;
+ right: 0;
+ min-width: 11.875rem;
+ z-index: 1;
+ }
+}
diff --git a/packages/excalidraw/components/Tooltip.scss b/packages/excalidraw/components/Tooltip.scss
new file mode 100644
index 0000000..37fc336
--- /dev/null
+++ b/packages/excalidraw/components/Tooltip.scss
@@ -0,0 +1,47 @@
+@import "../css/variables.module.scss";
+
+// container in body where the actual tooltip is appended to
+.excalidraw-tooltip {
+ --ui-font: Assistant, system-ui, BlinkMacSystemFont, -apple-system, Segoe UI,
+ Roboto, Helvetica, Arial, sans-serif;
+ font-family: var(--ui-font);
+ position: fixed;
+ z-index: var(--zIndex-popup);
+
+ padding: 8px;
+ border-radius: 6px;
+ box-sizing: border-box;
+ pointer-events: none;
+ word-wrap: break-word;
+
+ background: $oc-black;
+
+ line-height: 1.5;
+ text-align: center;
+ font-size: 13px;
+ font-weight: 500;
+ color: $oc-white;
+
+ display: none;
+
+ &.excalidraw-tooltip--visible {
+ display: block;
+ }
+}
+
+// wraps the element we want to apply the tooltip to
+.excalidraw-tooltip-wrapper {
+ display: flex;
+}
+
+.excalidraw-tooltip-icon {
+ width: 0.9em;
+ height: 0.9em;
+ margin-left: 5px;
+ margin-top: 1px;
+ display: flex;
+
+ @include isMobile {
+ display: none;
+ }
+}
diff --git a/packages/excalidraw/components/Tooltip.tsx b/packages/excalidraw/components/Tooltip.tsx
new file mode 100644
index 0000000..38c04ef
--- /dev/null
+++ b/packages/excalidraw/components/Tooltip.tsx
@@ -0,0 +1,119 @@
+import "./Tooltip.scss";
+
+import React, { useEffect } from "react";
+
+export const getTooltipDiv = () => {
+ const existingDiv = document.querySelector<HTMLDivElement>(
+ ".excalidraw-tooltip",
+ );
+ if (existingDiv) {
+ return existingDiv;
+ }
+ const div = document.createElement("div");
+ document.body.appendChild(div);
+ div.classList.add("excalidraw-tooltip");
+ return div;
+};
+
+export const updateTooltipPosition = (
+ tooltip: HTMLDivElement,
+ item: {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ },
+ position: "bottom" | "top" = "bottom",
+) => {
+ const tooltipRect = tooltip.getBoundingClientRect();
+
+ const viewportWidth = window.innerWidth;
+ const viewportHeight = window.innerHeight;
+
+ const margin = 5;
+
+ let left = item.left + item.width / 2 - tooltipRect.width / 2;
+ if (left < 0) {
+ left = margin;
+ } else if (left + tooltipRect.width >= viewportWidth) {
+ left = viewportWidth - tooltipRect.width - margin;
+ }
+
+ let top: number;
+
+ if (position === "bottom") {
+ top = item.top + item.height + margin;
+ if (top + tooltipRect.height >= viewportHeight) {
+ top = item.top - tooltipRect.height - margin;
+ }
+ } else {
+ top = item.top - tooltipRect.height - margin;
+ if (top < 0) {
+ top = item.top + item.height + margin;
+ }
+ }
+
+ Object.assign(tooltip.style, {
+ top: `${top}px`,
+ left: `${left}px`,
+ });
+};
+
+const updateTooltip = (
+ item: HTMLDivElement,
+ tooltip: HTMLDivElement,
+ label: string,
+ long: boolean,
+) => {
+ tooltip.classList.add("excalidraw-tooltip--visible");
+ tooltip.style.minWidth = long ? "50ch" : "10ch";
+ tooltip.style.maxWidth = long ? "50ch" : "15ch";
+
+ tooltip.textContent = label;
+
+ const itemRect = item.getBoundingClientRect();
+ updateTooltipPosition(tooltip, itemRect);
+};
+
+type TooltipProps = {
+ children: React.ReactNode;
+ label: string;
+ long?: boolean;
+ style?: React.CSSProperties;
+ disabled?: boolean;
+};
+
+export const Tooltip = ({
+ children,
+ label,
+ long = false,
+ style,
+ disabled,
+}: TooltipProps) => {
+ useEffect(() => {
+ return () =>
+ getTooltipDiv().classList.remove("excalidraw-tooltip--visible");
+ }, []);
+ if (disabled) {
+ return null;
+ }
+ return (
+ <div
+ className="excalidraw-tooltip-wrapper"
+ onPointerEnter={(event) =>
+ updateTooltip(
+ event.currentTarget as HTMLDivElement,
+ getTooltipDiv(),
+ label,
+ long,
+ )
+ }
+ onPointerLeave={() =>
+ getTooltipDiv().classList.remove("excalidraw-tooltip--visible")
+ }
+ style={style}
+ >
+ {children}
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/Trans.test.tsx b/packages/excalidraw/components/Trans.test.tsx
new file mode 100644
index 0000000..c331796
--- /dev/null
+++ b/packages/excalidraw/components/Trans.test.tsx
@@ -0,0 +1,72 @@
+import { render } from "@testing-library/react";
+
+import fallbackLangData from "../locales/en.json";
+
+import Trans from "./Trans";
+import type { TranslationKeys } from "../i18n";
+import { EditorJotaiProvider } from "../editor-jotai";
+
+describe("Test <Trans/>", () => {
+ it("should translate the the strings correctly", () => {
+ //@ts-ignore
+ fallbackLangData.transTest = {
+ key1: "Hello {{audience}}",
+ key2: "Please <link>click the button</link> to continue.",
+ key3: "Please <link>click {{location}}</link> to continue.",
+ key4: "Please <link>click <bold>{{location}}</bold></link> to continue.",
+ key5: "Please <connect-link>click the button</connect-link> to continue.",
+ };
+
+ const { getByTestId } = render(
+ <EditorJotaiProvider>
+ <div data-testid="test1">
+ <Trans
+ i18nKey={"transTest.key1" as unknown as TranslationKeys}
+ audience="world"
+ />
+ </div>
+ <div data-testid="test2">
+ <Trans
+ i18nKey={"transTest.key2" as unknown as TranslationKeys}
+ link={(el) => <a href="https://example.com">{el}</a>}
+ />
+ </div>
+ <div data-testid="test3">
+ <Trans
+ i18nKey={"transTest.key3" as unknown as TranslationKeys}
+ link={(el) => <a href="https://example.com">{el}</a>}
+ location="the button"
+ />
+ </div>
+ <div data-testid="test4">
+ <Trans
+ i18nKey={"transTest.key4" as unknown as TranslationKeys}
+ link={(el) => <a href="https://example.com">{el}</a>}
+ location="the button"
+ bold={(el) => <strong>{el}</strong>}
+ />
+ </div>
+ <div data-testid="test5">
+ <Trans
+ i18nKey={"transTest.key5" as unknown as TranslationKeys}
+ connect-link={(el) => <a href="https://example.com">{el}</a>}
+ />
+ </div>
+ </EditorJotaiProvider>,
+ );
+
+ expect(getByTestId("test1").innerHTML).toEqual("Hello world");
+ expect(getByTestId("test2").innerHTML).toEqual(
+ `Please <a href="https://example.com">click the button</a> to continue.`,
+ );
+ expect(getByTestId("test3").innerHTML).toEqual(
+ `Please <a href="https://example.com">click the button</a> to continue.`,
+ );
+ expect(getByTestId("test4").innerHTML).toEqual(
+ `Please <a href="https://example.com">click <strong>the button</strong></a> to continue.`,
+ );
+ expect(getByTestId("test5").innerHTML).toEqual(
+ `Please <a href="https://example.com">click the button</a> to continue.`,
+ );
+ });
+});
diff --git a/packages/excalidraw/components/Trans.tsx b/packages/excalidraw/components/Trans.tsx
new file mode 100644
index 0000000..0cb0f78
--- /dev/null
+++ b/packages/excalidraw/components/Trans.tsx
@@ -0,0 +1,170 @@
+import React from "react";
+
+import type { TranslationKeys } from "../i18n";
+import { useI18n } from "../i18n";
+
+// Used for splitting i18nKey into tokens in Trans component
+// Example:
+// "Please <link>click {{location}}</link> to continue.".split(SPLIT_REGEX).filter(Boolean)
+// produces
+// ["Please ", "<link>", "click ", "{{location}}", "</link>", " to continue."]
+const SPLIT_REGEX = /({{[\w-]+}})|(<[\w-]+>)|(<\/[\w-]+>)/g;
+// Used for extracting "location" from "{{location}}"
+const KEY_REGEXP = /{{([\w-]+)}}/;
+// Used for extracting "link" from "<link>"
+const TAG_START_REGEXP = /<([\w-]+)>/;
+// Used for extracting "link" from "</link>"
+const TAG_END_REGEXP = /<\/([\w-]+)>/;
+
+const getTransChildren = (
+ format: string,
+ props: {
+ [key: string]: React.ReactNode | ((el: React.ReactNode) => React.ReactNode);
+ },
+): React.ReactNode[] => {
+ const stack: { name: string; children: React.ReactNode[] }[] = [
+ {
+ name: "",
+ children: [],
+ },
+ ];
+
+ format
+ .split(SPLIT_REGEX)
+ .filter(Boolean)
+ .forEach((match) => {
+ const tagStartMatch = match.match(TAG_START_REGEXP);
+ const tagEndMatch = match.match(TAG_END_REGEXP);
+ const keyMatch = match.match(KEY_REGEXP);
+
+ if (tagStartMatch !== null) {
+ // The match is <tag>. Set the tag name as the name if it's one of the
+ // props, e.g. for "Please <link>click the button</link> to continue"
+ // tagStartMatch[1] = "link" and props contain "link" then it will be
+ // pushed to stack.
+ const name = tagStartMatch[1];
+ if (props.hasOwnProperty(name)) {
+ stack.push({
+ name,
+ children: [],
+ });
+ } else {
+ console.warn(
+ `Trans: missed to pass in prop ${name} for interpolating ${format}`,
+ );
+ }
+ } else if (tagEndMatch !== null) {
+ // If tag end match is found, this means we need to replace the content with
+ // its actual value in prop e.g. format = "Please <link>click the
+ // button</link> to continue", tagEndMatch is for "</link>", stack last item name =
+ // "link" and props.link = (el) => <a
+ // href="https://example.com">{el}</a> then its prop value will be
+ // pushed to "link"'s children so on DOM when rendering it's rendered as
+ // <a href="https://example.com">click the button</a>
+ const name = tagEndMatch[1];
+ if (name === stack[stack.length - 1].name) {
+ const item = stack.pop()!;
+ const itemChildren = React.createElement(
+ React.Fragment,
+ {},
+ ...item.children,
+ );
+ const fn = props[item.name];
+ if (typeof fn === "function") {
+ stack[stack.length - 1].children.push(fn(itemChildren));
+ }
+ } else {
+ console.warn(
+ `Trans: unexpected end tag ${match} for interpolating ${format}`,
+ );
+ }
+ } else if (keyMatch !== null) {
+ // The match is for {{key}}. Check if the key is present in props and set
+ // the prop value as children of last stack item e.g. format = "Hello
+ // {{name}}", key = "name" and props.name = "Excalidraw" then its prop
+ // value will be pushed to "name"'s children so it's rendered on DOM as
+ // "Hello Excalidraw"
+ const name = keyMatch[1];
+ if (props.hasOwnProperty(name)) {
+ stack[stack.length - 1].children.push(props[name] as React.ReactNode);
+ } else {
+ console.warn(
+ `Trans: key ${name} not in props for interpolating ${format}`,
+ );
+ }
+ } else {
+ // If none of cases match means we just need to push the string
+ // to stack eg - "Hello {{name}} Whats up?" "Hello", "Whats up" will be pushed
+ stack[stack.length - 1].children.push(match);
+ }
+ });
+
+ if (stack.length !== 1) {
+ console.warn(`Trans: stack not empty for interpolating ${format}`);
+ }
+
+ return stack[0].children;
+};
+
+/*
+Trans component is used for translating JSX.
+
+```json
+{
+ "example1": "Hello {{audience}}",
+ "example2": "Please <link>click the button</link> to continue.",
+ "example3": "Please <link>click {{location}}</link> to continue.",
+ "example4": "Please <link>click <bold>{{location}}</bold></link> to continue.",
+}
+```
+
+```jsx
+<Trans i18nKey="example1" audience="world" />
+
+<Trans
+ i18nKey="example2"
+ connectLink={(el) => <a href="https://example.com">{el}</a>}
+/>
+
+<Trans
+ i18nKey="example3"
+ connectLink={(el) => <a href="https://example.com">{el}</a>}
+ location="the button"
+/>
+
+<Trans
+ i18nKey="example4"
+ connectLink={(el) => <a href="https://example.com">{el}</a>}
+ location="the button"
+ bold={(el) => <strong>{el}</strong>}
+/>
+```
+
+Output:
+
+```html
+Hello world
+Please <a href="https://example.com">click the button</a> to continue.
+Please <a href="https://example.com">click the button</a> to continue.
+Please <a href="https://example.com">click <strong>the button</strong></a> to continue.
+```
+*/
+const Trans = ({
+ i18nKey,
+ children,
+ ...props
+}: {
+ i18nKey: TranslationKeys;
+ [key: string]: React.ReactNode | ((el: React.ReactNode) => React.ReactNode);
+}) => {
+ const { t } = useI18n();
+
+ // This is needed to avoid unique key error in list which gets rendered from getTransChildren
+ return React.createElement(
+ React.Fragment,
+ {},
+ ...getTransChildren(t(i18nKey), props),
+ );
+};
+
+export default Trans;
diff --git a/packages/excalidraw/components/UserList.scss b/packages/excalidraw/components/UserList.scss
new file mode 100644
index 0000000..fdcadef
--- /dev/null
+++ b/packages/excalidraw/components/UserList.scss
@@ -0,0 +1,160 @@
+@import "../css/variables.module";
+
+.excalidraw {
+ --avatar-size: 1.75rem;
+ --avatarList-gap: 0.625rem;
+ --userList-padding: var(--space-factor);
+
+ .UserList__wrapper {
+ display: flex;
+ width: 100%;
+ justify-content: flex-end;
+ align-items: center;
+ pointer-events: none !important;
+ }
+
+ .UserList {
+ pointer-events: none;
+ padding: var(--userList-padding);
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ align-items: center;
+ gap: var(--avatarList-gap);
+
+ box-sizing: border-box;
+
+ --max-size: calc(
+ var(--avatar-size) * var(--max-avatars, 2) + var(--avatarList-gap) *
+ (var(--max-avatars, 2) - 1) + var(--userList-padding) * 2
+ );
+
+ // max width & height set to fix the max-avatars
+ max-height: var(--max-size);
+ max-width: var(--max-size);
+
+ // Tweak in 30px increments to fit more/fewer avatars in a row/column ^^
+ }
+
+ .UserList > * {
+ pointer-events: var(--ui-pointerEvents);
+ }
+
+ .UserList_mobile {
+ padding: 0;
+ justify-content: normal;
+ margin: 0.5rem 0;
+ max-width: none;
+ max-height: none;
+ }
+
+ .UserList__more {
+ @include avatarStyles;
+ background-color: var(--color-gray-20);
+ border: 0 !important;
+ font-size: 0.625rem;
+ font-weight: 400;
+ flex-shrink: 0;
+ color: var(--color-gray-100);
+ font-weight: bold;
+ }
+
+ .UserList__collaborator-name {
+ text-overflow: ellipsis;
+ overflow: hidden;
+ white-space: nowrap;
+ }
+
+ .UserList__collaborator--avatar-only {
+ position: relative;
+ display: flex;
+ flex: 0 0 auto;
+ .UserList__collaborator-status-icon {
+ --size: 14px;
+ position: absolute;
+ display: flex;
+ flex: 0 0 auto;
+ bottom: -0.25rem;
+ right: -0.25rem;
+ width: var(--size);
+ height: var(--size);
+ svg {
+ flex: 0 0 auto;
+ width: var(--size);
+ height: var(--size);
+ }
+ }
+ }
+
+ .UserList__collaborator-status-icons {
+ margin-left: auto;
+ flex: 0 0 auto;
+ min-width: 2.25rem;
+ gap: 0.25rem;
+ justify-content: flex-end;
+ display: flex;
+ }
+
+ .UserList__collaborator.is-muted
+ .UserList__collaborator-status-icon-microphone-muted {
+ color: var(--color-danger);
+ filter: drop-shadow(0px 0px 0px rgba(0, 0, 0, 0.5));
+ }
+
+ .UserList__collaborator-status-icon-speaking-indicator {
+ display: flex;
+ flex-flow: row nowrap;
+ align-items: center;
+ justify-content: space-between;
+ width: 1rem;
+ padding: 0 3px;
+ box-sizing: border-box;
+
+ div {
+ width: 0.125rem;
+ height: 0.4rem;
+ // keep this in sync with constants.ts
+ background-color: #a2f1a6;
+ }
+
+ div:nth-of-type(1) {
+ animation: speaking-indicator-anim 1s -0.45s ease-in-out infinite;
+ }
+
+ div:nth-of-type(2) {
+ animation: speaking-indicator-anim 1s -0.9s ease-in-out infinite;
+ }
+
+ div:nth-of-type(3) {
+ animation: speaking-indicator-anim 1s -0.15s ease-in-out infinite;
+ }
+ }
+
+ @keyframes speaking-indicator-anim {
+ 0%,
+ 100% {
+ transform: scaleY(1);
+ }
+
+ 50% {
+ transform: scaleY(2);
+ }
+ }
+
+ --userlist-hint-bg-color: var(--color-gray-10);
+ --userlist-hint-heading-color: var(--color-gray-80);
+ --userlist-hint-text-color: var(--color-gray-60);
+ --userlist-collaborators-border-color: var(--color-gray-20);
+
+ &.theme--dark {
+ --userlist-hint-bg-color: var(--color-gray-90);
+ --userlist-hint-heading-color: var(--color-gray-30);
+ --userlist-hint-text-color: var(--color-gray-40);
+ --userlist-collaborators-border-color: var(--color-gray-80);
+ }
+
+ .UserList__collaborators {
+ top: auto;
+ max-height: 50vh;
+ }
+}
diff --git a/packages/excalidraw/components/UserList.tsx b/packages/excalidraw/components/UserList.tsx
new file mode 100644
index 0000000..9fbfc1a
--- /dev/null
+++ b/packages/excalidraw/components/UserList.tsx
@@ -0,0 +1,293 @@
+import "./UserList.scss";
+
+import React, { useLayoutEffect } from "react";
+import clsx from "clsx";
+import type { Collaborator, SocketId } from "../types";
+import { Tooltip } from "./Tooltip";
+import { useExcalidrawActionManager } from "./App";
+import type { ActionManager } from "../actions/manager";
+
+import * as Popover from "@radix-ui/react-popover";
+import { Island } from "./Island";
+import { QuickSearch } from "./QuickSearch";
+import { t } from "../i18n";
+import { isShallowEqual } from "../utils";
+import { supportsResizeObserver } from "../constants";
+import type { MarkRequired } from "../utility-types";
+import { ScrollableList } from "./ScrollableList";
+
+export type GoToCollaboratorComponentProps = {
+ socketId: SocketId;
+ collaborator: Collaborator;
+ withName: boolean;
+ isBeingFollowed: boolean;
+};
+
+/** collaborator user id or socket id (fallback) */
+type ClientId = string & { _brand: "UserId" };
+
+const DEFAULT_MAX_AVATARS = 4;
+const SHOW_COLLABORATORS_FILTER_AT = 8;
+
+const ConditionalTooltipWrapper = ({
+ shouldWrap,
+ children,
+ username,
+}: {
+ shouldWrap: boolean;
+ children: React.ReactNode;
+ username?: string | null;
+}) =>
+ shouldWrap ? (
+ <Tooltip label={username || "Unknown user"}>{children}</Tooltip>
+ ) : (
+ <>{children}</>
+ );
+
+const renderCollaborator = ({
+ actionManager,
+ collaborator,
+ socketId,
+ withName = false,
+ shouldWrapWithTooltip = false,
+ isBeingFollowed,
+}: {
+ actionManager: ActionManager;
+ collaborator: Collaborator;
+ socketId: SocketId;
+ withName?: boolean;
+ shouldWrapWithTooltip?: boolean;
+ isBeingFollowed: boolean;
+}) => {
+ const data: GoToCollaboratorComponentProps = {
+ socketId,
+ collaborator,
+ withName,
+ isBeingFollowed,
+ };
+ const avatarJSX = actionManager.renderAction("goToCollaborator", data);
+
+ return (
+ <ConditionalTooltipWrapper
+ key={socketId}
+ username={collaborator.username}
+ shouldWrap={shouldWrapWithTooltip}
+ >
+ {avatarJSX}
+ </ConditionalTooltipWrapper>
+ );
+};
+
+type UserListUserObject = Pick<
+ Collaborator,
+ | "avatarUrl"
+ | "id"
+ | "socketId"
+ | "username"
+ | "isInCall"
+ | "isSpeaking"
+ | "isMuted"
+>;
+
+type UserListProps = {
+ className?: string;
+ mobile?: boolean;
+ collaborators: Map<SocketId, UserListUserObject>;
+ userToFollow: SocketId | null;
+};
+
+const collaboratorComparatorKeys = [
+ "avatarUrl",
+ "id",
+ "socketId",
+ "username",
+ "isInCall",
+ "isSpeaking",
+ "isMuted",
+] as const;
+
+export const UserList = React.memo(
+ ({ className, mobile, collaborators, userToFollow }: UserListProps) => {
+ const actionManager = useExcalidrawActionManager();
+
+ const uniqueCollaboratorsMap = new Map<
+ ClientId,
+ MarkRequired<Collaborator, "socketId">
+ >();
+
+ collaborators.forEach((collaborator, socketId) => {
+ const userId = (collaborator.id || socketId) as ClientId;
+ uniqueCollaboratorsMap.set(
+ // filter on user id, else fall back on unique socketId
+ userId,
+ { ...collaborator, socketId },
+ );
+ });
+
+ const uniqueCollaboratorsArray = Array.from(
+ uniqueCollaboratorsMap.values(),
+ ).filter((collaborator) => collaborator.username?.trim());
+
+ const [searchTerm, setSearchTerm] = React.useState("");
+ const filteredCollaborators = uniqueCollaboratorsArray.filter(
+ (collaborator) =>
+ collaborator.username?.toLowerCase().includes(searchTerm),
+ );
+
+ const userListWrapper = React.useRef<HTMLDivElement | null>(null);
+
+ useLayoutEffect(() => {
+ if (userListWrapper.current) {
+ const updateMaxAvatars = (width: number) => {
+ const maxAvatars = Math.max(1, Math.min(8, Math.floor(width / 38)));
+ setMaxAvatars(maxAvatars);
+ };
+
+ updateMaxAvatars(userListWrapper.current.clientWidth);
+
+ if (!supportsResizeObserver) {
+ return;
+ }
+
+ const resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ const { width } = entry.contentRect;
+ updateMaxAvatars(width);
+ }
+ });
+
+ resizeObserver.observe(userListWrapper.current);
+
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }
+ }, []);
+
+ const [maxAvatars, setMaxAvatars] = React.useState(DEFAULT_MAX_AVATARS);
+
+ const firstNCollaborators = uniqueCollaboratorsArray.slice(
+ 0,
+ maxAvatars - 1,
+ );
+
+ const firstNAvatarsJSX = firstNCollaborators.map((collaborator) =>
+ renderCollaborator({
+ actionManager,
+ collaborator,
+ socketId: collaborator.socketId,
+ shouldWrapWithTooltip: true,
+ isBeingFollowed: collaborator.socketId === userToFollow,
+ }),
+ );
+
+ return mobile ? (
+ <div className={clsx("UserList UserList_mobile", className)}>
+ {uniqueCollaboratorsArray.map((collaborator) =>
+ renderCollaborator({
+ actionManager,
+ collaborator,
+ socketId: collaborator.socketId,
+ shouldWrapWithTooltip: true,
+ isBeingFollowed: collaborator.socketId === userToFollow,
+ }),
+ )}
+ </div>
+ ) : (
+ <div className="UserList__wrapper" ref={userListWrapper}>
+ <div
+ className={clsx("UserList", className)}
+ style={{ [`--max-avatars` as any]: maxAvatars }}
+ >
+ {firstNAvatarsJSX}
+
+ {uniqueCollaboratorsArray.length > maxAvatars - 1 && (
+ <Popover.Root>
+ <Popover.Trigger className="UserList__more">
+ +{uniqueCollaboratorsArray.length - maxAvatars + 1}
+ </Popover.Trigger>
+ <Popover.Content
+ style={{
+ zIndex: 2,
+ width: "15rem",
+ textAlign: "left",
+ }}
+ align="end"
+ sideOffset={10}
+ >
+ <Island padding={2}>
+ {uniqueCollaboratorsArray.length >=
+ SHOW_COLLABORATORS_FILTER_AT && (
+ <QuickSearch
+ placeholder={t("quickSearch.placeholder")}
+ onChange={setSearchTerm}
+ />
+ )}
+ <ScrollableList
+ className={"dropdown-menu UserList__collaborators"}
+ placeholder={t("userList.empty")}
+ >
+ {/* The list checks for `Children.count()`, hence defensively returning empty list */}
+ {filteredCollaborators.length > 0
+ ? [
+ <div className="hint">{t("userList.hint.text")}</div>,
+ filteredCollaborators.map((collaborator) =>
+ renderCollaborator({
+ actionManager,
+ collaborator,
+ socketId: collaborator.socketId,
+ withName: true,
+ isBeingFollowed:
+ collaborator.socketId === userToFollow,
+ }),
+ ),
+ ]
+ : []}
+ </ScrollableList>
+ <Popover.Arrow
+ width={20}
+ height={10}
+ style={{
+ fill: "var(--popup-bg-color)",
+ filter: "drop-shadow(rgba(0, 0, 0, 0.05) 0px 3px 2px)",
+ }}
+ />
+ </Island>
+ </Popover.Content>
+ </Popover.Root>
+ )}
+ </div>
+ </div>
+ );
+ },
+ (prev, next) => {
+ if (
+ prev.collaborators.size !== next.collaborators.size ||
+ prev.mobile !== next.mobile ||
+ prev.className !== next.className ||
+ prev.userToFollow !== next.userToFollow
+ ) {
+ return false;
+ }
+
+ const nextCollaboratorSocketIds = next.collaborators.keys();
+
+ for (const [socketId, collaborator] of prev.collaborators) {
+ const nextCollaborator = next.collaborators.get(socketId);
+ if (
+ !nextCollaborator ||
+ // this checks order of collaborators in the map is the same
+ // as previous render
+ socketId !== nextCollaboratorSocketIds.next().value ||
+ !isShallowEqual(
+ collaborator,
+ nextCollaborator,
+ collaboratorComparatorKeys,
+ )
+ ) {
+ return false;
+ }
+ }
+ return true;
+ },
+);
diff --git a/packages/excalidraw/components/__snapshots__/App.test.tsx.snap b/packages/excalidraw/components/__snapshots__/App.test.tsx.snap
new file mode 100644
index 0000000..49c2fd0
--- /dev/null
+++ b/packages/excalidraw/components/__snapshots__/App.test.tsx.snap
@@ -0,0 +1,50 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`Test <App/> > should show error modal when using brave and measureText API is not working 1`] = `
+<div
+ data-testid="brave-measure-text-error"
+>
+ <p>
+ Looks like you are using Brave browser with the
+ <span
+ style="font-weight: 600;"
+ >
+ Aggressively Block Fingerprinting
+ </span>
+ setting enabled.
+ </p>
+ <p>
+ This could result in breaking the
+ <span
+ style="font-weight: 600;"
+ >
+ Text Elements
+ </span>
+ in your drawings.
+ </p>
+ <p>
+ We strongly recommend disabling this setting. You can follow
+ <a
+ href="http://docs.excalidraw.com/docs/@excalidraw/excalidraw/faq#turning-off-aggresive-block-fingerprinting-in-brave-browser"
+ >
+ these steps
+ </a>
+ on how to do so.
+ </p>
+ <p>
+ If disabling this setting doesn't fix the display of text elements, please open an
+ <a
+ href="https://github.com/excalidraw/excalidraw/issues/new"
+ >
+ issue
+ </a>
+ on our GitHub, or write us on
+ <a
+ href="https://discord.gg/UexuTaE"
+ >
+ Discord
+ .
+ </a>
+ </p>
+</div>
+`;
diff --git a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
new file mode 100644
index 0000000..03ae0f6
--- /dev/null
+++ b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
@@ -0,0 +1,240 @@
+import React, { useEffect, useRef } from "react";
+import { isShallowEqual, sceneCoordsToViewportCoords } from "../../utils";
+import { CURSOR_TYPE } from "../../constants";
+import { t } from "../../i18n";
+import type { DOMAttributes } from "react";
+import type { AppState, Device, InteractiveCanvasAppState } from "../../types";
+import type {
+ InteractiveCanvasRenderConfig,
+ RenderableElementsMap,
+ RenderInteractiveSceneCallback,
+} from "../../scene/types";
+import type {
+ NonDeletedExcalidrawElement,
+ NonDeletedSceneElementsMap,
+} from "../../element/types";
+import { isRenderThrottlingEnabled } from "../../reactUtils";
+import { renderInteractiveScene } from "../../renderer/interactiveScene";
+
+type InteractiveCanvasProps = {
+ containerRef: React.RefObject<HTMLDivElement | null>;
+ canvas: HTMLCanvasElement | null;
+ elementsMap: RenderableElementsMap;
+ visibleElements: readonly NonDeletedExcalidrawElement[];
+ selectedElements: readonly NonDeletedExcalidrawElement[];
+ allElementsMap: NonDeletedSceneElementsMap;
+ sceneNonce: number | undefined;
+ selectionNonce: number | undefined;
+ scale: number;
+ appState: InteractiveCanvasAppState;
+ device: Device;
+ renderInteractiveSceneCallback: (
+ data: RenderInteractiveSceneCallback,
+ ) => void;
+ handleCanvasRef: (canvas: HTMLCanvasElement | null) => void;
+ onContextMenu: Exclude<
+ DOMAttributes<HTMLCanvasElement | HTMLDivElement>["onContextMenu"],
+ undefined
+ >;
+ onPointerMove: Exclude<
+ DOMAttributes<HTMLCanvasElement>["onPointerMove"],
+ undefined
+ >;
+ onPointerUp: Exclude<
+ DOMAttributes<HTMLCanvasElement>["onPointerUp"],
+ undefined
+ >;
+ onPointerCancel: Exclude<
+ DOMAttributes<HTMLCanvasElement>["onPointerCancel"],
+ undefined
+ >;
+ onTouchMove: Exclude<
+ DOMAttributes<HTMLCanvasElement>["onTouchMove"],
+ undefined
+ >;
+ onPointerDown: Exclude<
+ DOMAttributes<HTMLCanvasElement>["onPointerDown"],
+ undefined
+ >;
+ onDoubleClick: Exclude<
+ DOMAttributes<HTMLCanvasElement>["onDoubleClick"],
+ undefined
+ >;
+};
+
+const InteractiveCanvas = (props: InteractiveCanvasProps) => {
+ const isComponentMounted = useRef(false);
+
+ useEffect(() => {
+ if (!isComponentMounted.current) {
+ isComponentMounted.current = true;
+ return;
+ }
+
+ const remotePointerButton: InteractiveCanvasRenderConfig["remotePointerButton"] =
+ new Map();
+ const remotePointerViewportCoords: InteractiveCanvasRenderConfig["remotePointerViewportCoords"] =
+ new Map();
+ const remoteSelectedElementIds: InteractiveCanvasRenderConfig["remoteSelectedElementIds"] =
+ new Map();
+ const remotePointerUsernames: InteractiveCanvasRenderConfig["remotePointerUsernames"] =
+ new Map();
+ const remotePointerUserStates: InteractiveCanvasRenderConfig["remotePointerUserStates"] =
+ new Map();
+
+ props.appState.collaborators.forEach((user, socketId) => {
+ if (user.selectedElementIds) {
+ for (const id of Object.keys(user.selectedElementIds)) {
+ if (!remoteSelectedElementIds.has(id)) {
+ remoteSelectedElementIds.set(id, []);
+ }
+ remoteSelectedElementIds.get(id)!.push(socketId);
+ }
+ }
+ if (!user.pointer || user.pointer.renderCursor === false) {
+ return;
+ }
+ if (user.username) {
+ remotePointerUsernames.set(socketId, user.username);
+ }
+ if (user.userState) {
+ remotePointerUserStates.set(socketId, user.userState);
+ }
+ remotePointerViewportCoords.set(
+ socketId,
+ sceneCoordsToViewportCoords(
+ {
+ sceneX: user.pointer.x,
+ sceneY: user.pointer.y,
+ },
+ props.appState,
+ ),
+ );
+ remotePointerButton.set(socketId, user.button);
+ });
+
+ const selectionColor =
+ (props.containerRef?.current &&
+ getComputedStyle(props.containerRef.current).getPropertyValue(
+ "--color-selection",
+ )) ||
+ "#6965db";
+
+ renderInteractiveScene(
+ {
+ canvas: props.canvas,
+ elementsMap: props.elementsMap,
+ visibleElements: props.visibleElements,
+ selectedElements: props.selectedElements,
+ allElementsMap: props.allElementsMap,
+ scale: window.devicePixelRatio,
+ appState: props.appState,
+ renderConfig: {
+ remotePointerViewportCoords,
+ remotePointerButton,
+ remoteSelectedElementIds,
+ remotePointerUsernames,
+ remotePointerUserStates,
+ selectionColor,
+ renderScrollbars: false,
+ },
+ device: props.device,
+ callback: props.renderInteractiveSceneCallback,
+ },
+ isRenderThrottlingEnabled(),
+ );
+ });
+
+ return (
+ <canvas
+ className="excalidraw__canvas interactive"
+ style={{
+ width: props.appState.width,
+ height: props.appState.height,
+ cursor: props.appState.viewModeEnabled
+ ? CURSOR_TYPE.GRAB
+ : CURSOR_TYPE.AUTO,
+ }}
+ width={props.appState.width * props.scale}
+ height={props.appState.height * props.scale}
+ ref={props.handleCanvasRef}
+ onContextMenu={props.onContextMenu}
+ onPointerMove={props.onPointerMove}
+ onPointerUp={props.onPointerUp}
+ onPointerCancel={props.onPointerCancel}
+ onTouchMove={props.onTouchMove}
+ onPointerDown={props.onPointerDown}
+ onDoubleClick={
+ props.appState.viewModeEnabled ? undefined : props.onDoubleClick
+ }
+ >
+ {t("labels.drawingCanvas")}
+ </canvas>
+ );
+};
+
+const getRelevantAppStateProps = (
+ appState: AppState,
+): InteractiveCanvasAppState => ({
+ zoom: appState.zoom,
+ scrollX: appState.scrollX,
+ scrollY: appState.scrollY,
+ width: appState.width,
+ height: appState.height,
+ viewModeEnabled: appState.viewModeEnabled,
+ openDialog: appState.openDialog,
+ editingGroupId: appState.editingGroupId,
+ editingLinearElement: appState.editingLinearElement,
+ selectedElementIds: appState.selectedElementIds,
+ frameToHighlight: appState.frameToHighlight,
+ offsetLeft: appState.offsetLeft,
+ offsetTop: appState.offsetTop,
+ theme: appState.theme,
+ pendingImageElementId: appState.pendingImageElementId,
+ selectionElement: appState.selectionElement,
+ selectedGroupIds: appState.selectedGroupIds,
+ selectedLinearElement: appState.selectedLinearElement,
+ multiElement: appState.multiElement,
+ isBindingEnabled: appState.isBindingEnabled,
+ suggestedBindings: appState.suggestedBindings,
+ isRotating: appState.isRotating,
+ elementsToHighlight: appState.elementsToHighlight,
+ collaborators: appState.collaborators, // Necessary for collab. sessions
+ activeEmbeddable: appState.activeEmbeddable,
+ snapLines: appState.snapLines,
+ zenModeEnabled: appState.zenModeEnabled,
+ editingTextElement: appState.editingTextElement,
+ isCropping: appState.isCropping,
+ croppingElementId: appState.croppingElementId,
+ searchMatches: appState.searchMatches,
+});
+
+const areEqual = (
+ prevProps: InteractiveCanvasProps,
+ nextProps: InteractiveCanvasProps,
+) => {
+ // This could be further optimised if needed, as we don't have to render interactive canvas on each scene mutation
+ if (
+ prevProps.selectionNonce !== nextProps.selectionNonce ||
+ prevProps.sceneNonce !== nextProps.sceneNonce ||
+ prevProps.scale !== nextProps.scale ||
+ // we need to memoize on elementsMap because they may have renewed
+ // even if sceneNonce didn't change (e.g. we filter elements out based
+ // on appState)
+ prevProps.elementsMap !== nextProps.elementsMap ||
+ prevProps.visibleElements !== nextProps.visibleElements ||
+ prevProps.selectedElements !== nextProps.selectedElements
+ ) {
+ return false;
+ }
+
+ // Comparing the interactive appState for changes in case of some edge cases
+ return isShallowEqual(
+ // asserting AppState because we're being passed the whole AppState
+ // but resolve to only the InteractiveCanvas-relevant props
+ getRelevantAppStateProps(prevProps.appState as AppState),
+ getRelevantAppStateProps(nextProps.appState as AppState),
+ );
+};
+
+export default React.memo(InteractiveCanvas, areEqual);
diff --git a/packages/excalidraw/components/canvases/NewElementCanvas.tsx b/packages/excalidraw/components/canvases/NewElementCanvas.tsx
new file mode 100644
index 0000000..1815671
--- /dev/null
+++ b/packages/excalidraw/components/canvases/NewElementCanvas.tsx
@@ -0,0 +1,56 @@
+import { useEffect, useRef } from "react";
+import type { NonDeletedSceneElementsMap } from "../../element/types";
+import type { AppState } from "../../types";
+import type {
+ RenderableElementsMap,
+ StaticCanvasRenderConfig,
+} from "../../scene/types";
+import type { RoughCanvas } from "roughjs/bin/canvas";
+import { renderNewElementScene } from "../../renderer/renderNewElementScene";
+import { isRenderThrottlingEnabled } from "../../reactUtils";
+
+interface NewElementCanvasProps {
+ appState: AppState;
+ elementsMap: RenderableElementsMap;
+ allElementsMap: NonDeletedSceneElementsMap;
+ scale: number;
+ rc: RoughCanvas;
+ renderConfig: StaticCanvasRenderConfig;
+}
+
+const NewElementCanvas = (props: NewElementCanvasProps) => {
+ const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ useEffect(() => {
+ if (!canvasRef.current) {
+ return;
+ }
+ renderNewElementScene(
+ {
+ canvas: canvasRef.current,
+ scale: props.scale,
+ newElement: props.appState.newElement,
+ elementsMap: props.elementsMap,
+ allElementsMap: props.allElementsMap,
+ rc: props.rc,
+ renderConfig: props.renderConfig,
+ appState: props.appState,
+ },
+ isRenderThrottlingEnabled(),
+ );
+ });
+
+ return (
+ <canvas
+ className="excalidraw__canvas"
+ style={{
+ width: props.appState.width,
+ height: props.appState.height,
+ }}
+ width={props.appState.width * props.scale}
+ height={props.appState.height * props.scale}
+ ref={canvasRef}
+ />
+ );
+};
+
+export default NewElementCanvas;
diff --git a/packages/excalidraw/components/canvases/StaticCanvas.tsx b/packages/excalidraw/components/canvases/StaticCanvas.tsx
new file mode 100644
index 0000000..9185bdd
--- /dev/null
+++ b/packages/excalidraw/components/canvases/StaticCanvas.tsx
@@ -0,0 +1,141 @@
+import React, { useEffect, useRef } from "react";
+import type { RoughCanvas } from "roughjs/bin/canvas";
+import { renderStaticScene } from "../../renderer/staticScene";
+import { isShallowEqual } from "../../utils";
+import type { AppState, StaticCanvasAppState } from "../../types";
+import type {
+ RenderableElementsMap,
+ StaticCanvasRenderConfig,
+} from "../../scene/types";
+import type {
+ NonDeletedExcalidrawElement,
+ NonDeletedSceneElementsMap,
+} from "../../element/types";
+import { isRenderThrottlingEnabled } from "../../reactUtils";
+
+type StaticCanvasProps = {
+ canvas: HTMLCanvasElement;
+ rc: RoughCanvas;
+ elementsMap: RenderableElementsMap;
+ allElementsMap: NonDeletedSceneElementsMap;
+ visibleElements: readonly NonDeletedExcalidrawElement[];
+ sceneNonce: number | undefined;
+ selectionNonce: number | undefined;
+ scale: number;
+ appState: StaticCanvasAppState;
+ renderConfig: StaticCanvasRenderConfig;
+};
+
+const StaticCanvas = (props: StaticCanvasProps) => {
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const isComponentMounted = useRef(false);
+
+ useEffect(() => {
+ const wrapper = wrapperRef.current;
+ if (!wrapper) {
+ return;
+ }
+
+ const canvas = props.canvas;
+
+ if (!isComponentMounted.current) {
+ isComponentMounted.current = true;
+
+ wrapper.replaceChildren(canvas);
+ canvas.classList.add("excalidraw__canvas", "static");
+ }
+
+ const widthString = `${props.appState.width}px`;
+ const heightString = `${props.appState.height}px`;
+ if (canvas.style.width !== widthString) {
+ canvas.style.width = widthString;
+ }
+ if (canvas.style.height !== heightString) {
+ canvas.style.height = heightString;
+ }
+
+ const scaledWidth = props.appState.width * props.scale;
+ const scaledHeight = props.appState.height * props.scale;
+ // setting width/height resets the canvas even if dimensions not changed,
+ // which would cause flicker when we skip frame (due to throttling)
+ if (canvas.width !== scaledWidth) {
+ canvas.width = scaledWidth;
+ }
+ if (canvas.height !== scaledHeight) {
+ canvas.height = scaledHeight;
+ }
+
+ renderStaticScene(
+ {
+ canvas,
+ rc: props.rc,
+ scale: props.scale,
+ elementsMap: props.elementsMap,
+ allElementsMap: props.allElementsMap,
+ visibleElements: props.visibleElements,
+ appState: props.appState,
+ renderConfig: props.renderConfig,
+ },
+ isRenderThrottlingEnabled(),
+ );
+ });
+
+ return <div className="excalidraw__canvas-wrapper" ref={wrapperRef} />;
+};
+
+const getRelevantAppStateProps = (
+ appState: AppState,
+): StaticCanvasAppState => ({
+ zoom: appState.zoom,
+ scrollX: appState.scrollX,
+ scrollY: appState.scrollY,
+ width: appState.width,
+ height: appState.height,
+ viewModeEnabled: appState.viewModeEnabled,
+ openDialog: appState.openDialog,
+ hoveredElementIds: appState.hoveredElementIds,
+ offsetLeft: appState.offsetLeft,
+ offsetTop: appState.offsetTop,
+ theme: appState.theme,
+ pendingImageElementId: appState.pendingImageElementId,
+ shouldCacheIgnoreZoom: appState.shouldCacheIgnoreZoom,
+ viewBackgroundColor: appState.viewBackgroundColor,
+ exportScale: appState.exportScale,
+ selectedElementsAreBeingDragged: appState.selectedElementsAreBeingDragged,
+ gridSize: appState.gridSize,
+ gridStep: appState.gridStep,
+ frameRendering: appState.frameRendering,
+ selectedElementIds: appState.selectedElementIds,
+ frameToHighlight: appState.frameToHighlight,
+ editingGroupId: appState.editingGroupId,
+ currentHoveredFontFamily: appState.currentHoveredFontFamily,
+ croppingElementId: appState.croppingElementId,
+});
+
+const areEqual = (
+ prevProps: StaticCanvasProps,
+ nextProps: StaticCanvasProps,
+) => {
+ if (
+ prevProps.sceneNonce !== nextProps.sceneNonce ||
+ prevProps.scale !== nextProps.scale ||
+ // we need to memoize on elementsMap because they may have renewed
+ // even if sceneNonce didn't change (e.g. we filter elements out based
+ // on appState)
+ prevProps.elementsMap !== nextProps.elementsMap ||
+ prevProps.visibleElements !== nextProps.visibleElements
+ ) {
+ return false;
+ }
+
+ return (
+ isShallowEqual(
+ // asserting AppState because we're being passed the whole AppState
+ // but resolve to only the StaticCanvas-relevant props
+ getRelevantAppStateProps(prevProps.appState as AppState),
+ getRelevantAppStateProps(nextProps.appState as AppState),
+ ) && isShallowEqual(prevProps.renderConfig, nextProps.renderConfig)
+ );
+};
+
+export default React.memo(StaticCanvas, areEqual);
diff --git a/packages/excalidraw/components/canvases/index.tsx b/packages/excalidraw/components/canvases/index.tsx
new file mode 100644
index 0000000..b3956d7
--- /dev/null
+++ b/packages/excalidraw/components/canvases/index.tsx
@@ -0,0 +1,4 @@
+import InteractiveCanvas from "./InteractiveCanvas";
+import StaticCanvas from "./StaticCanvas";
+
+export { InteractiveCanvas, StaticCanvas };
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenu.scss b/packages/excalidraw/components/dropdownMenu/DropdownMenu.scss
new file mode 100644
index 0000000..e48f6d7
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenu.scss
@@ -0,0 +1,218 @@
+@import "../../css/variables.module.scss";
+
+.excalidraw {
+ .dropdown-menu {
+ position: absolute;
+ top: 100%;
+ margin-top: 0.5rem;
+
+ &--mobile {
+ left: 0;
+ width: 100%;
+ row-gap: 0.75rem;
+
+ .dropdown-menu-container {
+ padding: 8px 8px;
+ box-sizing: border-box;
+ // background-color: var(--island-bg-color);
+ box-shadow: var(--shadow-island);
+ border-radius: var(--border-radius-lg);
+ position: relative;
+ transition: box-shadow 0.5s ease-in-out;
+
+ &.zen-mode {
+ box-shadow: none;
+ }
+ }
+ }
+
+ .dropdown-menu-container {
+ background-color: var(--island-bg-color);
+ max-height: calc(100vh - 150px);
+ overflow-y: auto;
+ --gap: 2;
+ }
+
+ .dropdown-menu-item-base {
+ display: flex;
+ column-gap: 0.625rem;
+ font-size: 0.875rem;
+ color: var(--color-on-surface);
+ width: 100%;
+ box-sizing: border-box;
+ font-weight: 400;
+ font-family: inherit;
+ }
+
+ &.manual-hover {
+ // disable built-in hover due to keyboard navigation
+ .dropdown-menu-item {
+ &:hover {
+ background-color: transparent;
+ }
+
+ &--hovered {
+ background-color: var(--button-hover-bg) !important;
+ }
+
+ &--selected {
+ background-color: var(--color-primary-light) !important;
+ }
+ }
+ }
+
+ &.fonts {
+ margin-top: 1rem;
+ // display max 7 items per list, where each has 2rem (2.25) height and 1px margin top & bottom
+ // count in 2 groups, where each allocates 1.3*0.75rem font-size and 0.5rem margin bottom, plus one extra 1rem margin top
+ max-height: calc(7 * (2rem + 2px) + 2 * (0.5rem + 1.3 * 0.75rem) + 1rem);
+
+ @media screen and (min-width: 1921px) {
+ max-height: calc(
+ 7 * (2.25rem + 2px) + 2 * (0.5rem + 1.3 * 0.75rem) + 1rem
+ );
+ }
+
+ .dropdown-menu-item-base {
+ display: inline-flex;
+ }
+
+ .dropdown-menu-group:not(:first-child) {
+ margin-top: 1rem;
+ }
+
+ .dropdown-menu-group-title {
+ font-size: 0.75rem;
+ text-align: left;
+ font-weight: 400;
+ margin: 0 0 0.5rem;
+ line-height: 1.3;
+ }
+ }
+
+ .dropdown-menu-item {
+ height: 2rem;
+ margin: 1px;
+ padding: 0 0.5rem;
+ width: calc(100% - 2px);
+ background-color: transparent;
+ border: 1px solid transparent;
+ align-items: center;
+ cursor: pointer;
+ border-radius: var(--border-radius-md);
+
+ @media screen and (min-width: 1921px) {
+ height: 2.25rem;
+ }
+
+ &__text {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ white-space: nowrap;
+ gap: 0.75rem;
+ }
+
+ &__shortcut {
+ margin-inline-start: auto;
+ opacity: 0.5;
+
+ &--orphaned {
+ text-align: right;
+ font-size: 0.875rem;
+ padding: 0 0.625rem;
+ }
+ }
+
+ &--selected {
+ background: var(--color-primary-light);
+ --icon-fill-color: var(--color-primary-darker);
+ }
+
+ &:hover {
+ background-color: var(--button-hover-bg);
+ text-decoration: none;
+ }
+
+ &:active {
+ background-color: var(--button-hover-bg);
+ border-color: var(--color-brand-active);
+ }
+
+ svg {
+ width: 1rem;
+ height: 1rem;
+ display: block;
+ }
+ }
+
+ .dropdown-menu-item-bare {
+ align-items: center;
+ height: 2rem;
+ justify-content: space-between;
+
+ @media screen and (min-width: 1921px) {
+ height: 2.25rem;
+ }
+
+ svg {
+ width: 1rem;
+ height: 1rem;
+ display: block;
+ }
+ }
+
+ .dropdown-menu-item-custom {
+ margin-top: 0.5rem;
+ }
+
+ .dropdown-menu-group-title {
+ font-size: 14px;
+ text-align: left;
+ margin: 10px 0;
+ font-weight: 500;
+ }
+ }
+
+ .dropdown-menu-button {
+ @include outlineButtonStyles;
+ width: var(--lg-button-size);
+ height: var(--lg-button-size);
+
+ --background: var(--color-surface-mid);
+
+ background-color: var(--background);
+
+ @at-root .excalidraw.theme--dark#{&} {
+ --background: var(--color-surface-high);
+ &:hover {
+ --background: #363541;
+ }
+ }
+
+ &:hover {
+ --background: var(--color-surface-high);
+ background-color: var(--background);
+ text-decoration: none;
+ }
+
+ &:active {
+ border-color: var(--color-primary);
+ }
+
+ svg {
+ width: var(--lg-icon-size);
+ height: var(--lg-icon-size);
+ }
+
+ &--mobile {
+ border: none;
+ margin: 0;
+ padding: 0;
+ width: var(--default-button-size);
+ height: var(--default-button-size);
+ }
+ }
+}
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenu.test.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenu.test.tsx
new file mode 100644
index 0000000..0c8deec
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenu.test.tsx
@@ -0,0 +1,26 @@
+import React from "react";
+import { Excalidraw } from "../../index";
+import { KEYS } from "../../keys";
+import { Keyboard } from "../../tests/helpers/ui";
+import {
+ render,
+ waitFor,
+ getByTestId,
+ fireEvent,
+} from "../../tests/test-utils";
+
+describe("Test <DropdownMenu/>", () => {
+ it("should", async () => {
+ const { container } = await render(<Excalidraw />);
+
+ expect(window.h.state.openMenu).toBe(null);
+
+ fireEvent.click(getByTestId(container, "main-menu-trigger"));
+ expect(window.h.state.openMenu).toBe("canvas");
+
+ await waitFor(() => {
+ Keyboard.keyDown(KEYS.ESCAPE);
+ expect(window.h.state.openMenu).toBe(null);
+ });
+ });
+});
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenu.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenu.tsx
new file mode 100644
index 0000000..8f4ce43
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenu.tsx
@@ -0,0 +1,43 @@
+import React from "react";
+import DropdownMenuTrigger from "./DropdownMenuTrigger";
+import DropdownMenuItem from "./DropdownMenuItem";
+import MenuSeparator from "./DropdownMenuSeparator";
+import DropdownMenuGroup from "./DropdownMenuGroup";
+import DropdownMenuContent from "./DropdownMenuContent";
+import DropdownMenuItemLink from "./DropdownMenuItemLink";
+import DropdownMenuItemCustom from "./DropdownMenuItemCustom";
+import {
+ getMenuContentComponent,
+ getMenuTriggerComponent,
+} from "./dropdownMenuUtils";
+
+import "./DropdownMenu.scss";
+
+const DropdownMenu = ({
+ children,
+ open,
+}: {
+ children?: React.ReactNode;
+ open: boolean;
+}) => {
+ const MenuTriggerComp = getMenuTriggerComponent(children);
+ const MenuContentComp = getMenuContentComponent(children);
+ return (
+ <>
+ {MenuTriggerComp}
+ {open && MenuContentComp}
+ </>
+ );
+};
+
+DropdownMenu.Trigger = DropdownMenuTrigger;
+DropdownMenu.Content = DropdownMenuContent;
+DropdownMenu.Item = DropdownMenuItem;
+DropdownMenu.ItemLink = DropdownMenuItemLink;
+DropdownMenu.ItemCustom = DropdownMenuItemCustom;
+DropdownMenu.Group = DropdownMenuGroup;
+DropdownMenu.Separator = MenuSeparator;
+
+export default DropdownMenu;
+
+DropdownMenu.displayName = "DropdownMenu";
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx
new file mode 100644
index 0000000..a203124
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx
@@ -0,0 +1,88 @@
+import { Island } from "../Island";
+import { useDevice } from "../App";
+import clsx from "clsx";
+import Stack from "../Stack";
+import React, { useEffect, useRef } from "react";
+import { DropdownMenuContentPropsContext } from "./common";
+import { useOutsideClick } from "../../hooks/useOutsideClick";
+import { KEYS } from "../../keys";
+import { EVENT } from "../../constants";
+import { useStable } from "../../hooks/useStable";
+
+const MenuContent = ({
+ children,
+ onClickOutside,
+ className = "",
+ onSelect,
+ style,
+}: {
+ children?: React.ReactNode;
+ onClickOutside?: () => void;
+ className?: string;
+ /**
+ * Called when any menu item is selected (clicked on).
+ */
+ onSelect?: (event: Event) => void;
+ style?: React.CSSProperties;
+}) => {
+ const device = useDevice();
+ const menuRef = useRef<HTMLDivElement>(null);
+
+ const callbacksRef = useStable({ onClickOutside });
+
+ useOutsideClick(menuRef, () => {
+ callbacksRef.onClickOutside?.();
+ });
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === KEYS.ESCAPE) {
+ event.stopImmediatePropagation();
+ callbacksRef.onClickOutside?.();
+ }
+ };
+
+ const option = {
+ // so that we can stop propagation of the event before it reaches
+ // event handlers that were bound before this one
+ capture: true,
+ };
+
+ document.addEventListener(EVENT.KEYDOWN, onKeyDown, option);
+ return () => {
+ document.removeEventListener(EVENT.KEYDOWN, onKeyDown, option);
+ };
+ }, [callbacksRef]);
+
+ const classNames = clsx(`dropdown-menu ${className}`, {
+ "dropdown-menu--mobile": device.editor.isMobile,
+ }).trim();
+
+ return (
+ <DropdownMenuContentPropsContext.Provider value={{ onSelect }}>
+ <div
+ ref={menuRef}
+ className={classNames}
+ style={style}
+ data-testid="dropdown-menu"
+ >
+ {/* the zIndex ensures this menu has higher stacking order,
+ see https://github.com/excalidraw/excalidraw/pull/1445 */}
+ {device.editor.isMobile ? (
+ <Stack.Col className="dropdown-menu-container">{children}</Stack.Col>
+ ) : (
+ <Island
+ className="dropdown-menu-container"
+ padding={2}
+ style={{ zIndex: 2 }}
+ >
+ {children}
+ </Island>
+ )}
+ </div>
+ </DropdownMenuContentPropsContext.Provider>
+ );
+};
+MenuContent.displayName = "DropdownMenuContent";
+
+export default MenuContent;
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuGroup.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuGroup.tsx
new file mode 100644
index 0000000..aa4b49a
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuGroup.tsx
@@ -0,0 +1,23 @@
+import React from "react";
+
+const MenuGroup = ({
+ children,
+ className = "",
+ style,
+ title,
+}: {
+ children: React.ReactNode;
+ className?: string;
+ style?: React.CSSProperties;
+ title?: string;
+}) => {
+ return (
+ <div className={`dropdown-menu-group ${className}`} style={style}>
+ {title && <p className="dropdown-menu-group-title">{title}</p>}
+ {children}
+ </div>
+ );
+};
+
+export default MenuGroup;
+MenuGroup.displayName = "DropdownMenuGroup";
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuItem.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuItem.tsx
new file mode 100644
index 0000000..1ff53f8
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuItem.tsx
@@ -0,0 +1,123 @@
+import type { JSX } from "react";
+import React, { useEffect, useRef } from "react";
+import {
+ getDropdownMenuItemClassName,
+ useHandleDropdownMenuItemClick,
+} from "./common";
+import MenuItemContent from "./DropdownMenuItemContent";
+import { useExcalidrawAppState } from "../App";
+import { THEME } from "../../constants";
+import type { ValueOf } from "../../utility-types";
+
+const DropdownMenuItem = ({
+ icon,
+ value,
+ order,
+ children,
+ shortcut,
+ className,
+ hovered,
+ selected,
+ textStyle,
+ onSelect,
+ onClick,
+ ...rest
+}: {
+ icon?: JSX.Element;
+ value?: string | number | undefined;
+ order?: number;
+ onSelect?: (event: Event) => void;
+ children: React.ReactNode;
+ shortcut?: string;
+ hovered?: boolean;
+ selected?: boolean;
+ textStyle?: React.CSSProperties;
+ className?: string;
+} & Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "onSelect">) => {
+ const handleClick = useHandleDropdownMenuItemClick(onClick, onSelect);
+ const ref = useRef<HTMLButtonElement>(null);
+
+ useEffect(() => {
+ if (hovered) {
+ if (order === 0) {
+ // scroll into the first item differently, so it's visible what is above (i.e. group title)
+ ref.current?.scrollIntoView({ block: "end" });
+ } else {
+ ref.current?.scrollIntoView({ block: "nearest" });
+ }
+ }
+ }, [hovered, order]);
+
+ return (
+ <button
+ {...rest}
+ ref={ref}
+ value={value}
+ onClick={handleClick}
+ className={getDropdownMenuItemClassName(className, selected, hovered)}
+ title={rest.title ?? rest["aria-label"]}
+ >
+ <MenuItemContent textStyle={textStyle} icon={icon} shortcut={shortcut}>
+ {children}
+ </MenuItemContent>
+ </button>
+ );
+};
+DropdownMenuItem.displayName = "DropdownMenuItem";
+
+export const DropDownMenuItemBadgeType = {
+ GREEN: "green",
+ RED: "red",
+ BLUE: "blue",
+} as const;
+
+export const DropDownMenuItemBadge = ({
+ type = DropDownMenuItemBadgeType.BLUE,
+ children,
+}: {
+ type?: ValueOf<typeof DropDownMenuItemBadgeType>;
+ children: React.ReactNode;
+}) => {
+ const { theme } = useExcalidrawAppState();
+ const style = {
+ display: "inline-flex",
+ marginLeft: "auto",
+ padding: "2px 4px",
+ borderRadius: 6,
+ fontSize: 9,
+ fontFamily: "Cascadia, monospace",
+ border: theme === THEME.LIGHT ? "1.5px solid white" : "none",
+ };
+
+ switch (type) {
+ case DropDownMenuItemBadgeType.GREEN:
+ Object.assign(style, {
+ backgroundColor: "var(--background-color-badge)",
+ color: "var(--color-badge)",
+ });
+ break;
+ case DropDownMenuItemBadgeType.RED:
+ Object.assign(style, {
+ backgroundColor: "pink",
+ color: "darkred",
+ });
+ break;
+ case DropDownMenuItemBadgeType.BLUE:
+ default:
+ Object.assign(style, {
+ background: "var(--color-promo)",
+ color: "var(--color-surface-lowest)",
+ });
+ }
+
+ return (
+ <div className="DropDownMenuItemBadge" style={style}>
+ {children}
+ </div>
+ );
+};
+DropDownMenuItemBadge.displayName = "DropdownMenuItemBadge";
+
+DropdownMenuItem.Badge = DropDownMenuItemBadge;
+
+export default DropdownMenuItem;
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuItemContent.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuItemContent.tsx
new file mode 100644
index 0000000..000b8c3
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuItemContent.tsx
@@ -0,0 +1,28 @@
+import type { JSX } from "react";
+import { useDevice } from "../App";
+
+const MenuItemContent = ({
+ textStyle,
+ icon,
+ shortcut,
+ children,
+}: {
+ icon?: JSX.Element;
+ shortcut?: string;
+ textStyle?: React.CSSProperties;
+ children: React.ReactNode;
+}) => {
+ const device = useDevice();
+ return (
+ <>
+ {icon && <div className="dropdown-menu-item__icon">{icon}</div>}
+ <div style={textStyle} className="dropdown-menu-item__text">
+ {children}
+ </div>
+ {shortcut && !device.editor.isMobile && (
+ <div className="dropdown-menu-item__shortcut">{shortcut}</div>
+ )}
+ </>
+ );
+};
+export default MenuItemContent;
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuItemContentRadio.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuItemContentRadio.tsx
new file mode 100644
index 0000000..14bfe1a
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuItemContentRadio.tsx
@@ -0,0 +1,51 @@
+import { useDevice } from "../App";
+import { RadioGroup } from "../RadioGroup";
+
+type Props<T> = {
+ value: T;
+ shortcut?: string;
+ choices: {
+ value: T;
+ label: React.ReactNode;
+ ariaLabel?: string;
+ }[];
+ onChange: (value: T) => void;
+ children: React.ReactNode;
+ name: string;
+};
+
+const DropdownMenuItemContentRadio = <T,>({
+ value,
+ shortcut,
+ onChange,
+ choices,
+ children,
+ name,
+}: Props<T>) => {
+ const device = useDevice();
+
+ return (
+ <>
+ <div className="dropdown-menu-item-base dropdown-menu-item-bare">
+ <label className="dropdown-menu-item__text" htmlFor={name}>
+ {children}
+ </label>
+ <RadioGroup
+ name={name}
+ value={value}
+ onChange={onChange}
+ choices={choices}
+ />
+ </div>
+ {shortcut && !device.editor.isMobile && (
+ <div className="dropdown-menu-item__shortcut dropdown-menu-item__shortcut--orphaned">
+ {shortcut}
+ </div>
+ )}
+ </>
+ );
+};
+
+DropdownMenuItemContentRadio.displayName = "DropdownMenuItemContentRadio";
+
+export default DropdownMenuItemContentRadio;
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuItemCustom.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuItemCustom.tsx
new file mode 100644
index 0000000..795c5c7
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuItemCustom.tsx
@@ -0,0 +1,25 @@
+import React from "react";
+
+const DropdownMenuItemCustom = ({
+ children,
+ className = "",
+ selected,
+ ...rest
+}: {
+ children: React.ReactNode;
+ className?: string;
+ selected?: boolean;
+} & React.HTMLAttributes<HTMLDivElement>) => {
+ return (
+ <div
+ {...rest}
+ className={`dropdown-menu-item-base dropdown-menu-item-custom ${className} ${
+ selected ? `dropdown-menu-item--selected` : ``
+ }`.trim()}
+ >
+ {children}
+ </div>
+ );
+};
+
+export default DropdownMenuItemCustom;
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuItemLink.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuItemLink.tsx
new file mode 100644
index 0000000..2dbee75
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuItemLink.tsx
@@ -0,0 +1,49 @@
+import MenuItemContent from "./DropdownMenuItemContent";
+import type { JSX } from "react";
+import React from "react";
+import {
+ getDropdownMenuItemClassName,
+ useHandleDropdownMenuItemClick,
+} from "./common";
+
+const DropdownMenuItemLink = ({
+ icon,
+ shortcut,
+ href,
+ children,
+ onSelect,
+ className = "",
+ selected,
+ rel = "noreferrer",
+ ...rest
+}: {
+ href: string;
+ icon?: JSX.Element;
+ children: React.ReactNode;
+ shortcut?: string;
+ className?: string;
+ selected?: boolean;
+ onSelect?: (event: Event) => void;
+ rel?: string;
+} & React.AnchorHTMLAttributes<HTMLAnchorElement>) => {
+ const handleClick = useHandleDropdownMenuItemClick(rest.onClick, onSelect);
+
+ return (
+ <a
+ {...rest}
+ href={href}
+ target="_blank"
+ rel="noreferrer"
+ className={getDropdownMenuItemClassName(className, selected)}
+ title={rest.title ?? rest["aria-label"]}
+ onClick={handleClick}
+ >
+ <MenuItemContent icon={icon} shortcut={shortcut}>
+ {children}
+ </MenuItemContent>
+ </a>
+ );
+};
+
+export default DropdownMenuItemLink;
+DropdownMenuItemLink.displayName = "DropdownMenuItemLink";
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuSeparator.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuSeparator.tsx
new file mode 100644
index 0000000..ee41960
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuSeparator.tsx
@@ -0,0 +1,14 @@
+import React from "react";
+
+const MenuSeparator = () => (
+ <div
+ style={{
+ height: "1px",
+ backgroundColor: "var(--default-border-color)",
+ margin: ".5rem 0",
+ }}
+ />
+);
+
+export default MenuSeparator;
+MenuSeparator.displayName = "DropdownMenuSeparator";
diff --git a/packages/excalidraw/components/dropdownMenu/DropdownMenuTrigger.tsx b/packages/excalidraw/components/dropdownMenu/DropdownMenuTrigger.tsx
new file mode 100644
index 0000000..e7369ba
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/DropdownMenuTrigger.tsx
@@ -0,0 +1,40 @@
+import clsx from "clsx";
+import { useDevice } from "../App";
+
+const MenuTrigger = ({
+ className = "",
+ children,
+ onToggle,
+ title,
+ ...rest
+}: {
+ className?: string;
+ children: React.ReactNode;
+ onToggle: () => void;
+ title?: string;
+} & Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "onSelect">) => {
+ const device = useDevice();
+ const classNames = clsx(
+ `dropdown-menu-button ${className}`,
+ "zen-mode-transition",
+ {
+ "dropdown-menu-button--mobile": device.editor.isMobile,
+ },
+ ).trim();
+ return (
+ <button
+ data-prevent-outside-click
+ className={classNames}
+ onClick={onToggle}
+ type="button"
+ data-testid="dropdown-menu-button"
+ title={title}
+ {...rest}
+ >
+ {children}
+ </button>
+ );
+};
+
+export default MenuTrigger;
+MenuTrigger.displayName = "DropdownMenuTrigger";
diff --git a/packages/excalidraw/components/dropdownMenu/common.ts b/packages/excalidraw/components/dropdownMenu/common.ts
new file mode 100644
index 0000000..a2a46fc
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/common.ts
@@ -0,0 +1,38 @@
+import React, { useContext } from "react";
+import { EVENT } from "../../constants";
+import { composeEventHandlers } from "../../utils";
+
+export const DropdownMenuContentPropsContext = React.createContext<{
+ onSelect?: (event: Event) => void;
+}>({});
+
+export const getDropdownMenuItemClassName = (
+ className = "",
+ selected = false,
+ hovered = false,
+) => {
+ return `dropdown-menu-item dropdown-menu-item-base ${className}
+ ${selected ? "dropdown-menu-item--selected" : ""} ${
+ hovered ? "dropdown-menu-item--hovered" : ""
+ }`.trim();
+};
+
+export const useHandleDropdownMenuItemClick = (
+ origOnClick:
+ | React.MouseEventHandler<HTMLAnchorElement | HTMLButtonElement>
+ | undefined,
+ onSelect: ((event: Event) => void) | undefined,
+) => {
+ const DropdownMenuContentProps = useContext(DropdownMenuContentPropsContext);
+
+ return composeEventHandlers(origOnClick, (event) => {
+ const itemSelectEvent = new CustomEvent(EVENT.MENU_ITEM_SELECT, {
+ bubbles: true,
+ cancelable: true,
+ });
+ onSelect?.(itemSelectEvent);
+ if (!itemSelectEvent.defaultPrevented) {
+ DropdownMenuContentProps.onSelect?.(itemSelectEvent);
+ }
+ });
+};
diff --git a/packages/excalidraw/components/dropdownMenu/dropdownMenuUtils.ts b/packages/excalidraw/components/dropdownMenu/dropdownMenuUtils.ts
new file mode 100644
index 0000000..10d91fb
--- /dev/null
+++ b/packages/excalidraw/components/dropdownMenu/dropdownMenuUtils.ts
@@ -0,0 +1,35 @@
+import React from "react";
+
+export const getMenuTriggerComponent = (children: React.ReactNode) => {
+ const comp = React.Children.toArray(children).find(
+ (child) =>
+ React.isValidElement(child) &&
+ typeof child.type !== "string" &&
+ //@ts-ignore
+ child?.type.displayName &&
+ //@ts-ignore
+ child.type.displayName === "DropdownMenuTrigger",
+ );
+ if (!comp) {
+ return null;
+ }
+ //@ts-ignore
+ return comp;
+};
+
+export const getMenuContentComponent = (children: React.ReactNode) => {
+ const comp = React.Children.toArray(children).find(
+ (child) =>
+ React.isValidElement(child) &&
+ typeof child.type !== "string" &&
+ //@ts-ignore
+ child?.type.displayName &&
+ //@ts-ignore
+ child.type.displayName === "DropdownMenuContent",
+ );
+ if (!comp) {
+ return null;
+ }
+ //@ts-ignore
+ return comp;
+};
diff --git a/packages/excalidraw/components/footer/Footer.tsx b/packages/excalidraw/components/footer/Footer.tsx
new file mode 100644
index 0000000..ccbe9ea
--- /dev/null
+++ b/packages/excalidraw/components/footer/Footer.tsx
@@ -0,0 +1,95 @@
+import clsx from "clsx";
+import { actionShortcuts } from "../../actions";
+import type { ActionManager } from "../../actions/manager";
+import {
+ ExitZenModeAction,
+ FinalizeAction,
+ UndoRedoActions,
+ ZoomActions,
+} from "../Actions";
+import { useDevice } from "../App";
+import { useTunnels } from "../../context/tunnels";
+import { HelpButton } from "../HelpButton";
+import { Section } from "../Section";
+import Stack from "../Stack";
+import type { UIAppState } from "../../types";
+
+const Footer = ({
+ appState,
+ actionManager,
+ showExitZenModeBtn,
+ renderWelcomeScreen,
+}: {
+ appState: UIAppState;
+ actionManager: ActionManager;
+ showExitZenModeBtn: boolean;
+ renderWelcomeScreen: boolean;
+}) => {
+ const { FooterCenterTunnel, WelcomeScreenHelpHintTunnel } = useTunnels();
+
+ const device = useDevice();
+ const showFinalize =
+ !appState.viewModeEnabled && appState.multiElement && device.isTouchScreen;
+
+ return (
+ <footer
+ role="contentinfo"
+ className="layer-ui__wrapper__footer App-menu App-menu_bottom"
+ >
+ <div
+ className={clsx("layer-ui__wrapper__footer-left zen-mode-transition", {
+ "layer-ui__wrapper__footer-left--transition-left":
+ appState.zenModeEnabled,
+ })}
+ >
+ <Stack.Col gap={2}>
+ <Section heading="canvasActions">
+ <ZoomActions
+ renderAction={actionManager.renderAction}
+ zoom={appState.zoom}
+ />
+
+ {!appState.viewModeEnabled && (
+ <UndoRedoActions
+ renderAction={actionManager.renderAction}
+ className={clsx("zen-mode-transition", {
+ "layer-ui__wrapper__footer-left--transition-bottom":
+ appState.zenModeEnabled,
+ })}
+ />
+ )}
+ {showFinalize && (
+ <FinalizeAction
+ renderAction={actionManager.renderAction}
+ className={clsx("zen-mode-transition", {
+ "layer-ui__wrapper__footer-left--transition-left":
+ appState.zenModeEnabled,
+ })}
+ />
+ )}
+ </Section>
+ </Stack.Col>
+ </div>
+ <FooterCenterTunnel.Out />
+ <div
+ className={clsx("layer-ui__wrapper__footer-right zen-mode-transition", {
+ "transition-right": appState.zenModeEnabled,
+ })}
+ >
+ <div style={{ position: "relative" }}>
+ {renderWelcomeScreen && <WelcomeScreenHelpHintTunnel.Out />}
+ <HelpButton
+ onClick={() => actionManager.executeAction(actionShortcuts)}
+ />
+ </div>
+ </div>
+ <ExitZenModeAction
+ actionManager={actionManager}
+ showExitZenModeBtn={showExitZenModeBtn}
+ />
+ </footer>
+ );
+};
+
+export default Footer;
+Footer.displayName = "Footer";
diff --git a/packages/excalidraw/components/footer/FooterCenter.scss b/packages/excalidraw/components/footer/FooterCenter.scss
new file mode 100644
index 0000000..ce65659
--- /dev/null
+++ b/packages/excalidraw/components/footer/FooterCenter.scss
@@ -0,0 +1,11 @@
+.footer-center {
+ pointer-events: none;
+ & > * {
+ pointer-events: var(--ui-pointerEvents);
+ }
+
+ display: flex;
+ width: 100%;
+ justify-content: flex-start;
+ margin-inline-end: 0.6rem;
+}
diff --git a/packages/excalidraw/components/footer/FooterCenter.tsx b/packages/excalidraw/components/footer/FooterCenter.tsx
new file mode 100644
index 0000000..55a0fb9
--- /dev/null
+++ b/packages/excalidraw/components/footer/FooterCenter.tsx
@@ -0,0 +1,24 @@
+import clsx from "clsx";
+import { useTunnels } from "../../context/tunnels";
+import "./FooterCenter.scss";
+import { useUIAppState } from "../../context/ui-appState";
+
+const FooterCenter = ({ children }: { children?: React.ReactNode }) => {
+ const { FooterCenterTunnel } = useTunnels();
+ const appState = useUIAppState();
+ return (
+ <FooterCenterTunnel.In>
+ <div
+ className={clsx("footer-center zen-mode-transition", {
+ "layer-ui__wrapper__footer-left--transition-bottom":
+ appState.zenModeEnabled,
+ })}
+ >
+ {children}
+ </div>
+ </FooterCenterTunnel.In>
+ );
+};
+
+export default FooterCenter;
+FooterCenter.displayName = "FooterCenter";
diff --git a/packages/excalidraw/components/hoc/withInternalFallback.test.tsx b/packages/excalidraw/components/hoc/withInternalFallback.test.tsx
new file mode 100644
index 0000000..5543133
--- /dev/null
+++ b/packages/excalidraw/components/hoc/withInternalFallback.test.tsx
@@ -0,0 +1,101 @@
+import React from "react";
+import { render, queryAllByTestId } from "../../tests/test-utils";
+import { Excalidraw, MainMenu } from "../../index";
+
+describe("Test internal component fallback rendering", () => {
+ it("should render only one menu per excalidraw instance (custom menu first scenario)", async () => {
+ const { container } = await render(
+ <div>
+ <Excalidraw>
+ <MainMenu>test</MainMenu>
+ </Excalidraw>
+ <Excalidraw />
+ </div>,
+ );
+
+ expect(queryAllByTestId(container, "main-menu-trigger")?.length).toBe(2);
+
+ const excalContainers = container.querySelectorAll<HTMLDivElement>(
+ ".excalidraw-container",
+ );
+
+ expect(
+ queryAllByTestId(excalContainers[0], "main-menu-trigger")?.length,
+ ).toBe(1);
+ expect(
+ queryAllByTestId(excalContainers[1], "main-menu-trigger")?.length,
+ ).toBe(1);
+ });
+
+ it("should render only one menu per excalidraw instance (default menu first scenario)", async () => {
+ const { container } = await render(
+ <div>
+ <Excalidraw />
+ <Excalidraw>
+ <MainMenu>test</MainMenu>
+ </Excalidraw>
+ </div>,
+ );
+
+ expect(queryAllByTestId(container, "main-menu-trigger")?.length).toBe(2);
+
+ const excalContainers = container.querySelectorAll<HTMLDivElement>(
+ ".excalidraw-container",
+ );
+
+ expect(
+ queryAllByTestId(excalContainers[0], "main-menu-trigger")?.length,
+ ).toBe(1);
+ expect(
+ queryAllByTestId(excalContainers[1], "main-menu-trigger")?.length,
+ ).toBe(1);
+ });
+
+ it("should render only one menu per excalidraw instance (two custom menus scenario)", async () => {
+ const { container } = await render(
+ <div>
+ <Excalidraw>
+ <MainMenu>test</MainMenu>
+ </Excalidraw>
+ <Excalidraw>
+ <MainMenu>test</MainMenu>
+ </Excalidraw>
+ </div>,
+ );
+
+ expect(queryAllByTestId(container, "main-menu-trigger")?.length).toBe(2);
+
+ const excalContainers = container.querySelectorAll<HTMLDivElement>(
+ ".excalidraw-container",
+ );
+
+ expect(
+ queryAllByTestId(excalContainers[0], "main-menu-trigger")?.length,
+ ).toBe(1);
+ expect(
+ queryAllByTestId(excalContainers[1], "main-menu-trigger")?.length,
+ ).toBe(1);
+ });
+
+ it("should render only one menu per excalidraw instance (two default menus scenario)", async () => {
+ const { container } = await render(
+ <div>
+ <Excalidraw />
+ <Excalidraw />
+ </div>,
+ );
+
+ expect(queryAllByTestId(container, "main-menu-trigger")?.length).toBe(2);
+
+ const excalContainers = container.querySelectorAll<HTMLDivElement>(
+ ".excalidraw-container",
+ );
+
+ expect(
+ queryAllByTestId(excalContainers[0], "main-menu-trigger")?.length,
+ ).toBe(1);
+ expect(
+ queryAllByTestId(excalContainers[1], "main-menu-trigger")?.length,
+ ).toBe(1);
+ });
+});
diff --git a/packages/excalidraw/components/hoc/withInternalFallback.tsx b/packages/excalidraw/components/hoc/withInternalFallback.tsx
new file mode 100644
index 0000000..5906b30
--- /dev/null
+++ b/packages/excalidraw/components/hoc/withInternalFallback.tsx
@@ -0,0 +1,75 @@
+import React, { useLayoutEffect, useRef } from "react";
+import { useTunnels } from "../../context/tunnels";
+import { atom } from "../../editor-jotai";
+
+export const withInternalFallback = <P,>(
+ componentName: string,
+ Component: React.FC<P>,
+) => {
+ const renderAtom = atom(0);
+
+ const WrapperComponent: React.FC<
+ P & {
+ __fallback?: boolean;
+ }
+ > = (props) => {
+ const {
+ tunnelsJotai: { useAtom },
+ } = useTunnels();
+ // for rerenders
+ const [, setCounter] = useAtom(renderAtom);
+ // for initial & subsequent renders. Tracked as component state
+ // due to excalidraw multi-instance scanerios.
+ const metaRef = useRef({
+ // flag set on initial render to tell the fallback component to skip the
+ // render until mount counter are initialized. This is because the counter
+ // is initialized in an effect, and thus we could end rendering both
+ // components at the same time until counter is initialized.
+ preferHost: false,
+ counter: 0,
+ });
+
+ useLayoutEffect(() => {
+ const meta = metaRef.current;
+ setCounter((c) => {
+ const next = c + 1;
+ meta.counter = next;
+
+ return next;
+ });
+ return () => {
+ setCounter((c) => {
+ const next = c - 1;
+ meta.counter = next;
+ if (!next) {
+ meta.preferHost = false;
+ }
+ return next;
+ });
+ };
+ }, [setCounter]);
+
+ if (!props.__fallback) {
+ metaRef.current.preferHost = true;
+ }
+
+ // ensure we don't render fallback and host components at the same time
+ if (
+ // either before the counters are initialized
+ (!metaRef.current.counter &&
+ props.__fallback &&
+ metaRef.current.preferHost) ||
+ // or after the counters are initialized, and both are rendered
+ // (this is the default when host renders as well)
+ (metaRef.current.counter > 1 && props.__fallback)
+ ) {
+ return null;
+ }
+
+ return <Component {...props} />;
+ };
+
+ WrapperComponent.displayName = componentName;
+
+ return WrapperComponent;
+};
diff --git a/packages/excalidraw/components/hyperlink/Hyperlink.scss b/packages/excalidraw/components/hyperlink/Hyperlink.scss
new file mode 100644
index 0000000..6a5db32
--- /dev/null
+++ b/packages/excalidraw/components/hyperlink/Hyperlink.scss
@@ -0,0 +1,70 @@
+@import "../../css/variables.module.scss";
+
+.excalidraw-hyperlinkContainer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ position: absolute;
+ box-shadow: 0px 2px 4px 0 rgb(0 0 0 / 30%);
+ z-index: var(--zIndex-hyperlinkContainer);
+ background: var(--island-bg-color);
+ border-radius: var(--border-radius-md);
+ box-sizing: border-box;
+ // to account for LS due to rendering icons after new link created
+ min-height: 42px;
+
+ &-input,
+ button {
+ z-index: 100;
+ }
+
+ &-input,
+ &-link {
+ height: 24px;
+ padding: 0 8px;
+ line-height: 24px;
+ font-size: 0.9rem;
+ font-weight: 500;
+ font-family: var(--ui-font);
+ }
+
+ &-input {
+ width: 18rem;
+ border: none;
+ background-color: transparent;
+ color: var(--text-primary-color);
+
+ outline: none;
+ border: none;
+ box-shadow: none !important;
+ }
+
+ &-link {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 15rem;
+ }
+
+ button {
+ color: $oc-blue-6;
+ background-color: transparent !important;
+ font-weight: 500;
+ &.excalidraw-hyperlinkContainer--remove {
+ color: $oc-red-9;
+ }
+ }
+
+ &--remove .ToolIcon__icon svg {
+ color: $oc-red-6;
+ }
+
+ .ToolIcon__icon {
+ width: 2rem;
+ height: 2rem;
+ }
+
+ &__buttons {
+ flex: 0 0 auto;
+ }
+}
diff --git a/packages/excalidraw/components/hyperlink/Hyperlink.tsx b/packages/excalidraw/components/hyperlink/Hyperlink.tsx
new file mode 100644
index 0000000..4d3dce6
--- /dev/null
+++ b/packages/excalidraw/components/hyperlink/Hyperlink.tsx
@@ -0,0 +1,480 @@
+import type { AppState, ExcalidrawProps, UIAppState } from "../../types";
+import {
+ sceneCoordsToViewportCoords,
+ viewportCoordsToSceneCoords,
+ wrapEvent,
+} from "../../utils";
+import { getEmbedLink, embeddableURLValidator } from "../../element/embeddable";
+import { mutateElement } from "../../element/mutateElement";
+import type {
+ ElementsMap,
+ ExcalidrawEmbeddableElement,
+ NonDeletedExcalidrawElement,
+} from "../../element/types";
+
+import { ToolButton } from "../ToolButton";
+import { FreedrawIcon, TrashIcon, elementLinkIcon } from "../icons";
+import { t } from "../../i18n";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+import clsx from "clsx";
+import { KEYS } from "../../keys";
+import { EVENT, HYPERLINK_TOOLTIP_DELAY } from "../../constants";
+import { getElementAbsoluteCoords } from "../../element/bounds";
+import { getTooltipDiv, updateTooltipPosition } from "../../components/Tooltip";
+import { getSelectedElements } from "../../scene";
+import { hitElementBoundingBox } from "../../element/collision";
+import { isLocalLink, normalizeLink } from "../../data/url";
+import { trackEvent } from "../../analytics";
+import { useAppProps, useDevice, useExcalidrawAppState } from "../App";
+import { isEmbeddableElement } from "../../element/typeChecks";
+import { getLinkHandleFromCoords } from "./helpers";
+import { pointFrom, type GlobalPoint } from "@excalidraw/math";
+import { isElementLink } from "../../element/elementLink";
+
+import "./Hyperlink.scss";
+
+const POPUP_WIDTH = 380;
+const POPUP_HEIGHT = 42;
+const POPUP_PADDING = 5;
+const SPACE_BOTTOM = 85;
+const AUTO_HIDE_TIMEOUT = 500;
+
+let IS_HYPERLINK_TOOLTIP_VISIBLE = false;
+
+const embeddableLinkCache = new Map<
+ ExcalidrawEmbeddableElement["id"],
+ string
+>();
+
+export const Hyperlink = ({
+ element,
+ elementsMap,
+ setAppState,
+ onLinkOpen,
+ setToast,
+ updateEmbedValidationStatus,
+}: {
+ element: NonDeletedExcalidrawElement;
+ elementsMap: ElementsMap;
+ setAppState: React.Component<any, AppState>["setState"];
+ onLinkOpen: ExcalidrawProps["onLinkOpen"];
+ setToast: (
+ toast: { message: string; closable?: boolean; duration?: number } | null,
+ ) => void;
+ updateEmbedValidationStatus: (
+ element: ExcalidrawEmbeddableElement,
+ status: boolean,
+ ) => void;
+}) => {
+ const appState = useExcalidrawAppState();
+ const appProps = useAppProps();
+ const device = useDevice();
+
+ const linkVal = element.link || "";
+
+ const [inputVal, setInputVal] = useState(linkVal);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const isEditing = appState.showHyperlinkPopup === "editor";
+
+ const handleSubmit = useCallback(() => {
+ if (!inputRef.current) {
+ return;
+ }
+
+ const link = normalizeLink(inputRef.current.value) || null;
+
+ if (!element.link && link) {
+ trackEvent("hyperlink", "create");
+ }
+
+ if (isEmbeddableElement(element)) {
+ if (appState.activeEmbeddable?.element === element) {
+ setAppState({ activeEmbeddable: null });
+ }
+ if (!link) {
+ mutateElement(element, {
+ link: null,
+ });
+ updateEmbedValidationStatus(element, false);
+ return;
+ }
+
+ if (!embeddableURLValidator(link, appProps.validateEmbeddable)) {
+ if (link) {
+ setToast({ message: t("toast.unableToEmbed"), closable: true });
+ }
+ element.link && embeddableLinkCache.set(element.id, element.link);
+ mutateElement(element, {
+ link,
+ });
+ updateEmbedValidationStatus(element, false);
+ } else {
+ const { width, height } = element;
+ const embedLink = getEmbedLink(link);
+ if (embedLink?.error instanceof URIError) {
+ setToast({
+ message: t("toast.unrecognizedLinkFormat"),
+ closable: true,
+ });
+ }
+ const ar = embedLink
+ ? embedLink.intrinsicSize.w / embedLink.intrinsicSize.h
+ : 1;
+ const hasLinkChanged =
+ embeddableLinkCache.get(element.id) !== element.link;
+ mutateElement(element, {
+ ...(hasLinkChanged
+ ? {
+ width:
+ embedLink?.type === "video"
+ ? width > height
+ ? width
+ : height * ar
+ : width,
+ height:
+ embedLink?.type === "video"
+ ? width > height
+ ? width / ar
+ : height
+ : height,
+ }
+ : {}),
+ link,
+ });
+ updateEmbedValidationStatus(element, true);
+ if (embeddableLinkCache.has(element.id)) {
+ embeddableLinkCache.delete(element.id);
+ }
+ }
+ } else {
+ mutateElement(element, { link });
+ }
+ }, [
+ element,
+ setToast,
+ appProps.validateEmbeddable,
+ appState.activeEmbeddable,
+ setAppState,
+ updateEmbedValidationStatus,
+ ]);
+
+ useLayoutEffect(() => {
+ return () => {
+ handleSubmit();
+ };
+ }, [handleSubmit]);
+
+ useEffect(() => {
+ if (
+ isEditing &&
+ inputRef?.current &&
+ !(device.viewport.isMobile || device.isTouchScreen)
+ ) {
+ inputRef.current.select();
+ }
+ }, [isEditing, device.viewport.isMobile, device.isTouchScreen]);
+
+ useEffect(() => {
+ let timeoutId: number | null = null;
+
+ const handlePointerMove = (event: PointerEvent) => {
+ if (isEditing) {
+ return;
+ }
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+ const shouldHide = shouldHideLinkPopup(
+ element,
+ elementsMap,
+ appState,
+ pointFrom(event.clientX, event.clientY),
+ ) as boolean;
+ if (shouldHide) {
+ timeoutId = window.setTimeout(() => {
+ setAppState({ showHyperlinkPopup: false });
+ }, AUTO_HIDE_TIMEOUT);
+ }
+ };
+ window.addEventListener(EVENT.POINTER_MOVE, handlePointerMove, false);
+ return () => {
+ window.removeEventListener(EVENT.POINTER_MOVE, handlePointerMove, false);
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+ };
+ }, [appState, element, isEditing, setAppState, elementsMap]);
+
+ const handleRemove = useCallback(() => {
+ trackEvent("hyperlink", "delete");
+ mutateElement(element, { link: null });
+ setAppState({ showHyperlinkPopup: false });
+ }, [setAppState, element]);
+
+ const onEdit = () => {
+ trackEvent("hyperlink", "edit", "popup-ui");
+ setAppState({ showHyperlinkPopup: "editor" });
+ };
+ const { x, y } = getCoordsForPopover(element, appState, elementsMap);
+ if (
+ appState.contextMenu ||
+ appState.selectedElementsAreBeingDragged ||
+ appState.resizingElement ||
+ appState.isRotating ||
+ appState.openMenu ||
+ appState.viewModeEnabled
+ ) {
+ return null;
+ }
+
+ return (
+ <div
+ className="excalidraw-hyperlinkContainer"
+ style={{
+ top: `${y}px`,
+ left: `${x}px`,
+ width: POPUP_WIDTH,
+ padding: POPUP_PADDING,
+ }}
+ >
+ {isEditing ? (
+ <input
+ className={clsx("excalidraw-hyperlinkContainer-input")}
+ placeholder={t("labels.link.hint")}
+ ref={inputRef}
+ value={inputVal}
+ onChange={(event) => setInputVal(event.target.value)}
+ autoFocus
+ onKeyDown={(event) => {
+ event.stopPropagation();
+ // prevent cmd/ctrl+k shortcut when editing link
+ if (event[KEYS.CTRL_OR_CMD] && event.key === KEYS.K) {
+ event.preventDefault();
+ }
+ if (event.key === KEYS.ENTER || event.key === KEYS.ESCAPE) {
+ handleSubmit();
+ setAppState({ showHyperlinkPopup: "info" });
+ }
+ }}
+ />
+ ) : element.link ? (
+ <a
+ href={normalizeLink(element.link || "")}
+ className="excalidraw-hyperlinkContainer-link"
+ target={isLocalLink(element.link) ? "_self" : "_blank"}
+ onClick={(event) => {
+ if (element.link && onLinkOpen) {
+ const customEvent = wrapEvent(
+ EVENT.EXCALIDRAW_LINK,
+ event.nativeEvent,
+ );
+ onLinkOpen(
+ {
+ ...element,
+ link: normalizeLink(element.link),
+ },
+ customEvent,
+ );
+ if (customEvent.defaultPrevented) {
+ event.preventDefault();
+ }
+ }
+ }}
+ rel="noopener noreferrer"
+ >
+ {element.link}
+ </a>
+ ) : (
+ <div className="excalidraw-hyperlinkContainer-link">
+ {t("labels.link.empty")}
+ </div>
+ )}
+ <div className="excalidraw-hyperlinkContainer__buttons">
+ {!isEditing && (
+ <ToolButton
+ type="button"
+ title={t("buttons.edit")}
+ aria-label={t("buttons.edit")}
+ label={t("buttons.edit")}
+ onClick={onEdit}
+ className="excalidraw-hyperlinkContainer--edit"
+ icon={FreedrawIcon}
+ />
+ )}
+ <ToolButton
+ type="button"
+ title={t("labels.linkToElement")}
+ aria-label={t("labels.linkToElement")}
+ label={t("labels.linkToElement")}
+ onClick={() => {
+ setAppState({
+ openDialog: {
+ name: "elementLinkSelector",
+ sourceElementId: element.id,
+ },
+ });
+ }}
+ icon={elementLinkIcon}
+ />
+ {linkVal && !isEmbeddableElement(element) && (
+ <ToolButton
+ type="button"
+ title={t("buttons.remove")}
+ aria-label={t("buttons.remove")}
+ label={t("buttons.remove")}
+ onClick={handleRemove}
+ className="excalidraw-hyperlinkContainer--remove"
+ icon={TrashIcon}
+ />
+ )}
+ </div>
+ </div>
+ );
+};
+
+const getCoordsForPopover = (
+ element: NonDeletedExcalidrawElement,
+ appState: AppState,
+ elementsMap: ElementsMap,
+) => {
+ const [x1, y1] = getElementAbsoluteCoords(element, elementsMap);
+ const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
+ { sceneX: x1 + element.width / 2, sceneY: y1 },
+ appState,
+ );
+ const x = viewportX - appState.offsetLeft - POPUP_WIDTH / 2;
+ const y = viewportY - appState.offsetTop - SPACE_BOTTOM;
+ return { x, y };
+};
+
+export const getContextMenuLabel = (
+ elements: readonly NonDeletedExcalidrawElement[],
+ appState: UIAppState,
+) => {
+ const selectedElements = getSelectedElements(elements, appState);
+ const label = isEmbeddableElement(selectedElements[0])
+ ? "labels.link.editEmbed"
+ : selectedElements[0]?.link
+ ? "labels.link.edit"
+ : "labels.link.create";
+ return label;
+};
+
+let HYPERLINK_TOOLTIP_TIMEOUT_ID: number | null = null;
+export const showHyperlinkTooltip = (
+ element: NonDeletedExcalidrawElement,
+ appState: AppState,
+ elementsMap: ElementsMap,
+) => {
+ if (HYPERLINK_TOOLTIP_TIMEOUT_ID) {
+ clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
+ }
+ HYPERLINK_TOOLTIP_TIMEOUT_ID = window.setTimeout(
+ () => renderTooltip(element, appState, elementsMap),
+ HYPERLINK_TOOLTIP_DELAY,
+ );
+};
+
+const renderTooltip = (
+ element: NonDeletedExcalidrawElement,
+ appState: AppState,
+ elementsMap: ElementsMap,
+) => {
+ if (!element.link) {
+ return;
+ }
+
+ const tooltipDiv = getTooltipDiv();
+
+ tooltipDiv.classList.add("excalidraw-tooltip--visible");
+ tooltipDiv.style.maxWidth = "20rem";
+ tooltipDiv.textContent = isElementLink(element.link)
+ ? t("labels.link.goToElement")
+ : element.link;
+
+ const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
+
+ const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
+ [x1, y1, x2, y2],
+ element.angle,
+ appState,
+ );
+
+ const linkViewportCoords = sceneCoordsToViewportCoords(
+ { sceneX: linkX, sceneY: linkY },
+ appState,
+ );
+
+ updateTooltipPosition(
+ tooltipDiv,
+ {
+ left: linkViewportCoords.x,
+ top: linkViewportCoords.y,
+ width: linkWidth,
+ height: linkHeight,
+ },
+ "top",
+ );
+ trackEvent("hyperlink", "tooltip", "link-icon");
+
+ IS_HYPERLINK_TOOLTIP_VISIBLE = true;
+};
+export const hideHyperlinkToolip = () => {
+ if (HYPERLINK_TOOLTIP_TIMEOUT_ID) {
+ clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
+ }
+ if (IS_HYPERLINK_TOOLTIP_VISIBLE) {
+ IS_HYPERLINK_TOOLTIP_VISIBLE = false;
+ getTooltipDiv().classList.remove("excalidraw-tooltip--visible");
+ }
+};
+
+const shouldHideLinkPopup = (
+ element: NonDeletedExcalidrawElement,
+ elementsMap: ElementsMap,
+ appState: AppState,
+ [clientX, clientY]: GlobalPoint,
+): Boolean => {
+ const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
+ { clientX, clientY },
+ appState,
+ );
+
+ const threshold = 15 / appState.zoom.value;
+ // hitbox to prevent hiding when hovered in element bounding box
+ if (hitElementBoundingBox(sceneX, sceneY, element, elementsMap)) {
+ return false;
+ }
+ const [x1, y1, x2] = getElementAbsoluteCoords(element, elementsMap);
+ // hit box to prevent hiding when hovered in the vertical area between element and popover
+ if (
+ sceneX >= x1 &&
+ sceneX <= x2 &&
+ sceneY >= y1 - SPACE_BOTTOM &&
+ sceneY <= y1
+ ) {
+ return false;
+ }
+ // hit box to prevent hiding when hovered around popover within threshold
+ const { x: popoverX, y: popoverY } = getCoordsForPopover(
+ element,
+ appState,
+ elementsMap,
+ );
+
+ if (
+ clientX >= popoverX - threshold &&
+ clientX <= popoverX + POPUP_WIDTH + POPUP_PADDING * 2 + threshold &&
+ clientY >= popoverY - threshold &&
+ clientY <= popoverY + threshold + POPUP_PADDING * 2 + POPUP_HEIGHT
+ ) {
+ return false;
+ }
+ return true;
+};
diff --git a/packages/excalidraw/components/hyperlink/helpers.ts b/packages/excalidraw/components/hyperlink/helpers.ts
new file mode 100644
index 0000000..75c5dad
--- /dev/null
+++ b/packages/excalidraw/components/hyperlink/helpers.ts
@@ -0,0 +1,99 @@
+import type { GlobalPoint, Radians } from "@excalidraw/math";
+import { pointFrom, pointRotateRads } from "@excalidraw/math";
+import { MIME_TYPES } from "../../constants";
+import type { Bounds } from "../../element/bounds";
+import { getElementAbsoluteCoords } from "../../element/bounds";
+import { hitElementBoundingBox } from "../../element/collision";
+import type {
+ ElementsMap,
+ NonDeletedExcalidrawElement,
+} from "../../element/types";
+import { DEFAULT_LINK_SIZE } from "../../renderer/renderElement";
+import type { AppState, UIAppState } from "../../types";
+
+export const EXTERNAL_LINK_IMG = document.createElement("img");
+EXTERNAL_LINK_IMG.src = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
+ `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1971c2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-external-link"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`,
+)}`;
+
+export const ELEMENT_LINK_IMG = document.createElement("img");
+ELEMENT_LINK_IMG.src = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
+ `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1971c2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-arrow-big-right-line"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 9v-3.586a1 1 0 0 1 1.707 -.707l6.586 6.586a1 1 0 0 1 0 1.414l-6.586 6.586a1 1 0 0 1 -1.707 -.707v-3.586h-6v-6h6z" /><path d="M3 9v6" /></svg>`,
+)}`;
+
+export const getLinkHandleFromCoords = (
+ [x1, y1, x2, y2]: Bounds,
+ angle: Radians,
+ appState: Pick<UIAppState, "zoom">,
+): Bounds => {
+ const size = DEFAULT_LINK_SIZE;
+ const linkWidth = size / appState.zoom.value;
+ const linkHeight = size / appState.zoom.value;
+ const linkMarginY = size / appState.zoom.value;
+ const centerX = (x1 + x2) / 2;
+ const centerY = (y1 + y2) / 2;
+ const centeringOffset = (size - 8) / (2 * appState.zoom.value);
+ const dashedLineMargin = 4 / appState.zoom.value;
+
+ // Same as `ne` resize handle
+ const x = x2 + dashedLineMargin - centeringOffset;
+ const y = y1 - dashedLineMargin - linkMarginY + centeringOffset;
+
+ const [rotatedX, rotatedY] = pointRotateRads(
+ pointFrom(x + linkWidth / 2, y + linkHeight / 2),
+ pointFrom(centerX, centerY),
+ angle,
+ );
+ return [
+ rotatedX - linkWidth / 2,
+ rotatedY - linkHeight / 2,
+ linkWidth,
+ linkHeight,
+ ];
+};
+
+export const isPointHittingLinkIcon = (
+ element: NonDeletedExcalidrawElement,
+ elementsMap: ElementsMap,
+ appState: AppState,
+ [x, y]: GlobalPoint,
+) => {
+ const threshold = 4 / appState.zoom.value;
+ const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
+ const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
+ [x1, y1, x2, y2],
+ element.angle,
+ appState,
+ );
+ const hitLink =
+ x > linkX - threshold &&
+ x < linkX + threshold + linkWidth &&
+ y > linkY - threshold &&
+ y < linkY + linkHeight + threshold;
+ return hitLink;
+};
+
+export const isPointHittingLink = (
+ element: NonDeletedExcalidrawElement,
+ elementsMap: ElementsMap,
+ appState: AppState,
+ [x, y]: GlobalPoint,
+ isMobile: boolean,
+) => {
+ if (!element.link || appState.selectedElementIds[element.id]) {
+ return false;
+ }
+ if (
+ !isMobile &&
+ appState.viewModeEnabled &&
+ hitElementBoundingBox(x, y, element, elementsMap)
+ ) {
+ return true;
+ }
+ return isPointHittingLinkIcon(
+ element,
+ elementsMap,
+ appState,
+ pointFrom(x, y),
+ );
+};
diff --git a/packages/excalidraw/components/icons.tsx b/packages/excalidraw/components/icons.tsx
new file mode 100644
index 0000000..073d7a9
--- /dev/null
+++ b/packages/excalidraw/components/icons.tsx
@@ -0,0 +1,2222 @@
+//
+// All icons are imported from https://fontawesome.com/icons?d=gallery
+// Icons are under the license https://fontawesome.com/license
+//
+
+// Note: when adding new icons, review https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/RTL_Guidelines
+// to determine whether or not the icons should be mirrored in right-to-left languages.
+
+import React from "react";
+
+import oc from "open-color";
+import clsx from "clsx";
+import type { Theme } from "../element/types";
+import { THEME } from "../constants";
+
+export const iconFillColor = (theme: Theme) => "var(--icon-fill-color)";
+
+const handlerColor = (theme: Theme) =>
+ theme === THEME.LIGHT ? oc.white : "#1e1e1e";
+
+type Opts = {
+ width?: number;
+ height?: number;
+ mirror?: true;
+} & React.SVGProps<SVGSVGElement>;
+
+export const createIcon = (
+ d: string | React.ReactNode,
+ opts: number | Opts = 512,
+) => {
+ const {
+ width = 512,
+ height = width,
+ mirror,
+ style,
+ ...rest
+ } = typeof opts === "number" ? ({ width: opts } as Opts) : opts;
+ return (
+ <svg
+ aria-hidden="true"
+ focusable="false"
+ role="img"
+ viewBox={`0 0 ${width} ${height}`}
+ className={clsx({ "rtl-mirror": mirror })}
+ style={style}
+ {...rest}
+ >
+ {typeof d === "string" ? <path fill="currentColor" d={d} /> : d}
+ </svg>
+ );
+};
+
+const tablerIconProps: Opts = {
+ width: 24,
+ height: 24,
+ fill: "none",
+ strokeWidth: 2,
+ stroke: "currentColor",
+ strokeLinecap: "round",
+ strokeLinejoin: "round",
+} as const;
+
+const modifiedTablerIconProps: Opts = {
+ width: 20,
+ height: 20,
+ fill: "none",
+ stroke: "currentColor",
+ strokeLinecap: "round",
+ strokeLinejoin: "round",
+} as const;
+
+// -----------------------------------------------------------------------------
+
+// tabler-icons: present
+export const PlusPromoIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <rect x={3} y={8} width={18} height={4} rx={1} />
+ <line x1={12} y1={8} x2={12} y2={21} />
+ <path d="M19 12v7a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-7" />
+ <path d="M7.5 8a2.5 2.5 0 0 1 0 -5a4.8 8 0 0 1 4.5 5a4.8 8 0 0 1 4.5 -5a2.5 2.5 0 0 1 0 5" />
+ </g>,
+ tablerIconProps,
+);
+
+// tabler-icons: book
+export const LibraryIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0" />
+ <path d="M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0" />
+ <line x1="3" y1="6" x2="3" y2="19" />
+ <line x1="12" y1="6" x2="12" y2="19" />
+ <line x1="21" y1="6" x2="21" y2="19" />
+ </g>,
+ tablerIconProps,
+);
+
+// tabler-icons: plus
+export const PlusIcon = createIcon(
+ <svg strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="12" y1="5" x2="12" y2="19" />
+ <line x1="5" y1="12" x2="19" y2="12" />
+ </svg>,
+ tablerIconProps,
+);
+
+// tabler-icons: dots-vertical
+export const DotsIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <circle cx="12" cy="12" r="1"></circle>
+ <circle cx="12" cy="19" r="1"></circle>
+ <circle cx="12" cy="5" r="1"></circle>
+ </g>,
+ tablerIconProps,
+);
+
+// tabler-icons: pinned
+export const PinIcon = createIcon(
+ <svg strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M9 4v6l-2 4v2h10v-2l-2 -4v-6"></path>
+ <line x1="12" y1="16" x2="12" y2="21"></line>
+ <line x1="8" y1="4" x2="16" y2="4"></line>
+ </svg>,
+ tablerIconProps,
+);
+
+// tabler-icons: lock-open (via Figma)
+export const UnlockedIcon = createIcon(
+ <g>
+ <path
+ d="M13.542 8.542H6.458a2.5 2.5 0 0 0-2.5 2.5v3.75a2.5 2.5 0 0 0 2.5 2.5h7.084a2.5 2.5 0 0 0 2.5-2.5v-3.75a2.5 2.5 0 0 0-2.5-2.5Z"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ />
+ <path
+ d="M10 13.958a1.042 1.042 0 1 0 0-2.083 1.042 1.042 0 0 0 0 2.083Z"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ />
+ <mask
+ id="UnlockedIcon"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x={6}
+ y={1}
+ width={9}
+ height={9}
+ >
+ <path
+ stroke="none"
+ d="M6.399 9.561V5.175c0-.93.401-1.823 1.116-2.48a3.981 3.981 0 0 1 2.693-1.028c1.01 0 1.98.37 2.694 1.027.715.658 1.116 1.55 1.116 2.481"
+ fill="#fff"
+ />
+ </mask>
+ <g mask="url(#UnlockedIcon)">
+ <path
+ stroke="none"
+ d="M5.149 9.561v1.25h2.5v-1.25h-2.5Zm5.06-7.894V.417v1.25Zm2.559 3.508v1.25h2.5v-1.25h-2.5ZM7.648 8.51V5.175h-2.5V8.51h2.5Zm0-3.334c0-.564.243-1.128.713-1.561L6.668 1.775c-.959.883-1.52 2.104-1.52 3.4h2.5Zm.713-1.561a2.732 2.732 0 0 1 1.847-.697v-2.5c-1.31 0-2.585.478-3.54 1.358L8.36 3.614Zm1.847-.697c.71 0 1.374.26 1.847.697l1.694-1.839a5.231 5.231 0 0 0-3.54-1.358v2.5Zm1.847.697c.47.433.713.997.713 1.561h2.5c0-1.296-.56-2.517-1.52-3.4l-1.693 1.839Z"
+ fill="currentColor"
+ />
+ </g>
+ </g>,
+ modifiedTablerIconProps,
+);
+
+// tabler-icons: lock (via Figma)
+export const LockedIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path d="M13.542 8.542H6.458a2.5 2.5 0 0 0-2.5 2.5v3.75a2.5 2.5 0 0 0 2.5 2.5h7.084a2.5 2.5 0 0 0 2.5-2.5v-3.75a2.5 2.5 0 0 0-2.5-2.5Z" />
+ <path d="M10 13.958a1.042 1.042 0 1 0 0-2.083 1.042 1.042 0 0 0 0 2.083Z" />
+ <path d="M6.667 8.333V5.417C6.667 3.806 8.159 2.5 10 2.5c1.841 0 3.333 1.306 3.333 2.917v2.916" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+// custom
+export const WelcomeScreenMenuArrow = createIcon(
+ <>
+ <path
+ d="M38.5 83.5c-14-2-17.833-10.473-21-22.5C14.333 48.984 12 22 12 12.5"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="m12.005 10.478 7.905 14.423L6 25.75l6.005-15.273Z"
+ fill="currentColor"
+ />
+ <path
+ d="M12.005 10.478c1.92 3.495 3.838 7 7.905 14.423m-7.905-14.423c3.11 5.683 6.23 11.368 7.905 14.423m0 0c-3.68.226-7.35.455-13.91.85m13.91-.85c-5.279.33-10.566.647-13.91.85m0 0c1.936-4.931 3.882-9.86 6.005-15.273M6 25.75c2.069-5.257 4.135-10.505 6.005-15.272"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ />
+ </>,
+ { width: 41, height: 94, fill: "none" },
+);
+
+// custom
+export const WelcomeScreenHelpArrow = createIcon(
+ <>
+ <path
+ d="M18.026 1.232c-5.268 13.125-5.548 33.555 3.285 42.311 8.823 8.75 33.31 12.304 42.422 13.523"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="m72.181 59.247-13.058-10-2.948 13.62 16.006-3.62Z"
+ fill="currentColor"
+ />
+ <path
+ d="M72.181 59.247c-3.163-2.429-6.337-4.856-13.058-10m13.058 10c-5.145-3.936-10.292-7.882-13.058-10m0 0c-.78 3.603-1.563 7.196-2.948 13.62m2.948-13.62c-1.126 5.168-2.24 10.346-2.948 13.62m0 0c5.168-1.166 10.334-2.343 16.006-3.62m-16.006 3.62c5.51-1.248 11.01-2.495 16.006-3.62"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ />
+ </>,
+ { width: 85, height: 71, fill: "none" },
+);
+
+// custom
+export const WelcomeScreenTopToolbarArrow = createIcon(
+ <>
+ <path
+ d="M1 77c14-2 31.833-11.973 35-24 3.167-12.016-6-35-9.5-43.5"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="m24.165 1.093-2.132 16.309 13.27-4.258-11.138-12.05Z"
+ fill="currentColor"
+ />
+ <path
+ d="M24.165 1.093c-.522 3.953-1.037 7.916-2.132 16.309m2.131-16.309c-.835 6.424-1.68 12.854-2.13 16.308m0 0c3.51-1.125 7.013-2.243 13.27-4.257m-13.27 4.257c5.038-1.608 10.08-3.232 13.27-4.257m0 0c-3.595-3.892-7.197-7.777-11.14-12.05m11.14 12.05c-3.837-4.148-7.667-8.287-11.14-12.05"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ />
+ </>,
+ { width: 38, height: 78, fill: "none" },
+);
+
+// custom
+export const ExcalLogo = createIcon(
+ <g fill="currentColor">
+ <path
+ d="M39.9 32.889a.326.326 0 0 0-.279-.056c-2.094-3.083-4.774-6-7.343-8.833l-.419-.472a.212.212 0 0 0-.056-.139.586.586 0 0 0-.167-.111l-.084-.083-.056-.056c-.084-.167-.28-.278-.475-.167-.782.39-1.507.973-2.206 1.528-.92.722-1.842 1.445-2.708 2.25a8.405 8.405 0 0 0-.977 1.028c-.14.194-.028.361.14.444-.615.611-1.23 1.223-1.843 1.861a.315.315 0 0 0-.084.223c0 .083.056.166.111.194l1.09.833v.028c1.535 1.528 4.244 3.611 7.12 5.861.418.334.865.667 1.284 1 .195.223.39.473.558.695.084.11.28.139.391.055.056.056.14.111.196.167a.398.398 0 0 0 .167.056.255.255 0 0 0 .224-.111.394.394 0 0 0 .055-.167c.029 0 .028.028.056.028a.318.318 0 0 0 .224-.084l5.082-5.528a.309.309 0 0 0 0-.444Zm-14.63-1.917a.485.485 0 0 0 .111.14c.586.5 1.2 1 1.843 1.555l-2.569-1.945-.251-.166c-.056-.028-.112-.084-.168-.111l-.195-.167.056-.056.055-.055.112-.111c.866-.861 2.346-2.306 3.1-3.028-.81.805-2.43 3.167-2.095 3.944Zm8.767 6.89-2.122-1.612a44.713 44.713 0 0 0-2.625-2.5c1.145.861 2.122 1.611 2.262 1.75 1.117.972 1.06.806 1.815 1.445l.921.666a1.06 1.06 0 0 1-.251.25Zm.558.416-.056-.028c.084-.055.168-.111.252-.194l-.196.222ZM1.089 5.75c.055.361.14.722.195 1.056.335 1.833.67 3.5 1.284 4.75l.252.944c.084.361.223.806.363.917 1.424 1.25 3.602 3.11 5.947 4.889a.295.295 0 0 0 .363 0s0 .027.028.027a.254.254 0 0 0 .196.084.318.318 0 0 0 .223-.084c2.988-3.305 5.221-6.027 6.813-8.305.112-.111.14-.278.14-.417.111-.111.195-.25.307-.333.111-.111.111-.306 0-.39l-.028-.027c0-.055-.028-.139-.084-.167-.698-.666-1.2-1.138-1.731-1.638-.922-.862-1.871-1.75-3.881-3.75l-.028-.028c-.028-.028-.056-.056-.112-.056-.558-.194-1.703-.389-3.127-.639C6.087 2.223 3.21 1.723.614.944c0 0-.168 0-.196.028l-.083.084c-.028.027-.056.055-.224.11h.056-.056c.028.167.028.278.084.473 0 .055.112.5.112.555l.782 3.556Zm15.496 3.278-.335-.334c.084.112.196.195.335.334Zm-3.546 4.666-.056.056c0-.028.028-.056.056-.056Zm-2.038-10c.168.167.866.834 1.033.973-.726-.334-2.54-1.167-3.379-1.445.838.167 1.983.334 2.346.472ZM1.424 2.306c.419.722.754 3.222 1.089 5.666-.196-.778-.335-1.555-.503-2.278-.251-1.277-.503-2.416-.838-3.416.056 0 .14 0 .252.028Zm-.168-.584c-.112 0-.223-.028-.307-.028 0-.027 0-.055-.028-.055.14 0 .223.028.335.083Zm-1.089.222c0-.027 0-.027 0 0ZM39.453 1.333c.028-.11-.558-.61-.363-.639.42-.027.42-.666 0-.666-.558.028-1.144.166-1.675.25-.977.194-1.982.389-2.96.61-2.205.473-4.383.973-6.561 1.557-.67.194-1.424.333-2.066.666-.224.111-.196.333-.084.472-.056.028-.084.028-.14.056-.195.028-.363.056-.558.083-.168.028-.252.167-.224.334 0 .027.028.083.028.11-1.173 1.556-2.485 3.195-3.909 4.945-1.396 1.611-2.876 3.306-4.356 5.056-4.719 5.5-10.052 11.75-15.943 17.25a.268.268 0 0 0 0 .389c.028.027.056.055.084.055-.084.084-.168.14-.252.222-.056.056-.084.111-.084.167a.605.605 0 0 0-.111.139c-.112.111-.112.305.028.389.111.11.307.11.39-.028.029-.028.029-.056.056-.056a.44.44 0 0 1 .615 0c.335.362.67.723.977 1.028l-.698-.583c-.112-.111-.307-.083-.39.028-.113.11-.085.305.027.389l7.427 6.194c.056.056.112.056.196.056s.14-.028.195-.084l.168-.166c.028.027.083.027.111.027.084 0 .14-.027.196-.083 10.052-10.055 18.15-17.639 27.42-24.417.083-.055.111-.166.111-.25.112 0 .196-.083.251-.194 1.704-5.194 2.039-9.806 2.15-12.083v-.028c0-.028.028-.056.028-.083.028-.056.028-.084.028-.084a1.626 1.626 0 0 0-.111-1.028ZM21.472 9.5c.446-.5.893-1.028 1.34-1.5-2.876 3.778-7.65 9.583-14.408 16.5 4.607-5.083 9.242-10.333 13.068-15ZM5.193 35.778h.084-.084Zm3.462 3.194c-.027-.028-.027-.028 0-.028v.028Zm4.16-3.583c.224-.25.448-.472.699-.722 0 0 0 .027.028.027-.252.223-.475.445-.726.695Zm1.146-1.111c.14-.14.279-.334.446-.5l.028-.028c1.648-1.694 3.351-3.389 5.082-5.111l.028-.028c.419-.333.921-.694 1.368-1.028a379.003 379.003 0 0 0-6.952 6.695ZM24.794 6.472c-.921 1.195-1.954 2.778-2.82 4.028-2.736 3.944-11.532 13.583-11.727 13.75a1976.983 1976.983 0 0 1-8.042 7.639l-.167.167c-.14-.167-.14-.417.028-.556C14.49 19.861 22.03 10.167 25.074 5.917c-.084.194-.14.36-.28.555Zm4.83 5.695c-1.116-.64-1.646-1.64-1.34-2.611l.084-.334c.028-.083.084-.194.14-.277.307-.5.754-.917 1.257-1.167.027 0 .055 0 .083-.028-.028-.056-.028-.139-.028-.222.028-.167.14-.278.335-.278.335 0 1.369.306 1.76.639.111.083.223.194.335.305.14.167.363.445.474.667.056.028.112.306.196.445.056.222.111.472.084.694-.028.028 0 .194-.028.194a2.668 2.668 0 0 1-.363 1.028c-.028.028-.028.056-.056.084l-.028.027c-.14.223-.335.417-.53.556-.643.444-1.369.583-2.095.389 0 0-.195-.084-.28-.111Zm8.154-.834a39.098 39.098 0 0 1-.893 3.167c0 .028-.028.083 0 .111-.056 0-.084.028-.14.056-2.206 1.61-4.356 3.305-6.506 5.028 1.843-1.64 3.686-3.306 5.613-4.945.558-.5.949-1.139 1.06-1.861l.28-1.667v-.055c.14-.334.67-.195.586.166Z"
+ fill="currentColor"
+ />
+ </g>,
+ { width: 40, height: 40, fill: "none" },
+);
+
+// custom
+export const SelectionIcon = createIcon(
+ <g stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M6 6l4.153 11.793a0.365 .365 0 0 0 .331 .207a0.366 .366 0 0 0 .332 -.207l2.184 -4.793l4.787 -1.994a0.355 .355 0 0 0 .213 -.323a0.355 .355 0 0 0 -.213 -.323l-11.787 -4.36z" />
+ <path d="M13.5 13.5l4.5 4.5" />
+ </g>,
+ { fill: "none", width: 22, height: 22, strokeWidth: 1.25 },
+);
+
+// tabler-icons: square
+export const RectangleIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <rect x="4" y="4" width="16" height="16" rx="2"></rect>
+ </g>,
+ tablerIconProps,
+);
+
+// tabler-icons: square-rotated
+export const DiamondIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M10.5 20.4l-6.9 -6.9c-.781 -.781 -.781 -2.219 0 -3l6.9 -6.9c.781 -.781 2.219 -.781 3 0l6.9 6.9c.781 .781 .781 2.219 0 3l-6.9 6.9c-.781 .781 -2.219 .781 -3 0z" />
+ </g>,
+
+ tablerIconProps,
+);
+
+// tabler-icons: circle
+export const EllipseIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <circle cx="12" cy="12" r="9"></circle>
+ </g>,
+
+ tablerIconProps,
+);
+
+// tabler-icons: arrow-narrow-right
+export const ArrowIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <line x1="15" y1="16" x2="19" y2="12" />
+ <line x1="15" y1="8" x2="19" y2="12" />
+ </g>,
+ tablerIconProps,
+);
+
+// custom?
+export const LineIcon = createIcon(
+ <path d="M4.167 10h11.666" strokeWidth="1.5" />,
+ modifiedTablerIconProps,
+);
+
+export const PenModeIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M20 17v-12c0 -1.121 -.879 -2 -2 -2s-2 .879 -2 2v12l2 2l2 -2z"></path>
+ <path d="M16 7h4"></path>
+ <path d="M18 19h-13a2 2 0 1 1 0 -4h4a2 2 0 1 0 0 -4h-3"></path>
+ </g>,
+ tablerIconProps,
+);
+
+// modified tabler-icons: pencil
+export const FreedrawIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path
+ clipRule="evenodd"
+ d="m7.643 15.69 7.774-7.773a2.357 2.357 0 1 0-3.334-3.334L4.31 12.357a3.333 3.333 0 0 0-.977 2.357v1.953h1.953c.884 0 1.732-.352 2.357-.977Z"
+ />
+ <path d="m11.25 5.417 3.333 3.333" />
+ </g>,
+
+ modifiedTablerIconProps,
+);
+
+// tabler-icons: typography
+export const TextIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="4" y1="20" x2="7" y2="20" />
+ <line x1="14" y1="20" x2="21" y2="20" />
+ <line x1="6.9" y1="15" x2="13.8" y2="15" />
+ <line x1="10.2" y1="6.3" x2="16" y2="20" />
+ <polyline points="5 20 11 4 13 4 20 20"></polyline>
+ </g>,
+ tablerIconProps,
+);
+
+// modified tabler-icons: photo
+export const ImageIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path d="M12.5 6.667h.01" />
+ <path d="M4.91 2.625h10.18a2.284 2.284 0 0 1 2.285 2.284v10.182a2.284 2.284 0 0 1-2.284 2.284H4.909a2.284 2.284 0 0 1-2.284-2.284V4.909a2.284 2.284 0 0 1 2.284-2.284Z" />
+ <path d="m3.333 12.5 3.334-3.333c.773-.745 1.726-.745 2.5 0l4.166 4.166" />
+ <path d="m11.667 11.667.833-.834c.774-.744 1.726-.744 2.5 0l1.667 1.667" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+// tabler-icons: eraser
+export const EraserIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M19 20h-10.5l-4.21 -4.3a1 1 0 0 1 0 -1.41l10 -10a1 1 0 0 1 1.41 0l5 5a1 1 0 0 1 0 1.41l-9.2 9.3" />
+ <path d="M18 13.3l-6.3 -6.3" />
+ </g>,
+ tablerIconProps,
+);
+
+export const ZoomInIcon = createIcon(
+ <path strokeWidth="1.25" d="M10 4.167v11.666M4.167 10h11.666" />,
+ modifiedTablerIconProps,
+);
+
+export const ZoomOutIcon = createIcon(
+ <path d="M5 10h10" strokeWidth="1.25" />,
+ modifiedTablerIconProps,
+);
+
+export const ZoomResetIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M21 21l-6 -6" />
+ <path d="M3.268 12.043a7.017 7.017 0 0 0 6.634 4.957a7.012 7.012 0 0 0 7.043 -6.131a7 7 0 0 0 -5.314 -7.672a7.021 7.021 0 0 0 -8.241 4.403" />
+ <path d="M3 4v4h4" />
+ </g>,
+ tablerIconProps,
+);
+
+export const TrashIcon = createIcon(
+ <path
+ strokeWidth="1.25"
+ d="M3.333 5.833h13.334M8.333 9.167v5M11.667 9.167v5M4.167 5.833l.833 10c0 .92.746 1.667 1.667 1.667h6.666c.92 0 1.667-.746 1.667-1.667l.833-10M7.5 5.833v-2.5c0-.46.373-.833.833-.833h3.334c.46 0 .833.373.833.833v2.5"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const EmbedIcon = createIcon(
+ <g strokeWidth="1.25">
+ <polyline points="12 16 18 10 12 4" />
+ <polyline points="8 4 2 10 8 16" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+export const DuplicateIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path d="M14.375 6.458H8.958a2.5 2.5 0 0 0-2.5 2.5v5.417a2.5 2.5 0 0 0 2.5 2.5h5.417a2.5 2.5 0 0 0 2.5-2.5V8.958a2.5 2.5 0 0 0-2.5-2.5Z" />
+ <path
+ clipRule="evenodd"
+ d="M11.667 3.125c.517 0 .986.21 1.325.55.34.338.55.807.55 1.325v1.458H8.333c-.485 0-.927.185-1.26.487-.343.312-.57.75-.609 1.24l-.005 5.357H5a1.87 1.87 0 0 1-1.326-.55 1.87 1.87 0 0 1-.549-1.325V5c0-.518.21-.987.55-1.326.338-.34.807-.549 1.325-.549h6.667Z"
+ />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+export const MoonIcon = createIcon(
+ <path
+ clipRule="evenodd"
+ d="M10 2.5h.328a6.25 6.25 0 0 0 6.6 10.372A7.5 7.5 0 1 1 10 2.493V2.5Z"
+ stroke="currentColor"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const SunIcon = createIcon(
+ <g stroke="currentColor" strokeLinejoin="round">
+ <path d="M10 12.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM10 4.167V2.5M14.167 5.833l1.166-1.166M15.833 10H17.5M14.167 14.167l1.166 1.166M10 15.833V17.5M5.833 14.167l-1.166 1.166M5 10H3.333M5.833 5.833 4.667 4.667" />
+ </g>,
+ { ...modifiedTablerIconProps, strokeWidth: 1.5 },
+);
+
+export const HamburgerMenuIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <line x1="4" y1="6" x2="20" y2="6"></line>
+ <line x1="4" y1="12" x2="20" y2="12"></line>
+ <line x1="4" y1="18" x2="20" y2="18"></line>
+ </g>,
+ tablerIconProps,
+);
+
+export const ExportIcon = createIcon(
+ <path
+ strokeWidth="1.25"
+ d="M3.333 14.167v1.666c0 .92.747 1.667 1.667 1.667h10c.92 0 1.667-.746 1.667-1.667v-1.666M5.833 9.167 10 13.333l4.167-4.166M10 3.333v10"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const HelpIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <circle cx="12" cy="12" r="9"></circle>
+ <line x1="12" y1="17" x2="12" y2="17.01"></line>
+ <path d="M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"></path>
+ </g>,
+ tablerIconProps,
+);
+
+export const HelpIconThin = createIcon(
+ <g strokeWidth="1.25">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <circle cx="12" cy="12" r="9"></circle>
+ <line x1="12" y1="17" x2="12" y2="17.01"></line>
+ <path d="M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"></path>
+ </g>,
+ tablerIconProps,
+);
+
+export const ExternalLinkIcon = createIcon(
+ <path
+ strokeWidth="1.25"
+ d="M9.167 5.833H5.833c-1.254 0-2.5 1.282-2.5 2.5v5.834c0 1.283 1.252 2.5 2.5 2.5h5.834c1.251 0 2.5-1.25 2.5-2.5v-3.334M8.333 11.667l8.334-8.334M12.5 3.333h4.167V7.5"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const GithubIcon = createIcon(
+ <path
+ d="M7.5 15.833c-3.583 1.167-3.583-2.083-5-2.5m10 4.167v-2.917c0-.833.083-1.166-.417-1.666 2.334-.25 4.584-1.167 4.584-5a3.833 3.833 0 0 0-1.084-2.667 3.5 3.5 0 0 0-.083-2.667s-.917-.25-2.917 1.084a10.25 10.25 0 0 0-5.166 0C5.417 2.333 4.5 2.583 4.5 2.583a3.5 3.5 0 0 0-.083 2.667 3.833 3.833 0 0 0-1.084 2.667c0 3.833 2.25 4.75 4.584 5-.5.5-.5 1-.417 1.666V17.5"
+ strokeWidth="1.25"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const DiscordIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path d="M7.5 10.833a.833.833 0 1 0 0-1.666.833.833 0 0 0 0 1.666ZM12.5 10.833a.833.833 0 1 0 0-1.666.833.833 0 0 0 0 1.666ZM6.25 6.25c2.917-.833 4.583-.833 7.5 0M5.833 13.75c2.917.833 5.417.833 8.334 0" />
+ <path d="M12.917 14.167c0 .833 1.25 2.5 1.666 2.5 1.25 0 2.361-1.39 2.917-2.5.556-1.39.417-4.861-1.25-9.584-1.214-.846-2.5-1.116-3.75-1.25l-.833 2.084M7.083 14.167c0 .833-1.13 2.5-1.526 2.5-1.191 0-2.249-1.39-2.778-2.5-.529-1.39-.397-4.861 1.19-9.584 1.157-.846 2.318-1.116 3.531-1.25l.833 2.084" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+export const XBrandIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M4 4l11.733 16h4.267l-11.733 -16z" />
+ <path d="M4 20l6.768 -6.768m2.46 -2.46l6.772 -6.772" />
+ </g>,
+ tablerIconProps,
+);
+
+export const checkIcon = createIcon(
+ <polyline fill="none" stroke="currentColor" points="20 6 9 17 4 12" />,
+ {
+ width: 24,
+ height: 24,
+ },
+);
+
+export const LinkIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path d="M8.333 11.667a2.917 2.917 0 0 0 4.167 0l3.333-3.334a2.946 2.946 0 1 0-4.166-4.166l-.417.416" />
+ <path d="M11.667 8.333a2.917 2.917 0 0 0-4.167 0l-3.333 3.334a2.946 2.946 0 0 0 4.166 4.166l.417-.416" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+export const save = createIcon(
+ "M433.941 129.941l-83.882-83.882A48 48 0 0 0 316.118 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V163.882a48 48 0 0 0-14.059-33.941zM224 416c-35.346 0-64-28.654-64-64 0-35.346 28.654-64 64-64s64 28.654 64 64c0 35.346-28.654 64-64 64zm96-304.52V212c0 6.627-5.373 12-12 12H76c-6.627 0-12-5.373-12-12V108c0-6.627 5.373-12 12-12h228.52c3.183 0 6.235 1.264 8.485 3.515l3.48 3.48A11.996 11.996 0 0 1 320 111.48z",
+ { width: 448, height: 512 },
+);
+
+export const saveAs = createIcon(
+ "M252 54L203 8a28 27 0 00-20-8H28C12 0 0 12 0 27v195c0 15 12 26 28 26h204c15 0 28-11 28-26V73a28 27 0 00-8-19zM130 213c-21 0-37-16-37-36 0-19 16-35 37-35 20 0 37 16 37 35 0 20-17 36-37 36zm56-169v56c0 4-4 6-7 6H44c-4 0-7-2-7-6V42c0-4 3-7 7-7h133l4 2 3 2a7 7 0 012 5z M296 201l87 95-188 205-78 9c-10 1-19-8-18-20l9-84zm141-14l-41-44a31 31 0 00-46 0l-38 41 87 95 38-42c13-14 13-36 0-50z",
+ { width: 448, height: 512 },
+);
+
+// tabler-icon: folder
+export const LoadIcon = createIcon(
+ <path
+ d="m9.257 6.351.183.183H15.819c.34 0 .727.182 1.051.506.323.323.505.708.505 1.05v5.819c0 .316-.183.7-.52 1.035-.337.338-.723.522-1.037.522H4.182c-.352 0-.74-.181-1.058-.5-.318-.318-.499-.705-.499-1.057V5.182c0-.351.181-.736.5-1.054.32-.321.71-.503 1.057-.503H6.53l2.726 2.726Z"
+ strokeWidth="1.25"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const clipboard = createIcon(
+ "M384 112v352c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h80c0-35.29 28.71-64 64-64s64 28.71 64 64h80c26.51 0 48 21.49 48 48zM192 40c-13.255 0-24 10.745-24 24s10.745 24 24 24 24-10.745 24-24-10.745-24-24-24m96 114v-20a6 6 0 0 0-6-6H102a6 6 0 0 0-6 6v20a6 6 0 0 0 6 6h180a6 6 0 0 0 6-6z",
+ { width: 384, height: 512 },
+);
+
+export const palette = createIcon(
+ "M204.3 5C104.9 24.4 24.8 104.3 5.2 203.4c-37 187 131.7 326.4 258.8 306.7 41.2-6.4 61.4-54.6 42.5-91.7-23.1-45.4 9.9-98.4 60.9-98.4h79.7c35.8 0 64.8-29.6 64.9-65.3C511.5 97.1 368.1-26.9 204.3 5zM96 320c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm32-128c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128-64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128 64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32z",
+);
+
+export const bucketFillIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M5 16l1.465 1.638a2 2 0 1 1 -3.015 .099l1.55 -1.737z" />
+ <path d="M13.737 9.737c2.299 -2.3 3.23 -5.095 2.081 -6.245c-1.15 -1.15 -3.945 -.217 -6.244 2.082c-2.3 2.299 -3.231 5.095 -2.082 6.244c1.15 1.15 3.946 .218 6.245 -2.081z" />
+ <path d="M7.492 11.818c.362 .362 .768 .676 1.208 .934l6.895 4.047c1.078 .557 2.255 -.075 3.692 -1.512c1.437 -1.437 2.07 -2.614 1.512 -3.692c-.372 -.718 -1.72 -3.017 -4.047 -6.895a6.015 6.015 0 0 0 -.934 -1.208" />
+ </g>,
+ tablerIconProps,
+);
+
+export const ExportImageIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M15 8h.01"></path>
+ <path d="M12 20h-5a3 3 0 0 1 -3 -3v-10a3 3 0 0 1 3 -3h10a3 3 0 0 1 3 3v5"></path>
+ <path d="M4 15l4 -4c.928 -.893 2.072 -.893 3 0l4 4"></path>
+ <path d="M14 14l1 -1c.617 -.593 1.328 -.793 2.009 -.598"></path>
+ <path d="M19 16v6"></path>
+ <path d="M22 19l-3 3l-3 -3"></path>
+ </g>,
+ tablerIconProps,
+);
+
+export const exportToFileIcon = createIcon(
+ "M216 0h80c13.3 0 24 10.7 24 24v168h87.7c17.8 0 26.7 21.5 14.1 34.1L269.7 378.3c-7.5 7.5-19.8 7.5-27.3 0L90.1 226.1c-12.6-12.6-3.7-34.1 14.1-34.1H192V24c0-13.3 10.7-24 24-24zm296 376v112c0 13.3-10.7 24-24 24H24c-13.3 0-24-10.7-24-24V376c0-13.3 10.7-24 24-24h146.7l49 49c20.1 20.1 52.5 20.1 72.6 0l49-49H488c13.3 0 24 10.7 24 24zm-124 88c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20zm64 0c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20z",
+ { width: 512, height: 512 },
+);
+
+export const zoomIn = createIcon(
+ "M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z",
+ { width: 448, height: 512 },
+);
+
+export const zoomOut = createIcon(
+ "M416 208H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h384c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z",
+ { width: 448, height: 512 },
+);
+
+export const done = createIcon(
+ "M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z",
+);
+
+export const menu = createIcon(
+ "M16 132h416c8.837 0 16-7.163 16-16V76c0-8.837-7.163-16-16-16H16C7.163 60 0 67.163 0 76v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z",
+);
+
+export const UndoIcon = createIcon(
+ <path
+ d="M7.5 10.833 4.167 7.5 7.5 4.167M4.167 7.5h9.166a3.333 3.333 0 0 1 0 6.667H12.5"
+ strokeWidth="1.25"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const RedoIcon = createIcon(
+ <path
+ d="M12.5 10.833 15.833 7.5 12.5 4.167M15.833 7.5H6.667a3.333 3.333 0 1 0 0 6.667H7.5"
+ strokeWidth="1.25"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const questionCircle = createIcon(
+ "M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zM262.655 90c-54.497 0-89.255 22.957-116.549 63.758-3.536 5.286-2.353 12.415 2.715 16.258l34.699 26.31c5.205 3.947 12.621 3.008 16.665-2.122 17.864-22.658 30.113-35.797 57.303-35.797 20.429 0 45.698 13.148 45.698 32.958 0 14.976-12.363 22.667-32.534 33.976C247.128 238.528 216 254.941 216 296v4c0 6.627 5.373 12 12 12h56c6.627 0 12-5.373 12-12v-1.333c0-28.462 83.186-29.647 83.186-106.667 0-58.002-60.165-102-116.531-102zM256 338c-25.365 0-46 20.635-46 46 0 25.364 20.635 46 46 46s46-20.636 46-46c0-25.365-20.635-46-46-46z",
+ { mirror: true },
+);
+
+export const share = createIcon(
+ <path
+ d="M5 12.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM15 7.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM15 17.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM7.25 8.917l5.5-2.834M7.25 11.083l5.5 2.834"
+ strokeWidth="1.5"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const warning = createIcon(
+ "M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z",
+);
+
+export const shareIOS = createIcon(
+ "M16 5l-1.42 1.42-1.59-1.59V16h-1.98V4.83L9.42 6.42 8 5l4-4 4 4zm4 5v11c0 1.1-.9 2-2 2H6c-1.11 0-2-.9-2-2V10c0-1.11.89-2 2-2h3v2H6v11h12V10h-3V8h3c1.1 0 2 .89 2 2z",
+ { width: 24, height: 24 },
+);
+
+export const exportToPlus = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M8 9h-1a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-8a2 2 0 0 0 -2 -2h-1" />
+ <path d="M12 14v-11" />
+ <path d="M9 6l3 -3l3 3" />
+ </g>,
+ tablerIconProps,
+);
+
+export const shareWindows = createIcon(
+ <>
+ <path
+ fill="currentColor"
+ d="M40 5.6v6.1l-4.1.7c-8.9 1.4-16.5 6.9-20.6 15C13 32 10.9 43 12.4 43c.4 0 2.4-1.3 4.4-3 5-3.9 12.1-7 18.2-7.7l5-.6v12.8l11.2-11.3L62.5 22 51.2 10.8 40-.5v6.1zm10.2 22.6L44 34.5v-6.8l-6.9.6c-3.9.3-9.8 1.7-13.2 3.1-3.5 1.4-6.5 2.4-6.7 2.2-.9-1 3-7.5 6.4-10.8C28 18.6 34.4 16 40.1 16c3.7 0 3.9-.1 3.9-3.2V9.5l6.2 6.3 6.3 6.2-6.3 6.2z"
+ />
+ <path
+ stroke="currentColor"
+ fill="currentColor"
+ d="M0 36v20h48v-6.2c0-6 0-6.1-2-4.3-1.1 1-2 2.9-2 4.2V52H4V34c0-17.3-.1-18-2-18s-2 .7-2 20z"
+ />
+ </>,
+ { width: 64, height: 64 },
+);
+
+// Icon imported form Storybook
+// Storybook is licensed under MIT https://github.com/storybookjs/storybook/blob/next/LICENSE
+export const resetZoom = createIcon(
+ <path
+ stroke="currentColor"
+ strokeWidth="40"
+ fill="currentColor"
+ d="M148 560a318 318 0 0 0 522 110 316 316 0 0 0 0-450 316 316 0 0 0-450 0c-11 11-21 22-30 34v4h47c25 0 46 21 46 46s-21 45-46 45H90c-13 0-25-6-33-14-9-9-14-20-14-33V156c0-25 20-45 45-45s45 20 45 45v32l1 1a401 401 0 0 1 623 509l212 212a42 42 0 0 1-59 59L698 757A401 401 0 0 1 65 570a42 42 0 0 1 83-10z"
+ />,
+ { width: 1024 },
+);
+
+const arrowBarToTopJSX = (
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M12 10l0 10" />
+ <path d="M12 10l4 4" />
+ <path d="M12 10l-4 4" />
+ <path d="M4 4l16 0" />
+ </g>
+);
+
+const arrownNarrowUpJSX = (
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M12 5l0 14" />
+ <path d="M16 9l-4 -4" />
+ <path d="M8 9l4 -4" />
+ </g>
+);
+
+export const BringForwardIcon = createIcon(arrownNarrowUpJSX, tablerIconProps);
+
+export const SendBackwardIcon = createIcon(arrownNarrowUpJSX, {
+ ...tablerIconProps,
+ style: {
+ transform: "rotate(180deg)",
+ },
+});
+
+export const BringToFrontIcon = createIcon(arrowBarToTopJSX, tablerIconProps);
+
+export const SendToBackIcon = createIcon(arrowBarToTopJSX, {
+ ...tablerIconProps,
+ style: {
+ transform: "rotate(180deg)",
+ },
+});
+
+//
+// Align action icons created from scratch to match those of z-index actions
+// Note: vertical align icons are flipped so the larger item is always the
+// first one the user sees. Horizontal align icons should not be flipped since
+// that would make them lie about their function.
+//
+export const AlignTopIcon = createIcon(
+ <>
+ <g clipPath="url(#a)" stroke="currentColor" strokeWidth="1.25">
+ <path
+ d="M3.333 3.333h13.334"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M13.542 6.458h-.417c-.92 0-1.667.747-1.667 1.667v7.083c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667V8.125c0-.92-.746-1.667-1.666-1.667ZM6.875 6.458h-.417c-.92 0-1.666.747-1.666 1.667v3.75c0 .92.746 1.667 1.666 1.667h.417c.92 0 1.667-.746 1.667-1.667v-3.75c0-.92-.747-1.667-1.667-1.667Z" />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const AlignBottomIcon = createIcon(
+ <>
+ <g clipPath="url(#a)" stroke="currentColor" strokeWidth="1.25">
+ <path
+ d="M3.333 16.667h13.334"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M6.875 3.125h-.417c-.92 0-1.666.746-1.666 1.667v7.083c0 .92.746 1.667 1.666 1.667h.417c.92 0 1.667-.746 1.667-1.667V4.792c0-.92-.747-1.667-1.667-1.667ZM13.542 5.817h-.417c-.92 0-1.667.747-1.667 1.667v4.391c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667V7.484c0-.92-.746-1.667-1.666-1.667Z" />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const AlignLeftIcon = createIcon(
+ <>
+ <g clipPath="url(#a)" stroke="currentColor" strokeWidth="1.25">
+ <path
+ d="M3.333 3.333v13.334"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M15.208 4.792H8.125c-.92 0-1.667.746-1.667 1.666v.417c0 .92.747 1.667 1.667 1.667h7.083c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666ZM12.516 11.458H8.125c-.92 0-1.667.746-1.667 1.667v.417c0 .92.747 1.666 1.667 1.666h4.391c.92 0 1.667-.746 1.667-1.666v-.417c0-.92-.746-1.667-1.667-1.667Z" />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const AlignRightIcon = createIcon(
+ <>
+ <g clipPath="url(#a)" stroke="currentColor" strokeWidth="1.25">
+ <path
+ d="M16.667 3.333v13.334"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M11.875 4.792H4.792c-.92 0-1.667.746-1.667 1.666v.417c0 .92.746 1.667 1.667 1.667h7.083c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666ZM11.683 11.458H7.292c-.92 0-1.667.746-1.667 1.667v.417c0 .92.746 1.666 1.667 1.666h4.39c.921 0 1.667-.746 1.667-1.666v-.417c0-.92-.746-1.667-1.666-1.667Z" />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const DistributeHorizontallyIcon = createIcon(
+ <>
+ <g clipPath="url(#a)" stroke="currentColor" strokeWidth="1.25">
+ <path
+ d="M16.667 3.333v13.334M3.333 3.333v13.334"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M14.375 10.208v-.416c0-.92-.746-1.667-1.667-1.667H7.292c-.92 0-1.667.746-1.667 1.667v.416c0 .92.746 1.667 1.667 1.667h5.416c.92 0 1.667-.746 1.667-1.667Z" />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const DistributeVerticallyIcon = createIcon(
+ <>
+ <g clipPath="url(#a)" stroke="currentColor" strokeWidth="1.25">
+ <path
+ d="M3.333 3.333h13.334M3.333 16.667h13.334"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path d="M10.208 5.625h-.416c-.92 0-1.667.746-1.667 1.667v5.416c0 .92.746 1.667 1.667 1.667h.416c.92 0 1.667-.746 1.667-1.667V7.292c0-.92-.746-1.667-1.667-1.667Z" />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const CenterVerticallyIcon = createIcon(
+ <g stroke="currentColor" strokeWidth="1.25">
+ <path d="M1.667 10h2.916" strokeLinecap="round" strokeLinejoin="round" />
+ <path d="M8.333 10h3.334" strokeLinejoin="round" />
+ <path d="M15.417 10h2.916" strokeLinecap="round" strokeLinejoin="round" />
+ <path d="M6.875 4.792h-.417c-.92 0-1.666.746-1.666 1.666v7.084c0 .92.746 1.666 1.666 1.666h.417c.92 0 1.667-.746 1.667-1.666V6.458c0-.92-.747-1.666-1.667-1.666ZM13.542 6.458h-.417c-.92 0-1.667.747-1.667 1.667v3.75c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667v-3.75c0-.92-.746-1.667-1.666-1.667Z" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+export const CenterHorizontallyIcon = createIcon(
+ <g stroke="currentColor" strokeWidth="1.25">
+ <path d="M10 18.333v-2.916" strokeLinecap="round" strokeLinejoin="round" />
+ <path d="M10 11.667V8.333" strokeLinejoin="round" />
+ <path d="M10 4.583V1.667" strokeLinecap="round" strokeLinejoin="round" />
+ <path d="M4.792 13.125v.417c0 .92.746 1.666 1.666 1.666h7.084c.92 0 1.666-.746 1.666-1.666v-.417c0-.92-.746-1.667-1.666-1.667H6.458c-.92 0-1.666.746-1.666 1.667ZM6.458 6.458v.417c0 .92.747 1.667 1.667 1.667h3.75c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666h-3.75c-.92 0-1.667.746-1.667 1.666Z" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+export const usersIcon = createIcon(
+ <g strokeWidth="1.5">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <circle cx="9" cy="7" r="4"></circle>
+ <path d="M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"></path>
+ <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
+ <path d="M21 21v-2a4 4 0 0 0 -3 -3.85"></path>
+ </g>,
+ tablerIconProps,
+);
+
+// not mirrored because it's inspired by a playback control, which is always RTL
+export const start = createIcon(
+ "M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm115.7 272l-176 101c-15.8 8.8-35.7-2.5-35.7-21V152c0-18.4 19.8-29.8 35.7-21l176 107c16.4 9.2 16.4 32.9 0 42z",
+);
+
+export const stop = createIcon(
+ "M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm96 328c0 8.8-7.2 16-16 16H176c-8.8 0-16-7.2-16-16V176c0-8.8 7.2-16 16-16h160c8.8 0 16 7.2 16 16v160z",
+);
+
+export const CloseIcon = createIcon(
+ <>
+ <g
+ clipPath="url(#a)"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M15 5 5 15M5 5l10 10" />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const clone = createIcon(
+ "M464 0c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48H176c-26.51 0-48-21.49-48-48V48c0-26.51 21.49-48 48-48h288M176 416c-44.112 0-80-35.888-80-80V128H48c-26.51 0-48 21.49-48 48v288c0 26.51 21.49 48 48 48h288c26.51 0 48-21.49 48-48v-48H176z",
+ { mirror: true },
+);
+
+// modified https://feathericons.com/?query=shield
+export const shield = createIcon(
+ "M11.553 22.894a.998.998 0 00.894 0s3.037-1.516 5.465-4.097C19.616 16.987 21 14.663 21 12V5a1 1 0 00-.649-.936l-8-3a.998.998 0 00-.702 0l-8 3A1 1 0 003 5v7c0 2.663 1.384 4.987 3.088 6.797 2.428 2.581 5.465 4.097 5.465 4.097zm-1.303-8.481l6.644-6.644a.856.856 0 111.212 1.212l-7.25 7.25a.856.856 0 01-1.212 0l-3.75-3.75a.856.856 0 111.212-1.212l3.144 3.144z",
+ { width: 24 },
+);
+
+export const file = createIcon(
+ "M369.9 97.9L286 14C277 5 264.8-.1 252.1-.1H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V131.9c0-12.7-5.1-25-14.1-34zM332.1 128H256V51.9l76.1 76.1zM48 464V48h160v104c0 13.3 10.7 24 24 24h104v288H48zm32-48h224V288l-23.5-23.5c-4.7-4.7-12.3-4.7-17 0L176 352l-39.5-39.5c-4.7-4.7-12.3-4.7-17 0L80 352v64zm48-240c-26.5 0-48 21.5-48 48s21.5 48 48 48 48-21.5 48-48-21.5-48-48-48z",
+ { width: 384, height: 512 },
+);
+
+// TODO barnabasmolnar/editor-redesign
+// couldn't find a new icon for this
+export const GroupIcon = React.memo(({ theme }: { theme: Theme }) =>
+ createIcon(
+ <>
+ <path d="M25 26H111V111H25" fill={iconFillColor(theme)} />
+ <path
+ d="M25 111C25 80.2068 25 49.4135 25 26M25 26C48.6174 26 72.2348 26 111 26H25ZM25 26C53.3671 26 81.7343 26 111 26H25ZM111 26C111 52.303 111 78.606 111 111V26ZM111 26C111 51.2947 111 76.5893 111 111V26ZM111 111C87.0792 111 63.1585 111 25 111H111ZM111 111C87.4646 111 63.9293 111 25 111H111ZM25 111C25 81.1514 25 51.3028 25 26V111Z"
+ stroke={iconFillColor(theme)}
+ strokeWidth="2"
+ />
+ <path d="M100 100H160V160H100" fill={iconFillColor(theme)} />
+ <path
+ d="M100 160C100 144.106 100 128.211 100 100M100 100C117.706 100 135.412 100 160 100H100ZM100 100C114.214 100 128.428 100 160 100H100ZM160 100C160 120.184 160 140.369 160 160V100ZM160 100C160 113.219 160 126.437 160 160V100ZM160 160C145.534 160 131.068 160 100 160H160ZM160 160C143.467 160 126.934 160 100 160H160ZM100 160C100 143.661 100 127.321 100 100V160Z"
+ stroke={iconFillColor(theme)}
+ strokeWidth="2"
+ />
+ <g
+ fill={handlerColor(theme)}
+ stroke={iconFillColor(theme)}
+ strokeWidth="6"
+ >
+ <rect x="2.5" y="2.5" width="30" height="30" />
+ <rect x="2.5" y="149.5" width="30" height="30" />
+ <rect x="147.5" y="149.5" width="30" height="30" />
+ <rect x="147.5" y="2.5" width="30" height="30" />
+ </g>
+ </>,
+ { width: 182, height: 182, mirror: true },
+ ),
+);
+
+export const UngroupIcon = React.memo(({ theme }: { theme: Theme }) =>
+ createIcon(
+ <>
+ <path d="M25 26H111V111H25" fill={iconFillColor(theme)} />
+ <path
+ d="M25 111C25 80.2068 25 49.4135 25 26M25 26C48.6174 26 72.2348 26 111 26H25ZM25 26C53.3671 26 81.7343 26 111 26H25ZM111 26C111 52.303 111 78.606 111 111V26ZM111 26C111 51.2947 111 76.5893 111 111V26ZM111 111C87.0792 111 63.1585 111 25 111H111ZM111 111C87.4646 111 63.9293 111 25 111H111ZM25 111C25 81.1514 25 51.3028 25 26V111Z"
+ stroke={iconFillColor(theme)}
+ strokeWidth="2"
+ />
+ <path d="M100 100H160V160H100" fill={iconFillColor(theme)} />
+ <path
+ d="M100 160C100 144.106 100 128.211 100 100M100 100C117.706 100 135.412 100 160 100H100ZM100 100C114.214 100 128.428 100 160 100H100ZM160 100C160 120.184 160 140.369 160 160V100ZM160 100C160 113.219 160 126.437 160 160V100ZM160 160C145.534 160 131.068 160 100 160H160ZM160 160C143.467 160 126.934 160 100 160H160ZM100 160C100 143.661 100 127.321 100 100V160Z"
+ stroke={iconFillColor(theme)}
+ strokeWidth="2"
+ />
+ <g
+ fill={handlerColor(theme)}
+ stroke={iconFillColor(theme)}
+ strokeWidth="6"
+ >
+ <rect x="2.5" y="2.5" width="30" height="30" />
+ <rect x="78.5" y="149.5" width="30" height="30" />
+ <rect x="147.5" y="149.5" width="30" height="30" />
+ <rect x="147.5" y="78.5" width="30" height="30" />
+ <rect x="105.5" y="2.5" width="30" height="30" />
+ <rect x="2.5" y="102.5" width="30" height="30" />
+ </g>
+ </>,
+ { width: 182, height: 182, mirror: true },
+ ),
+);
+
+export const FillZigZagIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path d="M5.879 2.625h8.242a3.27 3.27 0 0 1 3.254 3.254v8.242a3.27 3.27 0 0 1-3.254 3.254H5.88a3.27 3.27 0 0 1-3.254-3.254V5.88A3.27 3.27 0 0 1 5.88 2.626l-.001-.001ZM4.518 16.118l7.608-12.83m.198 13.934 5.051-9.897M2.778 9.675l9.348-6.387m-7.608 12.83 12.857-8.793" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+export const FillHachureIcon = createIcon(
+ <>
+ <path
+ d="M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ />
+ <mask
+ id="FillHachureIcon"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x={2}
+ y={2}
+ width={16}
+ height={16}
+ >
+ <path
+ d="M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z"
+ fill="currentColor"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ />
+ </mask>
+ <g mask="url(#FillHachureIcon)">
+ <path
+ d="M2.258 15.156 15.156 2.258M7.324 20.222 20.222 7.325m-20.444 5.35L12.675-.222m-8.157 18.34L17.416 5.22"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </g>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const FillCrossHatchIcon = createIcon(
+ <>
+ <g clipPath="url(#a)">
+ <path
+ d="M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ />
+ <mask
+ id="FillCrossHatchIcon"
+ style={{ maskType: "alpha" }}
+ maskUnits="userSpaceOnUse"
+ x={-1}
+ y={-1}
+ width={22}
+ height={22}
+ >
+ <path
+ d="M2.426 15.044 15.044 2.426M7.383 20 20 7.383M0 12.617 12.617 0m-7.98 17.941L17.256 5.324m-2.211 12.25L2.426 4.956M20 12.617 7.383 0m5.234 20L0 7.383m17.941 7.98L5.324 2.745"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </mask>
+ <g mask="url(#FillCrossHatchIcon)">
+ <path
+ d="M14.121 2H5.88A3.879 3.879 0 0 0 2 5.879v8.242A3.879 3.879 0 0 0 5.879 18h8.242A3.879 3.879 0 0 0 18 14.121V5.88A3.879 3.879 0 0 0 14.121 2Z"
+ fill="currentColor"
+ />
+ </g>
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const FillSolidIcon = createIcon(
+ <>
+ <g clipPath="url(#a)">
+ <path
+ d="M4.91 2.625h10.18a2.284 2.284 0 0 1 2.285 2.284v10.182a2.284 2.284 0 0 1-2.284 2.284H4.909a2.284 2.284 0 0 1-2.284-2.284V4.909a2.284 2.284 0 0 1 2.284-2.284Z"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ { ...modifiedTablerIconProps, fill: "currentColor" },
+);
+
+export const StrokeWidthBaseIcon = createIcon(
+ <>
+ <path
+ d="M4.167 10h11.666"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const StrokeWidthBoldIcon = createIcon(
+ <path
+ d="M5 10h10"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const StrokeWidthExtraBoldIcon = createIcon(
+ <path
+ d="M5 10h10"
+ stroke="currentColor"
+ strokeWidth="3.75"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const StrokeStyleSolidIcon = React.memo(({ theme }: { theme: Theme }) =>
+ createIcon(
+ <path
+ d="M6 10H34"
+ stroke={iconFillColor(theme)}
+ strokeWidth={2}
+ fill="none"
+ strokeLinecap="round"
+ />,
+ {
+ width: 40,
+ height: 20,
+ },
+ ),
+);
+
+export const StrokeStyleDashedIcon = createIcon(
+ <g strokeWidth="2">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M5 12h2" />
+ <path d="M17 12h2" />
+ <path d="M11 12h2" />
+ </g>,
+ tablerIconProps,
+);
+
+// tabler-icons: line-dotted
+export const StrokeStyleDottedIcon = createIcon(
+ <g strokeWidth="2">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M4 12v.01" />
+ <path d="M8 12v.01" />
+ <path d="M12 12v.01" />
+ <path d="M16 12v.01" />
+ <path d="M20 12v.01" />
+ </g>,
+ tablerIconProps,
+);
+
+export const SloppinessArchitectIcon = createIcon(
+ <path
+ d="M2.5 12.038c1.655-.885 5.9-3.292 8.568-4.354 2.668-1.063.101 2.821 1.32 3.104 1.218.283 5.112-1.814 5.112-1.814"
+ strokeWidth="1.25"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const SloppinessArtistIcon = createIcon(
+ <path
+ d="M2.5 12.563c1.655-.886 5.9-3.293 8.568-4.355 2.668-1.062.101 2.822 1.32 3.105 1.218.283 5.112-1.814 5.112-1.814m-13.469 2.23c2.963-1.586 6.13-5.62 7.468-4.998 1.338.623-1.153 4.11-.132 5.595 1.02 1.487 6.133-1.43 6.133-1.43"
+ strokeWidth="1.25"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const SloppinessCartoonistIcon = createIcon(
+ <path
+ d="M2.5 11.936c1.737-.879 8.627-5.346 10.42-5.268 1.795.078-.418 5.138.345 5.736.763.598 3.53-1.789 4.235-2.147M2.929 9.788c1.164-.519 5.47-3.28 6.987-3.114 1.519.165 1 3.827 2.121 4.109 1.122.281 3.839-2.016 4.606-2.42"
+ strokeWidth="1.25"
+ />,
+ modifiedTablerIconProps,
+);
+
+export const EdgeSharpIcon = createIcon(
+ <svg strokeWidth="1.5">
+ <path d="M3.33334 9.99998V6.66665C3.33334 6.04326 3.33403 4.9332 3.33539 3.33646C4.95233 3.33436 6.06276 3.33331 6.66668 3.33331H10" />
+ <path d="M13.3333 3.33331V3.34331" />
+ <path d="M16.6667 3.33331V3.34331" />
+ <path d="M16.6667 6.66669V6.67669" />
+ <path d="M16.6667 10V10.01" />
+ <path d="M3.33334 13.3333V13.3433" />
+ <path d="M16.6667 13.3333V13.3433" />
+ <path d="M3.33334 16.6667V16.6767" />
+ <path d="M6.66666 16.6667V16.6767" />
+ <path d="M10 16.6667V16.6767" />
+ <path d="M13.3333 16.6667V16.6767" />
+ <path d="M16.6667 16.6667V16.6767" />
+ </svg>,
+ modifiedTablerIconProps,
+);
+
+// tabler-icons: border-radius
+export const EdgeRoundIcon = createIcon(
+ <g
+ strokeWidth="1.5"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M4 12v-4a4 4 0 0 1 4 -4h4" />
+ <line x1="16" y1="4" x2="16" y2="4.01" />
+ <line x1="20" y1="4" x2="20" y2="4.01" />
+ <line x1="20" y1="8" x2="20" y2="8.01" />
+ <line x1="20" y1="12" x2="20" y2="12.01" />
+ <line x1="4" y1="16" x2="4" y2="16.01" />
+ <line x1="20" y1="16" x2="20" y2="16.01" />
+ <line x1="4" y1="20" x2="4" y2="20.01" />
+ <line x1="8" y1="20" x2="8" y2="20.01" />
+ <line x1="12" y1="20" x2="12" y2="20.01" />
+ <line x1="16" y1="20" x2="16" y2="20.01" />
+ <line x1="20" y1="20" x2="20" y2="20.01" />
+ </g>,
+ tablerIconProps,
+);
+
+export const ArrowheadNoneIcon = createIcon(
+ <g stroke="currentColor" opacity={0.3} strokeWidth={2}>
+ <path d="M12 12l9 0" />
+ <path d="M3 9l6 6" />
+ <path d="M3 15l6 -6" />
+ </g>,
+ tablerIconProps,
+);
+
+export const ArrowheadArrowIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ transform={flip ? "translate(40, 0) scale(-1, 1)" : ""}
+ stroke="currentColor"
+ strokeWidth={2}
+ fill="none"
+ >
+ <path d="M34 10H6M34 10L27 5M34 10L27 15" />
+ <path d="M27.5 5L34.5 10L27.5 15" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadCircleIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="currentColor"
+ transform={flip ? "translate(40, 0) scale(-1, 1)" : ""}
+ >
+ <path d="M32 10L6 10" strokeWidth={2} />
+ <circle r="4" transform="matrix(-1 0 0 1 30 10)" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadCircleOutlineIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ transform={flip ? "translate(40, 0) scale(-1, 1)" : ""}
+ strokeWidth={2}
+ >
+ <path d="M26 10L6 10" />
+ <circle r="4" transform="matrix(-1 0 0 1 30 10)" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadBarIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g transform={flip ? "translate(40, 0) scale(-1, 1)" : ""}>
+ <path
+ d="M34 10H5.99996M34 10L34 5M34 10L34 15"
+ stroke="currentColor"
+ strokeWidth={2}
+ fill="none"
+ />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadTriangleIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="currentColor"
+ transform={flip ? "translate(40, 0) scale(-1, 1)" : ""}
+ >
+ <path d="M32 10L6 10" strokeWidth={2} />
+ <path d="M27.5 5.5L34.5 10L27.5 14.5L27.5 5.5" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadTriangleOutlineIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ transform={flip ? "translate(40, 0) scale(-1, 1)" : ""}
+ strokeWidth={2}
+ strokeLinejoin="round"
+ >
+ <path d="M6,9.5H27" />
+ <path d="M27,5L34,10L27,14Z" fill="none" />
+ </g>,
+
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadDiamondIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="currentColor"
+ transform={flip ? "translate(40, 0) scale(-1, 1)" : ""}
+ strokeLinejoin="round"
+ strokeWidth={2}
+ >
+ <path d="M6,9.5H20" />
+ <path d="M27,5L34,10L27,14L20,9.5Z" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadDiamondOutlineIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ transform={flip ? "translate(40, 0) scale(-1, 1)" : ""}
+ strokeLinejoin="round"
+ strokeWidth={2}
+ >
+ <path d="M6,9.5H20" />
+ <path d="M27,5L34,10L27,14L20,9.5Z" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadCrowfootIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ transform={flip ? "" : "translate(40, 0) scale(-1, 1)"}
+ strokeLinejoin="round"
+ strokeWidth={2}
+ >
+ <path d="M34,10 H6 M15,10 L7,5 M15,10 L7,15" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadCrowfootOneIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ transform={flip ? "" : "translate(40, 0) scale(-1, 1)"}
+ strokeLinejoin="round"
+ strokeWidth={2}
+ >
+ <path d="M34,10 H6 M15,10 L15,15 L15,5" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const ArrowheadCrowfootOneOrManyIcon = React.memo(
+ ({ flip = false }: { flip?: boolean }) =>
+ createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ transform={flip ? "" : "translate(40, 0) scale(-1, 1)"}
+ strokeLinejoin="round"
+ strokeWidth={2}
+ >
+ <path d="M34,10 H6 M15,10 L15,16 L15,4 M15,10 L7,5 M15,10 L7,15" />
+ </g>,
+ { width: 40, height: 20 },
+ ),
+);
+
+export const FontSizeSmallIcon = createIcon(
+ <>
+ <g clipPath="url(#a)">
+ <path
+ d="M14.167 6.667a3.333 3.333 0 0 0-3.334-3.334H9.167a3.333 3.333 0 0 0 0 6.667h1.666a3.333 3.333 0 0 1 0 6.667H9.167a3.333 3.333 0 0 1-3.334-3.334"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const FontSizeMediumIcon = createIcon(
+ <>
+ <g clipPath="url(#a)">
+ <path
+ d="M5 16.667V3.333L10 15l5-11.667v13.334"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const FontSizeLargeIcon = createIcon(
+ <>
+ <g clipPath="url(#a)">
+ <path
+ d="M5.833 3.333v13.334h8.334"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const FontSizeExtraLargeIcon = createIcon(
+ <>
+ <path
+ d="m1.667 3.333 6.666 13.334M8.333 3.333 1.667 16.667M11.667 3.333v13.334h6.666"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const fontSizeIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M3 7v-2h13v2" />
+ <path d="M10 5v14" />
+ <path d="M12 19h-4" />
+ <path d="M15 13v-1h6v1" />
+ <path d="M18 12v7" />
+ <path d="M17 19h2" />
+ </g>,
+ tablerIconProps,
+);
+
+export const FontFamilyHeadingIcon = createIcon(
+ <>
+ <g
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M7 12h10" />
+ <path d="M7 5v14" />
+ <path d="M17 5v14" />
+ <path d="M15 19h4" />
+ <path d="M15 5h4" />
+ <path d="M5 19h4" />
+ <path d="M5 5h4" />
+ </g>
+ </>,
+ tablerIconProps,
+);
+
+export const FontFamilyNormalIcon = createIcon(
+ <>
+ <g
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M5.833 16.667v-10a3.333 3.333 0 0 1 3.334-3.334h1.666a3.333 3.333 0 0 1 3.334 3.334v10M5.833 10.833h8.334" />
+ </g>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const FontFamilyCodeIcon = createIcon(
+ <>
+ <g
+ clipPath="url(#a)"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M5.833 6.667 2.5 10l3.333 3.333M14.167 6.667 17.5 10l-3.333 3.333M11.667 3.333 8.333 16.667" />
+ </g>
+ <defs>
+ <clipPath id="a">
+ <path fill="#fff" d="M0 0h20v20H0z" />
+ </clipPath>
+ </defs>
+ </>,
+ modifiedTablerIconProps,
+);
+
+export const TextAlignLeftIcon = createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ >
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="4" y1="8" x2="20" y2="8" />
+ <line x1="4" y1="12" x2="12" y2="12" />
+ <line x1="4" y1="16" x2="16" y2="16" />
+ </g>,
+ tablerIconProps,
+);
+
+export const TextAlignCenterIcon = createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="4" y1="8" x2="20" y2="8" />
+ <line x1="8" y1="12" x2="16" y2="12" />
+ <line x1="6" y1="16" x2="18" y2="16" />
+ </g>,
+ tablerIconProps,
+);
+
+export const TextAlignRightIcon = createIcon(
+ <g
+ stroke="currentColor"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="4" y1="8" x2="20" y2="8" />
+ <line x1="10" y1="12" x2="20" y2="12" />
+ <line x1="8" y1="16" x2="20" y2="16" />
+ </g>,
+ tablerIconProps,
+);
+
+// tabler-icons: layout-align-top
+export const TextAlignTopIcon = React.memo(({ theme }: { theme: Theme }) =>
+ createIcon(
+ <g
+ strokeWidth="1.5"
+ stroke="currentColor"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="4" y1="4" x2="20" y2="4" />
+ <rect x="9" y="8" width="6" height="12" rx="2" />
+ </g>,
+ tablerIconProps,
+ ),
+);
+
+// tabler-icons: layout-align-bottom
+export const TextAlignBottomIcon = React.memo(({ theme }: { theme: Theme }) =>
+ createIcon(
+ <g
+ strokeWidth="2"
+ stroke="currentColor"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="4" y1="20" x2="20" y2="20" />
+ <rect x="9" y="4" width="6" height="12" rx="2"></rect>
+ </g>,
+ tablerIconProps,
+ ),
+);
+
+// tabler-icons: layout-align-middle
+export const TextAlignMiddleIcon = React.memo(({ theme }: { theme: Theme }) =>
+ createIcon(
+ <g
+ strokeWidth="1.5"
+ stroke="currentColor"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <line x1="4" y1="12" x2="9" y2="12" />
+ <line x1="15" y1="12" x2="20" y2="12" />
+ <rect x="9" y="6" width="6" height="12" rx="2" />
+ </g>,
+ tablerIconProps,
+ ),
+);
+
+export const angleIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M21 19h-18l9 -15" />
+ <path d="M20.615 15.171h.015" />
+ <path d="M19.515 11.771h.015" />
+ <path d="M17.715 8.671h.015" />
+ <path d="M15.415 5.971h.015" />
+ </g>,
+ tablerIconProps,
+);
+
+export const publishIcon = createIcon(
+ <path
+ d="M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zM393.4 288H328v112c0 8.8-7.2 16-16 16h-48c-8.8 0-16-7.2-16-16V288h-65.4c-14.3 0-21.4-17.2-11.3-27.3l105.4-105.4c6.2-6.2 16.4-6.2 22.6 0l105.4 105.4c10.1 10.1 2.9 27.3-11.3 27.3z"
+ fill="currentColor"
+ />,
+ { width: 640, height: 512 },
+);
+
+export const eraser = createIcon(
+ <path d="M480 416C497.7 416 512 430.3 512 448C512 465.7 497.7 480 480 480H150.6C133.7 480 117.4 473.3 105.4 461.3L25.37 381.3C.3786 356.3 .3786 315.7 25.37 290.7L258.7 57.37C283.7 32.38 324.3 32.38 349.3 57.37L486.6 194.7C511.6 219.7 511.6 260.3 486.6 285.3L355.9 416H480zM265.4 416L332.7 348.7L195.3 211.3L70.63 336L150.6 416L265.4 416z" />,
+);
+
+export const handIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M8 13v-7.5a1.5 1.5 0 0 1 3 0v6.5"></path>
+ <path d="M11 5.5v-2a1.5 1.5 0 1 1 3 0v8.5"></path>
+ <path d="M14 5.5a1.5 1.5 0 0 1 3 0v6.5"></path>
+ <path d="M17 7.5a1.5 1.5 0 0 1 3 0v8.5a6 6 0 0 1 -6 6h-2h.208a6 6 0 0 1 -5.012 -2.7a69.74 69.74 0 0 1 -.196 -.3c-.312 -.479 -1.407 -2.388 -3.286 -5.728a1.5 1.5 0 0 1 .536 -2.022a1.867 1.867 0 0 1 2.28 .28l1.47 1.47"></path>
+ </g>,
+ tablerIconProps,
+);
+
+export const downloadIcon = createIcon(
+ <>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2"></path>
+ <path d="M7 11l5 5l5 -5"></path>
+ <path d="M12 4l0 12"></path>
+ </>,
+ tablerIconProps,
+);
+
+export const copyIcon = createIcon(
+ <>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M8 8m0 2a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2z"></path>
+ <path d="M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"></path>
+ </>,
+ tablerIconProps,
+);
+
+export const cutIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M7 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" />
+ <path d="M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" />
+ <path d="M9.15 14.85l8.85 -10.85" />
+ <path d="M6 4l8.85 10.85" />
+ </g>,
+ tablerIconProps,
+);
+
+export const helpIcon = createIcon(
+ <>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path>
+ <path d="M12 17l0 .01"></path>
+ <path d="M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"></path>
+ </>,
+ tablerIconProps,
+);
+
+export const playerPlayIcon = createIcon(
+ <>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M7 4v16l13 -8z"></path>
+ </>,
+ tablerIconProps,
+);
+
+export const playerStopFilledIcon = createIcon(
+ <>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path
+ d="M17 4h-10a3 3 0 0 0 -3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3 -3v-10a3 3 0 0 0 -3 -3z"
+ strokeWidth="0"
+ fill="currentColor"
+ ></path>
+ </>,
+ tablerIconProps,
+);
+
+export const tablerCheckIcon = createIcon(
+ <>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M5 12l5 5l10 -10"></path>
+ </>,
+ tablerIconProps,
+);
+
+export const alertTriangleIcon = createIcon(
+ <>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M10.24 3.957l-8.422 14.06a1.989 1.989 0 0 0 1.7 2.983h16.845a1.989 1.989 0 0 0 1.7 -2.983l-8.423 -14.06a1.989 1.989 0 0 0 -3.4 0z" />
+ <path d="M12 9v4" />
+ <path d="M12 17h.01" />
+ </>,
+ tablerIconProps,
+);
+
+export const eyeDropperIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M11 7l6 6"></path>
+ <path d="M4 16l11.7 -11.7a1 1 0 0 1 1.4 0l2.6 2.6a1 1 0 0 1 0 1.4l-11.7 11.7h-4v-4z"></path>
+ </g>,
+ tablerIconProps,
+);
+
+export const extraToolsIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M12 3l-4 7h8z"></path>
+ <path d="M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"></path>
+ <path d="M4 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z"></path>
+ </g>,
+ tablerIconProps,
+);
+
+export const frameToolIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M4 7l16 0"></path>
+ <path d="M4 17l16 0"></path>
+ <path d="M7 4l0 16"></path>
+ <path d="M17 4l0 16"></path>
+ </g>,
+ tablerIconProps,
+);
+
+export const mermaidLogoIcon = createIcon(
+ <path
+ fill="currentColor"
+ d="M407.48,111.18C335.587,108.103 269.573,152.338 245.08,220C220.587,152.338 154.573,108.103 82.68,111.18C80.285,168.229 107.577,222.632 154.74,254.82C178.908,271.419 193.35,298.951 193.27,328.27L193.27,379.13L296.9,379.13L296.9,328.27C296.816,298.953 311.255,271.42 335.42,254.82C382.596,222.644 409.892,168.233 407.48,111.18Z"
+ />,
+);
+
+export const ArrowRightIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path d="M4.16602 10H15.8327" />
+ <path d="M12.5 13.3333L15.8333 10" />
+ <path d="M12.5 6.66666L15.8333 9.99999" />
+ </g>,
+ modifiedTablerIconProps,
+);
+
+export const laserPointerToolIcon = createIcon(
+ <g
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.25"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ transform="rotate(90 10 10)"
+ >
+ <path
+ clipRule="evenodd"
+ d="m9.644 13.69 7.774-7.773a2.357 2.357 0 0 0-3.334-3.334l-7.773 7.774L8 12l1.643 1.69Z"
+ />
+ <path d="m13.25 3.417 3.333 3.333M10 10l2-2M5 15l3-3M2.156 17.894l1-1M5.453 19.029l-.144-1.407M2.377 11.887l.866 1.118M8.354 17.273l-1.194-.758M.953 14.652l1.408.13" />
+ </g>,
+
+ 20,
+);
+
+export const MagicIcon = createIcon(
+ <g stroke="currentColor" fill="none">
+ <path stroke="none" d="M0 0h24v24H0z" />
+ <path d="M6 21l15 -15l-3 -3l-15 15l3 3" />
+ <path d="M15 6l3 3" />
+ <path d="M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2" />
+ <path d="M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2" />
+ </g>,
+ tablerIconProps,
+);
+
+export const MagicIconThin = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" />
+ <path d="M6 21l15 -15l-3 -3l-15 15l3 3" />
+ <path d="M15 6l3 3" />
+ <path d="M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2" />
+ <path d="M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2" />
+ </g>,
+ tablerIconProps,
+);
+
+export const OpenAIIcon = createIcon(
+ <g stroke="currentColor" fill="none">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M11.217 19.384a3.501 3.501 0 0 0 6.783 -1.217v-5.167l-6 -3.35" />
+ <path d="M5.214 15.014a3.501 3.501 0 0 0 4.446 5.266l4.34 -2.534v-6.946" />
+ <path d="M6 7.63c-1.391 -.236 -2.787 .395 -3.534 1.689a3.474 3.474 0 0 0 1.271 4.745l4.263 2.514l6 -3.348" />
+ <path d="M12.783 4.616a3.501 3.501 0 0 0 -6.783 1.217v5.067l6 3.45" />
+ <path d="M18.786 8.986a3.501 3.501 0 0 0 -4.446 -5.266l-4.34 2.534v6.946" />
+ <path d="M18 16.302c1.391 .236 2.787 -.395 3.534 -1.689a3.474 3.474 0 0 0 -1.271 -4.745l-4.308 -2.514l-5.955 3.42" />
+ </g>,
+ tablerIconProps,
+);
+
+export const fullscreenIcon = createIcon(
+ <g stroke="currentColor" fill="none">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M4 8v-2a2 2 0 0 1 2 -2h2" />
+ <path d="M4 16v2a2 2 0 0 0 2 2h2" />
+ <path d="M16 4h2a2 2 0 0 1 2 2v2" />
+ <path d="M16 20h2a2 2 0 0 0 2 -2v-2" />
+ </g>,
+ tablerIconProps,
+);
+
+export const eyeIcon = createIcon(
+ <g stroke="currentColor" fill="none" strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0" />
+ <path d="M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6" />
+ </g>,
+ tablerIconProps,
+);
+
+export const eyeClosedIcon = createIcon(
+ <g stroke="currentColor" fill="none">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M10.585 10.587a2 2 0 0 0 2.829 2.828" />
+ <path d="M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87" />
+ <path d="M3 3l18 18" />
+ </g>,
+ tablerIconProps,
+);
+
+export const brainIcon = createIcon(
+ <g stroke="currentColor" fill="none">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M15.5 13a3.5 3.5 0 0 0 -3.5 3.5v1a3.5 3.5 0 0 0 7 0v-1.8" />
+ <path d="M8.5 13a3.5 3.5 0 0 1 3.5 3.5v1a3.5 3.5 0 0 1 -7 0v-1.8" />
+ <path d="M17.5 16a3.5 3.5 0 0 0 0 -7h-.5" />
+ <path d="M19 9.3v-2.8a3.5 3.5 0 0 0 -7 0" />
+ <path d="M6.5 16a3.5 3.5 0 0 1 0 -7h.5" />
+ <path d="M5 9.3v-2.8a3.5 3.5 0 0 1 7 0v10" />
+ </g>,
+ tablerIconProps,
+);
+
+export const brainIconThin = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M15.5 13a3.5 3.5 0 0 0 -3.5 3.5v1a3.5 3.5 0 0 0 7 0v-1.8" />
+ <path d="M8.5 13a3.5 3.5 0 0 1 3.5 3.5v1a3.5 3.5 0 0 1 -7 0v-1.8" />
+ <path d="M17.5 16a3.5 3.5 0 0 0 0 -7h-.5" />
+ <path d="M19 9.3v-2.8a3.5 3.5 0 0 0 -7 0" />
+ <path d="M6.5 16a3.5 3.5 0 0 1 0 -7h.5" />
+ <path d="M5 9.3v-2.8a3.5 3.5 0 0 1 7 0v10" />
+ </g>,
+ tablerIconProps,
+);
+
+export const searchIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0" />
+ <path d="M21 21l-6 -6" />
+ </g>,
+ tablerIconProps,
+);
+
+export const clockIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M20.984 12.53a9 9 0 1 0 -7.552 8.355" />
+ <path d="M12 7v5l3 3" />
+ <path d="M19 16l-2 3h4l-2 3" />
+ </g>,
+ tablerIconProps,
+);
+
+export const microphoneIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M9 2m0 3a3 3 0 0 1 3 -3h0a3 3 0 0 1 3 3v5a3 3 0 0 1 -3 3h0a3 3 0 0 1 -3 -3z" />
+ <path d="M5 10a7 7 0 0 0 14 0" />
+ <path d="M8 21l8 0" />
+ <path d="M12 17l0 4" />
+ </g>,
+ tablerIconProps,
+);
+
+export const microphoneMutedIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M3 3l18 18" />
+ <path d="M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1" />
+ <path d="M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85" />
+ <path d="M8 21l8 0" />
+ <path d="M12 17l0 4" />
+ </g>,
+ tablerIconProps,
+);
+
+export const boltIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M13 3l0 7l6 0l-8 11l0 -7l-6 0l8 -11" />
+ </g>,
+ tablerIconProps,
+);
+export const selectAllIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M8 8m0 1a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1z" />
+ <path d="M12 20v.01" />
+ <path d="M16 20v.01" />
+ <path d="M8 20v.01" />
+ <path d="M4 20v.01" />
+ <path d="M4 16v.01" />
+ <path d="M4 12v.01" />
+ <path d="M4 8v.01" />
+ <path d="M4 4v.01" />
+ <path d="M8 4v.01" />
+ <path d="M12 4v.01" />
+ <path d="M16 4v.01" />
+ <path d="M20 4v.01" />
+ <path d="M20 8v.01" />
+ <path d="M20 12v.01" />
+ <path d="M20 16v.01" />
+ <path d="M20 20v.01" />
+ </g>,
+ tablerIconProps,
+);
+
+export const abacusIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M5 3v18" />
+ <path d="M19 21v-18" />
+ <path d="M5 7h14" />
+ <path d="M5 15h14" />
+ <path d="M8 13v4" />
+ <path d="M11 13v4" />
+ <path d="M16 13v4" />
+ <path d="M14 5v4" />
+ <path d="M11 5v4" />
+ <path d="M8 5v4" />
+ <path d="M3 21h18" />
+ </g>,
+ tablerIconProps,
+);
+
+export const flipVertical = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M3 12l18 0" />
+ <path d="M7 16l10 0l-10 5l0 -5" />
+ <path d="M7 8l10 0l-10 -5l0 5" />
+ </g>,
+ tablerIconProps,
+);
+
+export const flipHorizontal = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M12 3l0 18" />
+ <path d="M16 7l0 10l5 0l-5 -10" />
+ <path d="M8 7l0 10l-5 0l5 -10" />
+ </g>,
+ tablerIconProps,
+);
+
+export const paintIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M5 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v2a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z" />
+ <path d="M19 6h1a2 2 0 0 1 2 2a5 5 0 0 1 -5 5l-5 0v2" />
+ <path d="M10 15m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z" />
+ </g>,
+ tablerIconProps,
+);
+
+export const zoomAreaIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M15 15m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0" />
+ <path d="M22 22l-3 -3" />
+ <path d="M6 18h-1a2 2 0 0 1 -2 -2v-1" />
+ <path d="M3 11v-1" />
+ <path d="M3 6v-1a2 2 0 0 1 2 -2h1" />
+ <path d="M10 3h1" />
+ <path d="M15 3h1a2 2 0 0 1 2 2v1" />
+ </g>,
+ tablerIconProps,
+);
+
+export const svgIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M14 3v4a1 1 0 0 0 1 1h4" />
+ <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4" />
+ <path d="M4 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75" />
+ <path d="M10 15l2 6l2 -6" />
+ <path d="M20 15h-1a2 2 0 0 0 -2 2v2a2 2 0 0 0 2 2h1v-3" />
+ </g>,
+ tablerIconProps,
+);
+
+export const pngIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M14 3v4a1 1 0 0 0 1 1h4" />
+ <path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4" />
+ <path d="M20 15h-1a2 2 0 0 0 -2 2v2a2 2 0 0 0 2 2h1v-3" />
+ <path d="M5 18h1.5a1.5 1.5 0 0 0 0 -3h-1.5v6" />
+ <path d="M11 21v-6l3 6v-6" />
+ </g>,
+ tablerIconProps,
+);
+
+export const magnetIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M4 13v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a2 2 0 0 0 6 0v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a8 8 0 0 1 -16 0" />
+ <path d="M4 8l5 0" />
+ <path d="M15 8l4 0" />
+ </g>,
+ tablerIconProps,
+);
+
+export const coffeeIcon = createIcon(
+ <g strokeWidth={1.25}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M3 14c.83 .642 2.077 1.017 3.5 1c1.423 .017 2.67 -.358 3.5 -1c.83 -.642 2.077 -1.017 3.5 -1c1.423 -.017 2.67 .358 3.5 1" />
+ <path d="M8 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2" />
+ <path d="M12 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2" />
+ <path d="M3 10h14v5a6 6 0 0 1 -6 6h-2a6 6 0 0 1 -6 -6v-5z" />
+ <path d="M16.746 16.726a3 3 0 1 0 .252 -5.555" />
+ </g>,
+ tablerIconProps,
+);
+
+export const DeviceDesktopIcon = createIcon(
+ <g stroke="currentColor">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M3 5a1 1 0 0 1 1-1h16a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-16a1 1 0 0 1-1-1v-10zM7 20h10M9 16v4M15 16v4" />
+ </g>,
+ { ...tablerIconProps, strokeWidth: 1.5 },
+);
+
+// login
+export const loginIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M15 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2" />
+ <path d="M21 12h-13l3 -3" />
+ <path d="M11 15l-3 -3" />
+ </g>,
+ tablerIconProps,
+);
+
+export const youtubeIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M2 8a4 4 0 0 1 4 -4h12a4 4 0 0 1 4 4v8a4 4 0 0 1 -4 4h-12a4 4 0 0 1 -4 -4v-8z" />
+ <path d="M10 9l5 3l-5 3z" />
+ </g>,
+ tablerIconProps,
+);
+
+export const gridIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M3 6h18" />
+ <path d="M3 12h18" />
+ <path d="M3 18h18" />
+ <path d="M6 3v18" />
+ <path d="M12 3v18" />
+ <path d="M18 3v18" />
+ </g>,
+ tablerIconProps,
+);
+
+export const lineEditorIcon = createIcon(
+ <g strokeWidth={1.5}>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M17 3m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z" />
+ <path d="M3 17m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z" />
+ <path d="M17 5c-6.627 0 -12 5.373 -12 12" />
+ </g>,
+ tablerIconProps,
+);
+
+// arrow-up-right (modified)
+export const sharpArrowIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M6 18l12 -12" />
+ <path d="M18 10v-4h-4" />
+ </g>,
+ tablerIconProps,
+);
+
+// arrow-guide (modified)
+export const elbowArrowIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M4,19L10,19C11.097,19 12,18.097 12,17L12,9C12,7.903 12.903,7 14,7L21,7" />
+ <path d="M18 4l3 3l-3 3" />
+ </g>,
+ tablerIconProps,
+);
+
+// arrow-ramp-right-2 (heavily modified)
+export const roundArrowIcon = createIcon(
+ <g>
+ <path d="M16,12L20,9L16,6" />
+ <path d="M6 20c0 -6.075 4.925 -11 11 -11h3" />
+ </g>,
+ tablerIconProps,
+);
+
+export const collapseDownIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M6 9l6 6l6 -6" />
+ </g>,
+ tablerIconProps,
+);
+
+export const collapseUpIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M6 15l6 -6l6 6" />
+ </g>,
+ tablerIconProps,
+);
+
+export const upIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M6 15l6 -6l6 6" />
+ </g>,
+ tablerIconProps,
+);
+
+export const cropIcon = createIcon(
+ <g strokeWidth="1.25">
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M8 5v10a1 1 0 0 0 1 1h10" />
+ <path d="M5 8h10a1 1 0 0 1 1 1v10" />
+ </g>,
+ tablerIconProps,
+);
+
+export const elementLinkIcon = createIcon(
+ <g>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
+ <path d="M5 5m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" />
+ <path d="M19 5m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" />
+ <path d="M5 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" />
+ <path d="M19 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" />
+ <path d="M5 7l0 10" />
+ <path d="M7 5l10 0" />
+ <path d="M7 19l10 0" />
+ <path d="M19 7l0 10" />
+ </g>,
+ tablerIconProps,
+);
diff --git a/packages/excalidraw/components/live-collaboration/LiveCollaborationTrigger.scss b/packages/excalidraw/components/live-collaboration/LiveCollaborationTrigger.scss
new file mode 100644
index 0000000..573fbcc
--- /dev/null
+++ b/packages/excalidraw/components/live-collaboration/LiveCollaborationTrigger.scss
@@ -0,0 +1,66 @@
+@import "../../css/variables.module.scss";
+
+.excalidraw {
+ .collab-button {
+ --button-bg: var(--color-primary);
+ --button-color: var(--color-surface-lowest);
+ --button-border: var(--color-primary);
+
+ --button-width: var(--lg-button-size);
+ --button-height: var(--lg-button-size);
+
+ --button-hover-bg: var(--color-primary-darker);
+ --button-hover-border: var(--color-primary-darker);
+
+ --button-active-bg: var(--color-primary-darker);
+
+ box-shadow: 0 0 0 1px var(--color-surface-lowest);
+
+ flex-shrink: 0;
+
+ // double .active to force specificity
+ &.active.active {
+ background-color: #0fb884;
+ border-color: #0fb884;
+
+ svg {
+ color: #fff;
+ }
+
+ &:hover,
+ &:active {
+ background-color: #0fb884;
+ border-color: #0fb884;
+ }
+ }
+ }
+
+ .CollabButton.is-collaborating {
+ background-color: var(--button-special-active-bg-color);
+
+ .ToolIcon__icon svg,
+ .ToolIcon__label {
+ color: var(--icon-green-fill-color);
+ }
+ }
+
+ .CollabButton-collaborators {
+ :root[dir="ltr"] & {
+ right: -5px;
+ }
+ :root[dir="rtl"] & {
+ left: -5px;
+ }
+ min-width: 1em;
+ min-height: 1em;
+ line-height: 1;
+ position: absolute;
+ bottom: -5px;
+ padding: 3px;
+ border-radius: 50%;
+ background-color: $oc-green-2;
+ color: $oc-green-9;
+ font-size: 0.6rem;
+ font-family: "Cascadia";
+ }
+}
diff --git a/packages/excalidraw/components/live-collaboration/LiveCollaborationTrigger.tsx b/packages/excalidraw/components/live-collaboration/LiveCollaborationTrigger.tsx
new file mode 100644
index 0000000..a22bc52
--- /dev/null
+++ b/packages/excalidraw/components/live-collaboration/LiveCollaborationTrigger.tsx
@@ -0,0 +1,42 @@
+import { t } from "../../i18n";
+import { share } from "../icons";
+import { Button } from "../Button";
+
+import clsx from "clsx";
+
+import "./LiveCollaborationTrigger.scss";
+import { useUIAppState } from "../../context/ui-appState";
+
+const LiveCollaborationTrigger = ({
+ isCollaborating,
+ onSelect,
+ ...rest
+}: {
+ isCollaborating: boolean;
+ onSelect: () => void;
+} & React.ButtonHTMLAttributes<HTMLButtonElement>) => {
+ const appState = useUIAppState();
+
+ const showIconOnly = appState.width < 830;
+
+ return (
+ <Button
+ {...rest}
+ className={clsx("collab-button", { active: isCollaborating })}
+ type="button"
+ onSelect={onSelect}
+ style={{ position: "relative", width: showIconOnly ? undefined : "auto" }}
+ title={t("labels.liveCollaboration")}
+ >
+ {showIconOnly ? share : t("labels.share")}
+ {appState.collaborators.size > 0 && (
+ <div className="CollabButton-collaborators">
+ {appState.collaborators.size}
+ </div>
+ )}
+ </Button>
+ );
+};
+
+export default LiveCollaborationTrigger;
+LiveCollaborationTrigger.displayName = "LiveCollaborationTrigger";
diff --git a/packages/excalidraw/components/main-menu/DefaultItems.scss b/packages/excalidraw/components/main-menu/DefaultItems.scss
new file mode 100644
index 0000000..404df84
--- /dev/null
+++ b/packages/excalidraw/components/main-menu/DefaultItems.scss
@@ -0,0 +1,21 @@
+.excalidraw {
+ .ActiveFile {
+ .ActiveFile__fileName {
+ display: flex;
+ align-items: center;
+
+ span {
+ text-overflow: ellipsis;
+ overflow: hidden;
+ white-space: nowrap;
+ width: 9.3em;
+ }
+
+ svg {
+ width: 1.15em;
+ margin-inline-end: 0.3em;
+ transform: scaleY(0.9);
+ }
+ }
+ }
+}
diff --git a/packages/excalidraw/components/main-menu/DefaultItems.tsx b/packages/excalidraw/components/main-menu/DefaultItems.tsx
new file mode 100644
index 0000000..632ea4f
--- /dev/null
+++ b/packages/excalidraw/components/main-menu/DefaultItems.tsx
@@ -0,0 +1,391 @@
+import { getShortcutFromShortcutName } from "../../actions/shortcuts";
+import { useI18n } from "../../i18n";
+import {
+ useExcalidrawSetAppState,
+ useExcalidrawActionManager,
+ useExcalidrawElements,
+ useAppProps,
+} from "../App";
+import {
+ boltIcon,
+ DeviceDesktopIcon,
+ ExportIcon,
+ ExportImageIcon,
+ HelpIcon,
+ LoadIcon,
+ MoonIcon,
+ save,
+ searchIcon,
+ SunIcon,
+ TrashIcon,
+ usersIcon,
+} from "../icons";
+import { GithubIcon, DiscordIcon, XBrandIcon } from "../icons";
+import DropdownMenuItem from "../dropdownMenu/DropdownMenuItem";
+import DropdownMenuItemLink from "../dropdownMenu/DropdownMenuItemLink";
+import {
+ actionClearCanvas,
+ actionLoadScene,
+ actionSaveToActiveFile,
+ actionShortcuts,
+ actionToggleSearchMenu,
+ actionToggleTheme,
+} from "../../actions";
+import clsx from "clsx";
+import { activeConfirmDialogAtom } from "../ActiveConfirmDialog";
+import { useSetAtom } from "../../editor-jotai";
+import { useUIAppState } from "../../context/ui-appState";
+import { openConfirmModal } from "../OverwriteConfirm/OverwriteConfirmState";
+import Trans from "../Trans";
+import DropdownMenuItemContentRadio from "../dropdownMenu/DropdownMenuItemContentRadio";
+import { THEME } from "../../constants";
+import type { Theme } from "../../element/types";
+import { trackEvent } from "../../analytics";
+import "./DefaultItems.scss";
+
+export const LoadScene = () => {
+ const { t } = useI18n();
+ const actionManager = useExcalidrawActionManager();
+ const elements = useExcalidrawElements();
+
+ if (!actionManager.isActionEnabled(actionLoadScene)) {
+ return null;
+ }
+
+ const handleSelect = async () => {
+ if (
+ !elements.length ||
+ (await openConfirmModal({
+ title: t("overwriteConfirm.modal.loadFromFile.title"),
+ actionLabel: t("overwriteConfirm.modal.loadFromFile.button"),
+ color: "warning",
+ description: (
+ <Trans
+ i18nKey="overwriteConfirm.modal.loadFromFile.description"
+ bold={(text) => <strong>{text}</strong>}
+ br={() => <br />}
+ />
+ ),
+ }))
+ ) {
+ actionManager.executeAction(actionLoadScene);
+ }
+ };
+
+ return (
+ <DropdownMenuItem
+ icon={LoadIcon}
+ onSelect={handleSelect}
+ data-testid="load-button"
+ shortcut={getShortcutFromShortcutName("loadScene")}
+ aria-label={t("buttons.load")}
+ >
+ {t("buttons.load")}
+ </DropdownMenuItem>
+ );
+};
+LoadScene.displayName = "LoadScene";
+
+export const SaveToActiveFile = () => {
+ const { t } = useI18n();
+ const actionManager = useExcalidrawActionManager();
+
+ if (!actionManager.isActionEnabled(actionSaveToActiveFile)) {
+ return null;
+ }
+
+ return (
+ <DropdownMenuItem
+ shortcut={getShortcutFromShortcutName("saveScene")}
+ data-testid="save-button"
+ onSelect={() => actionManager.executeAction(actionSaveToActiveFile)}
+ icon={save}
+ aria-label={`${t("buttons.save")}`}
+ >{`${t("buttons.save")}`}</DropdownMenuItem>
+ );
+};
+SaveToActiveFile.displayName = "SaveToActiveFile";
+
+export const SaveAsImage = () => {
+ const setAppState = useExcalidrawSetAppState();
+ const { t } = useI18n();
+ return (
+ <DropdownMenuItem
+ icon={ExportImageIcon}
+ data-testid="image-export-button"
+ onSelect={() => setAppState({ openDialog: { name: "imageExport" } })}
+ shortcut={getShortcutFromShortcutName("imageExport")}
+ aria-label={t("buttons.exportImage")}
+ >
+ {t("buttons.exportImage")}
+ </DropdownMenuItem>
+ );
+};
+SaveAsImage.displayName = "SaveAsImage";
+
+export const CommandPalette = (opts?: { className?: string }) => {
+ const setAppState = useExcalidrawSetAppState();
+ const { t } = useI18n();
+
+ return (
+ <DropdownMenuItem
+ icon={boltIcon}
+ data-testid="command-palette-button"
+ onSelect={() => {
+ trackEvent("command_palette", "open", "menu");
+ setAppState({ openDialog: { name: "commandPalette" } });
+ }}
+ shortcut={getShortcutFromShortcutName("commandPalette")}
+ aria-label={t("commandPalette.title")}
+ className={opts?.className}
+ >
+ {t("commandPalette.title")}
+ </DropdownMenuItem>
+ );
+};
+CommandPalette.displayName = "CommandPalette";
+
+export const SearchMenu = (opts?: { className?: string }) => {
+ const { t } = useI18n();
+ const actionManager = useExcalidrawActionManager();
+
+ return (
+ <DropdownMenuItem
+ icon={searchIcon}
+ data-testid="search-menu-button"
+ onSelect={() => {
+ actionManager.executeAction(actionToggleSearchMenu);
+ }}
+ shortcut={getShortcutFromShortcutName("searchMenu")}
+ aria-label={t("search.title")}
+ className={opts?.className}
+ >
+ {t("search.title")}
+ </DropdownMenuItem>
+ );
+};
+SearchMenu.displayName = "SearchMenu";
+
+export const Help = () => {
+ const { t } = useI18n();
+
+ const actionManager = useExcalidrawActionManager();
+
+ return (
+ <DropdownMenuItem
+ data-testid="help-menu-item"
+ icon={HelpIcon}
+ onSelect={() => actionManager.executeAction(actionShortcuts)}
+ shortcut="?"
+ aria-label={t("helpDialog.title")}
+ >
+ {t("helpDialog.title")}
+ </DropdownMenuItem>
+ );
+};
+Help.displayName = "Help";
+
+export const ClearCanvas = () => {
+ const { t } = useI18n();
+
+ const setActiveConfirmDialog = useSetAtom(activeConfirmDialogAtom);
+ const actionManager = useExcalidrawActionManager();
+
+ if (!actionManager.isActionEnabled(actionClearCanvas)) {
+ return null;
+ }
+
+ return (
+ <DropdownMenuItem
+ icon={TrashIcon}
+ onSelect={() => setActiveConfirmDialog("clearCanvas")}
+ data-testid="clear-canvas-button"
+ aria-label={t("buttons.clearReset")}
+ >
+ {t("buttons.clearReset")}
+ </DropdownMenuItem>
+ );
+};
+ClearCanvas.displayName = "ClearCanvas";
+
+export const ToggleTheme = (
+ props:
+ | {
+ allowSystemTheme: true;
+ theme: Theme | "system";
+ onSelect: (theme: Theme | "system") => void;
+ }
+ | {
+ allowSystemTheme?: false;
+ onSelect?: (theme: Theme) => void;
+ },
+) => {
+ const { t } = useI18n();
+ const appState = useUIAppState();
+ const actionManager = useExcalidrawActionManager();
+ const shortcut = getShortcutFromShortcutName("toggleTheme");
+
+ if (!actionManager.isActionEnabled(actionToggleTheme)) {
+ return null;
+ }
+
+ if (props?.allowSystemTheme) {
+ return (
+ <DropdownMenuItemContentRadio
+ name="theme"
+ value={props.theme}
+ onChange={(value: Theme | "system") => props.onSelect(value)}
+ choices={[
+ {
+ value: THEME.LIGHT,
+ label: SunIcon,
+ ariaLabel: `${t("buttons.lightMode")} - ${shortcut}`,
+ },
+ {
+ value: THEME.DARK,
+ label: MoonIcon,
+ ariaLabel: `${t("buttons.darkMode")} - ${shortcut}`,
+ },
+ {
+ value: "system",
+ label: DeviceDesktopIcon,
+ ariaLabel: t("buttons.systemMode"),
+ },
+ ]}
+ >
+ {t("labels.theme")}
+ </DropdownMenuItemContentRadio>
+ );
+ }
+
+ return (
+ <DropdownMenuItem
+ onSelect={(event) => {
+ // do not close the menu when changing theme
+ event.preventDefault();
+
+ if (props?.onSelect) {
+ props.onSelect(
+ appState.theme === THEME.DARK ? THEME.LIGHT : THEME.DARK,
+ );
+ } else {
+ return actionManager.executeAction(actionToggleTheme);
+ }
+ }}
+ icon={appState.theme === THEME.DARK ? SunIcon : MoonIcon}
+ data-testid="toggle-dark-mode"
+ shortcut={shortcut}
+ aria-label={
+ appState.theme === THEME.DARK
+ ? t("buttons.lightMode")
+ : t("buttons.darkMode")
+ }
+ >
+ {appState.theme === THEME.DARK
+ ? t("buttons.lightMode")
+ : t("buttons.darkMode")}
+ </DropdownMenuItem>
+ );
+};
+ToggleTheme.displayName = "ToggleTheme";
+
+export const ChangeCanvasBackground = () => {
+ const { t } = useI18n();
+ const appState = useUIAppState();
+ const actionManager = useExcalidrawActionManager();
+ const appProps = useAppProps();
+
+ if (
+ appState.viewModeEnabled ||
+ !appProps.UIOptions.canvasActions.changeViewBackgroundColor
+ ) {
+ return null;
+ }
+ return (
+ <div style={{ marginTop: "0.5rem" }}>
+ <div
+ data-testid="canvas-background-label"
+ style={{ fontSize: ".75rem", marginBottom: ".5rem" }}
+ >
+ {t("labels.canvasBackground")}
+ </div>
+ <div style={{ padding: "0 0.625rem" }}>
+ {actionManager.renderAction("changeViewBackgroundColor")}
+ </div>
+ </div>
+ );
+};
+ChangeCanvasBackground.displayName = "ChangeCanvasBackground";
+
+export const Export = () => {
+ const { t } = useI18n();
+ const setAppState = useExcalidrawSetAppState();
+ return (
+ <DropdownMenuItem
+ icon={ExportIcon}
+ onSelect={() => {
+ setAppState({ openDialog: { name: "jsonExport" } });
+ }}
+ data-testid="json-export-button"
+ aria-label={t("buttons.export")}
+ >
+ {t("buttons.export")}
+ </DropdownMenuItem>
+ );
+};
+Export.displayName = "Export";
+
+export const Socials = () => {
+ const { t } = useI18n();
+
+ return (
+ <>
+ <DropdownMenuItemLink
+ icon={GithubIcon}
+ href="https://github.com/excalidraw/excalidraw"
+ aria-label="GitHub"
+ >
+ GitHub
+ </DropdownMenuItemLink>
+ <DropdownMenuItemLink
+ icon={XBrandIcon}
+ href="https://x.com/excalidraw"
+ aria-label="X"
+ >
+ {t("labels.followUs")}
+ </DropdownMenuItemLink>
+ <DropdownMenuItemLink
+ icon={DiscordIcon}
+ href="https://discord.gg/UexuTaE"
+ aria-label="Discord"
+ >
+ {t("labels.discordChat")}
+ </DropdownMenuItemLink>
+ </>
+ );
+};
+Socials.displayName = "Socials";
+
+export const LiveCollaborationTrigger = ({
+ onSelect,
+ isCollaborating,
+}: {
+ onSelect: () => void;
+ isCollaborating: boolean;
+}) => {
+ const { t } = useI18n();
+ return (
+ <DropdownMenuItem
+ data-testid="collab-button"
+ icon={usersIcon}
+ className={clsx({
+ "active-collab": isCollaborating,
+ })}
+ onSelect={onSelect}
+ >
+ {t("labels.liveCollaboration")}
+ </DropdownMenuItem>
+ );
+};
+
+LiveCollaborationTrigger.displayName = "LiveCollaborationTrigger";
diff --git a/packages/excalidraw/components/main-menu/MainMenu.tsx b/packages/excalidraw/components/main-menu/MainMenu.tsx
new file mode 100644
index 0000000..07afd3c
--- /dev/null
+++ b/packages/excalidraw/components/main-menu/MainMenu.tsx
@@ -0,0 +1,84 @@
+import React from "react";
+import { useDevice, useExcalidrawSetAppState } from "../App";
+import DropdownMenu from "../dropdownMenu/DropdownMenu";
+
+import * as DefaultItems from "./DefaultItems";
+
+import { UserList } from "../UserList";
+import { t } from "../../i18n";
+import { HamburgerMenuIcon } from "../icons";
+import { withInternalFallback } from "../hoc/withInternalFallback";
+import { composeEventHandlers } from "../../utils";
+import { useTunnels } from "../../context/tunnels";
+import { useUIAppState } from "../../context/ui-appState";
+
+const MainMenu = Object.assign(
+ withInternalFallback(
+ "MainMenu",
+ ({
+ children,
+ onSelect,
+ }: {
+ children?: React.ReactNode;
+ /**
+ * Called when any menu item is selected (clicked on).
+ */
+ onSelect?: (event: Event) => void;
+ }) => {
+ const { MainMenuTunnel } = useTunnels();
+ const device = useDevice();
+ const appState = useUIAppState();
+ const setAppState = useExcalidrawSetAppState();
+ const onClickOutside = device.editor.isMobile
+ ? undefined
+ : () => setAppState({ openMenu: null });
+
+ return (
+ <MainMenuTunnel.In>
+ <DropdownMenu open={appState.openMenu === "canvas"}>
+ <DropdownMenu.Trigger
+ onToggle={() => {
+ setAppState({
+ openMenu: appState.openMenu === "canvas" ? null : "canvas",
+ });
+ }}
+ data-testid="main-menu-trigger"
+ className="main-menu-trigger"
+ >
+ {HamburgerMenuIcon}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content
+ onClickOutside={onClickOutside}
+ onSelect={composeEventHandlers(onSelect, () => {
+ setAppState({ openMenu: null });
+ })}
+ >
+ {children}
+ {device.editor.isMobile && appState.collaborators.size > 0 && (
+ <fieldset className="UserList-Wrapper">
+ <legend>{t("labels.collaborators")}</legend>
+ <UserList
+ mobile={true}
+ collaborators={appState.collaborators}
+ userToFollow={appState.userToFollow?.socketId || null}
+ />
+ </fieldset>
+ )}
+ </DropdownMenu.Content>
+ </DropdownMenu>
+ </MainMenuTunnel.In>
+ );
+ },
+ ),
+ {
+ Trigger: DropdownMenu.Trigger,
+ Item: DropdownMenu.Item,
+ ItemLink: DropdownMenu.ItemLink,
+ ItemCustom: DropdownMenu.ItemCustom,
+ Group: DropdownMenu.Group,
+ Separator: DropdownMenu.Separator,
+ DefaultItems,
+ },
+);
+
+export default MainMenu;
diff --git a/packages/excalidraw/components/welcome-screen/WelcomeScreen.Center.tsx b/packages/excalidraw/components/welcome-screen/WelcomeScreen.Center.tsx
new file mode 100644
index 0000000..4faa41b
--- /dev/null
+++ b/packages/excalidraw/components/welcome-screen/WelcomeScreen.Center.tsx
@@ -0,0 +1,195 @@
+import type { JSX } from "react";
+import { actionLoadScene, actionShortcuts } from "../../actions";
+import { getShortcutFromShortcutName } from "../../actions/shortcuts";
+import { t, useI18n } from "../../i18n";
+import { useDevice, useExcalidrawActionManager } from "../App";
+import { useTunnels } from "../../context/tunnels";
+import { HelpIcon, LoadIcon, usersIcon } from "../icons";
+import { useUIAppState } from "../../context/ui-appState";
+import { ExcalidrawLogo } from "../ExcalidrawLogo";
+
+const WelcomeScreenMenuItemContent = ({
+ icon,
+ shortcut,
+ children,
+}: {
+ icon?: JSX.Element;
+ shortcut?: string | null;
+ children: React.ReactNode;
+}) => {
+ const device = useDevice();
+ return (
+ <>
+ <div className="welcome-screen-menu-item__icon">{icon}</div>
+ <div className="welcome-screen-menu-item__text">{children}</div>
+ {shortcut && !device.editor.isMobile && (
+ <div className="welcome-screen-menu-item__shortcut">{shortcut}</div>
+ )}
+ </>
+ );
+};
+WelcomeScreenMenuItemContent.displayName = "WelcomeScreenMenuItemContent";
+
+const WelcomeScreenMenuItem = ({
+ onSelect,
+ children,
+ icon,
+ shortcut,
+ className = "",
+ ...props
+}: {
+ onSelect: () => void;
+ children: React.ReactNode;
+ icon?: JSX.Element;
+ shortcut?: string | null;
+} & React.ButtonHTMLAttributes<HTMLButtonElement>) => {
+ return (
+ <button
+ {...props}
+ type="button"
+ className={`welcome-screen-menu-item ${className}`}
+ onClick={onSelect}
+ >
+ <WelcomeScreenMenuItemContent icon={icon} shortcut={shortcut}>
+ {children}
+ </WelcomeScreenMenuItemContent>
+ </button>
+ );
+};
+WelcomeScreenMenuItem.displayName = "WelcomeScreenMenuItem";
+
+const WelcomeScreenMenuItemLink = ({
+ children,
+ href,
+ icon,
+ shortcut,
+ className = "",
+ ...props
+}: {
+ children: React.ReactNode;
+ href: string;
+ icon?: JSX.Element;
+ shortcut?: string | null;
+} & React.AnchorHTMLAttributes<HTMLAnchorElement>) => {
+ return (
+ <a
+ {...props}
+ className={`welcome-screen-menu-item ${className}`}
+ href={href}
+ target="_blank"
+ rel="noreferrer"
+ >
+ <WelcomeScreenMenuItemContent icon={icon} shortcut={shortcut}>
+ {children}
+ </WelcomeScreenMenuItemContent>
+ </a>
+ );
+};
+WelcomeScreenMenuItemLink.displayName = "WelcomeScreenMenuItemLink";
+
+const Center = ({ children }: { children?: React.ReactNode }) => {
+ const { WelcomeScreenCenterTunnel } = useTunnels();
+ return (
+ <WelcomeScreenCenterTunnel.In>
+ <div className="welcome-screen-center">
+ {children || (
+ <>
+ <Logo />
+ <Heading>{t("welcomeScreen.defaults.center_heading")}</Heading>
+ <Menu>
+ <MenuItemLoadScene />
+ <MenuItemHelp />
+ </Menu>
+ </>
+ )}
+ </div>
+ </WelcomeScreenCenterTunnel.In>
+ );
+};
+Center.displayName = "Center";
+
+const Logo = ({ children }: { children?: React.ReactNode }) => {
+ return (
+ <div className="welcome-screen-center__logo excalifont welcome-screen-decor">
+ {children || <ExcalidrawLogo withText />}
+ </div>
+ );
+};
+Logo.displayName = "Logo";
+
+const Heading = ({ children }: { children: React.ReactNode }) => {
+ return (
+ <div className="welcome-screen-center__heading welcome-screen-decor excalifont">
+ {children}
+ </div>
+ );
+};
+Heading.displayName = "Heading";
+
+const Menu = ({ children }: { children?: React.ReactNode }) => {
+ return <div className="welcome-screen-menu">{children}</div>;
+};
+Menu.displayName = "Menu";
+
+const MenuItemHelp = () => {
+ const actionManager = useExcalidrawActionManager();
+
+ return (
+ <WelcomeScreenMenuItem
+ onSelect={() => actionManager.executeAction(actionShortcuts)}
+ shortcut="?"
+ icon={HelpIcon}
+ >
+ {t("helpDialog.title")}
+ </WelcomeScreenMenuItem>
+ );
+};
+MenuItemHelp.displayName = "MenuItemHelp";
+
+const MenuItemLoadScene = () => {
+ const appState = useUIAppState();
+ const actionManager = useExcalidrawActionManager();
+
+ if (appState.viewModeEnabled) {
+ return null;
+ }
+
+ return (
+ <WelcomeScreenMenuItem
+ onSelect={() => actionManager.executeAction(actionLoadScene)}
+ shortcut={getShortcutFromShortcutName("loadScene")}
+ icon={LoadIcon}
+ >
+ {t("buttons.load")}
+ </WelcomeScreenMenuItem>
+ );
+};
+MenuItemLoadScene.displayName = "MenuItemLoadScene";
+
+const MenuItemLiveCollaborationTrigger = ({
+ onSelect,
+}: {
+ onSelect: () => any;
+}) => {
+ const { t } = useI18n();
+ return (
+ <WelcomeScreenMenuItem shortcut={null} onSelect={onSelect} icon={usersIcon}>
+ {t("labels.liveCollaboration")}
+ </WelcomeScreenMenuItem>
+ );
+};
+MenuItemLiveCollaborationTrigger.displayName =
+ "MenuItemLiveCollaborationTrigger";
+
+// -----------------------------------------------------------------------------
+
+Center.Logo = Logo;
+Center.Heading = Heading;
+Center.Menu = Menu;
+Center.MenuItem = WelcomeScreenMenuItem;
+Center.MenuItemLink = WelcomeScreenMenuItemLink;
+Center.MenuItemHelp = MenuItemHelp;
+Center.MenuItemLoadScene = MenuItemLoadScene;
+Center.MenuItemLiveCollaborationTrigger = MenuItemLiveCollaborationTrigger;
+
+export { Center };
diff --git a/packages/excalidraw/components/welcome-screen/WelcomeScreen.Hints.tsx b/packages/excalidraw/components/welcome-screen/WelcomeScreen.Hints.tsx
new file mode 100644
index 0000000..896f401
--- /dev/null
+++ b/packages/excalidraw/components/welcome-screen/WelcomeScreen.Hints.tsx
@@ -0,0 +1,52 @@
+import { t } from "../../i18n";
+import { useTunnels } from "../../context/tunnels";
+import {
+ WelcomeScreenHelpArrow,
+ WelcomeScreenMenuArrow,
+ WelcomeScreenTopToolbarArrow,
+} from "../icons";
+
+const MenuHint = ({ children }: { children?: React.ReactNode }) => {
+ const { WelcomeScreenMenuHintTunnel } = useTunnels();
+ return (
+ <WelcomeScreenMenuHintTunnel.In>
+ <div className="excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--menu">
+ {WelcomeScreenMenuArrow}
+ <div className="welcome-screen-decor-hint__label">
+ {children || t("welcomeScreen.defaults.menuHint")}
+ </div>
+ </div>
+ </WelcomeScreenMenuHintTunnel.In>
+ );
+};
+MenuHint.displayName = "MenuHint";
+
+const ToolbarHint = ({ children }: { children?: React.ReactNode }) => {
+ const { WelcomeScreenToolbarHintTunnel } = useTunnels();
+ return (
+ <WelcomeScreenToolbarHintTunnel.In>
+ <div className="excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--toolbar">
+ <div className="welcome-screen-decor-hint__label">
+ {children || t("welcomeScreen.defaults.toolbarHint")}
+ </div>
+ {WelcomeScreenTopToolbarArrow}
+ </div>
+ </WelcomeScreenToolbarHintTunnel.In>
+ );
+};
+ToolbarHint.displayName = "ToolbarHint";
+
+const HelpHint = ({ children }: { children?: React.ReactNode }) => {
+ const { WelcomeScreenHelpHintTunnel } = useTunnels();
+ return (
+ <WelcomeScreenHelpHintTunnel.In>
+ <div className="excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--help">
+ <div>{children || t("welcomeScreen.defaults.helpHint")}</div>
+ {WelcomeScreenHelpArrow}
+ </div>
+ </WelcomeScreenHelpHintTunnel.In>
+ );
+};
+HelpHint.displayName = "HelpHint";
+
+export { HelpHint, MenuHint, ToolbarHint };
diff --git a/packages/excalidraw/components/welcome-screen/WelcomeScreen.scss b/packages/excalidraw/components/welcome-screen/WelcomeScreen.scss
new file mode 100644
index 0000000..8e3a010
--- /dev/null
+++ b/packages/excalidraw/components/welcome-screen/WelcomeScreen.scss
@@ -0,0 +1,272 @@
+.excalidraw {
+ .excalifont {
+ font-family: "Excalifont", "Xiaolai";
+ }
+
+ // WelcomeSreen common
+ // ---------------------------------------------------------------------------
+
+ .welcome-screen-decor {
+ pointer-events: none;
+
+ color: var(--color-gray-40);
+
+ a {
+ --color: var(--color-primary);
+ color: var(--color);
+ text-decoration: none;
+ margin-bottom: -6px;
+ }
+ }
+
+ &.theme--dark {
+ .welcome-screen-decor {
+ color: var(--color-gray-60);
+ }
+ }
+
+ // WelcomeScreen.Hints
+ // ---------------------------------------------------------------------------
+
+ .welcome-screen-decor-hint {
+ @media (max-height: 599px) {
+ display: none !important;
+ }
+
+ @media (max-width: 1024px), (max-width: 800px) {
+ .welcome-screen-decor {
+ &--help,
+ &--menu {
+ display: none;
+ }
+ }
+ }
+
+ &--help {
+ display: flex;
+ position: absolute;
+ right: 0;
+ bottom: 100%;
+
+ :root[dir="rtl"] & {
+ left: 0;
+ right: auto;
+ }
+
+ svg {
+ margin-top: 0.5rem;
+ width: 85px;
+ height: 71px;
+
+ transform: scaleX(-1) rotate(80deg);
+
+ :root[dir="rtl"] & {
+ transform: rotate(80deg);
+ }
+ }
+ }
+
+ &--toolbar {
+ position: absolute;
+ top: 100%;
+ left: 50%;
+ transform: translateX(-50%);
+ margin-top: 2.5rem;
+ display: flex;
+ align-items: baseline;
+
+ .welcome-screen-decor-hint__label {
+ width: 120px;
+ position: relative;
+ top: -0.5rem;
+ }
+
+ svg {
+ width: 38px;
+ height: 78px;
+
+ :root[dir="rtl"] & {
+ transform: scaleX(-1);
+ }
+ }
+ }
+
+ &--menu {
+ position: absolute;
+ width: 320px;
+ font-size: 1rem;
+
+ top: 100%;
+ margin-top: 0.25rem;
+ margin-inline-start: 0.6rem;
+
+ display: flex;
+ align-items: flex-end;
+ gap: 0.5rem;
+
+ svg {
+ width: 41px;
+ height: 94px;
+
+ :root[dir="rtl"] & {
+ transform: scaleX(-1);
+ }
+ }
+
+ @media (max-width: 860px) {
+ .welcome-screen-decor-hint__label {
+ max-width: 160px;
+ }
+ }
+ }
+ }
+
+ // WelcomeSreen.Center
+ // ---------------------------------------------------------------------------
+
+ .welcome-screen-center {
+ display: flex;
+ flex-direction: column;
+ gap: 2rem;
+ justify-content: center;
+ align-items: center;
+ position: absolute;
+ pointer-events: none;
+ left: 1rem;
+ top: 1rem;
+ right: 1rem;
+ bottom: 1rem;
+ }
+
+ .welcome-screen-center__logo {
+ display: flex;
+ align-items: center;
+ column-gap: 0.75rem;
+ font-size: 2.25rem;
+ }
+
+ .welcome-screen-center__heading {
+ font-size: 1.125rem;
+ text-align: center;
+ }
+
+ .welcome-screen-menu {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ justify-content: center;
+ align-items: center;
+ }
+
+ .welcome-screen-menu-item {
+ box-sizing: border-box;
+
+ pointer-events: var(--ui-pointerEvents);
+
+ color: var(--color-gray-50);
+ font-size: 0.875rem;
+
+ width: 100%;
+ min-width: 300px;
+ max-width: 400px;
+ display: grid;
+ align-items: center;
+ justify-content: space-between;
+
+ background: none;
+ border: 1px solid transparent;
+
+ padding: 0.75rem;
+
+ border-radius: var(--border-radius-md);
+
+ grid-template-columns: calc(var(--default-icon-size) + 0.5rem) 1fr 3rem;
+
+ &__text {
+ display: flex;
+ align-items: center;
+ margin-right: auto;
+ text-align: left;
+ column-gap: 0.5rem;
+ }
+
+ &__icon {
+ width: var(--default-icon-size);
+ height: var(--default-icon-size);
+ }
+
+ &__shortcut {
+ margin-left: auto;
+ color: var(--color-gray-40);
+ font-size: 0.75rem;
+ }
+ }
+
+ .welcome-screen-menu-item:hover {
+ text-decoration: none;
+ background: var(--button-hover-bg);
+
+ .welcome-screen-menu-item__shortcut,
+ .welcome-screen-menu-item__icon,
+ .welcome-screen-menu-item__text {
+ color: var(--color-gray-100);
+ }
+ }
+
+ .welcome-screen-menu-item:active {
+ background: var(--button-hover-bg);
+ border-color: var(--color-brand-active);
+
+ .welcome-screen-menu-item__shortcut,
+ .welcome-screen-menu-item__icon,
+ .welcome-screen-menu-item__text {
+ color: var(--color-gray-100);
+ }
+ }
+
+ &.theme--dark {
+ .welcome-screen-menu-item {
+ color: var(--color-gray-60);
+
+ &__shortcut {
+ color: var(--color-gray-60);
+ }
+ }
+
+ .welcome-screen-menu-item:hover {
+ background-color: var(--color-surface-low);
+
+ .welcome-screen-menu-item__icon,
+ .welcome-screen-menu-item__shortcut,
+ .welcome-screen-menu-item__text {
+ color: var(--color-gray-10);
+ }
+ }
+
+ .welcome-screen-menu-item:active {
+ .welcome-screen-menu-item__icon,
+ .welcome-screen-menu-item__shortcut,
+ .welcome-screen-menu-item__text {
+ color: var(--color-gray-10);
+ }
+ }
+ }
+
+ @media (max-height: 599px) {
+ .welcome-screen-center {
+ margin-top: 4rem;
+ }
+ }
+ @media (min-height: 600px) and (max-height: 900px) {
+ .welcome-screen-center {
+ margin-top: 8rem;
+ }
+ }
+ @media (max-height: 500px), (max-width: 320px) {
+ .welcome-screen-center {
+ display: none;
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+}
diff --git a/packages/excalidraw/components/welcome-screen/WelcomeScreen.tsx b/packages/excalidraw/components/welcome-screen/WelcomeScreen.tsx
new file mode 100644
index 0000000..1f38b1c
--- /dev/null
+++ b/packages/excalidraw/components/welcome-screen/WelcomeScreen.tsx
@@ -0,0 +1,26 @@
+import { Center } from "./WelcomeScreen.Center";
+import { MenuHint, ToolbarHint, HelpHint } from "./WelcomeScreen.Hints";
+
+import "./WelcomeScreen.scss";
+
+const WelcomeScreen = (props: { children?: React.ReactNode }) => {
+ return (
+ <>
+ {props.children || (
+ <>
+ <Center />
+ <MenuHint />
+ <ToolbarHint />
+ <HelpHint />
+ </>
+ )}
+ </>
+ );
+};
+
+WelcomeScreen.displayName = "WelcomeScreen";
+
+WelcomeScreen.Center = Center;
+WelcomeScreen.Hints = { MenuHint, ToolbarHint, HelpHint };
+
+export default WelcomeScreen;