excalidraw/src/actions/actionDeleteSelected.tsx

79 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-05-30 22:48:57 +02:00
import { isSomeElementSelected } from "../scene";
import { KEYS } from "../keys";
import { ToolButton } from "../components/ToolButton";
import React from "react";
import { trash } from "../components/icons";
import { t } from "../i18n";
import { register } from "./register";
import { getNonDeletedElements } from "../element";
2020-05-30 22:48:57 +02:00
import { ExcalidrawElement } from "../element/types";
import { AppState } from "../types";
import { newElementWith } from "../element/mutateElement";
import { getElementsInGroup } from "../groups";
const deleteSelectedElements = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
return {
elements: elements.map((el) => {
if (appState.selectedElementIds[el.id]) {
return newElementWith(el, { isDeleted: true });
}
return el;
}),
appState: {
...appState,
selectedElementIds: {},
},
};
};
export const actionDeleteSelected = register({
name: "deleteSelectedElements",
perform: (elements, appState) => {
2020-05-30 22:48:57 +02:00
let {
elements: nextElements,
appState: nextAppState,
} = deleteSelectedElements(elements, appState);
2020-05-30 22:48:57 +02:00
if (appState.editingGroupId) {
const siblingElements = getElementsInGroup(
getNonDeletedElements(nextElements),
appState.editingGroupId!,
);
if (siblingElements.length) {
nextAppState = {
...nextAppState,
selectedElementIds: { [siblingElements[0].id]: true },
};
}
}
return {
elements: nextElements,
appState: {
...nextAppState,
elementType: "selection",
multiElement: null,
},
commitToHistory: isSomeElementSelected(
getNonDeletedElements(elements),
appState,
),
};
},
contextItemLabel: "labels.delete",
contextMenuOrder: 3,
keyTest: (event) => event.key === KEYS.BACKSPACE || event.key === KEYS.DELETE,
PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton
type="button"
icon={trash}
title={t("labels.delete")}
aria-label={t("labels.delete")}
onClick={() => updateData(null)}
visible={isSomeElementSelected(getNonDeletedElements(elements), appState)}
/>
),
});