From ea3b27f4b9d735fc12d6cedbab4f3b2782a9105a Mon Sep 17 00:00:00 2001 From: Mark Tolmacs Date: Wed, 2 Dec 2026 15:26:12 +0000 Subject: [PATCH] feat: headless example --- examples/with-headless/README.md | 15 ++ examples/with-headless/index.html | 12 ++ examples/with-headless/index.tsx | 175 ++++++++++++++++++ examples/with-headless/package.json | 20 ++ examples/with-headless/styles.css | 76 ++++++++ examples/with-headless/tsconfig.json | 9 + examples/with-headless/vite.config.mts | 14 ++ .../actions/actionDeleteSelected.tsx | 4 + .../CommandPalette/CommandPalette.tsx | 1 - .../__snapshots__/contextmenu.test.tsx.snap | 5 + .../excalidraw/tests/headlessAPI.test.tsx | 40 +++- pnpm-lock.yaml | 19 ++ 12 files changed, 388 insertions(+), 2 deletions(-) create mode 100644 examples/with-headless/README.md create mode 100644 examples/with-headless/index.html create mode 100644 examples/with-headless/index.tsx create mode 100644 examples/with-headless/package.json create mode 100644 examples/with-headless/styles.css create mode 100644 examples/with-headless/tsconfig.json create mode 100644 examples/with-headless/vite.config.mts diff --git a/examples/with-headless/README.md b/examples/with-headless/README.md new file mode 100644 index 0000000000..515e960322 --- /dev/null +++ b/examples/with-headless/README.md @@ -0,0 +1,15 @@ +# Headless Excalidraw + +A custom UI built on the headless editor API. `ui={false}` hides the default UI, and two bars rendered as children of `` drive the editor: + +- **Style properties** (`useProperty`): the swatches target the selection, or the active tool's defaults when nothing is selected. They are hidden where a property doesn't apply (no fill for arrows), and show "mixed" when the selected elements differ. +- **Commands** (`useCommand`): labels come from the editor, and Group / Ungroup / Delete are enabled by the actions' own predicates. +- **Host actions**: `host:shuffleFill` is registered through `excalidrawAPI.registerAction()` and then used like any built-in command, with its own predicate and undo support. +- **Selection and history** (`useSelection`, `useHistory`, `useEditorState`): the selection count, undo / redo availability and the active tool. +- **Default controls à la carte** (``): the stroke width picker is the default UI's own control, reused as is. + +```bash +pnpm install +pnpm build:packages +pnpm start +``` diff --git a/examples/with-headless/index.html b/examples/with-headless/index.html new file mode 100644 index 0000000000..c8fe4d91cf --- /dev/null +++ b/examples/with-headless/index.html @@ -0,0 +1,12 @@ + + + + + + Headless Excalidraw + + +
+ + + diff --git a/examples/with-headless/index.tsx b/examples/with-headless/index.tsx new file mode 100644 index 0000000000..98e12b4c2d --- /dev/null +++ b/examples/with-headless/index.tsx @@ -0,0 +1,175 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { + ActionControl, + CaptureUpdateAction, + Excalidraw, + newElementWith, + useCommand, + useEditorState, + useExcalidrawAPI, + useHistory, + useProperty, + useSelection, +} from "@excalidraw/excalidraw"; + +import "@excalidraw/excalidraw/index.css"; + +import type { ActionName, PropertyName } from "@excalidraw/excalidraw"; +import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types"; + +import "./styles.css"; + +const TOOLS = [ + "selection", + "rectangle", + "ellipse", + "arrow", + "freedraw", + "text", + "eraser", +] as const; + +const COLORS = ["#1e1e1e", "#e03131", "#2f9e44", "#1971c2"]; +const FILLS = ["transparent", "#ffc9c9", "#b2f2bb", "#a5d8ff"]; + +const FILLABLE_TYPES = ["rectangle", "ellipse", "diamond"]; + +// A host action. Once registered, it is a command like any built-in one: +// `useCommand("host:shuffleFill")` gives its label, its predicate as `enabled`, +// and runs it; the change lands in undo history. +const registerHostActions = (api: ExcalidrawImperativeAPI | null) => { + api?.registerAction({ + name: "host:shuffleFill", + label: "Shuffle fill", + trackEvent: false, + predicate: (elements, appState) => + elements.some( + (element) => + appState.selectedElementIds[element.id] && + FILLABLE_TYPES.includes(element.type), + ), + perform: (elements, appState) => ({ + elements: elements.map((element) => + appState.selectedElementIds[element.id] && + FILLABLE_TYPES.includes(element.type) + ? newElementWith(element, { + backgroundColor: + FILLS[1 + Math.floor(Math.random() * (FILLS.length - 1))], + fillStyle: "solid", + }) + : element, + ), + captureUpdate: CaptureUpdateAction.IMMEDIATELY, + }), + }); +}; + +// Color swatches for a style property. The property targets the selection, +// or the active tool's defaults when nothing is selected. It is hidden where +// it doesn't apply (e.g. fill for arrows), and has no value when the targeted +// elements differ. +const Swatches = ({ + name, + colors, +}: { + name: Extract; + colors: string[]; +}) => { + const property = useProperty(name); + + if (!property.isApplicable) { + return null; + } + + return ( +
+ {colors.map((color) => ( +
+ ); +}; + +/** A button running a command. Enabled when the command's predicate passes. */ +const CommandButton = ({ name }: { name: ActionName }) => { + const command = useCommand(name); + + if (!command.available) { + return null; + } + + return ( + + ); +}; + +const Toolbar = () => { + const excalidrawAPI = useExcalidrawAPI(); + const activeTool = useEditorState((state) => state.activeTool.type); + const { canUndo, canRedo } = useHistory(); + const undo = useCommand("undo"); + const redo = useCommand("redo"); + + return ( +
+ {TOOLS.map((type) => ( + + ))} + + +
+ ); +}; + +const StyleBar = () => { + const { selectedElements } = useSelection(); + const strokeWidth = useProperty("strokeWidth"); + + return ( +
+ {selectedElements.length} selected + + + {/* the default UI's own control, reused as is */} + {strokeWidth.isApplicable && } + + + + +
+ ); +}; + +createRoot(document.getElementById("root")!).render( + + + + + + , +); diff --git a/examples/with-headless/package.json b/examples/with-headless/package.json new file mode 100644 index 0000000000..f8553688bd --- /dev/null +++ b/examples/with-headless/package.json @@ -0,0 +1,20 @@ +{ + "name": "with-headless", + "version": "1.0.0", + "private": true, + "dependencies": { + "@excalidraw/excalidraw": "workspace:*", + "react": "19.0.0", + "react-dom": "19.0.0" + }, + "devDependencies": { + "typescript": "^5", + "vite": "5.4.21" + }, + "scripts": { + "start": "vite", + "build": "vite build", + "preview": "vite preview --port 5003", + "build:packages": "pnpm --dir ../../ build:packages" + } +} diff --git a/examples/with-headless/styles.css b/examples/with-headless/styles.css new file mode 100644 index 0000000000..4ec2a82af8 --- /dev/null +++ b/examples/with-headless/styles.css @@ -0,0 +1,76 @@ +html, +body, +#root { + height: 100%; + margin: 0; +} + +.bar { + position: absolute; + left: 50%; + transform: translateX(-50%); + z-index: var(--zIndex-layerUI); + display: flex; + align-items: center; + gap: 8px; + padding: 4px; + border: 1px solid #ccc; + border-radius: 6px; + background: #fff; + font: 13px system-ui, sans-serif; + white-space: nowrap; +} + +.bar.top { + top: 12px; +} + +.bar.bottom { + bottom: 12px; +} + +.bar .group { + display: flex; + align-items: center; + gap: 2px; +} + +.bar .hint { + padding: 0 4px; + color: #888; +} + +.bar > button, +.bar .group button { + padding: 4px 8px; + border: 1px solid transparent; + border-radius: 4px; + background: none; + font: inherit; + cursor: pointer; +} + +.bar button[aria-pressed="true"] { + border-color: #333; +} + +.bar button:disabled { + opacity: 0.4; + cursor: default; +} + +.bar .group .swatch { + width: 22px; + height: 22px; + border-color: #ddd; +} + +/* the reused default control: drop the fieldset chrome */ +.bar fieldset { + display: flex; + align-items: center; + gap: 4px; + margin: 0; + padding: 0; + border: 0; +} diff --git a/examples/with-headless/tsconfig.json b/examples/with-headless/tsconfig.json new file mode 100644 index 0000000000..be262d19b6 --- /dev/null +++ b/examples/with-headless/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "module": "ES2022", + "moduleResolution": "Bundler", + "lib": ["ESNext", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", + "skipLibCheck": true + } +} diff --git a/examples/with-headless/vite.config.mts b/examples/with-headless/vite.config.mts new file mode 100644 index 0000000000..89e9cf2aab --- /dev/null +++ b/examples/with-headless/vite.config.mts @@ -0,0 +1,14 @@ +import { defineConfig } from "vite"; + +export default defineConfig({ + server: { + port: 3002, + }, + optimizeDeps: { + esbuildOptions: { + // "Arbitrary module namespace identifier names" need es2022 + // https://github.com/vitejs/vite/issues/13556 + target: "es2022", + }, + }, +}); diff --git a/packages/excalidraw/actions/actionDeleteSelected.tsx b/packages/excalidraw/actions/actionDeleteSelected.tsx index ce46ed61c7..e37c0d3206 100644 --- a/packages/excalidraw/actions/actionDeleteSelected.tsx +++ b/packages/excalidraw/actions/actionDeleteSelected.tsx @@ -213,6 +213,10 @@ export const actionDeleteSelected = register<{ label: "labels.delete", icon: TrashIcon, trackEvent: { category: "element", action: "delete" }, + // `elements` may include deleted ones (`ActionManager#isActionEnabled`) + predicate: (elements, appState) => + !!appState.selectedLinearElement?.isEditing || + isSomeElementSelected(getNonDeletedElements(elements), appState), perform: (elements, appState, formData, app) => { if (appState.selectedLinearElement?.isEditing) { const { elementId, selectedPointsIndices } = diff --git a/packages/excalidraw/components/CommandPalette/CommandPalette.tsx b/packages/excalidraw/components/CommandPalette/CommandPalette.tsx index aaebe3e294..99343f4589 100644 --- a/packages/excalidraw/components/CommandPalette/CommandPalette.tsx +++ b/packages/excalidraw/components/CommandPalette/CommandPalette.tsx @@ -102,7 +102,6 @@ const isSameCommand = ( const SELECTION_COMMANDS = new Set([ "cut", "copy", - "deleteSelectedElements", "copyStyles", "pasteStyles", "bringToFront", diff --git a/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap index 89d8357a59..09c004f4de 100644 --- a/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap +++ b/packages/excalidraw/tests/__snapshots__/contextmenu.test.tsx.snap @@ -878,6 +878,7 @@ exports[`contextMenu element > right-clicking on a group should select whole gro "label": "labels.delete", "name": "deleteSelectedElements", "perform": [Function], + "predicate": [Function], "trackEvent": { "action": "delete", "category": "element", @@ -5739,6 +5740,7 @@ exports[`contextMenu element > shows 'Group selection' in context menu for multi "label": "labels.delete", "name": "deleteSelectedElements", "perform": [Function], + "predicate": [Function], "trackEvent": { "action": "delete", "category": "element", @@ -6965,6 +6967,7 @@ exports[`contextMenu element > shows 'Ungroup selection' in context menu for gro "label": "labels.delete", "name": "deleteSelectedElements", "perform": [Function], + "predicate": [Function], "trackEvent": { "action": "delete", "category": "element", @@ -8996,6 +8999,7 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap "label": "labels.delete", "name": "deleteSelectedElements", "perform": [Function], + "predicate": [Function], "trackEvent": { "action": "delete", "category": "element", @@ -9992,6 +9996,7 @@ exports[`contextMenu element > shows context menu for element > [end of test] ap "label": "labels.delete", "name": "deleteSelectedElements", "perform": [Function], + "predicate": [Function], "trackEvent": { "action": "delete", "category": "element", diff --git a/packages/excalidraw/tests/headlessAPI.test.tsx b/packages/excalidraw/tests/headlessAPI.test.tsx index 109af9200e..b57d1a8e44 100644 --- a/packages/excalidraw/tests/headlessAPI.test.tsx +++ b/packages/excalidraw/tests/headlessAPI.test.tsx @@ -1,7 +1,8 @@ import React from "react"; import { vi } from "vitest"; -import { resolvablePromise } from "@excalidraw/common"; +import { arrayToMap, resolvablePromise } from "@excalidraw/common"; +import { LinearElementEditor } from "@excalidraw/element"; import { CaptureUpdateAction } from "@excalidraw/history"; import { @@ -113,6 +114,43 @@ describe("public headless API", () => { expect(text("can-undo")).toBe("true"); }); + it("enables deleting only with a selection", async () => { + const DeleteButton = () => { + const command = useCommand("deleteSelectedElements"); + return ( + {String(command.enabled)} + ); + }; + + await render( + + + , + ); + expect(text("delete-enabled")).toBe("false"); + + selectTwoRectangles(); + expect(text("delete-enabled")).toBe("true"); + + act(() => { + API.setSelectedElements([]); + }); + expect(text("delete-enabled")).toBe("false"); + + // editing a line's points deletes points, whatever the selection + const line = API.createElement({ type: "line" }); + act(() => { + API.setElements([line]); + API.setAppState({ + selectedLinearElement: { + ...new LinearElementEditor(line, arrayToMap([line])), + isEditing: true, + }, + }); + }); + expect(text("delete-enabled")).toBe("true"); + }); + it("reads and sets style properties", async () => { await renderHostPanel(); selectTwoRectangles(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e8f525afc4..ec1614b021 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -159,6 +159,25 @@ importers: specifier: 4.0.0 version: 4.0.0 + examples/with-headless: + dependencies: + '@excalidraw/excalidraw': + specifier: workspace:* + version: link:../../packages/excalidraw + react: + specifier: 19.0.0 + version: 19.0.0 + react-dom: + specifier: 19.0.0 + version: 19.0.0(react@19.0.0) + devDependencies: + typescript: + specifier: ^5 + version: 5.9.3 + vite: + specifier: 5.4.21 + version: 5.4.21(@types/node@22.13.10)(sass@1.85.1)(terser@5.39.0) + examples/with-nextjs: dependencies: '@excalidraw/excalidraw':