mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-12-05 18:55:28 +03:00
feat: headless example
This commit is contained in:
12 files changed
+388
-2
No files matched your search
@@ -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 `<Excalidraw>` 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** (`<ActionControl>`): the stroke width picker is the default UI's own control, reused as is.
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm build:packages
|
||||
pnpm start
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Headless Excalidraw</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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<PropertyName, "strokeColor" | "backgroundColor">;
|
||||
colors: string[];
|
||||
}) => {
|
||||
const property = useProperty(name);
|
||||
|
||||
if (!property.isApplicable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group" title={name}>
|
||||
{colors.map((color) => (
|
||||
<button
|
||||
key={color}
|
||||
className="swatch"
|
||||
title={color}
|
||||
aria-pressed={property.value === color}
|
||||
style={{ background: color }}
|
||||
onClick={() => property.set(color)}
|
||||
/>
|
||||
))}
|
||||
{property.mixed && <span className="hint">mixed</span>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
/** 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 (
|
||||
<button
|
||||
disabled={!command.enabled}
|
||||
title={command.shortcut}
|
||||
onClick={() => command.execute()}
|
||||
>
|
||||
{command.label}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
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 (
|
||||
<div className="bar top">
|
||||
{TOOLS.map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
aria-pressed={activeTool === type}
|
||||
onClick={() => excalidrawAPI?.setActiveTool({ type })}
|
||||
>
|
||||
{type}
|
||||
</button>
|
||||
))}
|
||||
<button disabled={!canUndo} onClick={() => undo.execute()}>
|
||||
{undo.label}
|
||||
</button>
|
||||
<button disabled={!canRedo} onClick={() => redo.execute()}>
|
||||
{redo.label}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const StyleBar = () => {
|
||||
const { selectedElements } = useSelection();
|
||||
const strokeWidth = useProperty("strokeWidth");
|
||||
|
||||
return (
|
||||
<div className="bar bottom">
|
||||
<span className="hint">{selectedElements.length} selected</span>
|
||||
<Swatches name="strokeColor" colors={COLORS} />
|
||||
<Swatches name="backgroundColor" colors={FILLS} />
|
||||
{/* the default UI's own control, reused as is */}
|
||||
{strokeWidth.isApplicable && <ActionControl name="changeStrokeWidth" />}
|
||||
<CommandButton name="group" />
|
||||
<CommandButton name="ungroup" />
|
||||
<CommandButton name="deleteSelectedElements" />
|
||||
<CommandButton name="host:shuffleFill" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<Excalidraw ui={false} onExcalidrawAPI={registerHostActions}>
|
||||
<Toolbar />
|
||||
<StyleBar />
|
||||
</Excalidraw>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "ES2022",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||
"jsx": "react-jsx",
|
||||
"skipLibCheck": true
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -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 } =
|
||||
|
||||
@@ -102,7 +102,6 @@ const isSameCommand = (
|
||||
const SELECTION_COMMANDS = new Set<BuiltinActionName>([
|
||||
"cut",
|
||||
"copy",
|
||||
"deleteSelectedElements",
|
||||
"copyStyles",
|
||||
"pasteStyles",
|
||||
"bringToFront",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 (
|
||||
<span data-testid="delete-enabled">{String(command.enabled)}</span>
|
||||
);
|
||||
};
|
||||
|
||||
await render(
|
||||
<Excalidraw>
|
||||
<DeleteButton />
|
||||
</Excalidraw>,
|
||||
);
|
||||
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();
|
||||
|
||||
Generated
+19
@@ -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':
|
||||
|
||||
Reference in new issue
Block a user