excalidraw/src/actions/actionHistory.tsx

94 lines
2.6 KiB
TypeScript
Raw Normal View History

import { Action, ActionResult } from "./types";
import React from "react";
import { undo, redo } from "../components/icons";
import { ToolButton } from "../components/ToolButton";
import { t } from "../i18n";
import { SceneHistory, HistoryEntry } from "../history";
import { ExcalidrawElement } from "../element/types";
import { AppState } from "../types";
import { KEYS } from "../keys";
2020-03-14 20:46:57 -07:00
import { getElementMap } from "../element";
import { newElementWith } from "../element/mutateElement";
const writeData = (
2020-03-14 20:46:57 -07:00
prevElements: readonly ExcalidrawElement[],
appState: AppState,
updater: () => HistoryEntry | null,
): ActionResult => {
const commitToHistory = false;
if (
!appState.multiElement &&
!appState.resizingElement &&
!appState.editingElement &&
!appState.draggingElement
) {
const data = updater();
2020-03-14 20:46:57 -07:00
if (data === null) {
return { commitToHistory };
2020-03-14 20:46:57 -07:00
}
2020-03-14 20:46:57 -07:00
const prevElementMap = getElementMap(prevElements);
const nextElements = data.elements;
const nextElementMap = getElementMap(nextElements);
return {
elements: nextElements
.map((nextElement) =>
2020-03-14 20:46:57 -07:00
newElementWith(
prevElementMap[nextElement.id] || nextElement,
nextElement,
),
)
.concat(
prevElements
.filter(
(prevElement) => !nextElementMap.hasOwnProperty(prevElement.id),
2020-03-14 20:46:57 -07:00
)
.map((prevElement) =>
2020-03-14 20:46:57 -07:00
newElementWith(prevElement, { isDeleted: true }),
),
),
appState: { ...appState, ...data.appState },
commitToHistory,
syncHistory: true,
2020-03-14 20:46:57 -07:00
};
}
return { commitToHistory };
};
const testUndo = (shift: boolean) => (event: KeyboardEvent) =>
event[KEYS.CTRL_OR_CMD] && /z/i.test(event.key) && event.shiftKey === shift;
type ActionCreator = (history: SceneHistory) => Action;
export const createUndoAction: ActionCreator = (history) => ({
name: "undo",
2020-03-14 20:46:57 -07:00
perform: (elements, appState) =>
writeData(elements, appState, () => history.undoOnce()),
keyTest: testUndo(false),
PanelComponent: ({ updateData }) => (
<ToolButton
type="button"
icon={undo}
aria-label={t("buttons.undo")}
onClick={updateData}
/>
),
commitToHistory: () => false,
});
export const createRedoAction: ActionCreator = (history) => ({
name: "redo",
2020-03-14 20:46:57 -07:00
perform: (elements, appState) =>
writeData(elements, appState, () => history.redoOnce()),
keyTest: testUndo(true),
PanelComponent: ({ updateData }) => (
<ToolButton
type="button"
icon={redo}
aria-label={t("buttons.redo")}
onClick={updateData}
/>
),
commitToHistory: () => false,
});