excalidraw/src/actions/manager.tsx
Gasim Gasimzada f465121f9b Feature: Action System (#298)
* Add Action System

- Add keyboard test
- Add context menu label
- Add PanelComponent

* Show context menu items based on actions

* Add render action feature

- Replace bringForward etc buttons with action manager render functions

* Move all property changes and canvas into actions

* Remove unnecessary functions and add forgotten force update when elements array change

* Extract export operations into actions

* Add elements and app state as arguments to `keyTest` function

* Add key priorities

- Sort actions by key priority when handling key presses

* Extract copy/paste styles

* Add Context Menu Item order

- Sort context menu items based on menu item order parameter

* Remove unnecessary functions from App component
2020-01-11 14:22:03 -08:00

90 lines
2.4 KiB
TypeScript

import React from "react";
import { Action, ActionsManagerInterface, UpdaterFn } from "./types";
import { ExcalidrawElement } from "../element/types";
import { AppState } from "../types";
export class ActionManager implements ActionsManagerInterface {
actions: { [keyProp: string]: Action } = {};
updater:
| ((elements: ExcalidrawElement[], appState: AppState) => void)
| null = null;
setUpdater(
updater: (elements: ExcalidrawElement[], appState: AppState) => void
) {
this.updater = updater;
}
registerAction(action: Action) {
this.actions[action.name] = action;
}
handleKeyDown(
event: KeyboardEvent,
elements: readonly ExcalidrawElement[],
appState: AppState
) {
const data = Object.values(this.actions)
.sort((a, b) => (b.keyPriority || 0) - (a.keyPriority || 0))
.filter(
action => action.keyTest && action.keyTest(event, elements, appState)
);
if (data.length === 0) return {};
event.preventDefault();
return data[0].perform(elements, appState, null);
}
getContextMenuItems(
elements: readonly ExcalidrawElement[],
appState: AppState,
updater: UpdaterFn
) {
console.log(
Object.values(this.actions)
.filter(action => "contextItemLabel" in action)
.map(a => ({ name: a.name, label: a.contextItemLabel }))
);
return Object.values(this.actions)
.filter(action => "contextItemLabel" in action)
.sort(
(a, b) =>
(a.contextMenuOrder !== undefined ? a.contextMenuOrder : 999) -
(b.contextMenuOrder !== undefined ? b.contextMenuOrder : 999)
)
.map(action => ({
label: action.contextItemLabel!,
action: () => {
updater(action.perform(elements, appState, null));
}
}));
}
renderAction(
name: string,
elements: readonly ExcalidrawElement[],
appState: AppState,
updater: UpdaterFn
) {
if (this.actions[name] && "PanelComponent" in this.actions[name]) {
const action = this.actions[name];
const PanelComponent = action.PanelComponent!;
const updateData = (formState: any) => {
updater(action.perform(elements, appState, formState));
};
return (
<PanelComponent
elements={elements}
appState={appState}
updateData={updateData}
/>
);
}
return null;
}
}