Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(editor): toolbar / active tool rewrites (#11649)

David Luzar339d3c373314
diff --git a/excalidraw-app/components/ExportToExcalidrawPlus.tsx b/excalidraw-app/components/ExportToExcalidrawPlus.tsx
index 0e9703a107..de40deacca 100644
--- a/excalidraw-app/components/ExportToExcalidrawPlus.tsx
+++ b/excalidraw-app/components/ExportToExcalidrawPlus.tsx
@@ -5,7 +5,7 @@ import { nanoid } from "nanoid";
import { trackEvent } from "@excalidraw/excalidraw/analytics";
import { Card } from "@excalidraw/excalidraw/components/Card";
import { ExcalidrawLogo } from "@excalidraw/excalidraw/components/ExcalidrawLogo";
-import { ToolButton } from "@excalidraw/excalidraw/components/ToolButton";
+import { IconButton } from "@excalidraw/excalidraw/components/IconButton";
import { MIME_TYPES, getFrame } from "@excalidraw/common";
import {
encryptData,
@@ -111,7 +111,7 @@ export const ExportToExcalidrawPlus: React.FC<{
<div className="Card-details">
{t("exportDialog.excalidrawplus_description")}
</div>
- <ToolButton
+ <IconButton
className="Card-button"
type="button"
title={t("exportDialog.excalidrawplus_button")}
diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts
index 0b168fa946..550bcdb208 100644
--- a/packages/common/src/utils.ts
+++ b/packages/common/src/utils.ts
@@ -252,7 +252,7 @@ export const updateActiveTool = (
}
| { type: "custom"; customType: string }
) & { locked?: boolean; fromSelection?: boolean }) & {
- lastActiveToolBeforeEraser?: ActiveTool | null;
+ lastActiveTool?: ActiveTool | null;
},
): AppState["activeTool"] => {
if (data.type === "custom") {
@@ -267,9 +267,9 @@ export const updateActiveTool = (
return {
...appState.activeTool,
lastActiveTool:
- data.lastActiveToolBeforeEraser === undefined
+ data.lastActiveTool === undefined
? appState.activeTool.lastActiveTool
- : data.lastActiveToolBeforeEraser,
+ : data.lastActiveTool,
type: data.type,
customType: null,
locked: data.locked ?? appState.activeTool.locked,
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index d403df6d04..09d1f55d29 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -15,6 +15,35 @@ Please add the latest change on the top under the correct section.
## Excalidraw API
+### Tool system & toolbar rework
+
+The toolbar UI was rewritten from hidden radio/checkbox inputs to real `<button>` elements composed from a central tool registry, and all tool activation now goes through a single `setActiveTool` code path.
+
+#### Breaking changes
+
+- `ExcalidrawAPI.setActiveTool(tool, keepSelection?)` — the second parameter changed from a boolean to an options object: `setActiveTool(tool, { keepSelection?: boolean; toggle?: boolean = false })`. The hand and eraser tools are now _toggle tools_: activating one records the previously active tool, and if `toggle=true`, activating it again switches back — including via `setActiveTool` itself, so repeated `setActiveTool({ type: "hand" }, { toggle: true })` calls alternate rather than no-op. By default `false` for idempotent activation.
+
+- Tool buttons render as semantic `<button>` elements with `aria-pressed` instead of `<label>`-wrapped hidden `<input type="radio">` / `<input type="checkbox">`. If you style or query the editor DOM:
+
+ - The `.ToolIcon_type_radio`, `.ToolIcon_type_checkbox`, and `.ToolIcon--selected` class names no longer exist — the pressed state is exposed through the `.ToolIcon--checked` class and the `aria-pressed` attribute.
+ - `<Sidebar.Trigger>` (including the default Library trigger) renders a `<button>` instead of a `<label>` + checkbox.
+
+- Removed internal actions superseded by the `setActiveTool` funnel and the tool registry: `toggleHandTool`, `toggleEraserTool`, `toggleLassoTool`, `setFrameAsActiveTool`, `setEmbeddableAsActiveTool` (these `ActionName`s no longer exist).
+
+#### Behavior changes
+
+- Hand (`H`) and eraser (`E`) shortcuts now reliably toggle back to the previously active tool (previously inconsistent across platforms and input paths, and unavailable for hand in view mode). Pressing `Escape` while hand or eraser is active likewise returns to the previous tool. Re-clicking their toolbar buttons is a no-op.
+- Clicking the active selection tool switches to lasso on all platforms (previously this only worked on iOS due to a controlled-radio quirk).
+- Tool letter shortcuts are CapsLock-insensitive, `Shift+letter` never switches tools, and `Ctrl+E` no longer toggles the eraser.
+- Switching tools no longer creates undo-history entries.
+- Command palette tool commands are derived from the tool registry: the duplicate "Hand" entry is gone, "Web Embed" was added, and "Lasso" is always listed.
+- Pen mode now activates on the first pen tap on any tool button (previously deferred and occasionally dropped).
+
+#### Fixes
+
+- Mobile toolbar popovers: the active option stays highlighted after tapping it (the highlight was being suppressed by sticky touch-hover).
+- The active-tool highlight can no longer desync from the actually active tool (controlled-radio DOM desync).
+
### Viewport control & scroll/zoom locking
`ExcalidrawAPI.scrollToContent` was rebuilt into `ExcalidrawAPI.setViewport()` — a single API for navigating the viewport (`fit: "scale-down" | "contain" | "none"`), locking scroll/zoom to a target (with rubberband overscroll), fitting around the rendered editor UI, and initializing the viewport on scene load [#11554](https://github.com/excalidraw/excalidraw/pull/11554).
@@ -163,6 +192,8 @@ Please add the latest change on the top under the correct section.
### Breaking changes
+- `updateActiveTool` (from `@excalidraw/common`): the `lastActiveToolBeforeEraser` property of the `data` parameter was renamed to `lastActiveTool` (it was already stored under that name on `appState.activeTool`, and is no longer eraser-specific).
+
- `getClosestElementBounds` is no longer exported from `@excalidraw/element`. Use `getCommonBounds` / `getElementBounds` from `@excalidraw/element`, or reimplement the closest-target distance check with `getElementBounds` if you need the same behavior [#11554](https://github.com/excalidraw/excalidraw/pull/11554).
## 0.18.0 (2025-03-11)
diff --git a/packages/excalidraw/actions/actionAlign.tsx b/packages/excalidraw/actions/actionAlign.tsx
index 2bbe4fab97..83d2831087 100644
--- a/packages/excalidraw/actions/actionAlign.tsx
+++ b/packages/excalidraw/actions/actionAlign.tsx
@@ -16,7 +16,7 @@ import type { ExcalidrawElement } from "@excalidraw/element/types";
import type { Alignment } from "@excalidraw/element";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import {
AlignBottomIcon,
AlignLeftIcon,
@@ -96,7 +96,7 @@ export const actionAlignTop = register({
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.shiftKey && event.key === KEYS.ARROW_UP,
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!alignActionsPredicate(appState, app)}
type="button"
icon={AlignTopIcon}
@@ -130,7 +130,7 @@ export const actionAlignBottom = register({
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.shiftKey && event.key === KEYS.ARROW_DOWN,
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!alignActionsPredicate(appState, app)}
type="button"
icon={AlignBottomIcon}
@@ -164,7 +164,7 @@ export const actionAlignLeft = register({
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.shiftKey && event.key === KEYS.ARROW_LEFT,
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!alignActionsPredicate(appState, app)}
type="button"
icon={AlignLeftIcon}
@@ -198,7 +198,7 @@ export const actionAlignRight = register({
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.shiftKey && event.key === KEYS.ARROW_RIGHT,
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!alignActionsPredicate(appState, app)}
type="button"
icon={AlignRightIcon}
@@ -230,7 +230,7 @@ export const actionAlignVerticallyCentered = register({
};
},
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!alignActionsPredicate(appState, app)}
type="button"
icon={CenterVerticallyIcon}
@@ -260,7 +260,7 @@ export const actionAlignHorizontallyCentered = register({
};
},
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!alignActionsPredicate(appState, app)}
type="button"
icon={CenterHorizontallyIcon}
diff --git a/packages/excalidraw/actions/actionCanvas.tsx b/packages/excalidraw/actions/actionCanvas.tsx
index 69e2d5ba8c..fa378df291 100644
--- a/packages/excalidraw/actions/actionCanvas.tsx
+++ b/packages/excalidraw/actions/actionCanvas.tsx
@@ -1,11 +1,9 @@
import {
DEFAULT_CANVAS_BACKGROUND_PICKS,
- CURSOR_TYPE,
MAX_ZOOM,
MIN_ZOOM,
THEME,
ZOOM_STEP,
- updateActiveTool,
CODES,
KEYS,
} from "@excalidraw/common";
@@ -18,17 +16,11 @@ import { CaptureUpdateAction } from "@excalidraw/element";
import type { ExcalidrawElement } from "@excalidraw/element/types";
-import {
- getDefaultAppState,
- isEraserActive,
- isHandToolActive,
-} from "../appState";
+import { getDefaultAppState } from "../appState";
import { ColorPicker } from "../components/ColorPicker/ColorPicker";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { Tooltip } from "../components/Tooltip";
import {
- handIcon,
- LassoIcon,
MoonIcon,
SunIcon,
TrashIcon,
@@ -37,7 +29,6 @@ import {
ZoomOutIcon,
ZoomResetIcon,
} from "../components/icons";
-import { setCursor } from "../cursor";
import { useAppStateValue } from "../hooks/useAppStateValue";
import { t } from "../i18n";
@@ -157,7 +148,7 @@ export const actionZoomIn = register({
PanelComponent: ({ updateData }) => {
const zoomValue = useAppStateValue((appState) => appState.zoom.value);
return (
- <ToolButton
+ <IconButton
type="button"
className="zoom-in-button zoom-button"
icon={ZoomInIcon}
@@ -202,7 +193,7 @@ export const actionZoomOut = register({
PanelComponent: ({ updateData }) => {
const zoomValue = useAppStateValue((appState) => appState.zoom.value);
return (
- <ToolButton
+ <IconButton
type="button"
className="zoom-out-button zoom-button"
icon={ZoomOutIcon}
@@ -254,7 +245,7 @@ export const actionResetZoom = register({
const zoomValue = useAppStateValue((appState) => appState.zoom.value);
return (
<Tooltip label={t("buttons.resetZoom")} style={{ height: "100%" }}>
- <ToolButton
+ <IconButton
type="button"
className="reset-zoom-button zoom-button"
title={t("buttons.resetZoom")}
@@ -264,7 +255,7 @@ export const actionResetZoom = register({
}}
>
{(zoomValue * 100).toFixed(0)}%
- </ToolButton>
+ </IconButton>
</Tooltip>
);
},
@@ -404,117 +395,3 @@ export const actionToggleTheme = register<AppState["theme"]>({
return !!app.props.UIOptions.canvasActions.toggleTheme;
},
});
-
-export const actionToggleEraserTool = register({
- name: "toggleEraserTool",
- label: "toolBar.eraser",
- trackEvent: { category: "toolbar" },
- perform: (elements, appState, _, app) => {
- let activeTool: AppState["activeTool"];
-
- if (isEraserActive(appState)) {
- activeTool = updateActiveTool(appState, {
- ...(appState.activeTool.lastActiveTool || {
- type: app.state.preferredSelectionTool.type,
- }),
- lastActiveToolBeforeEraser: null,
- });
- } else {
- activeTool = updateActiveTool(appState, {
- type: "eraser",
- lastActiveToolBeforeEraser: appState.activeTool,
- });
- }
-
- return {
- appState: {
- ...appState,
- selectedElementIds: {},
- selectedGroupIds: {},
- activeEmbeddable: null,
- activeTool,
- },
- captureUpdate: CaptureUpdateAction.IMMEDIATELY,
- };
- },
- keyTest: (event, appState) =>
- event.key === KEYS.E &&
- !appState.newElement &&
- !appState.selectedLinearElement?.isEditing &&
- !appState.selectedLinearElement?.isDragging,
-});
-
-export const actionToggleLassoTool = register({
- name: "toggleLassoTool",
- label: "toolBar.lasso",
- icon: LassoIcon,
- trackEvent: { category: "toolbar" },
- predicate: (elements, appState, props, app) => {
- return app.state.preferredSelectionTool.type !== "lasso";
- },
- perform: (elements, appState, _, app) => {
- let activeTool: AppState["activeTool"];
-
- if (appState.activeTool.type !== "lasso") {
- activeTool = updateActiveTool(appState, {
- type: "lasso",
- fromSelection: false,
- });
- setCursor(app.interactiveCanvas, CURSOR_TYPE.CROSSHAIR);
- } else {
- activeTool = updateActiveTool(appState, {
- type: "selection",
- });
- }
-
- return {
- appState: {
- ...appState,
- selectedElementIds: {},
- selectedGroupIds: {},
- activeEmbeddable: null,
- activeTool,
- },
- captureUpdate: CaptureUpdateAction.NEVER,
- };
- },
-});
-
-export const actionToggleHandTool = register({
- name: "toggleHandTool",
- label: "toolBar.hand",
- trackEvent: { category: "toolbar" },
- icon: handIcon,
- viewMode: false,
- perform: (elements, appState, _, app) => {
- let activeTool: AppState["activeTool"];
-
- if (isHandToolActive(appState)) {
- activeTool = updateActiveTool(appState, {
- ...(appState.activeTool.lastActiveTool || {
- type: "selection",
- }),
- lastActiveToolBeforeEraser: null,
- });
- } else {
- activeTool = updateActiveTool(appState, {
- type: "hand",
- lastActiveToolBeforeEraser: appState.activeTool,
- });
- setCursor(app.interactiveCanvas, CURSOR_TYPE.GRAB);
- }
-
- return {
- appState: {
- ...appState,
- selectedElementIds: {},
- selectedGroupIds: {},
- activeEmbeddable: null,
- activeTool,
- },
- captureUpdate: CaptureUpdateAction.IMMEDIATELY,
- };
- },
- keyTest: (event) =>
- !event.altKey && !event[KEYS.CTRL_OR_CMD] && event.key === KEYS.H,
-});
diff --git a/packages/excalidraw/actions/actionCropEditor.tsx b/packages/excalidraw/actions/actionCropEditor.tsx
index d143bba192..ae66185acc 100644
--- a/packages/excalidraw/actions/actionCropEditor.tsx
+++ b/packages/excalidraw/actions/actionCropEditor.tsx
@@ -4,7 +4,7 @@ import { CaptureUpdateAction } from "@excalidraw/element";
import type { ExcalidrawImageElement } from "@excalidraw/element/types";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { cropIcon } from "../components/icons";
import { t } from "../i18n";
@@ -47,7 +47,7 @@ export const actionToggleCropEditor = register({
const label = t("helpDialog.cropStart");
return (
- <ToolButton
+ <IconButton
type="button"
icon={cropIcon}
title={label}
diff --git a/packages/excalidraw/actions/actionDeleteSelected.tsx b/packages/excalidraw/actions/actionDeleteSelected.tsx
index 8112e1b9f3..193f5d86d4 100644
--- a/packages/excalidraw/actions/actionDeleteSelected.tsx
+++ b/packages/excalidraw/actions/actionDeleteSelected.tsx
@@ -28,7 +28,7 @@ import type { ExcalidrawElement } from "@excalidraw/element/types";
import { t } from "../i18n";
import { getSelectedElements, isSomeElementSelected } from "../scene";
import { TrashIcon } from "../components/icons";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { useStylesPanelMode } from "../components/App";
@@ -309,7 +309,7 @@ export const actionDeleteSelected = register({
const isMobile = useStylesPanelMode() === "mobile";
return (
- <ToolButton
+ <IconButton
type="button"
icon={TrashIcon}
title={t("labels.delete")}
diff --git a/packages/excalidraw/actions/actionDeselect.ts b/packages/excalidraw/actions/actionDeselect.ts
index c9a92c7138..16c763a20a 100644
--- a/packages/excalidraw/actions/actionDeselect.ts
+++ b/packages/excalidraw/actions/actionDeselect.ts
@@ -9,6 +9,8 @@ import { KEYS, isWritableElement, updateActiveTool } from "@excalidraw/common";
import type { GroupId } from "@excalidraw/element/types";
+import { TOGGLE_TOOLS } from "../components/Tools";
+
import { register } from "./register";
import type { AppClassProperties, AppState } from "../types";
@@ -17,12 +19,12 @@ const getNextActiveTool = (
appState: Readonly<AppState>,
app: AppClassProperties,
) => {
- if (appState.activeTool.type === "eraser") {
+ if (TOGGLE_TOOLS.includes(appState.activeTool.type)) {
return updateActiveTool(appState, {
...(appState.activeTool.lastActiveTool || {
type: app.state.preferredSelectionTool.type,
}),
- lastActiveToolBeforeEraser: null,
+ lastActiveTool: null,
});
}
diff --git a/packages/excalidraw/actions/actionDistribute.tsx b/packages/excalidraw/actions/actionDistribute.tsx
index eb37030461..817f7ae4df 100644
--- a/packages/excalidraw/actions/actionDistribute.tsx
+++ b/packages/excalidraw/actions/actionDistribute.tsx
@@ -16,7 +16,7 @@ import type { ExcalidrawElement } from "@excalidraw/element/types";
import type { Distribution } from "@excalidraw/element";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import {
DistributeHorizontallyIcon,
DistributeVerticallyIcon,
@@ -87,7 +87,7 @@ export const distributeHorizontally = register({
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.H,
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!enableActionGroup(appState, app)}
type="button"
icon={DistributeHorizontallyIcon}
@@ -118,7 +118,7 @@ export const distributeVertically = register({
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.V,
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!enableActionGroup(appState, app)}
type="button"
icon={DistributeVerticallyIcon}
diff --git a/packages/excalidraw/actions/actionDuplicateSelection.tsx b/packages/excalidraw/actions/actionDuplicateSelection.tsx
index 4c22a80ee7..21d48ffd8e 100644
--- a/packages/excalidraw/actions/actionDuplicateSelection.tsx
+++ b/packages/excalidraw/actions/actionDuplicateSelection.tsx
@@ -20,7 +20,7 @@ import { duplicateElements } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { DuplicateIcon } from "../components/icons";
import { t } from "../i18n";
@@ -113,7 +113,7 @@ export const actionDuplicateSelection = register({
const isMobile = useStylesPanelMode() === "mobile";
return (
- <ToolButton
+ <IconButton
type="button"
icon={DuplicateIcon}
title={`${t("labels.duplicateSelection")} — ${getShortcutKey(
diff --git a/packages/excalidraw/actions/actionEmbeddable.ts b/packages/excalidraw/actions/actionEmbeddable.ts
deleted file mode 100644
index ff3828845b..0000000000
--- a/packages/excalidraw/actions/actionEmbeddable.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { updateActiveTool } from "@excalidraw/common";
-
-import { CaptureUpdateAction } from "@excalidraw/element";
-
-import { setCursorForShape } from "../cursor";
-
-import { register } from "./register";
-
-export const actionSetEmbeddableAsActiveTool = register({
- name: "setEmbeddableAsActiveTool",
- trackEvent: { category: "toolbar" },
- target: "Tool",
- label: "toolBar.embeddable",
- perform: (elements, appState, _, app) => {
- const nextActiveTool = updateActiveTool(appState, {
- type: "embeddable",
- });
-
- setCursorForShape(app.canvas, {
- ...appState,
- activeTool: nextActiveTool,
- });
-
- return {
- elements,
- appState: {
- ...appState,
- activeTool: updateActiveTool(appState, {
- type: "embeddable",
- }),
- },
- captureUpdate: CaptureUpdateAction.EVENTUALLY,
- };
- },
-});
diff --git a/packages/excalidraw/actions/actionExport.tsx b/packages/excalidraw/actions/actionExport.tsx
index dceeee0e4c..bee75d7a80 100644
--- a/packages/excalidraw/actions/actionExport.tsx
+++ b/packages/excalidraw/actions/actionExport.tsx
@@ -1,11 +1,4 @@
-import {
- KEYS,
- DEFAULT_EXPORT_PADDING,
- EXPORT_SCALES,
- THEME,
-} from "@excalidraw/common";
-
-import { getNonDeletedElements } from "@excalidraw/element";
+import { KEYS, THEME } from "@excalidraw/common";
import { CaptureUpdateAction } from "@excalidraw/element";
@@ -16,7 +9,7 @@ import { CheckboxItem } from "../components/CheckboxItem";
import { DarkModeToggle } from "../components/DarkModeToggle";
import { ProjectName } from "../components/ProjectName";
import { Toast } from "../components/Toast";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { Tooltip } from "../components/Tooltip";
import { ExportIcon, questionCircle, saveAs } from "../components/icons";
import { loadFromJSON, saveAsJSON } from "../data";
@@ -26,8 +19,6 @@ import { nativeFileSystemSupported } from "../data/filesystem";
import { resaveAsImageWithScene } from "../data/resave";
import { t } from "../i18n";
-import { getSelectedElements, isSomeElementSelected } from "../scene";
-import { getExportSize } from "../scene/export";
import "../components/ToolIcon.scss";
@@ -73,44 +64,6 @@ export const actionChangeExportScale = register<AppState["exportScale"]>({
captureUpdate: CaptureUpdateAction.EVENTUALLY,
};
},
- PanelComponent: ({ elements: allElements, appState, updateData }) => {
- const elements = getNonDeletedElements(allElements);
- const exportSelected = isSomeElementSelected(elements, appState);
- const exportedElements = exportSelected
- ? getSelectedElements(elements, appState)
- : elements;
-
- return (
- <>
- {EXPORT_SCALES.map((s) => {
- const [width, height] = getExportSize(
- exportedElements,
- DEFAULT_EXPORT_PADDING,
- s,
- );
-
- const scaleButtonTitle = `${t(
- "imageExportDialog.label.scale",
- )} ${s}x (${width}x${height})`;
-
- return (
- <ToolButton
- key={s}
- size="small"
- type="radio"
- icon={`${s}x`}
- name="export-canvas-scale"
- title={scaleButtonTitle}
- aria-label={scaleButtonTitle}
- id="export-canvas-scale"
- checked={s === appState.exportScale}
- onChange={() => updateData(s)}
- />
- );
- })}
- </>
- );
- },
});
export const actionChangeExportBackground = register<
@@ -424,7 +377,7 @@ export const actionSaveFileToDisk = register({
event.shiftKey &&
event[KEYS.CTRL_OR_CMD],
PanelComponent: ({ updateData }) => (
- <ToolButton
+ <IconButton
type="button"
icon={saveAs}
title={t("buttons.saveAs")}
diff --git a/packages/excalidraw/actions/actionFinalize.tsx b/packages/excalidraw/actions/actionFinalize.tsx
index eaa0c9201b..bdf3a5d7a7 100644
--- a/packages/excalidraw/actions/actionFinalize.tsx
+++ b/packages/excalidraw/actions/actionFinalize.tsx
@@ -38,7 +38,8 @@ import type {
import { t } from "../i18n";
import { resetCursor } from "../cursor";
import { done } from "../components/icons";
-import { ToolButton } from "../components/ToolButton";
+import { TOGGLE_TOOLS } from "../components/Tools";
+import { IconButton } from "../components/IconButton";
import { register } from "./register";
@@ -325,12 +326,12 @@ export const actionFinalize = register<FormData>({
}
let activeTool: AppState["activeTool"];
- if (appState.activeTool.type === "eraser") {
+ if (TOGGLE_TOOLS.includes(appState.activeTool.type)) {
activeTool = updateActiveTool(appState, {
...(appState.activeTool.lastActiveTool || {
type: app.state.preferredSelectionTool.type,
}),
- lastActiveToolBeforeEraser: null,
+ lastActiveTool: null,
});
} else {
activeTool = updateActiveTool(appState, {
@@ -398,7 +399,7 @@ export const actionFinalize = register<FormData>({
((event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) &&
appState.multiElement !== null),
PanelComponent: ({ appState, updateData, data }) => (
- <ToolButton
+ <IconButton
type="button"
icon={done}
title={t("buttons.done")}
diff --git a/packages/excalidraw/actions/actionFrame.ts b/packages/excalidraw/actions/actionFrame.ts
index eebce334af..6ffcc5f5e8 100644
--- a/packages/excalidraw/actions/actionFrame.ts
+++ b/packages/excalidraw/actions/actionFrame.ts
@@ -8,8 +8,6 @@ import {
} from "@excalidraw/element";
import { getFrameChildren } from "@excalidraw/element";
-import { KEYS, updateActiveTool } from "@excalidraw/common";
-
import { getElementsInGroup } from "@excalidraw/element";
import { getCommonBounds } from "@excalidraw/element";
@@ -18,8 +16,6 @@ import { CaptureUpdateAction } from "@excalidraw/element";
import type { ExcalidrawElement } from "@excalidraw/element/types";
-import { setCursorForShape } from "../cursor";
-import { frameToolIcon } from "../components/icons";
import { getSelectedElements } from "../scene";
import { register } from "./register";
@@ -126,40 +122,6 @@ export const actionupdateFrameRendering = register({
checked: (appState) => appState.frameRendering.enabled,
});
-export const actionSetFrameAsActiveTool = register({
- name: "setFrameAsActiveTool",
- label: "toolBar.frame",
- trackEvent: { category: "toolbar" },
- icon: frameToolIcon,
- viewMode: false,
- perform: (elements, appState, _, app) => {
- const nextActiveTool = updateActiveTool(appState, {
- type: "frame",
- });
-
- setCursorForShape(app.interactiveCanvas, {
- ...appState,
- activeTool: nextActiveTool,
- });
-
- return {
- elements,
- appState: {
- ...appState,
- activeTool: updateActiveTool(appState, {
- type: "frame",
- }),
- },
- captureUpdate: CaptureUpdateAction.EVENTUALLY,
- };
- },
- keyTest: (event) =>
- !event[KEYS.CTRL_OR_CMD] &&
- !event.shiftKey &&
- !event.altKey &&
- event.key.toLocaleLowerCase() === KEYS.F,
-});
-
export const actionWrapSelectionInFrame = register({
name: "wrapSelectionInFrame",
label: "labels.wrapSelectionInFrame",
diff --git a/packages/excalidraw/actions/actionGroup.tsx b/packages/excalidraw/actions/actionGroup.tsx
index fd72dfcb50..9a21e8277f 100644
--- a/packages/excalidraw/actions/actionGroup.tsx
+++ b/packages/excalidraw/actions/actionGroup.tsx
@@ -36,7 +36,7 @@ import type {
OrderedExcalidrawElement,
} from "@excalidraw/element/types";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { UngroupIcon, GroupIcon } from "../components/icons";
import { t } from "../i18n";
@@ -199,7 +199,7 @@ export const actionGroup = register({
keyTest: (event) =>
!event.shiftKey && event[KEYS.CTRL_OR_CMD] && event.key === KEYS.G,
PanelComponent: ({ elements, appState, updateData, app }) => (
- <ToolButton
+ <IconButton
hidden={!enableActionGroup(elements, appState, app)}
type="button"
icon={<GroupIcon theme={appState.theme} />}
@@ -207,7 +207,7 @@ export const actionGroup = register({
title={`${t("labels.group")} — ${getShortcutKey("CtrlOrCmd+G")}`}
aria-label={t("labels.group")}
visible={isSomeElementSelected(getNonDeletedElements(elements), appState)}
- ></ToolButton>
+ ></IconButton>
),
});
@@ -307,7 +307,7 @@ export const actionUngroup = register({
predicate: (elements, appState) => getSelectedGroupIds(appState).length > 0,
PanelComponent: ({ elements, appState, updateData }) => (
- <ToolButton
+ <IconButton
type="button"
hidden={getSelectedGroupIds(appState).length === 0}
icon={<UngroupIcon theme={appState.theme} />}
@@ -315,6 +315,6 @@ export const actionUngroup = register({
title={`${t("labels.ungroup")} — ${getShortcutKey("CtrlOrCmd+Shift+G")}`}
aria-label={t("labels.ungroup")}
visible={isSomeElementSelected(getNonDeletedElements(elements), appState)}
- ></ToolButton>
+ ></IconButton>
),
});
diff --git a/packages/excalidraw/actions/actionHistory.tsx b/packages/excalidraw/actions/actionHistory.tsx
index 5db66670b7..03c56db694 100644
--- a/packages/excalidraw/actions/actionHistory.tsx
+++ b/packages/excalidraw/actions/actionHistory.tsx
@@ -11,7 +11,7 @@ import { orderByFractionalIndex } from "@excalidraw/element";
import type { SceneElementsMap } from "@excalidraw/element/types";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { UndoIcon, RedoIcon } from "../components/icons";
import { HistoryChangedEvent } from "../history";
import { useEmitter } from "../hooks/useEmitter";
@@ -85,7 +85,7 @@ export const createUndoAction: ActionCreator = (history) => ({
const isMobile = useStylesPanelMode() === "mobile";
return (
- <ToolButton
+ <IconButton
type="button"
icon={UndoIcon}
aria-label={t("buttons.undo")}
@@ -125,7 +125,7 @@ export const createRedoAction: ActionCreator = (history) => ({
const isMobile = useStylesPanelMode() === "mobile";
return (
- <ToolButton
+ <IconButton
type="button"
icon={RedoIcon}
aria-label={t("buttons.redo")}
diff --git a/packages/excalidraw/actions/actionLinearEditor.tsx b/packages/excalidraw/actions/actionLinearEditor.tsx
index 8437ece8b5..cd136caec7 100644
--- a/packages/excalidraw/actions/actionLinearEditor.tsx
+++ b/packages/excalidraw/actions/actionLinearEditor.tsx
@@ -16,12 +16,10 @@ import type {
} from "@excalidraw/element/types";
import { DEFAULT_CATEGORIES } from "../components/CommandPalette/CommandPalette";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { lineEditorIcon, polygonIcon } from "../components/icons";
import { t } from "../i18n";
-import { ButtonIcon } from "../components/ButtonIcon";
-
import { newElementWith } from "../../element/src/mutateElement";
import { register } from "./register";
@@ -98,7 +96,7 @@ export const actionToggleLinearEditor = register({
: "labels.lineEditor.edit",
);
return (
- <ToolButton
+ <IconButton
type="button"
icon={lineEditorIcon}
title={label}
@@ -204,12 +202,13 @@ export const actionTogglePolygon = register({
);
return (
- <ButtonIcon
+ <IconButton
+ type="toggle"
icon={polygonIcon}
title={label}
aria-label={label}
- active={allPolygon}
- onClick={() => updateData(null)}
+ checked={allPolygon}
+ onSelect={() => updateData(null)}
style={{ marginLeft: "auto" }}
/>
);
diff --git a/packages/excalidraw/actions/actionLink.tsx b/packages/excalidraw/actions/actionLink.tsx
index a228f51d55..0d45f5bd2c 100644
--- a/packages/excalidraw/actions/actionLink.tsx
+++ b/packages/excalidraw/actions/actionLink.tsx
@@ -7,7 +7,7 @@ import { KEYS } from "@excalidraw/common";
import { CaptureUpdateAction } from "@excalidraw/element";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { getContextMenuLabel } from "../components/hyperlink/Hyperlink";
import { LinkIcon } from "../components/icons";
import { t } from "../i18n";
@@ -46,8 +46,8 @@ export const actionLink = register({
const selectedElements = getSelectedElements(elements, appState);
return (
- <ToolButton
- type="button"
+ <IconButton
+ type="toggle"
icon={LinkIcon}
aria-label={t(
getContextMenuLabel(getNonDeletedElements(elements), appState),
@@ -57,8 +57,8 @@ export const actionLink = register({
? t("labels.link.labelEmbed")
: t("labels.link.label")
} - ${getShortcutKey("CtrlOrCmd+K")}`}
- onClick={() => updateData(null)}
- selected={selectedElements.length === 1 && !!selectedElements[0].link}
+ onSelect={() => updateData(null)}
+ checked={selectedElements.length === 1 && !!selectedElements[0].link}
/>
);
},
diff --git a/packages/excalidraw/actions/actionProperties.tsx b/packages/excalidraw/actions/actionProperties.tsx
index d807c42ca5..c7ee2751ca 100644
--- a/packages/excalidraw/actions/actionProperties.tsx
+++ b/packages/excalidraw/actions/actionProperties.tsx
@@ -93,7 +93,7 @@ import type { CaptureUpdateActionType } from "@excalidraw/element";
import { trackEvent } from "../analytics";
import { RadioSelection } from "../components/RadioSelection";
-import { ToolButton } from "../components/ToolButton";
+import { IconButton } from "../components/IconButton";
import { ColorPicker } from "../components/ColorPicker/ColorPicker";
import { FontPicker } from "../components/FontPicker/FontPicker";
import { IconPicker } from "../components/IconPicker";
@@ -737,7 +737,7 @@ export const actionChangeFreedrawMode = register<StrokeVariability>({
if (data?.cycle) {
const isVariable = strokeVariability === "variable";
return (
- <ToolButton
+ <IconButton
type="button"
icon={
isVariable
diff --git a/packages/excalidraw/actions/index.ts b/packages/excalidraw/actions/index.ts
index 0d378b5c49..f1964e034b 100644
--- a/packages/excalidraw/actions/index.ts
+++ b/packages/excalidraw/actions/index.ts
@@ -32,8 +32,6 @@ export {
actionToggleTheme,
} from "./actionCanvas";
-export { actionSetEmbeddableAsActiveTool } from "./actionEmbeddable";
-
export { actionFinalize } from "./actionFinalize";
export { actionDeselect } from "./actionDeselect";
diff --git a/packages/excalidraw/actions/shortcuts.ts b/packages/excalidraw/actions/shortcuts.ts
index ca4119d251..10bcfd64df 100644
--- a/packages/excalidraw/actions/shortcuts.ts
+++ b/packages/excalidraw/actions/shortcuts.ts
@@ -44,9 +44,6 @@ export type ShortcutName =
| "zoomToFit"
| "zoomToFitSelectionInViewport"
| "zoomToFitSelection"
- | "toggleEraserTool"
- | "toggleHandTool"
- | "setFrameAsActiveTool"
| "saveFileToDisk"
| "saveToActiveFile"
| "toggleShortcuts"
@@ -110,9 +107,6 @@ const shortcutMap: Record<ShortcutName, string[]> = {
zoomToFitSelection: [getShortcutKey("Shift+3")],
zoomToFit: [getShortcutKey("Shift+1")],
zoomToFitSelectionInViewport: [getShortcutKey("Shift+2")],
- toggleEraserTool: [getShortcutKey("E")],
- toggleHandTool: [getShortcutKey("H")],
- setFrameAsActiveTool: [getShortcutKey("F")],
saveFileToDisk: [getShortcutKey("CtrlOrCmd+S")],
saveToActiveFile: [getShortcutKey("CtrlOrCmd+S")],
toggleShortcuts: [getShortcutKey("?")],
diff --git a/packages/excalidraw/actions/types.ts b/packages/excalidraw/actions/types.ts
index ba9c64bd54..0aed4559a9 100644
--- a/packages/excalidraw/actions/types.ts
+++ b/packages/excalidraw/actions/types.ts
@@ -127,13 +127,9 @@ export type ActionName =
| "unlockAllElements"
| "toggleElementLock"
| "toggleLinearEditor"
- | "toggleEraserTool"
- | "toggleHandTool"
| "selectAllElementsInFrame"
| "removeAllElementsFromFrame"
| "updateFrameRendering"
- | "setFrameAsActiveTool"
- | "setEmbeddableAsActiveTool"
| "createContainerFromText"
| "wrapTextInContainer"
| "commandPalette"
@@ -144,7 +140,6 @@ export type ActionName =
| "linkToElement"
| "cropEditor"
| "wrapSelectionInFrame"
- | "toggleLassoTool"
| "toggleShapeSwitch"
| "togglePolygon";
diff --git a/packages/excalidraw/components/Actions.tsx b/packages/excalidraw/components/Actions.tsx
index 84b09466ef..bb2e2ac3ad 100644
--- a/packages/excalidraw/components/Actions.tsx
+++ b/packages/excalidraw/components/Actions.tsx
@@ -1,8 +1,8 @@
import clsx from "clsx";
-import { useRef, useState } from "react";
+import { useRef } from "react";
import { Popover } from "radix-ui";
-import { CLASSES, KEYS, capitalizeString } from "@excalidraw/common";
+import { CLASSES } from "@excalidraw/common";
import { isArrowElement } from "@excalidraw/element";
@@ -14,9 +14,6 @@ import type {
import { actionToggleZenMode } from "../actions";
-import { trackEvent } from "../analytics";
-import { useTunnels } from "../context/tunnels";
-
import { t } from "../i18n";
import { getTargetElements } from "../scene";
@@ -26,32 +23,19 @@ import { useTextEditorFocus } from "../hooks/useTextEditorFocus";
import { actionToggleViewMode } from "../actions/actionToggleViewMode";
-import { getToolbarTools } from "./shapes";
-
import "./Actions.scss";
-import { useStylesPanelMode, useExcalidrawContainer } from "./App";
+import { useExcalidrawContainer } from "./App";
import Stack from "./Stack";
-import { ToolButton } from "./ToolButton";
-import { ToolPopover } from "./ToolPopover";
import { Tooltip } from "./Tooltip";
-import DropdownMenu from "./dropdownMenu/DropdownMenu";
import { PropertiesPopover } from "./PropertiesPopover";
import {
- EmbedIcon,
- extraToolsIcon,
- frameToolIcon,
- mermaidLogoIcon,
- laserPointerToolIcon,
- MagicIcon,
- LassoIcon,
sharpArrowIcon,
roundArrowIcon,
elbowArrowIcon,
TextSizeIcon,
adjustmentsIcon,
DotsHorizontalIcon,
- SelectionIcon,
pencilIcon,
} from "./icons";
@@ -60,12 +44,7 @@ import { Island } from "./Island";
import { getShapeActionPredicates } from "./shapeActionPredicates";
import type { ShapeActionPredicates } from "./shapeActionPredicates";
-import type {
- AppClassProperties,
- AppProps,
- UIAppState,
- AppState,
-} from "../types";
+import type { AppClassProperties, UIAppState, AppState } from "../types";
import type { ActionManager } from "../actions/manager";
// re-exported for consumers outside the styles panel (e.g. CommandPalette)
@@ -882,261 +861,6 @@ export const MobileShapeActions = ({
);
};
-export const ShapesSwitcher = ({
- activeTool,
- setAppState,
- app,
- UIOptions,
-}: {
- activeTool: UIAppState["activeTool"];
- setAppState: React.Component<any, AppState>["setState"];
- app: AppClassProperties;
- UIOptions: AppProps["UIOptions"];
-}) => {
- const [isExtraToolsMenuOpen, setIsExtraToolsMenuOpen] = useState(false);
- const stylesPanelMode = useStylesPanelMode();
- const isFullStylesPanel = stylesPanelMode === "full";
- const isCompactStylesPanel = stylesPanelMode === "compact";
-
- // a pen detected on a tool button's pointer-down, to be applied (enabling
- // pen mode) only after the tap's `change` has committed — see the tool
- // button handlers below
- const pendingPenDetectionRef = useRef(false);
-
- const SELECTION_TOOLS = [
- {
- type: "selection",
- icon: SelectionIcon,
- title: capitalizeString(t("toolBar.selection")),
- },
- {
- type: "lasso",
- icon: LassoIcon,
- title: capitalizeString(t("toolBar.lasso")),
- },
- ] as const;
-
- const frameToolSelected = activeTool.type === "frame";
- const laserToolSelected = activeTool.type === "laser";
- const lassoToolSelected =
- isFullStylesPanel &&
- activeTool.type === "lasso" &&
- app.state.preferredSelectionTool.type !== "lasso";
-
- const embeddableToolSelected = activeTool.type === "embeddable";
-
- const { TTDDialogTriggerTunnel } = useTunnels();
-
- return (
- <>
- {getToolbarTools(app).map(
- ({ value, icon, key, numericKey, fillable, toolbar }) => {
- if (
- toolbar === false ||
- 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}`;
- const keybindingLabel =
- value === "hand" ? undefined : numericKey || letter;
-
- // when in compact styles panel mode (tablet)
- // use a ToolPopover for selection/lasso toggle as well
- if (
- (value === "selection" || value === "lasso") &&
- isCompactStylesPanel
- ) {
- return (
- <ToolPopover
- key={"selection-popover"}
- app={app}
- options={SELECTION_TOOLS}
- activeTool={activeTool}
- defaultOption={app.state.preferredSelectionTool.type}
- namePrefix="selectionType"
- title={capitalizeString(t("toolBar.selection"))}
- data-testid="toolbar-selection"
- onToolChange={(type: string) => {
- if (type === "selection" || type === "lasso") {
- app.setActiveTool({ type });
- setAppState({
- preferredSelectionTool: { type, initialized: true },
- });
- }
- }}
- displayedOption={
- SELECTION_TOOLS.find(
- (tool) =>
- tool.type === app.state.preferredSelectionTool.type,
- ) || SELECTION_TOOLS[0]
- }
- fillable={activeTool.type === "selection"}
- />
- );
- }
-
- 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={keybindingLabel}
- aria-label={capitalizeString(label)}
- aria-keyshortcuts={shortcut}
- data-testid={`toolbar-${value}`}
- onPointerDown={({ pointerType }) => {
- // Detect the pen here (pointerType is reliable on pointer-down)
- // but DON'T enable pen mode yet: calling setState mid-gesture
- // re-renders the controlled radio and, on iOS/iPadOS, aborts
- // the ensuing click so the tool isn't selected on the first pen
- // tap. Defer it until the tap's `change` has committed (below).
- if (!app.state.penDetected && pointerType === "pen") {
- pendingPenDetectionRef.current = true;
- }
-
- if (value === "selection") {
- if (app.state.activeTool.type === "selection") {
- app.setActiveTool({ type: "lasso" });
- } else {
- app.setActiveTool({ type: "selection" });
- }
- }
- }}
- onChange={() => {
- if (app.state.activeTool.type !== value) {
- trackEvent("toolbar", value, "ui");
- }
- app.setActiveTool({ type: value });
-
- // Apply the pen detection captured on pointer-down now that the
- // tool is selected. rAF keeps the resulting re-render out of the
- // `change` event itself. We rely on the pointer-down detection
- // rather than this handler's pointerType because the latter is
- // unreliable on iOS (its backing ref is cleared before the
- // delayed click fires).
- if (pendingPenDetectionRef.current) {
- pendingPenDetectionRef.current = false;
- requestAnimationFrame(() => app.togglePenMode(true));
- }
- }}
- />
- );
- },
- )}
- <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 ||
- lassoToolSelected ||
- // 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);
- setAppState({ openMenu: null, openPopup: null });
- }}
- title={t("toolBar.extraTools")}
- >
- {frameToolSelected
- ? frameToolIcon
- : embeddableToolSelected
- ? EmbedIcon
- : laserToolSelected && !app.props.isCollaborating
- ? laserPointerToolIcon
- : lassoToolSelected
- ? LassoIcon
- : 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>
- {isFullStylesPanel && (
- <DropdownMenu.Item
- onSelect={() => app.setActiveTool({ type: "lasso" })}
- icon={LassoIcon}
- data-testid="toolbar-lasso"
- selected={lassoToolSelected}
- >
- {t("toolBar.lasso")}
- </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"
- badge={<DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>}
- >
- {t("toolBar.magicframe")}
- </DropdownMenu.Item>
- )}
- </DropdownMenu.Content>
- </DropdownMenu>
- </>
- );
-};
-
export const ZoomActions = ({
renderAction,
}: {
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index cfb93a3100..4f54c0fa5d 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -331,7 +331,6 @@ import {
actionToggleCropEditor,
} from "../actions";
import { actionWrapTextInContainer } from "../actions/actionBoundText";
-import { actionToggleHandTool } from "../actions/actionCanvas";
import { actionPaste } from "../actions/actionClipboard";
import { actionCopyElementLink } from "../actions/actionElementLink";
import { actionUnlockAllElements } from "../actions/actionElementLock";
@@ -465,7 +464,7 @@ import { CursorHint, CursorHints } from "./CursorHint";
import { MagicIcon, copyIcon, fullscreenIcon } from "./icons";
import { AppStateObserver, type OnStateChange } from "./AppStateObserver";
-import { findShapeByKey } from "./shapes";
+import { findShapeByKey, TOGGLE_TOOLS } from "./Tools";
import UnlockPopup from "./UnlockPopup";
@@ -2237,7 +2236,6 @@ class App extends React.Component<AppProps, AppState> {
elements={this.scene.getNonDeletedElements()}
onLockToggle={this.toggleLock}
onPenModeToggle={this.togglePenMode}
- onHandToolToggle={this.onHandToolToggle}
langCode={getLanguage().code}
renderTopLeftUI={renderTopLeftUI}
renderTopRightUI={renderTopRightUI}
@@ -4001,7 +3999,7 @@ class App extends React.Component<AppProps, AppState> {
this.setActiveTool(
{ type: this.state.preferredSelectionTool.type },
- true,
+ { keepSelection: true },
);
event?.preventDefault();
},
@@ -4152,7 +4150,10 @@ class App extends React.Component<AppProps, AppState> {
}
},
);
- this.setActiveTool({ type: this.state.preferredSelectionTool.type }, true);
+ this.setActiveTool(
+ { type: this.state.preferredSelectionTool.type },
+ { keepSelection: true },
+ );
if (opts.fit) {
this.setViewport({
@@ -4423,10 +4424,6 @@ class App extends React.Component<AppProps, AppState> {
});
};
- onHandToolToggle = () => {
- this.actionManager.executeAction(actionToggleHandTool);
- };
-
/**
* Zooms on canvas viewport center
*/
@@ -5299,6 +5296,9 @@ class App extends React.Component<AppProps, AppState> {
!event.ctrlKey &&
!event.altKey &&
!event.metaKey &&
+ // so that an uppercase letter can only mean CapsLock (Shift+letter
+ // must not switch tools — findShapeByKey lowercases the key)
+ !event.shiftKey &&
!this.state.newElement &&
!this.state.selectionElement &&
!this.state.selectedElementsAreBeingDragged
@@ -5342,7 +5342,7 @@ class App extends React.Component<AppProps, AppState> {
type: this.state.preferredSelectionTool.type,
});
} else {
- this.setActiveTool({ type: shape });
+ this.setActiveTool({ type: shape }, { toggle: true });
}
event.stopPropagation();
@@ -5778,8 +5778,20 @@ class App extends React.Component<AppProps, AppState> {
locked?: boolean;
fromSelection?: boolean;
},
- keepSelection = false,
+ opts: {
+ keepSelection?: boolean;
+ /**
+ * When `true`, re-activating an already-active toggle tool (see
+ * `TOGGLE_TOOLS`) switches back to the previously active tool.
+ * Activation is idempotent by default; toggle tools always record the
+ * previously active tool regardless (so ESC and the next `toggle`
+ * activation can switch back to it).
+ */
+ toggle?: boolean;
+ } = {},
) => {
+ const { keepSelection = false } = opts;
+
if (!this.isToolSupported(tool.type)) {
console.warn(
`"${tool.type}" tool is disabled via "UIOptions.canvasActions.tools.${tool.type}"`,
@@ -5787,7 +5799,26 @@ class App extends React.Component<AppProps, AppState> {
return;
}
- const nextActiveTool = updateActiveTool(this.state, tool);
+ const isToggleTool = TOGGLE_TOOLS.includes(tool.type);
+ const toggle = opts.toggle === true && isToggleTool;
+
+ const nextActiveTool =
+ toggle && this.state.activeTool.type === tool.type
+ ? // toggle back to the tool that was active before this one
+ updateActiveTool(this.state, {
+ ...(this.state.activeTool.lastActiveTool || {
+ type: this.state.preferredSelectionTool.type,
+ }),
+ lastActiveTool: null,
+ })
+ : isToggleTool && this.state.activeTool.type !== tool.type
+ ? // activating a toggle tool records the currently active tool so
+ // ESC and the next `toggle` activation can switch back to it
+ updateActiveTool(this.state, {
+ ...tool,
+ lastActiveTool: this.state.activeTool,
+ })
+ : updateActiveTool(this.state, tool);
if (nextActiveTool.type === "hand") {
setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
} else if (!isHoldingSpace) {
@@ -8161,7 +8192,7 @@ class App extends React.Component<AppProps, AppState> {
{
activeTool: updateActiveTool(this.state, {
type: TOOL_TYPE.eraser,
- lastActiveToolBeforeEraser: this.state.activeTool,
+ lastActiveTool: this.state.activeTool,
}),
},
() => {
@@ -8175,7 +8206,7 @@ class App extends React.Component<AppProps, AppState> {
...(this.state.activeTool.lastActiveTool || {
type: TOOL_TYPE.selection,
}),
- lastActiveToolBeforeEraser: null,
+ lastActiveTool: null,
}),
});
}
@@ -10684,7 +10715,7 @@ class App extends React.Component<AppProps, AppState> {
if (event.altKey) {
this.setActiveTool(
{ type: "lasso", fromSelection: true },
- event.shiftKey,
+ { keepSelection: event.shiftKey },
);
this.lassoTrail.startPath(
pointerDownState.origin.x,
diff --git a/packages/excalidraw/components/ButtonIcon.scss b/packages/excalidraw/components/ButtonIcon.scss
deleted file mode 100644
index 769a195e2f..0000000000
--- a/packages/excalidraw/components/ButtonIcon.scss
+++ /dev/null
@@ -1,12 +0,0 @@
-@use "../css/theme" as *;
-
-.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/CommandPalette/CommandPalette.tsx b/packages/excalidraw/components/CommandPalette/CommandPalette.tsx
index bfa336cf21..a58c7958cb 100644
--- a/packages/excalidraw/components/CommandPalette/CommandPalette.tsx
+++ b/packages/excalidraw/components/CommandPalette/CommandPalette.tsx
@@ -6,7 +6,6 @@ import {
DEFAULT_SIDEBAR,
EVENT,
KEYS,
- capitalizeString,
isWritableElement,
} from "@excalidraw/common";
@@ -54,7 +53,7 @@ import {
historyCommandIcon,
} from "../icons";
-import { SHAPES } from "../shapes";
+import { TOOLS, getToolLetter } from "../Tools";
import { canChangeBackgroundColor, canChangeStrokeColor } from "../Actions";
import { useStableCallback } from "../../hooks/useStableCallback";
import { activeConfirmDialogAtom } from "../ActiveConfirmDialog";
@@ -76,6 +75,7 @@ import * as defaultItems from "./defaultCommandPaletteItems";
import "./CommandPalette.scss";
import type { CommandPaletteItem } from "./types";
+import type { ToolbarToolType } from "../Tools";
import type { AppProps, AppState, LibraryItem, UIAppState } from "../../types";
import type { ShortcutName } from "../../actions/shortcuts";
import type { TranslationKeys } from "../../i18n";
@@ -356,12 +356,6 @@ function CommandPaletteInner({
}),
),
);
- const toolCommands: CommandPaletteItem[] = [
- actionManager.actions.toggleHandTool,
- actionManager.actions.setFrameAsActiveTool,
- actionManager.actions.toggleLassoTool,
- ].map((action) => actionToCommand(action, DEFAULT_CATEGORIES.tools));
-
const editorCommands: CommandPaletteItem[] = [
actionManager.actions.undo,
actionManager.actions.redo,
@@ -514,47 +508,41 @@ function CommandPaletteInner({
}));
},
},
- ...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;
- }
+ ...(Object.keys(TOOLS) as ToolbarToolType[]).reduce(
+ (acc: CommandPaletteItem[], value) => {
+ const config = TOOLS[value];
+
+ if (
+ appProps.UIOptions.tools?.[
+ value as Extract<
+ typeof value,
+ keyof AppProps["UIOptions"]["tools"]
+ >
+ ] === false
+ ) {
+ return acc;
+ }
+
+ const shortcut = getToolLetter(value) || config.numericKey;
+
+ const command: CommandPaletteItem = {
+ label: t(`toolBar.${value}`),
+ category: DEFAULT_CATEGORIES.tools,
+ shortcut,
+ icon: config.icon,
+ keywords: ["toolbar"],
+ viewMode: false,
+ perform: () => {
+ app.setActiveTool({ type: value }, { toggle: false });
+ },
+ };
+
+ acc.push(command);
- 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,
- });
- } else {
- app.setActiveTool({ type: value });
- }
- },
- };
-
- acc.push(command);
-
- return acc;
- }, []),
- ...toolCommands,
+ return acc;
+ },
+ [],
+ ),
{
label: t("toolBar.lock"),
category: DEFAULT_CATEGORIES.tools,
diff --git a/packages/excalidraw/components/ConvertElementTypePopup.tsx b/packages/excalidraw/components/ConvertElementTypePopup.tsx
index 910301288c..4ad6391dbc 100644
--- a/packages/excalidraw/components/ConvertElementTypePopup.tsx
+++ b/packages/excalidraw/components/ConvertElementTypePopup.tsx
@@ -81,7 +81,7 @@ import { trackEvent } from "../analytics";
import { atom } from "../editor-jotai";
import "./ConvertElementTypePopup.scss";
-import { ToolButton } from "./ToolButton";
+import { IconButton } from "./IconButton";
import {
DiamondIcon,
elbowArrowIcon,
@@ -332,18 +332,19 @@ const Panel = ({
getLinearElementSubType(linearElements[0]) === type));
return (
- <ToolButton
- className="Shape"
+ <IconButton
key={`${elements[0].id}${elements[0].version}_${type}`}
- type="radio"
+ type="toggle"
icon={icon}
checked={isSelected}
- name="convertElementType-option"
title={type}
- keyBindingLabel={""}
aria-label={type}
data-testid={`toolbar-${type}`}
- onChange={() => {
+ onSelect={() => {
+ // selecting the already-selected type is a no-op
+ if (isSelected) {
+ return;
+ }
if (app.state.activeTool.type !== type) {
trackEvent("convertElementType", type, "ui");
}
diff --git a/packages/excalidraw/components/DarkModeToggle.tsx b/packages/excalidraw/components/DarkModeToggle.tsx
index 474181ba4a..22ed744809 100644
--- a/packages/excalidraw/components/DarkModeToggle.tsx
+++ b/packages/excalidraw/components/DarkModeToggle.tsx
@@ -4,7 +4,7 @@ import type { Theme } from "@excalidraw/element/types";
import { t } from "../i18n";
-import { ToolButton } from "./ToolButton";
+import { IconButton } from "./IconButton";
import "./ToolIcon.scss";
@@ -22,7 +22,7 @@ export const DarkModeToggle = (props: {
: t("buttons.darkMode"));
return (
- <ToolButton
+ <IconButton
type="icon"
icon={props.value === THEME.LIGHT ? ICONS.MOON : ICONS.SUN}
title={title}
diff --git a/packages/excalidraw/components/ElementLinkDialog.tsx b/packages/excalidraw/components/ElementLinkDialog.tsx
index 5d4309c9eb..e5219f96b4 100644
--- a/packages/excalidraw/components/ElementLinkDialog.tsx
+++ b/packages/excalidraw/components/ElementLinkDialog.tsx
@@ -16,7 +16,7 @@ import { getSelectedElements } from "../scene";
import DialogActionButton from "./DialogActionButton";
import { TextField } from "./TextField";
-import { ToolButton } from "./ToolButton";
+import { IconButton } from "./IconButton";
import { TrashIcon } from "./icons";
import "./ElementLinkDialog.scss";
@@ -137,7 +137,7 @@ const ElementLinkDialog = ({
/>
{originalLink && nextLink && (
- <ToolButton
+ <IconButton
type="button"
title={t("buttons.remove")}
aria-label={t("buttons.remove")}
diff --git a/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx b/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx
index eea1cdb8d1..9000b1fb23 100644
--- a/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx
+++ b/packages/excalidraw/components/FontPicker/FontPickerTrigger.tsx
@@ -5,7 +5,7 @@ import { MOBILE_ACTION_BUTTON_BG } from "@excalidraw/common";
import type { FontFamilyValues } from "@excalidraw/element/types";
import { t } from "../../i18n";
-import { ButtonIcon } from "../ButtonIcon";
+import { IconButton } from "../IconButton";
import { TextIcon } from "../icons";
import { useExcalidrawSetAppState } from "../App";
@@ -34,14 +34,15 @@ export const FontPickerTrigger = ({
return (
<Popover.Trigger asChild>
<div data-openpopup="fontFamily" className="properties-trigger">
- <ButtonIcon
- standalone
+ <IconButton
+ type="toggle"
icon={TextIcon}
title={t("labels.showFonts")}
- className="properties-trigger"
- testId={"font-family-show-fonts"}
- active={isOpened}
- onClick={() => {
+ aria-label={t("labels.showFonts")}
+ className="standalone properties-trigger"
+ data-testid="font-family-show-fonts"
+ checked={isOpened}
+ onSelect={() => {
setAppState((appState) => ({
openPopup:
appState.openPopup === "fontFamily" ? null : appState.openPopup,
diff --git a/packages/excalidraw/components/HandButton.tsx b/packages/excalidraw/components/HandButton.tsx
deleted file mode 100644
index db653a8103..0000000000
--- a/packages/excalidraw/components/HandButton.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import clsx from "clsx";
-
-import { KEYS } from "@excalidraw/common";
-
-import { ToolButton } from "./ToolButton";
-import { handIcon } from "./icons";
-
-import "./ToolIcon.scss";
-
-type LockIconProps = {
- title?: string;
- name?: string;
- checked: boolean;
- onChange?(): void;
- isMobile?: boolean;
-};
-
-export const HandButton = (props: LockIconProps) => {
- return (
- <ToolButton
- className={clsx("Shape", { fillable: false, active: props.checked })}
- 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/HelpDialog.tsx b/packages/excalidraw/components/HelpDialog.tsx
index 5f315c70a8..eb68326017 100644
--- a/packages/excalidraw/components/HelpDialog.tsx
+++ b/packages/excalidraw/components/HelpDialog.tsx
@@ -115,7 +115,7 @@ const Shortcut = ({
<div className="HelpDialog__shortcut">
<div>{label}</div>
<div className="HelpDialog__key-container">
- {[...intersperse(splitShortcutKeys, isOr ? t("helpDialog.or") : null)]}
+ {[...intersperse(splitShortcutKeys, isOr ? t("helpDialog.or") : "")]}
</div>
</div>
);
diff --git a/packages/excalidraw/components/ToolButton.tsx b/packages/excalidraw/components/IconButton.tsx
similarity index 70%
rename from packages/excalidraw/components/ToolButton.tsx
rename to packages/excalidraw/components/IconButton.tsx
index f833a6d1f0..4dc3e113ec 100644
--- a/packages/excalidraw/components/ToolButton.tsx
+++ b/packages/excalidraw/components/IconButton.tsx
@@ -10,67 +10,64 @@ import { AbortError } from "../errors";
import "./ToolIcon.scss";
import Spinner from "./Spinner";
-import { useExcalidrawContainer } from "./App";
import type { CSSProperties } from "react";
-export type ToolButtonSize = "small" | "medium";
+export type IconButtonSize = "small" | "medium";
-type ToolButtonBaseProps = {
+type IconButtonBaseProps = {
icon?: React.ReactNode;
"aria-label": string;
"aria-keyshortcuts"?: string;
"data-testid"?: string;
label?: string;
title?: string;
- name?: string;
- id?: string;
- size?: ToolButtonSize;
+ size?: IconButtonSize;
keyBindingLabel?: string | null;
showAriaLabel?: boolean;
hidden?: boolean;
visible?: boolean;
- selected?: boolean;
disabled?: boolean;
className?: string;
style?: CSSProperties;
isLoading?: boolean;
};
-type ToolButtonProps =
- | (ToolButtonBaseProps & {
+type IconButtonProps =
+ | (IconButtonBaseProps & {
type: "button";
children?: React.ReactNode;
onClick?(event: React.MouseEvent): void;
})
- | (ToolButtonBaseProps & {
- type: "submit";
- children?: React.ReactNode;
- onClick?(event: React.MouseEvent): void;
- })
- | (ToolButtonBaseProps & {
+ | (IconButtonBaseProps & {
type: "icon";
children?: React.ReactNode;
onClick?(): void;
})
- | (ToolButtonBaseProps & {
- type: "radio";
+ // a stateful (pressed/unpressed) tool button
+ | (IconButtonBaseProps & {
+ type: "toggle";
checked: boolean;
- onChange?(data: { pointerType: PointerType | null }): void;
- onPointerDown?(data: { pointerType: PointerType }): void;
+ /**
+ * Fired on activation — a completed pointer gesture (via `click`, so a
+ * press canceled by sliding off the button doesn't select) or
+ * keyboard/AT activation, in which case pointerType is null.
+ * pointerType is captured on pointer-down, where it's reliable
+ * (unlike the click event's own pointerType on iOS).
+ */
+ onSelect?(data: { pointerType: PointerType | null }): void;
});
-export const ToolButton = React.forwardRef(
+export const IconButton = React.forwardRef(
(
{
size = "medium",
visible = true,
className = "",
...props
- }: ToolButtonProps,
+ }: IconButtonProps,
ref,
) => {
- const { id: excalId } = useExcalidrawContainer();
const innerRef = React.useRef(null);
React.useImperativeHandle(ref, () => innerRef.current);
const sizeCn = `ToolIcon_size_${size}`;
@@ -109,14 +106,7 @@ export const ToolButton = React.forwardRef(
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";
+ if (props.type === "button" || props.type === "icon") {
return (
<button
className={clsx(
@@ -128,7 +118,6 @@ export const ToolButton = React.forwardRef(
: "ToolIcon_type_button--hide",
{
ToolIcon: !props.hidden,
- "ToolIcon--selected": props.selected,
"ToolIcon--plain": props.type === "icon",
},
)}
@@ -137,7 +126,7 @@ export const ToolButton = React.forwardRef(
hidden={props.hidden}
title={props.title}
aria-label={props["aria-label"]}
- type={type}
+ type="button"
onClick={onClick}
ref={innerRef}
disabled={isLoading || props.isLoading || !!props.disabled}
@@ -168,33 +157,30 @@ export const ToolButton = React.forwardRef(
}
return (
- <label
- className={clsx("ToolIcon", className)}
+ <button
+ className={clsx("ToolIcon", "ToolIcon_type_toggle", sizeCn, className, {
+ "ToolIcon--checked": props.checked,
+ })}
+ type="button"
+ style={props.style}
title={props.title}
+ aria-label={props["aria-label"]}
+ aria-keyshortcuts={props["aria-keyshortcuts"]}
+ aria-pressed={props.checked}
+ data-testid={props["data-testid"]}
onPointerDown={(event) => {
lastPointerTypeRef.current = event.pointerType || null;
- props.onPointerDown?.({ pointerType: event.pointerType || null });
}}
onPointerUp={() => {
requestAnimationFrame(() => {
lastPointerTypeRef.current = null;
});
}}
+ onClick={() => {
+ props.onSelect?.({ pointerType: lastPointerTypeRef.current });
+ }}
+ ref={innerRef}
>
- <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 && (
@@ -203,9 +189,9 @@ export const ToolButton = React.forwardRef(
</span>
)}
</div>
- </label>
+ </button>
);
},
);
-ToolButton.displayName = "ToolButton";
+IconButton.displayName = "IconButton";
diff --git a/packages/excalidraw/components/JSONExportDialog.tsx b/packages/excalidraw/components/JSONExportDialog.tsx
index 4dfedc6922..9d94042cb1 100644
--- a/packages/excalidraw/components/JSONExportDialog.tsx
+++ b/packages/excalidraw/components/JSONExportDialog.tsx
@@ -12,7 +12,7 @@ import { t } from "../i18n";
import { Card } from "./Card";
import { Dialog } from "./Dialog";
-import { ToolButton } from "./ToolButton";
+import { IconButton } from "./IconButton";
import { exportToFileIcon, LinkIcon } from "./icons";
import "./ExportDialog.scss";
@@ -58,7 +58,7 @@ const JSONExportModal = ({
{!nativeFileSystemSupported &&
actionManager.renderAction("changeProjectName")}
</div>
- <ToolButton
+ <IconButton
className="Card-button"
type="button"
title={t("exportDialog.disk_button")}
@@ -75,7 +75,7 @@ const JSONExportModal = ({
<div className="Card-icon">{LinkIcon}</div>
<h2>{t("exportDialog.link_title")}</h2>
<div className="Card-details">{t("exportDialog.link_details")}</div>
- <ToolButton
+ <IconButton
className="Card-button"
type="button"
title={t("exportDialog.link_button")}
diff --git a/packages/excalidraw/components/LaserPointerButton.tsx b/packages/excalidraw/components/LaserPointerButton.tsx
index 237d0831c8..d421b6e653 100644
--- a/packages/excalidraw/components/LaserPointerButton.tsx
+++ b/packages/excalidraw/components/LaserPointerButton.tsx
@@ -1,43 +1,29 @@
import clsx from "clsx";
-import "./ToolIcon.scss";
-
+import { IconButton } from "./IconButton";
import { laserPointerToolIcon } from "./icons";
-import type { ToolButtonSize } from "./ToolButton";
-
-type LaserPointerIconProps = {
+type LaserPointerButtonProps = {
title?: string;
- name?: string;
checked: boolean;
onChange?(): void;
isMobile?: boolean;
};
-const DEFAULT_SIZE: ToolButtonSize = "small";
-
-export const LaserPointerButton = (props: LaserPointerIconProps) => {
+export const LaserPointerButton = (props: LaserPointerButtonProps) => {
return (
- <label
- className={clsx(
- "ToolIcon ToolIcon__LaserPointer",
- `ToolIcon_size_${DEFAULT_SIZE}`,
- {
- "is-mobile": props.isMobile,
- },
- )}
+ <IconButton
+ className={clsx("ToolIcon__LaserPointer", {
+ "is-mobile": props.isMobile,
+ })}
+ type="toggle"
+ size="small"
+ icon={laserPointerToolIcon}
+ checked={props.checked}
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>
+ aria-label={`${props.title}`}
+ data-testid="toolbar-LaserPointer"
+ onSelect={() => props.onChange?.()}
+ />
);
};
diff --git a/packages/excalidraw/components/LayerUI.scss b/packages/excalidraw/components/LayerUI.scss
index ea1ae68391..ba603fb8e8 100644
--- a/packages/excalidraw/components/LayerUI.scss
+++ b/packages/excalidraw/components/LayerUI.scss
@@ -133,7 +133,7 @@
}
// no shadow while pen mode is active (the active fill is enough)
- .ToolIcon_type_checkbox:checked + .ToolIcon__icon {
+ &.ToolIcon--checked .ToolIcon__icon {
box-shadow: none;
}
}
diff --git a/packages/excalidraw/components/LayerUI.tsx b/packages/excalidraw/components/LayerUI.tsx
index e094140b92..d9ad4abd91 100644
--- a/packages/excalidraw/components/LayerUI.tsx
+++ b/packages/excalidraw/components/LayerUI.tsx
@@ -27,13 +27,8 @@ import { useAtom, useAtomValue } from "../editor-jotai";
import { t } from "../i18n";
import { getScrollToContentState } from "../scene";
-import {
- SelectedShapeActions,
- ShapesSwitcher,
- CompactShapeActions,
-} from "./Actions";
+import { SelectedShapeActions, CompactShapeActions } from "./Actions";
import { LoadingMessage } from "./LoadingMessage";
-import { LockButton } from "./LockButton";
import { MobileMenu } from "./MobileMenu";
import { PasteChartDialog } from "./PasteChartDialog";
import { Section } from "./Section";
@@ -55,12 +50,12 @@ import { ErrorDialog } from "./ErrorDialog";
import { EyeDropper, activeEyeDropperAtom } from "./EyeDropper";
import { FixedSideContainer } from "./FixedSideContainer";
import { HelpDialog } from "./HelpDialog";
-import { HintViewer } from "./HintViewer";
import { ImageExportDialog } from "./ImageExportDialog";
import { Island } from "./Island";
import { JSONExportDialog } from "./JSONExportDialog";
import { LaserPointerButton } from "./LaserPointerButton";
import { Toast } from "./Toast";
+import { Toolbar } from "./Toolbar";
import "./LayerUI.scss";
import "./Toolbar.scss";
@@ -85,7 +80,6 @@ interface LayerUIProps {
setAppState: React.Component<any, AppState>["setState"];
elements: readonly NonDeletedExcalidrawElement[];
onLockToggle: () => void;
- onHandToolToggle: () => void;
onPenModeToggle: AppClassProperties["togglePenMode"];
showExitZenModeBtn: boolean;
langCode: Language["code"];
@@ -145,7 +139,6 @@ const LayerUI = ({
elements,
canvas,
onLockToggle,
- onHandToolToggle,
onPenModeToggle,
showExitZenModeBtn,
renderTopLeftUI,
@@ -323,7 +316,6 @@ const LayerUI = ({
!appState.viewModeEnabled &&
shouldRenderSelectedShapeActions && (
<PenModeButton
- zenModeEnabled={appState.zenModeEnabled}
checked={appState.penMode}
onChange={() => onPenModeToggle(null)}
title={t("toolBar.penMode")}
@@ -347,50 +339,15 @@ const LayerUI = ({
"zen-mode": appState.zenModeEnabled,
})}
>
- <Island
- padding={spacing.islandPadding}
- className={clsx("App-toolbar", {
- "zen-mode": appState.zenModeEnabled,
- "App-toolbar--compact": isCompactStylesPanel,
- })}
- data-viewport-ui="top"
- >
- <HintViewer
- appState={appState}
- isMobile={editorInterface.formFactor === "phone"}
- editorInterface={editorInterface}
- app={app}
- />
- {heading}
- <Stack.Row gap={spacing.toolbarInnerRowGap}>
- {/* in compact UI the pen mode button is rendered
- as a separate floating button below the compact
- actions menu */}
- {!isCompactStylesPanel && (
- <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" />
-
- <ShapesSwitcher
- setAppState={setAppState}
- activeTool={appState.activeTool}
- UIOptions={UIOptions}
- app={app}
- />
- </Stack.Row>
- </Island>
+ <Toolbar
+ app={app}
+ appState={appState}
+ setAppState={setAppState}
+ UIOptions={UIOptions}
+ onPenModeToggle={onPenModeToggle}
+ onLockToggle={onLockToggle}
+ heading={heading}
+ />
{isCollaborating && (
<Island
style={{
@@ -602,7 +559,6 @@ const LayerUI = ({
renderJSONExportDialog={renderJSONExportDialog}
renderImageExportDialog={renderImageExportDialog}
setAppState={setAppState}
- onHandToolToggle={onHandToolToggle}
onPenModeToggle={onPenModeToggle}
renderTopLeftUI={renderTopLeftUI}
renderTopRightUI={renderTopRightUI}
diff --git a/packages/excalidraw/components/LibraryMenuHeaderContent.tsx b/packages/excalidraw/components/LibraryMenuHeaderContent.tsx
index 9d7e0d1c84..4b9e3edd14 100644
--- a/packages/excalidraw/components/LibraryMenuHeaderContent.tsx
+++ b/packages/excalidraw/components/LibraryMenuHeaderContent.tsx
@@ -16,7 +16,7 @@ import ConfirmDialog from "./ConfirmDialog";
import { Dialog } from "./Dialog";
import { isLibraryMenuOpenAtom } from "./LibraryMenu";
import PublishLibrary from "./PublishLibrary";
-import { ToolButton } from "./ToolButton";
+import { IconButton } from "./IconButton";
import Trans from "./Trans";
import DropdownMenu from "./dropdownMenu/DropdownMenu";
import {
@@ -127,7 +127,7 @@ export const LibraryDropdownMenuButton: React.FC<{
)}
/>
</p>
- <ToolButton
+ <IconButton
type="button"
title={t("buttons.close")}
aria-label={t("buttons.close")}
diff --git a/packages/excalidraw/components/LockButton.tsx b/packages/excalidraw/components/LockButton.tsx
index 8363ffa0cf..028b71c0c5 100644
--- a/packages/excalidraw/components/LockButton.tsx
+++ b/packages/excalidraw/components/LockButton.tsx
@@ -1,50 +1,26 @@
import clsx from "clsx";
-import "./ToolIcon.scss";
-
+import { IconButton } from "./IconButton";
import { LockedIcon, UnlockedIcon } from "./icons";
-import type { ToolButtonSize } from "./ToolButton";
-
-type LockIconProps = {
+type LockButtonProps = {
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) => {
+export const LockButton = (props: LockButtonProps) => {
return (
- <label
- className={clsx(
- "ToolIcon ToolIcon__lock",
- `ToolIcon_size_${DEFAULT_SIZE}`,
- {
- "is-mobile": props.isMobile,
- },
- )}
+ <IconButton
+ className={clsx("ToolIcon__lock", { "is-mobile": props.isMobile })}
+ type="toggle"
+ icon={props.checked ? LockedIcon : UnlockedIcon}
+ checked={props.checked}
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>
+ aria-label={`${props.title}`}
+ data-testid="toolbar-lock"
+ onSelect={() => props.onChange?.()}
+ />
);
};
diff --git a/packages/excalidraw/components/MagicButton.tsx b/packages/excalidraw/components/MagicButton.tsx
index b2bbd03e2e..904c51ea7a 100644
--- a/packages/excalidraw/components/MagicButton.tsx
+++ b/packages/excalidraw/components/MagicButton.tsx
@@ -1,40 +1,28 @@
import clsx from "clsx";
-import "./ToolIcon.scss";
+import { IconButton } from "./IconButton";
-import type { ToolButtonSize } from "./ToolButton";
import type { JSX } from "react";
-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,
- },
- )}
+ <IconButton
+ className={clsx("ToolIcon__MagicButton", {
+ "is-mobile": props.isMobile,
+ })}
+ type="toggle"
+ size="small"
+ icon={props.icon}
+ checked={props.checked}
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>
+ aria-label={`${props.title}`}
+ onSelect={() => props.onChange?.()}
+ />
);
};
diff --git a/packages/excalidraw/components/MobileMenu.tsx b/packages/excalidraw/components/MobileMenu.tsx
index 1d5482d5d1..2702f978b4 100644
--- a/packages/excalidraw/components/MobileMenu.tsx
+++ b/packages/excalidraw/components/MobileMenu.tsx
@@ -8,7 +8,7 @@ import { getScrollToContentState } from "../scene";
import { SCROLLBAR_WIDTH, SCROLLBAR_MARGIN } from "../scene/scrollbars";
import { ExitViewModeButton, MobileShapeActions } from "./Actions";
-import { MobileToolBar } from "./MobileToolBar";
+import { MobileToolbar } from "./MobileToolbar";
import { FixedSideContainer } from "./FixedSideContainer";
import { Island } from "./Island";
@@ -31,7 +31,6 @@ type MobileMenuProps = {
renderImageExportDialog: () => React.ReactNode;
setAppState: React.Component<any, AppState>["setState"];
elements: readonly NonDeletedExcalidrawElement[];
- onHandToolToggle: () => void;
onPenModeToggle: AppClassProperties["togglePenMode"];
renderTopRightUI?: (
@@ -53,7 +52,6 @@ export const MobileMenu = ({
elements,
actionManager,
setAppState,
- onHandToolToggle,
renderTopLeftUI,
renderTopRightUI,
renderSidebars,
@@ -116,13 +114,7 @@ export const MobileMenu = ({
};
const renderToolbar = () => {
- return (
- <MobileToolBar
- app={app}
- onHandToolToggle={onHandToolToggle}
- setAppState={setAppState}
- />
- );
+ return <MobileToolbar app={app} setAppState={setAppState} />;
};
return (
diff --git a/packages/excalidraw/components/MobileToolBar.scss b/packages/excalidraw/components/MobileToolbar.scss
similarity index 76%
rename from packages/excalidraw/components/MobileToolBar.scss
rename to packages/excalidraw/components/MobileToolbar.scss
index 985c676eee..56f4d18640 100644
--- a/packages/excalidraw/components/MobileToolBar.scss
+++ b/packages/excalidraw/components/MobileToolbar.scss
@@ -31,17 +31,17 @@
width: 2.25rem;
height: 2.25rem;
+ // hover has no meaning on touch devices (and sticks to the last-tapped
+ // element), so suppress the hover background…
&:hover {
background-color: transparent;
}
}
- &.active {
- background: var(
- --color-surface-primary-container,
- var(--island-bg-color)
- );
- border-color: var(--button-active-border, var(--color-primary-darkest));
+ // …but not on checked buttons, where the sticky hover of the tap that
+ // checked them would otherwise suppress the checked highlight
+ &.ToolIcon--checked .ToolIcon__icon:hover {
+ background-color: var(--color-surface-primary-container);
}
svg {
diff --git a/packages/excalidraw/components/MobileToolBar.tsx b/packages/excalidraw/components/MobileToolbar.tsx
similarity index 58%
rename from packages/excalidraw/components/MobileToolBar.tsx
rename to packages/excalidraw/components/MobileToolbar.tsx
index 7b541bb311..033fa956bb 100644
--- a/packages/excalidraw/components/MobileToolBar.tsx
+++ b/packages/excalidraw/components/MobileToolbar.tsx
@@ -3,95 +3,45 @@ import clsx from "clsx";
import { KEYS, capitalizeString } from "@excalidraw/common";
-import { trackEvent } from "../analytics";
-
import { t } from "../i18n";
-import { isHandToolActive } from "../appState";
-
import { useTunnels } from "../context/tunnels";
-import { HandButton } from "./HandButton";
-import { ToolButton } from "./ToolButton";
import DropdownMenu from "./dropdownMenu/DropdownMenu";
import { ToolPopover } from "./ToolPopover";
+import {
+ EraserToolButton,
+ FrameToolButton,
+ FreedrawToolButton,
+ HandToolButton,
+ ImageToolButton,
+ SelectionToolPopover,
+ TextToolButton,
+ TOOLS,
+} from "./Tools";
import {
- SelectionIcon,
- FreedrawIcon,
- EraserIcon,
- RectangleIcon,
- ArrowIcon,
- extraToolsIcon,
- DiamondIcon,
- EllipseIcon,
- LineIcon,
TextIcon,
ImageIcon,
+ extraToolsIcon,
frameToolIcon,
EmbedIcon,
laserPointerToolIcon,
- LassoIcon,
mermaidLogoIcon,
MagicIcon,
} from "./icons";
import "./ToolIcon.scss";
-import "./MobileToolBar.scss";
-
-import type { AppClassProperties, ToolType, UIAppState } from "../types";
-
-const SHAPE_TOOLS = [
- {
- type: "rectangle",
- icon: RectangleIcon,
- title: capitalizeString(t("toolBar.rectangle")),
- },
- {
- type: "diamond",
- icon: DiamondIcon,
- title: capitalizeString(t("toolBar.diamond")),
- },
- {
- type: "ellipse",
- icon: EllipseIcon,
- title: capitalizeString(t("toolBar.ellipse")),
- },
-] as const;
-
-const SELECTION_TOOLS = [
- {
- type: "selection",
- icon: SelectionIcon,
- title: capitalizeString(t("toolBar.selection")),
- },
- {
- type: "lasso",
- icon: LassoIcon,
- title: capitalizeString(t("toolBar.lasso")),
- },
-] as const;
-
-const LINEAR_ELEMENT_TOOLS = [
- {
- type: "arrow",
- icon: ArrowIcon,
- title: capitalizeString(t("toolBar.arrow")),
- },
- { type: "line", icon: LineIcon, title: capitalizeString(t("toolBar.line")) },
-] as const;
-
-type MobileToolBarProps = {
+import "./MobileToolbar.scss";
+
+import type { AppClassProperties, UIAppState } from "../types";
+
+type MobileToolbarProps = {
app: AppClassProperties;
- onHandToolToggle: () => void;
setAppState: React.Component<any, UIAppState>["setState"];
};
-export const MobileToolBar = ({
- app,
- onHandToolToggle,
- setAppState,
-}: MobileToolBarProps) => {
+export const MobileToolbar = ({ app, setAppState }: MobileToolbarProps) => {
const activeTool = app.state.activeTool;
const [isOtherShapesMenuOpen, setIsOtherShapesMenuOpen] = useState(false);
const [lastActiveGenericShape, setLastActiveGenericShape] = useState<
@@ -125,21 +75,21 @@ export const MobileToolBar = ({
const { TTDDialogTriggerTunnel } = useTunnels();
- const handleToolChange = (toolType: string, pointerType?: string) => {
- if (app.state.activeTool.type !== toolType) {
- trackEvent("toolbar", toolType, "ui");
- }
+ const SHAPE_TOOLS = (["rectangle", "diamond", "ellipse"] as const).map(
+ (type) => ({
+ type,
+ icon: TOOLS[type].icon,
+ title: capitalizeString(t(`toolBar.${type}`)),
+ fillable: TOOLS[type].fillable,
+ }),
+ );
- if (toolType === "selection") {
- if (app.state.activeTool.type === "selection") {
- // Toggle selection tool behavior if needed
- } else {
- app.setActiveTool({ type: "selection" });
- }
- } else {
- app.setActiveTool({ type: toolType as ToolType });
- }
- };
+ const LINEAR_ELEMENT_TOOLS = (["arrow", "line"] as const).map((type) => ({
+ type,
+ icon: TOOLS[type].icon,
+ title: capitalizeString(t(`toolBar.${type}`)),
+ fillable: TOOLS[type].fillable,
+ }));
const [toolbarWidth, setToolbarWidth] = useState(0);
@@ -155,19 +105,12 @@ export const MobileToolBar = ({
const showImageToolOutside = toolbarWidth >= MIN_WIDTH + 2 * ADDITIONAL_WIDTH;
const showFrameToolOutside = toolbarWidth >= MIN_WIDTH + 3 * ADDITIONAL_WIDTH;
- const extraTools = [
- "text",
- "frame",
- "embeddable",
- "laser",
- "magicframe",
- ].filter((tool) => {
+ const extraTools: readonly typeof activeTool.type[] = (
+ ["text", "frame", "embeddable", "laser", "magicframe"] as const
+ ).filter((tool) => {
if (showTextToolOutside && tool === "text") {
return false;
}
- if (showImageToolOutside && tool === "image") {
- return false;
- }
if (showFrameToolOutside && tool === "frame") {
return false;
}
@@ -190,6 +133,8 @@ export const MobileToolBar = ({
: extraToolsIcon
: extraToolsIcon;
+ const toolProps = { app, activeTool };
+
return (
<div
className="mobile-toolbar"
@@ -200,85 +145,23 @@ export const MobileToolBar = ({
}}
>
{/* Hand Tool */}
- <HandButton
- checked={isHandToolActive(app.state)}
- onChange={onHandToolToggle}
- title={t("toolBar.hand")}
- isMobile
- />
+ <HandToolButton {...toolProps} hideKeyBinding />
{/* Selection Tool */}
- <ToolPopover
- app={app}
- options={SELECTION_TOOLS}
- activeTool={activeTool}
- defaultOption={app.state.preferredSelectionTool.type}
- namePrefix="selectionType"
- title={capitalizeString(t("toolBar.selection"))}
- data-testid="toolbar-selection"
- onToolChange={(type: string) => {
- if (type === "selection" || type === "lasso") {
- app.setActiveTool({ type });
- setAppState({
- preferredSelectionTool: { type, initialized: true },
- });
- }
- }}
- displayedOption={
- SELECTION_TOOLS.find(
- (tool) => tool.type === app.state.preferredSelectionTool.type,
- ) || SELECTION_TOOLS[0]
- }
- />
+ <SelectionToolPopover {...toolProps} setAppState={setAppState} />
{/* Free Draw */}
- <ToolButton
- className={clsx({
- active: activeTool.type === "freedraw",
- })}
- type="radio"
- icon={FreedrawIcon}
- checked={activeTool.type === "freedraw"}
- name="editor-current-shape"
- title={`${capitalizeString(t("toolBar.freedraw"))}`}
- aria-label={capitalizeString(t("toolBar.freedraw"))}
- data-testid="toolbar-freedraw"
- onChange={() => handleToolChange("freedraw")}
- />
+ <FreedrawToolButton {...toolProps} hideShortcut />
{/* Eraser */}
- <ToolButton
- className={clsx({
- active: activeTool.type === "eraser",
- })}
- type="radio"
- icon={EraserIcon}
- checked={activeTool.type === "eraser"}
- name="editor-current-shape"
- title={`${capitalizeString(t("toolBar.eraser"))}`}
- aria-label={capitalizeString(t("toolBar.eraser"))}
- data-testid="toolbar-eraser"
- onChange={() => handleToolChange("eraser")}
- />
+ <EraserToolButton {...toolProps} hideShortcut />
- {/* Rectangle */}
+ {/* Rectangle/Diamond/Ellipse */}
<ToolPopover
app={app}
options={SHAPE_TOOLS}
activeTool={activeTool}
defaultOption={lastActiveGenericShape}
- namePrefix="shapeType"
- title={capitalizeString(
- t(
- lastActiveGenericShape === "rectangle"
- ? "toolBar.rectangle"
- : lastActiveGenericShape === "diamond"
- ? "toolBar.diamond"
- : lastActiveGenericShape === "ellipse"
- ? "toolBar.ellipse"
- : "toolBar.rectangle",
- ),
- )}
data-testid="toolbar-rectangle"
onToolChange={(type: string) => {
if (
@@ -302,16 +185,7 @@ export const MobileToolBar = ({
options={LINEAR_ELEMENT_TOOLS}
activeTool={activeTool}
defaultOption={lastActiveLinearElement}
- namePrefix="linearElementType"
- title={capitalizeString(
- t(
- lastActiveLinearElement === "arrow"
- ? "toolBar.arrow"
- : "toolBar.line",
- ),
- )}
data-testid="toolbar-arrow"
- fillable={true}
onToolChange={(type: string) => {
if (type === "arrow" || type === "line") {
setLastActiveLinearElement(type);
@@ -326,53 +200,13 @@ export const MobileToolBar = ({
/>
{/* Text Tool */}
- {showTextToolOutside && (
- <ToolButton
- className={clsx({
- active: activeTool.type === "text",
- })}
- type="radio"
- icon={TextIcon}
- checked={activeTool.type === "text"}
- name="editor-current-shape"
- title={`${capitalizeString(t("toolBar.text"))}`}
- aria-label={capitalizeString(t("toolBar.text"))}
- data-testid="toolbar-text"
- onChange={() => handleToolChange("text")}
- />
- )}
+ {showTextToolOutside && <TextToolButton {...toolProps} hideShortcut />}
{/* Image */}
- {showImageToolOutside && (
- <ToolButton
- className={clsx({
- active: activeTool.type === "image",
- })}
- type="radio"
- icon={ImageIcon}
- checked={activeTool.type === "image"}
- name="editor-current-shape"
- title={`${capitalizeString(t("toolBar.image"))}`}
- aria-label={capitalizeString(t("toolBar.image"))}
- data-testid="toolbar-image"
- onChange={() => handleToolChange("image")}
- />
- )}
+ {showImageToolOutside && <ImageToolButton {...toolProps} hideShortcut />}
{/* Frame Tool */}
- {showFrameToolOutside && (
- <ToolButton
- className={clsx({ active: frameToolSelected })}
- type="radio"
- icon={frameToolIcon}
- checked={frameToolSelected}
- name="editor-current-shape"
- title={`${capitalizeString(t("toolBar.frame"))}`}
- aria-label={capitalizeString(t("toolBar.frame"))}
- data-testid="toolbar-frame"
- onChange={() => handleToolChange("frame")}
- />
- )}
+ {showFrameToolOutside && <FrameToolButton {...toolProps} hideShortcut />}
{/* Other Shapes */}
<DropdownMenu open={isOtherShapesMenuOpen}>
diff --git a/packages/excalidraw/components/PenModeButton.tsx b/packages/excalidraw/components/PenModeButton.tsx
index e5df8ac9b3..c9c2147721 100644
--- a/packages/excalidraw/components/PenModeButton.tsx
+++ b/packages/excalidraw/components/PenModeButton.tsx
@@ -1,48 +1,30 @@
import clsx from "clsx";
-import "./ToolIcon.scss";
-
+import { IconButton } from "./IconButton";
import { PenModeIcon } from "./icons";
-import type { ToolButtonSize } from "./ToolButton";
-
-type PenModeIconProps = {
+type PenModeButtonProps = {
title?: string;
- name?: string;
checked: boolean;
onChange?(): void;
- zenModeEnabled?: boolean;
isMobile?: boolean;
penDetected: boolean;
};
-const DEFAULT_SIZE: ToolButtonSize = "medium";
-
-export const PenModeButton = (props: PenModeIconProps) => {
+export const PenModeButton = (props: PenModeButtonProps) => {
if (!props.penDetected) {
return null;
}
return (
- <label
- className={clsx(
- "ToolIcon ToolIcon__penMode",
- `ToolIcon_size_${DEFAULT_SIZE}`,
- {
- "is-mobile": props.isMobile,
- },
- )}
+ <IconButton
+ className={clsx("ToolIcon__penMode", { "is-mobile": props.isMobile })}
+ type="toggle"
+ icon={PenModeIcon}
+ checked={props.checked}
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>
+ aria-label={`${props.title}`}
+ onSelect={() => props.onChange?.()}
+ />
);
};
diff --git a/packages/excalidraw/components/PublishLibrary.tsx b/packages/excalidraw/components/PublishLibrary.tsx
index 0376f812a5..c9376895da 100644
--- a/packages/excalidraw/components/PublishLibrary.tsx
+++ b/packages/excalidraw/components/PublishLibrary.tsx
@@ -16,7 +16,7 @@ import { t } from "../i18n";
import { Dialog } from "./Dialog";
import DialogActionButton from "./DialogActionButton";
-import { ToolButton } from "./ToolButton";
+import { IconButton } from "./IconButton";
import Trans from "./Trans";
import { CloseIcon } from "./icons";
@@ -148,7 +148,7 @@ const SingleLibraryItem = ({
</span>
)}
<div ref={svgRef} className="single-library-item__svg" />
- <ToolButton
+ <IconButton
aria-label={t("buttons.remove")}
type="button"
icon={CloseIcon}
diff --git a/packages/excalidraw/components/ButtonIcon.tsx b/packages/excalidraw/components/RadioButton.tsx
similarity index 62%
rename from packages/excalidraw/components/ButtonIcon.tsx
rename to packages/excalidraw/components/RadioButton.tsx
index 77a918b3ac..b1aa08c707 100644
--- a/packages/excalidraw/components/ButtonIcon.tsx
+++ b/packages/excalidraw/components/RadioButton.tsx
@@ -1,27 +1,22 @@
import clsx from "clsx";
import { forwardRef } from "react";
-import "./ButtonIcon.scss";
-
import type { JSX } from "react";
-interface ButtonIconProps {
+interface RadioButtonProps {
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;
style?: React.CSSProperties;
}
-export const ButtonIcon = forwardRef<HTMLButtonElement, ButtonIconProps>(
+export const RadioButton = forwardRef<HTMLButtonElement, RadioButtonProps>(
(props, ref) => {
- const { title, className, testId, active, standalone, icon, onClick } =
- props;
+ const { title, className, testId, active, icon, onClick } = props;
return (
<button
type="button"
@@ -29,7 +24,7 @@ export const ButtonIcon = forwardRef<HTMLButtonElement, ButtonIconProps>(
key={title}
title={title}
data-testid={testId}
- className={clsx(className, { standalone, active })}
+ className={clsx(className, { active })}
onClick={onClick}
style={props.style}
>
diff --git a/packages/excalidraw/components/RadioSelection.tsx b/packages/excalidraw/components/RadioSelection.tsx
index 9cdc47e483..a8cffc1eab 100644
--- a/packages/excalidraw/components/RadioSelection.tsx
+++ b/packages/excalidraw/components/RadioSelection.tsx
@@ -1,6 +1,6 @@
import clsx from "clsx";
-import { ButtonIcon } from "./ButtonIcon";
+import { RadioButton } from "./RadioButton";
import type { JSX } from "react";
@@ -30,7 +30,7 @@ export const RadioSelection = <T extends Object>(
<>
{props.options.map((option) =>
props.type === "button" ? (
- <ButtonIcon
+ <RadioButton
key={option.text}
icon={option.icon}
title={option.text}
diff --git a/packages/excalidraw/components/Sidebar/SidebarTrigger.scss b/packages/excalidraw/components/Sidebar/SidebarTrigger.scss
index 6deaa54d66..8f9752d452 100644
--- a/packages/excalidraw/components/Sidebar/SidebarTrigger.scss
+++ b/packages/excalidraw/components/Sidebar/SidebarTrigger.scss
@@ -22,8 +22,18 @@
height: var(--lg-icon-size);
}
+ // the <button> wrapper — resets the native button chrome (the visual
+ // styling lives on the inner .sidebar-trigger)
&__label-element {
align-self: flex-start;
+ appearance: none;
+ margin: 0;
+ padding: 0;
+ border: none;
+ background-color: transparent;
+ font: inherit;
+ color: inherit;
+ text-align: inherit;
}
}
diff --git a/packages/excalidraw/components/Sidebar/SidebarTrigger.tsx b/packages/excalidraw/components/Sidebar/SidebarTrigger.tsx
index 706a6abe52..e65ff7afc3 100644
--- a/packages/excalidraw/components/Sidebar/SidebarTrigger.tsx
+++ b/packages/excalidraw/components/Sidebar/SidebarTrigger.tsx
@@ -20,32 +20,34 @@ export const SidebarTrigger = ({
const setAppState = useExcalidrawSetAppState();
const appState = useUIAppState();
+ const isOpen = appState.openSidebar?.name === name;
+
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,
- openMenu: null,
- openPopup: null,
- });
- onToggle?.(isOpen);
- }}
- checked={appState.openSidebar?.name === name}
- aria-label={title}
- aria-keyshortcuts="0"
- />
+ <button
+ type="button"
+ title={title}
+ className="sidebar-trigger__label-element"
+ aria-label={title}
+ aria-keyshortcuts="0"
+ aria-pressed={isOpen}
+ onClick={() => {
+ document
+ .querySelector(".layer-ui__wrapper")
+ ?.classList.remove("animate");
+ const nextOpen = !isOpen;
+ setAppState({
+ openSidebar: nextOpen ? { name, tab } : null,
+ openMenu: null,
+ openPopup: null,
+ });
+ onToggle?.(nextOpen);
+ }}
+ >
<div className={clsx("sidebar-trigger", className)} style={style}>
{icon && <div>{icon}</div>}
{children && <div className="sidebar-trigger__label">{children}</div>}
</div>
- </label>
+ </button>
);
};
SidebarTrigger.displayName = "SidebarTrigger";
diff --git a/packages/excalidraw/components/Toast.tsx b/packages/excalidraw/components/Toast.tsx
index e30b4b2fa0..7c1208197f 100644
--- a/packages/excalidraw/components/Toast.tsx
+++ b/packages/excalidraw/components/Toast.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef } from "react";
import { CloseIcon } from "./icons";
-import { ToolButton } from "./ToolButton";
+import { IconButton } from "./IconButton";
import "./Toast.scss";
@@ -65,7 +65,7 @@ const ToastComponent = ({
>
<div className="Toast__message">{message}</div>
{closable && (
- <ToolButton
+ <IconButton
icon={CloseIcon}
aria-label="close"
type="icon"
diff --git a/packages/excalidraw/components/ToolIcon.scss b/packages/excalidraw/components/ToolIcon.scss
index 191d866dd3..baeea6701c 100644
--- a/packages/excalidraw/components/ToolIcon.scss
+++ b/packages/excalidraw/components/ToolIcon.scss
@@ -25,11 +25,22 @@
}
}
- .ToolIcon_type_radio,
- .ToolIcon_type_checkbox {
- position: absolute;
- opacity: 0;
- pointer-events: none;
+ // a <button> replacement for the former radio/checkbox-input ToolIcon —
+ // resets the native button chrome; state styling lives on the inner
+ // .ToolIcon__icon (see toolbarButtonColorStates)
+ .ToolIcon_type_toggle {
+ appearance: none;
+ margin: 0;
+ padding: 0;
+ border: none;
+ background-color: transparent;
+ font: inherit;
+ color: inherit;
+ text-align: inherit;
+
+ &:focus-visible {
+ box-shadow: 0 0 0 2px var(--focus-highlight-color);
+ }
}
.ToolIcon__icon {
@@ -87,14 +98,6 @@
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);
}
diff --git a/packages/excalidraw/components/ToolPopover.tsx b/packages/excalidraw/components/ToolPopover.tsx
index 853fc9c2f4..ce8f2f830f 100644
--- a/packages/excalidraw/components/ToolPopover.tsx
+++ b/packages/excalidraw/components/ToolPopover.tsx
@@ -7,7 +7,7 @@ import { Popover } from "radix-ui";
import { trackEvent } from "../analytics";
-import { ToolButton } from "./ToolButton";
+import { IconButton } from "./IconButton";
import "./ToolPopover.scss";
@@ -18,7 +18,8 @@ import type { AppClassProperties } from "../types";
type ToolOption = {
type: string;
icon: React.ReactNode;
- title?: string;
+ title: string;
+ fillable?: boolean;
};
type ToolPopoverProps = {
@@ -26,13 +27,9 @@ type ToolPopoverProps = {
options: readonly ToolOption[];
activeTool: { type: string };
defaultOption: string;
- className?: string;
- namePrefix: string;
- title: string;
"data-testid": string;
onToolChange: (type: string) => void;
displayedOption: ToolOption;
- fillable?: boolean;
};
export const ToolPopover = ({
@@ -40,13 +37,9 @@ export const ToolPopover = ({
options,
activeTool,
defaultOption,
- className = "Shape",
- namePrefix,
- title,
"data-testid": dataTestId,
onToolChange,
displayedOption,
- fillable = false,
}: ToolPopoverProps) => {
const [isPopupOpen, setIsPopupOpen] = useState(false);
const currentType = activeTool.type;
@@ -71,19 +64,15 @@ export const ToolPopover = ({
return (
<Popover.Root open={isPopupOpen}>
<Popover.Trigger asChild>
- <ToolButton
- className={clsx(className, {
- fillable,
- active: options.some((o) => o.type === activeTool.type),
- })}
- type="radio"
+ <IconButton
+ className={clsx({ fillable: displayedOption.fillable })}
+ type="toggle"
icon={displayedOption.icon}
checked={isActive}
- name="editor-current-shape"
- title={title}
- aria-label={title}
+ title={capitalizeString(displayedOption.title)}
+ aria-label={capitalizeString(displayedOption.title)}
data-testid={dataTestId}
- onPointerDown={() => {
+ onSelect={() => {
setIsPopupOpen((v) => !v);
onToolChange(defaultOption);
}}
@@ -95,26 +84,22 @@ export const ToolPopover = ({
sideOffset={SIDE_OFFSET}
collisionBoundary={container ?? undefined}
>
- {options.map(({ type, icon, title }) => (
- <ToolButton
- className={clsx(className, {
- active: currentType === type,
- })}
+ {options.map(({ type, icon, title, fillable }) => (
+ <IconButton
+ className={clsx({ fillable })}
key={type}
- type="radio"
+ type="toggle"
icon={icon}
checked={currentType === type}
- name={`${namePrefix}-option`}
- title={title || capitalizeString(type)}
- keyBindingLabel=""
- aria-label={title || capitalizeString(type)}
+ title={capitalizeString(type)}
+ aria-label={capitalizeString(type)}
data-testid={`toolbar-${type}`}
- onChange={() => {
+ onSelect={() => {
if (app.state.activeTool.type !== type) {
trackEvent("toolbar", type, "ui");
+ app.setActiveTool({ type: type as any });
+ onToolChange?.(type);
}
- app.setActiveTool({ type: type as any });
- onToolChange?.(type);
}}
/>
))}
diff --git a/packages/excalidraw/components/Toolbar.tsx b/packages/excalidraw/components/Toolbar.tsx
new file mode 100644
index 0000000000..b99185b2d4
--- /dev/null
+++ b/packages/excalidraw/components/Toolbar.tsx
@@ -0,0 +1,252 @@
+import clsx from "clsx";
+import { useState } from "react";
+
+import { KEYS } from "@excalidraw/common";
+
+import { useTunnels } from "../context/tunnels";
+import { t } from "../i18n";
+
+import { useEditorInterface, useStylesPanelMode } from "./App";
+import { HintViewer } from "./HintViewer";
+import { Island } from "./Island";
+import { LockButton } from "./LockButton";
+import { PenModeButton } from "./PenModeButton";
+import Stack from "./Stack";
+import DropdownMenu from "./dropdownMenu/DropdownMenu";
+import {
+ EmbedIcon,
+ extraToolsIcon,
+ frameToolIcon,
+ LassoIcon,
+ laserPointerToolIcon,
+ MagicIcon,
+ mermaidLogoIcon,
+} from "./icons";
+import {
+ ArrowToolButton,
+ DiamondToolButton,
+ EllipseToolButton,
+ EraserToolButton,
+ FreedrawToolButton,
+ HandToolButton,
+ ImageToolButton,
+ LassoToolButton,
+ LineToolButton,
+ RectangleToolButton,
+ SelectionToolButton,
+ SelectionToolPopover,
+ TextToolButton,
+} from "./Tools";
+
+import type {
+ AppClassProperties,
+ AppProps,
+ AppState,
+ UIAppState,
+} from "../types";
+
+const ExtraToolsDropdown = ({
+ app,
+ activeTool,
+ setAppState,
+}: {
+ app: AppClassProperties;
+ activeTool: UIAppState["activeTool"];
+ setAppState: React.Component<any, AppState>["setState"];
+}) => {
+ const [isExtraToolsMenuOpen, setIsExtraToolsMenuOpen] = useState(false);
+ const isFullStylesPanel = useStylesPanelMode() === "full";
+ const { TTDDialogTriggerTunnel } = useTunnels();
+
+ const frameToolSelected = activeTool.type === "frame";
+ const laserToolSelected = activeTool.type === "laser";
+ const lassoToolSelected =
+ isFullStylesPanel &&
+ activeTool.type === "lasso" &&
+ app.state.preferredSelectionTool.type !== "lasso";
+ const embeddableToolSelected = activeTool.type === "embeddable";
+
+ return (
+ <DropdownMenu open={isExtraToolsMenuOpen}>
+ <DropdownMenu.Trigger
+ className={clsx("App-toolbar__extra-tools-trigger", {
+ "App-toolbar__extra-tools-trigger--selected":
+ frameToolSelected ||
+ embeddableToolSelected ||
+ lassoToolSelected ||
+ // 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);
+ setAppState({ openMenu: null, openPopup: null });
+ }}
+ title={t("toolBar.extraTools")}
+ >
+ {frameToolSelected
+ ? frameToolIcon
+ : embeddableToolSelected
+ ? EmbedIcon
+ : laserToolSelected && !app.props.isCollaborating
+ ? laserPointerToolIcon
+ : lassoToolSelected
+ ? LassoIcon
+ : 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>
+ {isFullStylesPanel && (
+ <DropdownMenu.Item
+ onSelect={() => app.setActiveTool({ type: "lasso" })}
+ icon={LassoIcon}
+ data-testid="toolbar-lasso"
+ selected={lassoToolSelected}
+ >
+ {t("toolBar.lasso")}
+ </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"
+ badge={<DropdownMenu.Item.Badge>AI</DropdownMenu.Item.Badge>}
+ >
+ {t("toolBar.magicframe")}
+ </DropdownMenu.Item>
+ )}
+ </DropdownMenu.Content>
+ </DropdownMenu>
+ );
+};
+
+/** the main (desktop/tablet) toolbar island */
+export const Toolbar = ({
+ app,
+ appState,
+ setAppState,
+ UIOptions,
+ onPenModeToggle,
+ onLockToggle,
+ heading,
+}: {
+ app: AppClassProperties;
+ appState: UIAppState;
+ setAppState: React.Component<any, AppState>["setState"];
+ UIOptions: AppProps["UIOptions"];
+ onPenModeToggle: AppClassProperties["togglePenMode"];
+ onLockToggle: () => void;
+ heading: React.ReactNode;
+}) => {
+ const editorInterface = useEditorInterface();
+ const isCompactStylesPanel = useStylesPanelMode() === "compact";
+
+ const activeTool = appState.activeTool;
+ const toolProps = { app, activeTool };
+
+ return (
+ <Island
+ padding={1}
+ className={clsx("App-toolbar", {
+ "zen-mode": appState.zenModeEnabled,
+ "App-toolbar--compact": isCompactStylesPanel,
+ })}
+ data-viewport-ui="top"
+ >
+ <HintViewer
+ appState={appState}
+ isMobile={editorInterface.formFactor === "phone"}
+ editorInterface={editorInterface}
+ app={app}
+ />
+ {heading}
+ <Stack.Row gap={isCompactStylesPanel ? 0.5 : 1}>
+ {/* in compact UI the pen mode button is rendered as a separate
+ floating button below the compact actions menu */}
+ {!isCompactStylesPanel && (
+ <PenModeButton
+ 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" />
+
+ <HandToolButton {...toolProps} hideKeyBinding />
+ {isCompactStylesPanel ? (
+ <SelectionToolPopover {...toolProps} setAppState={setAppState} />
+ ) : appState.preferredSelectionTool.type === "lasso" ? (
+ <LassoToolButton {...toolProps} />
+ ) : (
+ <SelectionToolButton {...toolProps} />
+ )}
+ <RectangleToolButton {...toolProps} />
+ <DiamondToolButton {...toolProps} />
+ <EllipseToolButton {...toolProps} />
+ <ArrowToolButton {...toolProps} />
+ <LineToolButton {...toolProps} />
+ <FreedrawToolButton {...toolProps} />
+ <TextToolButton {...toolProps} />
+ {UIOptions.tools?.image !== false && <ImageToolButton {...toolProps} />}
+ <EraserToolButton {...toolProps} />
+
+ <div className="App-toolbar__divider" />
+
+ <ExtraToolsDropdown
+ app={app}
+ activeTool={activeTool}
+ setAppState={setAppState}
+ />
+ </Stack.Row>
+ </Island>
+ );
+};
diff --git a/packages/excalidraw/components/Tools.tsx b/packages/excalidraw/components/Tools.tsx
new file mode 100644
index 0000000000..602b0bfb2c
--- /dev/null
+++ b/packages/excalidraw/components/Tools.tsx
@@ -0,0 +1,372 @@
+import clsx from "clsx";
+
+import { KEYS, capitalizeString } from "@excalidraw/common";
+
+import type { PointerType } from "@excalidraw/element/types";
+
+import { trackEvent } from "../analytics";
+import { t } from "../i18n";
+
+import { IconButton } from "./IconButton";
+import { ToolPopover } from "./ToolPopover";
+import {
+ SelectionIcon,
+ RectangleIcon,
+ DiamondIcon,
+ EllipseIcon,
+ ArrowIcon,
+ LineIcon,
+ FreedrawIcon,
+ TextIcon,
+ ImageIcon,
+ EraserIcon,
+ laserPointerToolIcon,
+ LassoIcon,
+ handIcon,
+ frameToolIcon,
+ EmbedIcon,
+} from "./icons";
+
+import type {
+ AppClassProperties,
+ AppState,
+ ToolType,
+ UIAppState,
+} from "../types";
+
+export type ToolConfig = {
+ icon: React.ReactNode;
+ /** letter shortcut(s) — the first one is shown in tooltips */
+ letterKey?: string | readonly string[];
+ numericKey?: string;
+ /** whether the tool's shapes can be filled — fills the icon when active */
+ fillable?: boolean;
+ /**
+ * re-activating the tool switches back to the previously active tool
+ * (via the keyboard shortcut or ESC — see `setActiveTool`'s `toggle`
+ * option)
+ */
+ toggle?: boolean;
+};
+
+/** preserves the exact keys while typing every entry as ToolConfig */
+const defineTools = <T extends Record<string, ToolConfig>>(tools: T) =>
+ tools as { [K in keyof T]: ToolConfig };
+
+/**
+ * Tool data — the single source of truth for tool buttons, keyboard
+ * shortcuts (`findShapeByKey`), and the command palette. Toolbar placement
+ * is not defined here: toolbars compose the `*ToolButton` components below
+ * manually, so entries without a toolbar slot (e.g. laser) are data-only.
+ */
+export const TOOLS = defineTools({
+ hand: {
+ icon: handIcon,
+ letterKey: KEYS.H,
+ toggle: true,
+ },
+ selection: {
+ icon: SelectionIcon,
+ letterKey: KEYS.V,
+ numericKey: KEYS["1"],
+ fillable: true,
+ },
+ rectangle: {
+ icon: RectangleIcon,
+ letterKey: KEYS.R,
+ numericKey: KEYS["2"],
+ fillable: true,
+ },
+ diamond: {
+ icon: DiamondIcon,
+ letterKey: KEYS.D,
+ numericKey: KEYS["3"],
+ fillable: true,
+ },
+ ellipse: {
+ icon: EllipseIcon,
+ letterKey: KEYS.O,
+ numericKey: KEYS["4"],
+ fillable: true,
+ },
+ arrow: {
+ icon: ArrowIcon,
+ letterKey: KEYS.A,
+ numericKey: KEYS["5"],
+ fillable: true,
+ },
+ line: {
+ icon: LineIcon,
+ letterKey: KEYS.L,
+ numericKey: KEYS["6"],
+ fillable: true,
+ },
+ freedraw: {
+ icon: FreedrawIcon,
+ letterKey: [KEYS.P, KEYS.X],
+ numericKey: KEYS["7"],
+ },
+ text: {
+ icon: TextIcon,
+ letterKey: KEYS.T,
+ numericKey: KEYS["8"],
+ },
+ image: {
+ icon: ImageIcon,
+ numericKey: KEYS["9"],
+ },
+ eraser: {
+ icon: EraserIcon,
+ letterKey: KEYS.E,
+ numericKey: KEYS["0"],
+ toggle: true,
+ },
+ frame: {
+ icon: frameToolIcon,
+ letterKey: KEYS.F,
+ },
+ embeddable: {
+ icon: EmbedIcon,
+ },
+ laser: {
+ icon: laserPointerToolIcon,
+ letterKey: KEYS.K,
+ },
+ lasso: {
+ icon: LassoIcon,
+ fillable: false,
+ },
+});
+
+export type ToolbarToolType = keyof typeof TOOLS;
+
+/**
+ * tools that, when activated while already active, switch back to the
+ * previously active tool (see `setActiveTool`'s `toggle` option)
+ */
+export const TOGGLE_TOOLS: readonly (ToolType | "custom")[] = (
+ Object.keys(TOOLS) as ToolbarToolType[]
+).filter((type) => TOOLS[type].toggle);
+
+export const getToolLetter = (type: ToolbarToolType) => {
+ const { letterKey } = TOOLS[type];
+ return (
+ letterKey &&
+ capitalizeString(typeof letterKey === "string" ? letterKey : letterKey[0])
+ );
+};
+
+/** human-readable shortcut hint, e.g. "R or 2", used in tooltips & aria */
+export const getToolShortcut = (type: ToolbarToolType) => {
+ const letter = getToolLetter(type);
+ const { numericKey } = TOOLS[type];
+ return letter && numericKey != null
+ ? `${letter} ${t("helpDialog.or")} ${numericKey}`
+ : `${letter || numericKey}`;
+};
+
+export const findShapeByKey = (key: string, app: AppClassProperties) => {
+ // CapsLock-insensitive (the caller excludes modified keypresses, incl.
+ // shift, so a capital letter here means CapsLock)
+ const lowerKey = key.toLowerCase();
+
+ for (const type of Object.keys(TOOLS) as ToolbarToolType[]) {
+ const { letterKey, numericKey } = TOOLS[type];
+ if (
+ (numericKey != null && key === numericKey) ||
+ (letterKey &&
+ (typeof letterKey === "string"
+ ? letterKey === lowerKey
+ : letterKey.includes(lowerKey)))
+ ) {
+ // the selection shortcut activates whichever selection tool the user
+ // prefers (selection or lasso)
+ return type === "selection"
+ ? app.state.preferredSelectionTool.type
+ : type;
+ }
+ }
+ return null;
+};
+
+export type ToolButtonComponentProps = {
+ app: AppClassProperties;
+ activeTool: UIAppState["activeTool"];
+ /** hide the keybinding badge rendered in the button's corner */
+ hideKeyBinding?: boolean;
+ /**
+ * hide all shortcut affordances (tooltip hint, aria-keyshortcuts, and the
+ * keybinding badge) — used on mobile where there's no keyboard
+ */
+ hideShortcut?: boolean;
+};
+
+type ToolButtonBehavior = {
+ /**
+ * display the shortcut of another tool (tooltip, aria, keybinding badge) —
+ * e.g. the lasso button shows the selection shortcut, which activates it
+ * when lasso is the preferred selection tool
+ */
+ shortcutType?: ToolbarToolType;
+ /**
+ * custom activation — replaces the default track + `setActiveTool` (pen
+ * detection still runs before it)
+ */
+ onSelect?: (
+ app: AppClassProperties,
+ data: { pointerType: PointerType | null },
+ ) => void;
+};
+
+/**
+ * Creates a toolbar button component for the given tool. Activation is
+ * uniform: track + `setActiveTool` (recording the previous tool for toggle
+ * tools), with pen detection on the first pen interaction.
+ */
+const createToolButton = (
+ type: ToolbarToolType,
+ behavior?: ToolButtonBehavior,
+) => {
+ const config = TOOLS[type];
+ const shortcutType = behavior?.shortcutType ?? type;
+
+ const ToolButtonComponent = ({
+ app,
+ activeTool,
+ hideKeyBinding,
+ hideShortcut,
+ }: ToolButtonComponentProps) => {
+ const label = capitalizeString(t(`toolBar.${type}`));
+ const shortcut = hideShortcut ? null : getToolShortcut(shortcutType);
+
+ return (
+ <IconButton
+ className={clsx({ fillable: config.fillable })}
+ type="toggle"
+ icon={config.icon}
+ checked={activeTool.type === type}
+ title={shortcut ? `${label} — ${shortcut}` : label}
+ keyBindingLabel={
+ hideKeyBinding || hideShortcut
+ ? undefined
+ : TOOLS[shortcutType].numericKey || getToolLetter(shortcutType)
+ }
+ aria-label={label}
+ aria-keyshortcuts={shortcut ?? undefined}
+ data-testid={`toolbar-${type}`}
+ onSelect={({ pointerType }) => {
+ if (!app.state.penDetected && pointerType === "pen") {
+ app.togglePenMode(true);
+ }
+
+ if (behavior?.onSelect) {
+ behavior.onSelect(app, { pointerType });
+ return;
+ }
+
+ if (app.state.activeTool.type !== type) {
+ trackEvent("toolbar", type, "ui");
+ app.setActiveTool({ type });
+ }
+ }}
+ />
+ );
+ };
+
+ ToolButtonComponent.displayName = `${capitalizeString(type)}IconButton`;
+
+ return ToolButtonComponent;
+};
+
+export const HandToolButton = createToolButton("hand");
+export const RectangleToolButton = createToolButton("rectangle");
+export const DiamondToolButton = createToolButton("diamond");
+export const EllipseToolButton = createToolButton("ellipse");
+export const ArrowToolButton = createToolButton("arrow");
+export const LineToolButton = createToolButton("line");
+export const FreedrawToolButton = createToolButton("freedraw");
+export const TextToolButton = createToolButton("text");
+export const ImageToolButton = createToolButton("image");
+export const EraserToolButton = createToolButton("eraser");
+export const FrameToolButton = createToolButton("frame");
+
+/**
+ * The selection tool button — pointer-clicking it while the selection tool
+ * is active switches to lasso.
+ */
+export const SelectionToolButton = createToolButton("selection", {
+ onSelect: (app, { pointerType }) => {
+ if (app.state.activeTool.type === "selection" && pointerType !== null) {
+ // pointer-clicking the active selection tool switches to lasso;
+ // keyboard/AT activation stays on selection
+ app.setActiveTool({ type: "lasso" });
+ return;
+ }
+
+ if (app.state.activeTool.type !== "selection") {
+ trackEvent("toolbar", "selection", "ui");
+ app.setActiveTool({ type: "selection" });
+ }
+ },
+});
+
+/**
+ * Rendered in place of the selection button when lasso is the preferred
+ * selection tool; the selection shortcut activates it then.
+ */
+export const LassoToolButton = createToolButton("lasso", {
+ shortcutType: "selection",
+});
+
+/**
+ * The selection ⇄ lasso popover used in compact (tablet) and mobile
+ * toolbars; picking an option also makes it the preferred selection tool.
+ */
+export const SelectionToolPopover = ({
+ app,
+ activeTool,
+ setAppState,
+}: {
+ app: AppClassProperties;
+ activeTool: UIAppState["activeTool"];
+ setAppState: React.Component<any, AppState>["setState"];
+}) => {
+ const SELECTION_TOOLS = [
+ {
+ type: "selection",
+ icon: TOOLS.selection.icon,
+ fillable: TOOLS.selection.fillable,
+ title: capitalizeString(t("toolBar.selection")),
+ },
+ {
+ type: "lasso",
+ icon: TOOLS.lasso.icon,
+ fillable: TOOLS.lasso.fillable,
+ title: capitalizeString(t("toolBar.lasso")),
+ },
+ ] as const;
+
+ const displayedOption =
+ SELECTION_TOOLS.find(
+ (tool) => tool.type === app.state.preferredSelectionTool.type,
+ ) || SELECTION_TOOLS[0];
+
+ return (
+ <ToolPopover
+ app={app}
+ options={SELECTION_TOOLS}
+ activeTool={activeTool}
+ defaultOption={app.state.preferredSelectionTool.type}
+ data-testid="toolbar-selection"
+ onToolChange={(type: string) => {
+ if (type === "selection" || type === "lasso") {
+ app.setActiveTool({ type });
+ setAppState({
+ preferredSelectionTool: { type, initialized: true },
+ });
+ }
+ }}
+ displayedOption={displayedOption}
+ />
+ );
+};
diff --git a/packages/excalidraw/components/hyperlink/Hyperlink.tsx b/packages/excalidraw/components/hyperlink/Hyperlink.tsx
index 8e15bb0d54..d5fa4475a7 100644
--- a/packages/excalidraw/components/hyperlink/Hyperlink.tsx
+++ b/packages/excalidraw/components/hyperlink/Hyperlink.tsx
@@ -42,7 +42,7 @@ import { getTooltipDiv, updateTooltipPosition } from "../../components/Tooltip";
import { t } from "../../i18n";
import { useAppProps, useEditorInterface, useExcalidrawAppState } from "../App";
-import { ToolButton } from "../ToolButton";
+import { IconButton } from "../IconButton";
import { FreedrawIcon, TrashIcon, elementLinkIcon } from "../icons";
import { getSelectedElements } from "../../scene";
@@ -312,7 +312,7 @@ export const Hyperlink = ({
)}
<div className="excalidraw-hyperlinkContainer__buttons">
{!isEditing && (
- <ToolButton
+ <IconButton
type="button"
title={t("buttons.edit")}
aria-label={t("buttons.edit")}
@@ -322,7 +322,7 @@ export const Hyperlink = ({
icon={FreedrawIcon}
/>
)}
- <ToolButton
+ <IconButton
type="button"
title={t("labels.linkToElement")}
aria-label={t("labels.linkToElement")}
@@ -338,7 +338,7 @@ export const Hyperlink = ({
icon={elementLinkIcon}
/>
{linkVal && !isEmbeddableElement(element) && (
- <ToolButton
+ <IconButton
type="button"
title={t("buttons.remove")}
aria-label={t("buttons.remove")}
diff --git a/packages/excalidraw/components/shapes.tsx b/packages/excalidraw/components/shapes.tsx
deleted file mode 100644
index d69a34505f..0000000000
--- a/packages/excalidraw/components/shapes.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-import { KEYS } from "@excalidraw/common";
-
-import {
- SelectionIcon,
- RectangleIcon,
- DiamondIcon,
- EllipseIcon,
- ArrowIcon,
- LineIcon,
- FreedrawIcon,
- TextIcon,
- ImageIcon,
- EraserIcon,
- laserPointerToolIcon,
- handIcon,
-} from "./icons";
-
-import type { AppClassProperties } from "../types";
-
-export const SHAPES = [
- {
- icon: handIcon,
- value: "hand",
- key: KEYS.H,
- numericKey: null,
- fillable: false,
- toolbar: true,
- },
- {
- icon: SelectionIcon,
- value: "selection",
- key: KEYS.V,
- numericKey: KEYS["1"],
- fillable: true,
- toolbar: true,
- },
- {
- icon: RectangleIcon,
- value: "rectangle",
- key: KEYS.R,
- numericKey: KEYS["2"],
- fillable: true,
- toolbar: true,
- },
- {
- icon: DiamondIcon,
- value: "diamond",
- key: KEYS.D,
- numericKey: KEYS["3"],
- fillable: true,
- toolbar: true,
- },
- {
- icon: EllipseIcon,
- value: "ellipse",
- key: KEYS.O,
- numericKey: KEYS["4"],
- fillable: true,
- toolbar: true,
- },
- {
- icon: ArrowIcon,
- value: "arrow",
- key: KEYS.A,
- numericKey: KEYS["5"],
- fillable: true,
- toolbar: true,
- },
- {
- icon: LineIcon,
- value: "line",
- key: KEYS.L,
- numericKey: KEYS["6"],
- fillable: true,
- toolbar: true,
- },
- {
- icon: FreedrawIcon,
- value: "freedraw",
- key: [KEYS.P, KEYS.X],
- numericKey: KEYS["7"],
- fillable: false,
- toolbar: true,
- },
- {
- icon: TextIcon,
- value: "text",
- key: KEYS.T,
- numericKey: KEYS["8"],
- fillable: false,
- toolbar: true,
- },
- {
- icon: ImageIcon,
- value: "image",
- key: null,
- numericKey: KEYS["9"],
- fillable: false,
- toolbar: true,
- },
- {
- icon: EraserIcon,
- value: "eraser",
- key: KEYS.E,
- numericKey: KEYS["0"],
- fillable: false,
- toolbar: true,
- },
- {
- icon: laserPointerToolIcon,
- value: "laser",
- key: KEYS.K,
- numericKey: null,
- fillable: false,
- toolbar: false,
- },
-] as const;
-
-export const getToolbarTools = (app: AppClassProperties) => {
- return app.state.preferredSelectionTool.type === "lasso"
- ? ([
- SHAPES[0],
- {
- ...SHAPES[1],
- value: "lasso",
- },
- ...SHAPES.slice(2),
- ] as const)
- : SHAPES;
-};
-
-export const findShapeByKey = (key: string, app: AppClassProperties) => {
- const shape = getToolbarTools(app).find((shape, index) => {
- return (
- (shape.numericKey != null && key === shape.numericKey.toString()) ||
- (shape.key &&
- (typeof shape.key === "string"
- ? shape.key === key
- : (shape.key as readonly string[]).includes(key)))
- );
- });
- return shape?.value || null;
-};
diff --git a/packages/excalidraw/css/styles.scss b/packages/excalidraw/css/styles.scss
index 2341130e23..5c3a005576 100644
--- a/packages/excalidraw/css/styles.scss
+++ b/packages/excalidraw/css/styles.scss
@@ -254,6 +254,23 @@ body.excalidraw-cursor-resize * {
}
}
+ // an icon button rendered outside a .buttonList context (e.g. the font
+ // picker trigger)
+ button.standalone {
+ @include outlineButtonIconStyles;
+
+ .ToolIcon__icon {
+ all: unset !important;
+ display: flex !important;
+ }
+
+ & > * {
+ // disallow pointer events on children, so we always have event.target
+ // on the button itself
+ pointer-events: none;
+ }
+ }
+
.App-top-bar {
z-index: var(--zIndex-ui-top);
display: flex;
diff --git a/packages/excalidraw/css/variables.module.scss b/packages/excalidraw/css/variables.module.scss
index 433a82d89c..8e07f1223a 100644
--- a/packages/excalidraw/css/variables.module.scss
+++ b/packages/excalidraw/css/variables.module.scss
@@ -29,29 +29,25 @@ $color-blue-8: #1971c2;
}
}
+// the .ToolIcon_type_toggle.ToolIcon--checked selectors use both classes so
+// they keep outranking the :hover/:active rules below
@mixin toolbarButtonColorStates {
&.fillable {
- .ToolIcon_type_radio,
- .ToolIcon_type_checkbox {
- &:checked + .ToolIcon__icon {
- --icon-fill-color: var(--color-on-primary-container);
-
- svg {
- fill: var(--icon-fill-color);
- }
+ &.ToolIcon_type_toggle.ToolIcon--checked .ToolIcon__icon {
+ --icon-fill-color: var(--color-on-primary-container);
+
+ svg {
+ fill: var(--icon-fill-color);
}
}
}
- .ToolIcon_type_radio,
- .ToolIcon_type_checkbox {
- &:checked + .ToolIcon__icon {
- background: var(--color-surface-primary-container);
- --keybinding-color: var(--color-on-primary-container);
+ &.ToolIcon_type_toggle.ToolIcon--checked .ToolIcon__icon {
+ background: var(--color-surface-primary-container);
+ --keybinding-color: var(--color-on-primary-container);
- svg {
- color: var(--color-on-primary-container);
- }
+ svg {
+ color: var(--color-on-primary-container);
}
}
@@ -124,7 +120,8 @@ $color-blue-8: #1971c2;
border-color: var(--button-active-border, var(--color-primary-darkest));
}
- &.active {
+ &.active,
+ &.ToolIcon--checked {
background-color: var(
--button-selected-bg,
var(--color-surface-primary-container)
diff --git a/packages/excalidraw/tests/queries/toolQueries.ts b/packages/excalidraw/tests/queries/toolQueries.ts
index 8413bf5fb9..ba73f6d531 100644
--- a/packages/excalidraw/tests/queries/toolQueries.ts
+++ b/packages/excalidraw/tests/queries/toolQueries.ts
@@ -6,7 +6,13 @@ import type { ToolType } from "@excalidraw/excalidraw/types";
const _getAllByToolName = (container: HTMLElement, tool: ToolType | "lock") => {
const toolTitle = tool === "lock" ? "lock" : TOOL_TYPE[tool];
- return queries.getAllByTestId(container, `toolbar-${toolTitle}`);
+ return (
+ queries
+ .getAllByTestId(container, `toolbar-${toolTitle}`)
+ // an open ToolPopover renders options with the same testids as the
+ // toolbar buttons — "by tool name" means the toolbar-level button
+ .filter((el) => !el.closest(".tool-popover-content"))
+ );
};
const getMultipleError = (_container: any, tool: any) =>
diff --git a/packages/excalidraw/tests/selection.test.tsx b/packages/excalidraw/tests/selection.test.tsx
index 683f46b6f2..976a74a692 100644
--- a/packages/excalidraw/tests/selection.test.tsx
+++ b/packages/excalidraw/tests/selection.test.tsx
@@ -9,7 +9,7 @@ import {
} from "@excalidraw/element";
import { pointFrom, pointRotateRads, type LocalPoint } from "@excalidraw/math";
-import { SHAPES } from "../components/shapes";
+import { TOOLS } from "../components/Tools";
import { Excalidraw } from "../index";
import * as InteractiveCanvas from "../renderer/interactiveScene";
@@ -1339,14 +1339,18 @@ describe("tool locking & selection", () => {
UI.clickTool("lock");
expect(h.state.activeTool.locked).toBe(true);
- for (const { value } of Object.values(SHAPES)) {
+ for (const value of Object.keys(TOOLS) as (keyof typeof TOOLS)[]) {
if (
value !== "image" &&
value !== "selection" &&
+ value !== "lasso" &&
value !== "eraser" &&
value !== "arrow" &&
value !== "hand" &&
- value !== "laser"
+ value !== "laser" &&
+ // no top-level toolbar button (rendered in the extra-tools dropdown)
+ value !== "frame" &&
+ value !== "embeddable"
) {
const element = UI.createElement(value);
expect(h.state.selectedElementIds[element.id]).not.toBe(true);
diff --git a/packages/excalidraw/tests/tool.test.tsx b/packages/excalidraw/tests/tool.test.tsx
index cf85f86eee..d4bc193890 100644
--- a/packages/excalidraw/tests/tool.test.tsx
+++ b/packages/excalidraw/tests/tool.test.tsx
@@ -4,7 +4,7 @@ import { resolvablePromise } from "@excalidraw/common";
import { Excalidraw } from "../index";
-import { getToolbarTools } from "../components/shapes";
+import { findShapeByKey } from "../components/Tools";
import { Pointer } from "./helpers/ui";
import { act, render } from "./test-utils";
@@ -68,27 +68,37 @@ describe("setActiveTool()", () => {
expect(h.state.activeTool.customType).toBe("comment");
});
});
-describe("getToolbarTools()", () => {
- const getToolValues = (preferredSelectionTool: "selection" | "lasso") =>
- getToolbarTools({
+describe("findShapeByKey()", () => {
+ const appWithPreferredTool = (
+ preferredSelectionTool: "selection" | "lasso",
+ ) =>
+ ({
state: {
preferredSelectionTool: {
type: preferredSelectionTool,
},
},
- } as AppClassProperties).map((tool) => tool.value);
+ } as AppClassProperties);
- it("does not include lasso when selection is preferred", () => {
- const toolValues = getToolValues("selection");
+ it("selection shortcuts activate selection when it's preferred", () => {
+ const app = appWithPreferredTool("selection");
- expect(toolValues.filter((value) => value === "selection")).toHaveLength(1);
- expect(toolValues.filter((value) => value === "lasso")).toHaveLength(0);
+ expect(findShapeByKey("v", app)).toBe("selection");
+ expect(findShapeByKey("1", app)).toBe("selection");
});
- it("replaces selection with lasso when lasso is preferred", () => {
- const toolValues = getToolValues("lasso");
+ it("selection shortcuts activate lasso when it's preferred", () => {
+ const app = appWithPreferredTool("lasso");
- expect(toolValues.filter((value) => value === "lasso")).toHaveLength(1);
- expect(toolValues.filter((value) => value === "selection")).toHaveLength(0);
+ expect(findShapeByKey("v", app)).toBe("lasso");
+ expect(findShapeByKey("1", app)).toBe("lasso");
+ });
+
+ it("letter shortcuts are CapsLock-insensitive", () => {
+ const app = appWithPreferredTool("selection");
+
+ expect(findShapeByKey("V", app)).toBe("selection");
+ expect(findShapeByKey("R", app)).toBe("rectangle");
+ expect(findShapeByKey("X", app)).toBe("freedraw");
});
});