Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

fix(editor): narrow `NonDeleted` type to `isDeleted: false` (#11470)

Augusto Xavierdd8296af1802
diff --git a/excalidraw-app/components/AI.tsx b/excalidraw-app/components/AI.tsx
index 546cfa18dc..f4f28271b5 100644
--- a/excalidraw-app/components/AI.tsx
+++ b/excalidraw-app/components/AI.tsx
@@ -1,6 +1,7 @@
import {
DiagramToCodePlugin,
exportToBlob,
+ getNonDeletedElements,
getTextFromElements,
MIME_TYPES,
TTDDialog,
@@ -24,8 +25,15 @@ export const AIComponents = ({
generate={async ({ frame, children }) => {
const appState = excalidrawAPI.getAppState();
+ // SAFETY: This should never happen, but log it just in case
+ if (children.some((el) => el.isDeleted)) {
+ console.error(
+ "[NONDELETED][INVARIANT] Generated children elements should not be `isDeleted: true`",
+ );
+ }
+
const blob = await exportToBlob({
- elements: children,
+ elements: getNonDeletedElements(children),
appState: {
...appState,
exportBackground: true,
diff --git a/packages/element/src/Scene.ts b/packages/element/src/Scene.ts
index 35b0cf4b95..815a3d755d 100644
--- a/packages/element/src/Scene.ts
+++ b/packages/element/src/Scene.ts
@@ -51,7 +51,7 @@ const getNonDeletedElements = <T extends ExcalidrawElement>(
allElements: readonly T[],
) => {
const elementsMap = new Map() as NonDeletedSceneElementsMap;
- const elements: T[] = [];
+ const elements: NonDeleted<T>[] = [];
for (const element of allElements) {
if (!element.isDeleted) {
elements.push(element as NonDeleted<T>);
@@ -187,7 +187,7 @@ export class Scene {
// selection-related options
includeBoundTextElement?: boolean;
includeElementsInFrames?: boolean;
- }): NonDeleted<ExcalidrawElement>[] {
+ }): NonDeletedExcalidrawElement[] {
const hash = hashSelectionOpts(opts);
const elements = opts?.elements || this.nonDeletedElements;
diff --git a/packages/element/src/align.ts b/packages/element/src/align.ts
index 3068aee8d1..860e3473d3 100644
--- a/packages/element/src/align.ts
+++ b/packages/element/src/align.ts
@@ -4,10 +4,12 @@ import { updateBoundElements } from "./binding";
import { getCommonBoundingBox } from "./bounds";
import { getSelectedElementsByGroup } from "./groups";
+import { getNonDeletedElements } from ".";
+
import type { Scene } from "./Scene";
import type { BoundingBox } from "./bounds";
-import type { ExcalidrawElement } from "./types";
+import type { ExcalidrawElement, NonDeletedExcalidrawElement } from "./types";
export interface Alignment {
position: "start" | "center" | "end";
@@ -15,16 +17,16 @@ export interface Alignment {
}
export const alignElements = (
- selectedElements: ExcalidrawElement[],
+ selectedElements: NonDeletedExcalidrawElement[],
alignment: Alignment,
scene: Scene,
appState: Readonly<AppState>,
-): ExcalidrawElement[] => {
- const groups: ExcalidrawElement[][] = getSelectedElementsByGroup(
+): NonDeletedExcalidrawElement[] => {
+ const groups = getSelectedElementsByGroup(
selectedElements,
scene.getNonDeletedElementsMap(),
appState,
- );
+ ).map(getNonDeletedElements); // Nothing to align on deleted elements
const selectionBoundingBox = getCommonBoundingBox(selectedElements);
return groups.flatMap((group) => {
@@ -50,7 +52,7 @@ export const alignElements = (
};
const calculateTranslation = (
- group: ExcalidrawElement[],
+ group: readonly ExcalidrawElement[],
selectionBoundingBox: BoundingBox,
{ axis, position }: Alignment,
): { x: number; y: number } => {
diff --git a/packages/element/src/arrows/focus.ts b/packages/element/src/arrows/focus.ts
index fa8018adbe..2f95e3c2e5 100644
--- a/packages/element/src/arrows/focus.ts
+++ b/packages/element/src/arrows/focus.ts
@@ -27,6 +27,7 @@ import type {
ElementsMap,
ExcalidrawArrowElement,
ExcalidrawBindableElement,
+ NonDeleted,
NonDeletedSceneElementsMap,
PointsPositionUpdates,
} from "../types";
@@ -100,7 +101,7 @@ export const isFocusPointVisible = (
// Updates the arrow endpoints in "orbit" configuration
const focusPointUpdate = (
- arrow: ExcalidrawArrowElement,
+ arrow: NonDeleted<ExcalidrawArrowElement>,
bindableElement: ExcalidrawBindableElement | null,
isStartBinding: boolean,
elementsMap: NonDeletedSceneElementsMap,
@@ -212,7 +213,7 @@ export const handleFocusPointDrag = (
const arrow = LinearElementEditor.getElement(
linearElementEditor.elementId,
elementsMap,
- ) as any;
+ );
// Sanity checks
if (
diff --git a/packages/element/src/binding.ts b/packages/element/src/binding.ts
index 4f126b52b7..ac8845580d 100644
--- a/packages/element/src/binding.ts
+++ b/packages/element/src/binding.ts
@@ -63,6 +63,8 @@ import {
projectFixedPointOntoDiagonal,
} from "./utils";
+import { isNonDeletedElement } from ".";
+
import type { Scene } from "./Scene";
import type { ElementUpdate } from "./mutateElement";
@@ -371,7 +373,7 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
if (allHits.find((el) => el.id === startBinding.elementId)) {
const otherElement = elementsMap.get(
arrow.startBinding.elementId,
- ) as ExcalidrawBindableElement;
+ ) as NonDeleted<ExcalidrawBindableElement>;
invariant(otherElement, "Other element must be in the elements map");
@@ -396,7 +398,7 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
if (arrow.startBinding && arrow.startBinding.elementId !== hit?.id) {
const otherElement = elementsMap.get(
arrow.startBinding.elementId,
- ) as ExcalidrawBindableElement;
+ ) as NonDeleted<ExcalidrawBindableElement>;
invariant(otherElement, "Other element must be in the elements map");
const otherIsInsideBinding =
@@ -475,7 +477,9 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
)
: false;
const oppositeElement = oppositeBinding
- ? (elementsMap.get(oppositeBinding.elementId) as ExcalidrawBindableElement)
+ ? (elementsMap.get(
+ oppositeBinding.elementId,
+ ) as NonDeleted<ExcalidrawBindableElement>)
: null;
const otherIsTransparent =
isOverlapping && oppositeElement
@@ -1021,7 +1025,7 @@ export const bindOrUnbindBindingElements = (
export const bindBindingElement = (
arrow: NonDeleted<ExcalidrawArrowElement>,
- hoveredElement: ExcalidrawBindableElement,
+ hoveredElement: NonDeleted<ExcalidrawBindableElement>,
mode: BindMode,
startOrEnd: "start" | "end",
scene: Scene,
@@ -1074,7 +1078,7 @@ export const bindBindingElement = (
};
export const unbindBindingElement = (
- arrow: NonDeleted<ExcalidrawArrowElement>,
+ arrow: ExcalidrawArrowElement,
startOrEnd: "start" | "end",
scene: Scene,
): ExcalidrawBindableElement["id"] | null => {
@@ -1092,7 +1096,7 @@ export const unbindBindingElement = (
// end is not bound to the same element
const boundElement = scene
.getNonDeletedElementsMap()
- .get(binding.elementId) as ExcalidrawBindableElement;
+ .get(binding.elementId) as NonDeleted<ExcalidrawBindableElement>;
scene.mutateElement(boundElement, {
boundElements: boundElement.boundElements?.filter(
(element) => element.id !== arrow.id,
@@ -1111,7 +1115,7 @@ export const updateBoundElements = (
changedElement: NonDeletedExcalidrawElement,
scene: Scene,
options?: {
- simultaneouslyUpdated?: readonly ExcalidrawElement[];
+ simultaneouslyUpdated?: readonly NonDeletedExcalidrawElement[];
changedElements?: Map<string, ExcalidrawElement>;
},
) => {
@@ -1133,7 +1137,14 @@ export const updateBoundElements = (
}
const visitor = (element: ExcalidrawElement | undefined) => {
- if (!isArrowElement(element) || element.isDeleted) {
+ // SAFETY: This should never happen, but log it just in case
+ if (element && !isNonDeletedElement(element)) {
+ console.error(
+ "[NONDELETED][INVARIANT] updateBoundElements(): `isDeleted: true` in visitor",
+ );
+ }
+
+ if (!isArrowElement(element) || !isNonDeletedElement(element)) {
return;
}
@@ -1210,7 +1221,7 @@ export const updateBoundElements = (
};
const updateArrowBindings = (
- latestElement: ExcalidrawArrowElement,
+ latestElement: NonDeleted<ExcalidrawArrowElement>,
startOrEnd: "startBinding" | "endBinding",
elementsMap: NonDeletedSceneElementsMap,
scene: Scene,
@@ -1224,7 +1235,9 @@ const updateArrowBindings = (
const binding = latestElement[startOrEnd];
const bindableElement =
binding &&
- (elementsMap.get(binding.elementId) as ExcalidrawBindableElement);
+ (elementsMap.get(
+ binding.elementId,
+ ) as NonDeleted<ExcalidrawBindableElement>);
const point = LinearElementEditor.getPointAtIndexGlobalCoordinates(
latestElement,
startOrEnd === "startBinding" ? 0 : -1,
@@ -1272,11 +1285,11 @@ const updateArrowBindings = (
};
export const updateBindings = (
- latestElement: ExcalidrawElement,
+ latestElement: NonDeletedExcalidrawElement,
scene: Scene,
appState: AppState,
options?: {
- simultaneouslyUpdated?: readonly ExcalidrawElement[];
+ simultaneouslyUpdated?: readonly NonDeletedExcalidrawElement[];
newSize?: { width: number; height: number };
},
) => {
@@ -1731,7 +1744,7 @@ const extractBinding = (
const element = elementsMap.get(
binding.elementId,
- ) as ExcalidrawBindableElement;
+ ) as NonDeleted<ExcalidrawBindableElement>;
return {
element,
@@ -1957,7 +1970,7 @@ export const calculateFixedPointForElbowArrowBinding = (
export const calculateFixedPointForNonElbowArrowBinding = (
linearElement: NonDeleted<ExcalidrawArrowElement>,
- hoveredElement: ExcalidrawBindableElement,
+ hoveredElement: NonDeleted<ExcalidrawBindableElement>,
startOrEnd: "start" | "end",
elementsMap: ElementsMap,
focusPoint?: GlobalPoint,
diff --git a/packages/element/src/bounds.ts b/packages/element/src/bounds.ts
index 7c59964258..09c4ae5148 100644
--- a/packages/element/src/bounds.ts
+++ b/packages/element/src/bounds.ts
@@ -1028,7 +1028,7 @@ export const getCommonBounds = (
};
export const getDraggedElementsBounds = (
- elements: ExcalidrawElement[],
+ elements: readonly NonDeletedExcalidrawElement[],
dragOffset: { x: number; y: number },
) => {
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
@@ -1269,7 +1269,7 @@ export const boundsContainBounds = (outerBounds: Bounds, innerBounds: Bounds) =>
* It can be used to get elements overlapping a selection box, for example.
*
*/
-export const elementsOverlappingBBox = ({
+export const elementsOverlappingBBox = <T extends ExcalidrawElement>({
elements,
elementsMap,
bounds,
@@ -1277,7 +1277,7 @@ export const elementsOverlappingBBox = ({
excludeElementsInFrames,
shouldIgnoreElementFromSelection,
}: {
- elements: readonly NonDeletedExcalidrawElement[];
+ elements: readonly T[];
elementsMap?: ElementsMap;
bounds: Bounds | ExcalidrawElement;
/**
@@ -1286,9 +1286,7 @@ export const elementsOverlappingBBox = ({
**/
type: "contain" | "overlap";
excludeElementsInFrames?: boolean;
- shouldIgnoreElementFromSelection?: (
- element: NonDeletedExcalidrawElement,
- ) => boolean;
+ shouldIgnoreElementFromSelection?: (element: T) => boolean;
}) => {
if (!elementsMap) {
elementsMap = arrayToMap(elements) as ElementsMap;
@@ -1317,10 +1315,10 @@ export const elementsOverlappingBBox = ({
];
const framesInSelection = excludeElementsInFrames
- ? new Set<NonDeletedExcalidrawElement["id"]>()
+ ? new Set<ExcalidrawElement["id"]>()
: null;
- const groups: Record<string, NonDeletedExcalidrawElement[]> = {};
- const elementsInSelection: Set<NonDeletedExcalidrawElement> = new Set();
+ const groups: Record<string, T[]> = {};
+ const elementsInSelection: Set<T> = new Set();
for (const element of elements) {
if (shouldIgnoreElementFromSelection?.(element)) {
diff --git a/packages/element/src/collision.ts b/packages/element/src/collision.ts
index 6999512b44..a29992713c 100644
--- a/packages/element/src/collision.ts
+++ b/packages/element/src/collision.ts
@@ -373,7 +373,7 @@ export const getHoveredElementForFocusPoint = (
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
tolerance?: number,
-): ExcalidrawBindableElement | null => {
+): NonDeleted<ExcalidrawBindableElement> | null => {
const candidateElements: NonDeleted<ExcalidrawBindableElement>[] = [];
// We need to to hit testing from front (end of the array) to back (beginning of the array)
// because array is ordered from lower z-index to highest and we want element z-index
diff --git a/packages/element/src/cropElement.ts b/packages/element/src/cropElement.ts
index 3803944caf..7111b679b7 100644
--- a/packages/element/src/cropElement.ts
+++ b/packages/element/src/cropElement.ts
@@ -26,7 +26,6 @@ import type {
ExcalidrawElement,
ExcalidrawImageElement,
ImageCrop,
- NonDeleted,
} from "./types";
export const MINIMAL_CROP_SIZE = 10;
@@ -406,7 +405,7 @@ export const cropElement = (
};
const recomputeOrigin = (
- stateAtCropStart: NonDeleted<ExcalidrawElement>,
+ stateAtCropStart: ExcalidrawElement,
transformHandle: TransformHandleType,
width: number,
height: number,
diff --git a/packages/element/src/delta.ts b/packages/element/src/delta.ts
index 97b9403bcc..1f26da07c8 100644
--- a/packages/element/src/delta.ts
+++ b/packages/element/src/delta.ts
@@ -14,6 +14,7 @@ import type {
ExcalidrawLinearElement,
ExcalidrawTextElement,
NonDeleted,
+ NonDeletedExcalidrawElement,
Ordered,
OrderedExcalidrawElement,
SceneElementsMap,
@@ -1968,9 +1969,13 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
for (const element of changed.values()) {
if (!element.isDeleted && isBindableElement(element)) {
// TODO: with precise bindings this is quite expensive, so consider optimisation so it's only triggered when the arrow does not intersect (imprecise) element bounds
- updateBoundElements(element, scene, {
- changedElements: changed,
- });
+ updateBoundElements(
+ element as NonDeletedExcalidrawElement, // NOTE: Assumed correct, no runtime check for isDeleted due to performance reasons
+ scene,
+ {
+ changedElements: changed,
+ },
+ );
}
}
}
diff --git a/packages/element/src/distribute.ts b/packages/element/src/distribute.ts
index bb9c2708d2..7409a61084 100644
--- a/packages/element/src/distribute.ts
+++ b/packages/element/src/distribute.ts
@@ -5,9 +5,11 @@ import { getCommonBoundingBox } from "./bounds";
import { getSelectedElementsByGroup } from "./groups";
+import { getNonDeletedElements } from ".";
+
import type { Scene } from "./Scene";
-import type { ElementsMap, ExcalidrawElement } from "./types";
+import type { ElementsMap, NonDeletedExcalidrawElement } from "./types";
export interface Distribution {
space: "between";
@@ -15,12 +17,12 @@ export interface Distribution {
}
export const distributeElements = (
- selectedElements: ExcalidrawElement[],
+ selectedElements: NonDeletedExcalidrawElement[],
elementsMap: ElementsMap,
distribution: Distribution,
appState: Readonly<AppState>,
scene: Scene,
-): ExcalidrawElement[] => {
+): NonDeletedExcalidrawElement[] => {
const [start, mid, end, extent] =
distribution.axis === "x"
? (["minX", "midX", "maxX", "width"] as const)
@@ -32,6 +34,7 @@ export const distributeElements = (
elementsMap,
appState,
)
+ .map(getNonDeletedElements) // Nothing to distribute on deleted elements
.map((group) => [group, getCommonBoundingBox(group)] as const)
.sort((a, b) => a[1][mid] - b[1][mid]);
diff --git a/packages/element/src/dragElements.ts b/packages/element/src/dragElements.ts
index 796685d8f8..38afdceabe 100644
--- a/packages/element/src/dragElements.ts
+++ b/packages/element/src/dragElements.ts
@@ -203,7 +203,7 @@ const calculateOffset = (
const updateElementCoords = (
pointerDownState: PointerDownState,
- element: NonDeletedExcalidrawElement,
+ element: ExcalidrawElement,
scene: Scene,
dragOffset: { x: number; y: number },
) => {
diff --git a/packages/element/src/duplicate.ts b/packages/element/src/duplicate.ts
index 24135c0879..7058aba035 100644
--- a/packages/element/src/duplicate.ts
+++ b/packages/element/src/duplicate.ts
@@ -38,10 +38,13 @@ import { getBoundTextElement, getContainerElement } from "./textElement";
import { fixDuplicatedBindingsAfterDuplication } from "./binding";
+import { isNonDeletedElement } from ".";
+
import type {
ElementsMap,
ExcalidrawElement,
GroupId,
+ NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
} from "./types";
@@ -157,7 +160,7 @@ export const duplicateElements = (
// loop over them.
const processedIds = new Map<ExcalidrawElement["id"], true>();
const groupIdMap = new Map();
- const duplicatedElements: ExcalidrawElement[] = [];
+ const duplicatedElements: NonDeletedExcalidrawElement[] = [];
const origElements: ExcalidrawElement[] = [];
const origIdToDuplicateId = new Map<
ExcalidrawElement["id"],
@@ -167,7 +170,7 @@ export const duplicateElements = (
ExcalidrawElement["id"],
ExcalidrawElement
>();
- const duplicateElementsMap = new Map<string, ExcalidrawElement>();
+ const duplicateElementsMap = new Map<string, NonDeletedExcalidrawElement>();
const elementsMap = arrayToMap(elements) as ElementsMap;
const _idsOfElementsToDuplicate =
opts.type === "in-place"
@@ -209,12 +212,20 @@ export const duplicateElements = (
processedIds.set(element.id, true);
+ // SAFETY: this should never happen, but we
+ // want to make sure we log it if it does
+ if (!isNonDeletedElement(element)) {
+ console.error(
+ "[NONDELETED][INVARIANT] Element to duplicate should be non-deleted",
+ );
+ }
+
const newElement = duplicateElement(
appState.editingGroupId,
groupIdMap,
element,
opts.randomizeSeed,
- );
+ ) as NonDeletedExcalidrawElement;
processedIds.set(newElement.id, true);
diff --git a/packages/element/src/embeddable.ts b/packages/element/src/embeddable.ts
index 917ca0a7af..87c7073a78 100644
--- a/packages/element/src/embeddable.ts
+++ b/packages/element/src/embeddable.ts
@@ -13,9 +13,9 @@ import { wrapText } from "./textWrapping";
import { isIframeElement } from "./typeChecks";
import type {
- ExcalidrawElement,
ExcalidrawIframeLikeElement,
IframeData,
+ NonDeletedExcalidrawElement,
} from "./types";
type IframeDataWithSandbox = MarkRequired<IframeData, "sandbox">;
@@ -401,7 +401,7 @@ export const getEmbedLink = (
export const createPlaceholderEmbeddableLabel = (
element: ExcalidrawIframeLikeElement,
-): ExcalidrawElement => {
+): NonDeletedExcalidrawElement => {
let text: string;
if (isIframeElement(element)) {
text = "IFrame element";
diff --git a/packages/element/src/flowchart.ts b/packages/element/src/flowchart.ts
index daa98ed397..0b781e69d2 100644
--- a/packages/element/src/flowchart.ts
+++ b/packages/element/src/flowchart.ts
@@ -30,10 +30,12 @@ import {
isFlowchartNodeElement,
} from "./typeChecks";
import {
+ type NonDeleted,
type ElementsMap,
type ExcalidrawBindableElement,
type ExcalidrawElement,
type ExcalidrawFlowchartNodeElement,
+ type NonDeletedExcalidrawElement,
type NonDeletedSceneElementsMap,
type Ordered,
type OrderedExcalidrawElement,
@@ -238,7 +240,7 @@ const getOffsets = (
};
const addNewNode = (
- element: ExcalidrawFlowchartNodeElement,
+ element: NonDeleted<ExcalidrawFlowchartNodeElement>,
appState: AppState,
direction: LinkDirection,
scene: Scene,
@@ -290,14 +292,14 @@ const addNewNode = (
};
export const addNewNodes = (
- startNode: ExcalidrawFlowchartNodeElement,
+ startNode: NonDeleted<ExcalidrawFlowchartNodeElement>,
appState: AppState,
direction: LinkDirection,
scene: Scene,
numberOfNodes: number,
) => {
// always start from 0 and distribute evenly
- const newNodes: ExcalidrawElement[] = [];
+ const newNodes: NonDeletedExcalidrawElement[] = [];
for (let i = 0; i < numberOfNodes; i++) {
let nextX: number;
@@ -369,8 +371,8 @@ export const addNewNodes = (
};
const createBindingArrow = (
- startBindingElement: ExcalidrawFlowchartNodeElement,
- endBindingElement: ExcalidrawFlowchartNodeElement,
+ startBindingElement: NonDeleted<ExcalidrawFlowchartNodeElement>,
+ endBindingElement: NonDeleted<ExcalidrawFlowchartNodeElement>,
direction: LinkDirection,
appState: AppState,
scene: Scene,
@@ -490,7 +492,7 @@ const createBindingArrow = (
[startBindingElement.id, startBindingElement],
[endBindingElement.id, endBindingElement],
[bindingArrow.id, bindingArrow],
- ] as [string, Ordered<ExcalidrawElement>][]),
+ ] as [string, Ordered<NonDeletedExcalidrawElement>][]),
),
{ points: bindingArrow.points },
);
@@ -498,6 +500,7 @@ const createBindingArrow = (
return {
...bindingArrow,
...update,
+ isDeleted: bindingArrow.isDeleted,
};
};
@@ -639,7 +642,7 @@ export class FlowChartCreator {
pendingNodes: PendingExcalidrawElements | null = null;
createNodes(
- startNode: ExcalidrawFlowchartNodeElement,
+ startNode: NonDeleted<ExcalidrawFlowchartNodeElement>,
appState: AppState,
direction: LinkDirection,
scene: Scene,
diff --git a/packages/element/src/fractionalIndex.ts b/packages/element/src/fractionalIndex.ts
index 90a2e7c217..8e94934129 100644
--- a/packages/element/src/fractionalIndex.ts
+++ b/packages/element/src/fractionalIndex.ts
@@ -13,6 +13,7 @@ import type {
ElementsMap,
ExcalidrawElement,
FractionalIndex,
+ Ordered,
OrderedExcalidrawElement,
SceneElementsMap,
} from "./types";
@@ -203,9 +204,9 @@ export const syncMovedIndices = (
*
* WARN: in edge cases it could modify the elements which were not moved, as it's impossible to guess the actually moved elements from the elements array itself.
*/
-export const syncInvalidIndices = (
- elements: readonly ExcalidrawElement[],
-): OrderedExcalidrawElement[] => {
+export const syncInvalidIndices = <T extends ExcalidrawElement>(
+ elements: readonly T[],
+): Ordered<T>[] => {
const elementsMap = arrayToMap(elements);
const indicesGroups = getInvalidIndicesGroups(elements);
const elementsUpdates = generateIndices(elements, indicesGroups);
@@ -214,7 +215,7 @@ export const syncInvalidIndices = (
mutateElement(element, elementsMap, { index });
}
- return elements as OrderedExcalidrawElement[];
+ return elements as Ordered<T>[];
};
/**
diff --git a/packages/element/src/frame.ts b/packages/element/src/frame.ts
index 36ebf5ee02..bc2cdf2854 100644
--- a/packages/element/src/frame.ts
+++ b/packages/element/src/frame.ts
@@ -33,6 +33,8 @@ import {
isTextElement,
} from "./typeChecks";
+import { getNonDeletedElements } from ".";
+
import type { ExcalidrawElementsIncludingDeleted } from "./Scene";
import type {
@@ -266,8 +268,8 @@ export const getFrameLikeElements = (
*
* Considers non-frame bound elements (container or arrow labels) as root.
*/
-export const getRootElements = (
- allElements: ExcalidrawElementsIncludingDeleted,
+export const getRootElements = <T extends ExcalidrawElement>(
+ allElements: readonly T[],
) => {
const frameElements = arrayToMap(getFrameLikeElements(allElements));
return allElements.filter(
@@ -348,9 +350,12 @@ export const getElementsInResizingFrame = (
const newGroupElementsCompletelyInFrame = Array.from(
elementsCompletelyInFrame,
).filter((element) => element.groupIds.length > 0);
+ const nonDeletedNewGroupElementsCompletelyInFrame = getNonDeletedElements(
+ newGroupElementsCompletelyInFrame,
+ );
const groupIds = selectGroupsFromGivenElements(
- newGroupElementsCompletelyInFrame,
+ nonDeletedNewGroupElementsCompletelyInFrame,
appState,
);
@@ -538,7 +543,7 @@ export const getFrameChildrenInsertionIndex = (
*/
export const addElementsToFrame = <T extends ElementsMapOrArray>(
allElements: T,
- elementsToAdd: NonDeletedExcalidrawElement[],
+ elementsToAdd: ExcalidrawElement[],
frame: ExcalidrawFrameLikeElement,
): T => {
const elementsMap = arrayToMap(allElements);
@@ -630,7 +635,7 @@ export const addElementsToFrame = <T extends ElementsMapOrArray>(
};
export const removeElementsFromFrame = (
- elementsToRemove: ReadonlySetLike<NonDeletedExcalidrawElement>,
+ elementsToRemove: ReadonlySetLike<ExcalidrawElement>,
elementsMap: ElementsMap,
) => {
const _elementsToRemove = new Map<
@@ -975,8 +980,8 @@ export const getFrameLikeTitle = (element: ExcalidrawFrameLikeElement) => {
return element.name === null ? getDefaultFrameName(element) : element.name;
};
-export const getElementsOverlappingFrame = (
- elements: readonly ExcalidrawElement[],
+export const getElementsOverlappingFrame = <T extends ExcalidrawElement>(
+ elements: readonly T[],
frame: ExcalidrawFrameLikeElement,
elementsMap: ElementsMap,
) => {
diff --git a/packages/element/src/groups.ts b/packages/element/src/groups.ts
index b5f9282ba0..401b4d4569 100644
--- a/packages/element/src/groups.ts
+++ b/packages/element/src/groups.ts
@@ -15,15 +15,16 @@ import type {
GroupId,
ExcalidrawElement,
NonDeleted,
- NonDeletedExcalidrawElement,
ElementsMapOrArray,
ElementsMap,
+ NonDeletedExcalidrawElement,
+ NonDeletedElementsMapOrArray,
} from "./types";
export const selectGroup = (
groupId: GroupId,
appState: InteractiveCanvasAppState,
- elements: readonly NonDeleted<ExcalidrawElement>[],
+ elements: readonly NonDeletedExcalidrawElement[],
): Pick<
InteractiveCanvasAppState,
"selectedGroupIds" | "selectedElementIds" | "editingGroupId"
@@ -68,14 +69,14 @@ export const selectGroupsForSelectedElements = (function () {
"selectedGroupIds" | "editingGroupId" | "selectedElementIds"
>;
- let lastSelectedElements: readonly NonDeleted<ExcalidrawElement>[] | null =
+ let lastSelectedElements: readonly NonDeletedExcalidrawElement[] | null =
null;
- let lastElements: readonly NonDeleted<ExcalidrawElement>[] | null = null;
+ let lastElements: readonly NonDeletedExcalidrawElement[] | null = null;
let lastReturnValue: SelectGroupsReturnType | null = null;
const _selectGroups = (
- selectedElements: readonly NonDeleted<ExcalidrawElement>[],
- elements: readonly NonDeleted<ExcalidrawElement>[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
+ elements: readonly NonDeletedExcalidrawElement[],
appState: Pick<AppState, "selectedElementIds" | "editingGroupId">,
prevAppState: InteractiveCanvasAppState,
): SelectGroupsReturnType => {
@@ -240,7 +241,7 @@ export const getSelectedGroupIds = (
// given a list of elements, return the the actual group ids that should be selected
// or used to update the elements
export const selectGroupsFromGivenElements = (
- elements: readonly NonDeleted<ExcalidrawElement>[],
+ elements: readonly NonDeletedExcalidrawElement[],
appState: InteractiveCanvasAppState,
) => {
let nextAppState: InteractiveCanvasAppState = {
@@ -285,14 +286,18 @@ export const editGroupForSelectedElement = (
export const isElementInGroup = (element: ExcalidrawElement, groupId: string) =>
element.groupIds.includes(groupId);
-export const getElementsInGroup = (
- elements: ElementsMapOrArray,
+export const getElementsInGroup = <
+ P extends NonDeletedExcalidrawElement | ExcalidrawElement,
+>(
+ elements: P extends NonDeletedExcalidrawElement
+ ? NonDeletedElementsMapOrArray
+ : ElementsMapOrArray,
groupId: string,
-) => {
- const elementsInGroup: ExcalidrawElement[] = [];
+): P[] => {
+ const elementsInGroup: P[] = [];
for (const element of elements.values()) {
if (isElementInGroup(element, groupId)) {
- elementsInGroup.push(element);
+ elementsInGroup.push(element as P);
}
}
return elementsInGroup;
@@ -324,15 +329,14 @@ export const removeFromSelectedGroups = (
selectedGroupIds: { [groupId: string]: boolean },
) => groupIds.filter((groupId) => !selectedGroupIds[groupId]);
-export const getMaximumGroups = (
- elements: ExcalidrawElement[],
+export const getMaximumGroups = <
+ T extends NonDeletedExcalidrawElement | ExcalidrawElement,
+>(
+ elements: T[],
elementsMap: ElementsMap,
-): ExcalidrawElement[][] => {
- const groups: Map<String, ExcalidrawElement[]> = new Map<
- String,
- ExcalidrawElement[]
- >();
- elements.forEach((element: ExcalidrawElement) => {
+): T[][] => {
+ const groups: Map<String, T[]> = new Map<String, T[]>();
+ elements.forEach((element: T) => {
const groupId =
element.groupIds.length === 0
? element.id
@@ -343,7 +347,7 @@ export const getMaximumGroups = (
// Include bound text if present when grouping
const boundTextElement = getBoundTextElement(element, elementsMap);
if (boundTextElement) {
- currentGroupMembers.push(boundTextElement);
+ currentGroupMembers.push(boundTextElement as T);
}
groups.set(groupId, [...currentGroupMembers, element]);
});
@@ -386,7 +390,7 @@ export const elementsAreInSameGroup = (
return maxGroup === elements.length;
};
-export const isInGroup = (element: NonDeletedExcalidrawElement) => {
+export const isInGroup = (element: ExcalidrawElement) => {
return element.groupIds.length > 0;
};
@@ -414,7 +418,7 @@ export const getSelectedElementsByGroup = (
selectedElements: ExcalidrawElement[],
elementsMap: ElementsMap,
appState: Readonly<Pick<AppState, "selectedGroupIds" | "editingGroupId">>,
-): ExcalidrawElement[][] => {
+): NonDeletedExcalidrawElement[][] => {
const selectedGroupIds = getSelectedGroupIds(appState);
const unboundElements = selectedElements.filter(
(element) => !isBoundToContainer(element),
@@ -480,5 +484,7 @@ export const getSelectedElementsByGroup = (
addToGroupsMap(element, selectedGroupId);
}
});
- return Array.from(groups.values()).concat(Array.from(elements.values()));
+ return Array.from(groups.values()).concat(
+ Array.from(elements.values()),
+ ) as NonDeletedExcalidrawElement[][];
};
diff --git a/packages/element/src/index.ts b/packages/element/src/index.ts
index c55537d451..6459082130 100644
--- a/packages/element/src/index.ts
+++ b/packages/element/src/index.ts
@@ -40,19 +40,21 @@ export const hashString = (s: string): number => {
return hash >>> 0; // Ensure unsigned 32-bit integer
};
-export const getVisibleElements = (elements: readonly ExcalidrawElement[]) =>
+export const isNonDeletedElement = <T extends ExcalidrawElement>(
+ element: T,
+): element is NonDeleted<T> => !element.isDeleted;
+
+export const getVisibleElements = (
+ elements: readonly ExcalidrawElement[],
+): readonly NonDeletedExcalidrawElement[] =>
elements.filter(
- (el) => !el.isDeleted && !isInvisiblySmallElement(el),
- ) as readonly NonDeletedExcalidrawElement[];
+ (el): el is NonDeletedExcalidrawElement =>
+ isNonDeletedElement(el) && !isInvisiblySmallElement(el),
+ );
export const getNonDeletedElements = <T extends ExcalidrawElement>(
elements: readonly T[],
-) =>
- elements.filter((element) => !element.isDeleted) as readonly NonDeleted<T>[];
-
-export const isNonDeletedElement = <T extends ExcalidrawElement>(
- element: T,
-): element is NonDeleted<T> => !element.isDeleted;
+): readonly NonDeleted<T>[] => elements.filter(isNonDeletedElement);
export * from "./align";
export * from "./binding";
diff --git a/packages/element/src/linearElementEditor.ts b/packages/element/src/linearElementEditor.ts
index d2f80a50b3..40c20dd3fc 100644
--- a/packages/element/src/linearElementEditor.ts
+++ b/packages/element/src/linearElementEditor.ts
@@ -217,7 +217,7 @@ export class LinearElementEditor {
static getElement<T extends ExcalidrawLinearElement>(
id: InstanceType<typeof LinearElementEditor>["elementId"],
elementsMap: ElementsMap,
- ): T | null {
+ ): NonDeleted<T> | null {
const element = elementsMap.get(id);
if (element) {
return element as NonDeleted<T>;
@@ -769,7 +769,7 @@ export class LinearElementEditor {
}
static getEditorMidPoints = (
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
elementsMap: ElementsMap,
appState: InteractiveCanvasAppState,
): (GlobalPoint | null)[] => {
@@ -893,7 +893,7 @@ export class LinearElementEditor {
};
static isSegmentTooShort<P extends GlobalPoint | LocalPoint>(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
startPoint: P,
endPoint: P,
index: number,
@@ -934,7 +934,7 @@ export class LinearElementEditor {
}
static getSegmentMidPoint(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
index: number,
elementsMap: ElementsMap,
): GlobalPoint {
@@ -1254,7 +1254,7 @@ export class LinearElementEditor {
/** scene coords */
static getPointGlobalCoordinates(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
p: LocalPoint,
elementsMap: ElementsMap,
): GlobalPoint {
@@ -1272,7 +1272,7 @@ export class LinearElementEditor {
/** scene coords */
static getPointsGlobalCoordinates(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
elementsMap: ElementsMap,
): GlobalPoint[] {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
@@ -1289,7 +1289,7 @@ export class LinearElementEditor {
}
static getPointAtIndexGlobalCoordinates(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
indexMaybeFromEnd: number, // -1 for last element
elementsMap: ElementsMap,
): GlobalPoint {
@@ -1312,7 +1312,7 @@ export class LinearElementEditor {
}
static pointFromAbsoluteCoords(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
absoluteCoords: GlobalPoint,
elementsMap: ElementsMap,
): LocalPoint {
@@ -1336,7 +1336,7 @@ export class LinearElementEditor {
}
static getPointIndexUnderCursor(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
elementsMap: ElementsMap,
zoom: AppState["zoom"],
x: number,
@@ -1364,7 +1364,7 @@ export class LinearElementEditor {
}
static createPointAt(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
elementsMap: ElementsMap,
scenePointerX: number,
scenePointerY: number,
@@ -1798,7 +1798,7 @@ export class LinearElementEditor {
}
private static _getShiftLockedDelta(
- element: NonDeleted<ExcalidrawLinearElement>,
+ element: ExcalidrawLinearElement,
elementsMap: ElementsMap,
referencePoint: LocalPoint,
scenePointer: GlobalPoint,
diff --git a/packages/element/src/mutateElement.ts b/packages/element/src/mutateElement.ts
index eb6350c2bf..62a1670fa5 100644
--- a/packages/element/src/mutateElement.ts
+++ b/packages/element/src/mutateElement.ts
@@ -61,7 +61,7 @@ export const mutateElement = <TElement extends Mutable<ExcalidrawElement>>(
angle: 0 as Radians,
...updateElbowArrowPoints(
{
- ...element,
+ ...(element as ExcalidrawElbowArrowElement),
x: updates.x || element.x,
y: updates.y || element.y,
},
diff --git a/packages/element/src/newElement.ts b/packages/element/src/newElement.ts
index a2658aabd9..db509ba774 100644
--- a/packages/element/src/newElement.ts
+++ b/packages/element/src/newElement.ts
@@ -124,7 +124,10 @@ const _newElementBase = <T extends ExcalidrawElement>(
}
// assign type to guard against excess properties
- const element: Merge<ExcalidrawGenericElement, { type: T["type"] }> = {
+ const element: Merge<
+ ExcalidrawGenericElement,
+ { type: T["type"]; isDeleted: false }
+ > = {
id: rest.id || randomId(),
type,
x,
@@ -266,7 +269,7 @@ export const newTextElement = (
metrics,
);
- const textElementProps: ExcalidrawTextElement = {
+ const textElementProps: NonDeleted<ExcalidrawTextElement> = {
..._newElementBase<ExcalidrawTextElement>("text", opts),
text,
fontSize,
@@ -283,7 +286,7 @@ export const newTextElement = (
lineHeight,
};
- const textElement: ExcalidrawTextElement = newElementWith(
+ const textElement: NonDeleted<ExcalidrawTextElement> = newElementWith(
textElementProps,
{},
);
diff --git a/packages/element/src/renderElement.ts b/packages/element/src/renderElement.ts
index 29539966b1..44b5e941af 100644
--- a/packages/element/src/renderElement.ts
+++ b/packages/element/src/renderElement.ts
@@ -71,6 +71,7 @@ import { ShapeCache } from "./shape";
import type {
ExcalidrawElement,
ExcalidrawTextElement,
+ NonDeleted,
NonDeletedExcalidrawElement,
ExcalidrawFreeDrawElement,
ExcalidrawImageElement,
@@ -1016,7 +1017,10 @@ export const renderElement = (
context.globalAlpha = 0.1;
const uncroppedElementCanvas = generateElementCanvas(
- getUncroppedImageElement(elementWithCanvas.element, elementsMap),
+ getUncroppedImageElement(
+ elementWithCanvas.element,
+ elementsMap,
+ ) as NonDeleted<ExcalidrawImageElement>,
allElementsMap,
appState.zoom,
renderConfig,
diff --git a/packages/element/src/resizeElements.ts b/packages/element/src/resizeElements.ts
index bb9094a5d2..a04dcc76a4 100644
--- a/packages/element/src/resizeElements.ts
+++ b/packages/element/src/resizeElements.ts
@@ -234,7 +234,7 @@ const rotateSingleElement = (
if (isBindingElement(element)) {
update = {
...update,
- } as ElementUpdate<ExcalidrawArrowElement>;
+ } as ElementUpdate<NonDeletedExcalidrawElement>;
if (element.startBinding) {
unbindBindingElement(element, "start", scene);
@@ -388,7 +388,7 @@ export const resizeSingleTextElement = (
shouldResizeFromCenter,
);
- const resizedElement: Partial<ExcalidrawTextElement> = {
+ const resizedElement: Partial<NonDeleted<ExcalidrawTextElement>> = {
width: Math.abs(newWidth),
height: Math.abs(metrics.height),
x: newOrigin.x,
@@ -722,8 +722,8 @@ const getResizedOrigin = (
export const resizeSingleElement = (
nextWidth: number,
nextHeight: number,
- latestElement: ExcalidrawElement,
- origElement: ExcalidrawElement,
+ latestElement: NonDeletedExcalidrawElement,
+ origElement: NonDeletedExcalidrawElement,
originalElementsMap: ElementsMap,
scene: Scene,
handleDirection: TransformHandleDirection,
@@ -1200,7 +1200,10 @@ export const resizeMultipleElements = (
}[],
element,
) => {
- const origElement = originalElementsMap!.get(element.id);
+ // originalElementsMap holds snapshots of the (non-deleted) selection
+ const origElement = originalElementsMap!.get(element.id) as
+ | NonDeletedExcalidrawElement
+ | undefined;
if (origElement) {
acc.push({ orig: origElement, latest: element });
}
@@ -1239,9 +1242,10 @@ export const resizeMultipleElements = (
];
}, [] as ExcalidrawTextElementWithContainer[]);
- boundingBox = getCommonBoundingBox(
- targetElements.map(({ orig }) => orig).concat(boundTextElements),
- );
+ boundingBox = getCommonBoundingBox([
+ ...targetElements.map(({ orig }) => orig),
+ ...boundTextElements,
+ ]);
}
const { minX, minY, maxX, maxY, midX, midY } = boundingBox;
const width = maxX - minX;
diff --git a/packages/element/src/selection.ts b/packages/element/src/selection.ts
index 6c8de26820..9ac82c46b0 100644
--- a/packages/element/src/selection.ts
+++ b/packages/element/src/selection.ts
@@ -19,6 +19,8 @@ import { getFrameChildren } from "./frame";
import { LinearElementEditor } from "./linearElementEditor";
import { selectGroupsForSelectedElements } from "./groups";
+import { isNonDeletedElement } from ".";
+
import type {
ElementsMap,
ElementsMapOrArray,
@@ -28,9 +30,8 @@ import type {
NonDeletedExcalidrawElement,
} from "./types";
-const shouldIgnoreElementFromSelection = (
- element: NonDeletedExcalidrawElement,
-) => element.locked || isBoundToContainer(element);
+const shouldIgnoreElementFromSelection = (element: ExcalidrawElement) =>
+ element.locked || isBoundToContainer(element);
const excludeElementsFromFrames = <T extends ExcalidrawElement>(
selectedElements: readonly T[],
@@ -66,14 +67,14 @@ export const excludeElementsInFramesFromSelection = <
return excludeElementsFromFrames(selectedElements, framesInSelection);
};
-export const getElementsWithinSelection = (
- elements: readonly NonDeletedExcalidrawElement[],
- selection: NonDeletedExcalidrawElement,
+export const getElementsWithinSelection = <T extends ExcalidrawElement>(
+ elements: readonly T[],
+ selection: ExcalidrawElement,
elementsMap: ElementsMap,
// TODO remove (this flag is effectively unused AFAIK)
excludeElementsInFrames: boolean = true,
boxSelectionMode: BoxSelectionMode = "contain",
-): NonDeletedExcalidrawElement[] => {
+): T[] => {
const [selectionStartX, selectionStartY, selectionEndX, selectionEndY] =
getElementAbsoluteCoords(selection, elementsMap);
const selectionX1 = Math.min(selectionStartX, selectionEndX);
@@ -97,9 +98,11 @@ export const getElementsWithinSelection = (
});
};
-export const getVisibleAndNonSelectedElements = (
- elements: readonly NonDeletedExcalidrawElement[],
- selectedElements: readonly NonDeletedExcalidrawElement[],
+export const getVisibleAndNonSelectedElements = <
+ T extends NonDeletedExcalidrawElement,
+>(
+ elements: readonly T[],
+ selectedElements: readonly ExcalidrawElement[],
appState: AppState,
elementsMap: ElementsMap,
) => {
@@ -164,11 +167,18 @@ export const getSelectedElements = (
},
) => {
const addedElements = new Set<ExcalidrawElement["id"]>();
- const selectedElements: ExcalidrawElement[] = [];
+ // selection can only contain non-deleted elements
+ const selectedElements: NonDeletedExcalidrawElement[] = [];
for (const element of elements.values()) {
if (appState.selectedElementIds[element.id]) {
- selectedElements.push(element);
- addedElements.add(element.id);
+ if (isNonDeletedElement(element)) {
+ selectedElements.push(element as NonDeletedExcalidrawElement);
+ addedElements.add(element.id);
+ } else {
+ console.error(
+ "[NONDELETED][INVARIANT] getSelectedElements skipping deleted selected element which should not be in the selection",
+ );
+ }
continue;
}
if (
@@ -176,18 +186,20 @@ export const getSelectedElements = (
isBoundToContainer(element) &&
appState.selectedElementIds[element?.containerId]
) {
- selectedElements.push(element);
+ selectedElements.push(element as NonDeletedExcalidrawElement);
addedElements.add(element.id);
continue;
}
}
if (opts?.includeElementsInFrames) {
- const elementsToInclude: ExcalidrawElement[] = [];
+ const elementsToInclude: NonDeletedExcalidrawElement[] = [];
selectedElements.forEach((element) => {
if (isFrameLikeElement(element)) {
getFrameChildren(elements, element.id).forEach(
- (e) => !addedElements.has(e.id) && elementsToInclude.push(e),
+ (e) =>
+ !addedElements.has(e.id) &&
+ elementsToInclude.push(e as NonDeletedExcalidrawElement),
);
}
elementsToInclude.push(element);
@@ -230,7 +242,7 @@ export const makeNextSelectedElementIds = (
};
const _getLinearElementEditor = (
- targetElements: readonly ExcalidrawElement[],
+ targetElements: readonly NonDeletedExcalidrawElement[],
allElements: readonly NonDeletedExcalidrawElement[],
) => {
const linears = targetElements.filter(isLinearElement);
@@ -250,7 +262,7 @@ const _getLinearElementEditor = (
};
export const getSelectionStateForElements = (
- targetElements: readonly ExcalidrawElement[],
+ targetElements: readonly NonDeletedExcalidrawElement[],
allElements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
) => {
diff --git a/packages/element/src/shape.ts b/packages/element/src/shape.ts
index 337437a1c3..ecc5580c13 100644
--- a/packages/element/src/shape.ts
+++ b/packages/element/src/shape.ts
@@ -68,7 +68,6 @@ import { shouldTestInside } from "./collision";
import type {
ExcalidrawElement,
- NonDeletedExcalidrawElement,
ExcalidrawSelectionElement,
ExcalidrawLinearElement,
ExcalidrawFreeDrawElement,
@@ -260,7 +259,7 @@ export const generateRoughOptions = (
};
const modifyIframeLikeForRoughOptions = (
- element: NonDeletedExcalidrawElement,
+ element: ExcalidrawElement,
isExporting: boolean,
embedsValidationStatus: EmbedsValidationStatus | null,
) => {
@@ -751,7 +750,7 @@ export const generateLinearCollisionShape = (
* @private
*/
const _generateElementShape = (
- element: Exclude<NonDeletedExcalidrawElement, ExcalidrawSelectionElement>,
+ element: Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
generator: RoughGenerator,
{
isExporting,
diff --git a/packages/element/src/textElement.ts b/packages/element/src/textElement.ts
index 9ff53d035c..6757a818f1 100644
--- a/packages/element/src/textElement.ts
+++ b/packages/element/src/textElement.ts
@@ -30,6 +30,8 @@ import {
isTextElement,
} from "./typeChecks";
+import { isNonDeletedElement } from ".";
+
import type { Scene } from "./Scene";
import type { MaybeTransformHandleType } from "./transformHandles";
@@ -40,7 +42,7 @@ import type {
ExcalidrawTextContainer,
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
- NonDeletedExcalidrawElement,
+ NonDeleted,
} from "./types";
export const redrawTextBoundingBox = (
@@ -140,7 +142,7 @@ export const redrawTextBoundingBox = (
};
export const handleBindTextResize = (
- container: NonDeletedExcalidrawElement,
+ container: ExcalidrawElement,
scene: Scene,
transformHandleType: MaybeTransformHandleType,
shouldMaintainAspectRatio = false,
@@ -286,29 +288,40 @@ export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
export const getBoundTextElement = (
element: ExcalidrawElement | null,
elementsMap: ElementsMap,
-) => {
+): NonDeleted<ExcalidrawTextElementWithContainer> | null => {
if (!element) {
return null;
}
const boundTextElementId = getBoundTextElementId(element);
if (boundTextElementId) {
- return (elementsMap.get(boundTextElementId) ||
- null) as ExcalidrawTextElementWithContainer | null;
+ const boundTextElement = (elementsMap.get(boundTextElementId) ||
+ null) as NonDeleted<ExcalidrawTextElementWithContainer> | null;
+
+ // SAFETY: This should never happen, but log it just in case
+ if (boundTextElement && !isNonDeletedElement(boundTextElement)) {
+ console.error(
+ "[NONDELETED][INVARIANT] Bound text element `isDeleted: true` which is not expected.",
+ );
+ }
+
+ return boundTextElement;
}
return null;
};
-export const getContainerElement = (
- element: ExcalidrawTextElement | null,
+export const getContainerElement = <
+ T extends ExcalidrawTextElement,
+ R extends ExcalidrawTextContainer,
+>(
+ element: T | null,
elementsMap: ElementsMap,
-): ExcalidrawTextContainer | null => {
+): R | null => {
if (!element) {
return null;
}
if (element.containerId) {
- return (elementsMap.get(element.containerId) ||
- null) as ExcalidrawTextContainer | null;
+ return (elementsMap.get(element.containerId) || null) as R | null;
}
return null;
};
@@ -353,7 +366,7 @@ export const getContainerCenter = (
return { x: midSegmentMidpoint[0], y: midSegmentMidpoint[1] };
};
-export const getContainerCoords = (container: NonDeletedExcalidrawElement) => {
+export const getContainerCoords = (container: ExcalidrawElement) => {
let offsetX = BOUND_TEXT_PADDING;
let offsetY = BOUND_TEXT_PADDING;
@@ -401,7 +414,7 @@ export const getBoundTextElementPosition = (
};
export const shouldAllowVerticalAlign = (
- selectedElements: NonDeletedExcalidrawElement[],
+ selectedElements: readonly ExcalidrawElement[],
elementsMap: ElementsMap,
) => {
return selectedElements.some((element) => {
@@ -417,7 +430,7 @@ export const shouldAllowVerticalAlign = (
};
export const suppportsHorizontalAlign = (
- selectedElements: NonDeletedExcalidrawElement[],
+ selectedElements: readonly ExcalidrawElement[],
elementsMap: ElementsMap,
) => {
return selectedElements.some((element) => {
diff --git a/packages/element/src/transform.ts b/packages/element/src/transform.ts
index 22828fe263..dd71cb30ec 100644
--- a/packages/element/src/transform.ts
+++ b/packages/element/src/transform.ts
@@ -57,7 +57,10 @@ import type {
ExcalidrawTextElement,
FileId,
FontFamilyValues,
+ NonDeleted,
+ NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
+ Ordered,
TextAlign,
VerticalAlign,
} from "./types";
@@ -243,7 +246,7 @@ const bindTextToContainer = (
};
const bindLinearElementToElement = (
- linearElement: ExcalidrawArrowElement,
+ linearElement: NonDeleted<ExcalidrawArrowElement>,
start: ValidLinearElement["start"],
end: ValidLinearElement["end"],
elementStore: ElementStore,
@@ -331,7 +334,7 @@ const bindLinearElementToElement = (
bindBindingElement(
linearElement,
- startBoundElement as ExcalidrawBindableElement,
+ startBoundElement as NonDeleted<ExcalidrawBindableElement>,
"orbit",
"start",
scene,
@@ -407,7 +410,7 @@ const bindLinearElementToElement = (
bindBindingElement(
linearElement,
- endBoundElement as ExcalidrawBindableElement,
+ endBoundElement as NonDeleted<ExcalidrawBindableElement>,
"orbit",
"end",
scene,
@@ -492,7 +495,10 @@ class ElementStore {
};
getElements = () => {
- return syncInvalidIndices(Array.from(this.excalidrawElements.values()));
+ // programmatically created elements are always non-deleted
+ return syncInvalidIndices(
+ Array.from(this.excalidrawElements.values()),
+ ) as Ordered<NonDeletedExcalidrawElement>[];
};
getElementsMap = () => {
@@ -691,7 +697,7 @@ export const convertToExcalidrawElements = (
}
const { linearElement, startBoundElement, endBoundElement } =
bindLinearElementToElement(
- container,
+ container as NonDeleted<ExcalidrawArrowElement>,
originalStart,
originalEnd,
elementStore,
@@ -716,7 +722,7 @@ export const convertToExcalidrawElements = (
}
const { linearElement, startBoundElement, endBoundElement } =
bindLinearElementToElement(
- excalidrawElement as ExcalidrawArrowElement,
+ excalidrawElement as NonDeleted<ExcalidrawArrowElement>,
start,
end,
elementStore,
diff --git a/packages/element/src/typeChecks.ts b/packages/element/src/typeChecks.ts
index 3a8f5e36ef..53b9a654b0 100644
--- a/packages/element/src/typeChecks.ts
+++ b/packages/element/src/typeChecks.ts
@@ -31,68 +31,68 @@ import type {
ExcalidrawLinearElementSubType,
} from "./types";
-export const isInitializedImageElement = (
- element: ExcalidrawElement | null,
-): element is InitializedExcalidrawImageElement => {
+export const isInitializedImageElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & InitializedExcalidrawImageElement => {
return !!element && element.type === "image" && !!element.fileId;
};
-export const isImageElement = (
- element: ExcalidrawElement | null,
-): element is ExcalidrawImageElement => {
+export const isImageElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & ExcalidrawImageElement => {
return !!element && element.type === "image";
};
-export const isEmbeddableElement = (
- element: ExcalidrawElement | null | undefined,
-): element is ExcalidrawEmbeddableElement => {
+export const isEmbeddableElement = <T extends ExcalidrawElement>(
+ element: T | null | undefined,
+): element is T & ExcalidrawEmbeddableElement => {
return !!element && element.type === "embeddable";
};
-export const isIframeElement = (
- element: ExcalidrawElement | null,
-): element is ExcalidrawIframeElement => {
+export const isIframeElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & ExcalidrawIframeElement => {
return !!element && element.type === "iframe";
};
-export const isIframeLikeElement = (
- element: ExcalidrawElement | null,
-): element is ExcalidrawIframeLikeElement => {
+export const isIframeLikeElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & ExcalidrawIframeLikeElement => {
return (
!!element && (element.type === "iframe" || element.type === "embeddable")
);
};
-export const isTextElement = (
- element: ExcalidrawElement | null,
-): element is ExcalidrawTextElement => {
+export const isTextElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & ExcalidrawTextElement => {
return element != null && element.type === "text";
};
-export const isFrameElement = (
- element: ExcalidrawElement | null,
-): element is ExcalidrawFrameElement => {
+export const isFrameElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & ExcalidrawFrameElement => {
return element != null && element.type === "frame";
};
-export const isMagicFrameElement = (
- element: ExcalidrawElement | null,
-): element is ExcalidrawMagicFrameElement => {
+export const isMagicFrameElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & ExcalidrawMagicFrameElement => {
return element != null && element.type === "magicframe";
};
-export const isFrameLikeElement = (
- element: ExcalidrawElement | null,
-): element is ExcalidrawFrameLikeElement => {
+export const isFrameLikeElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & ExcalidrawFrameLikeElement => {
return (
element != null &&
(element.type === "frame" || element.type === "magicframe")
);
};
-export const isFreeDrawElement = (
- element?: ExcalidrawElement | null,
-): element is ExcalidrawFreeDrawElement => {
+export const isFreeDrawElement = <T extends ExcalidrawElement>(
+ element?: T | null,
+): element is T & ExcalidrawFreeDrawElement => {
return element != null && isFreeDrawElementType(element.type);
};
@@ -102,48 +102,48 @@ export const isFreeDrawElementType = (
return elementType === "freedraw";
};
-export const isLinearElement = (
- element?: ExcalidrawElement | null,
-): element is ExcalidrawLinearElement => {
+export const isLinearElement = <T extends ExcalidrawElement>(
+ element?: T | null,
+): element is T & ExcalidrawLinearElement => {
return element != null && isLinearElementType(element.type);
};
-export const isLineElement = (
- element?: ExcalidrawElement | null,
-): element is ExcalidrawLineElement => {
+export const isLineElement = <T extends ExcalidrawElement>(
+ element?: T | null,
+): element is T & ExcalidrawLineElement => {
return element != null && element.type === "line";
};
-export const isArrowElement = (
- element?: ExcalidrawElement | null,
-): element is ExcalidrawArrowElement => {
+export const isArrowElement = <T extends ExcalidrawElement>(
+ element?: T | null,
+): element is T & ExcalidrawArrowElement => {
return element != null && element.type === "arrow";
};
-export const isElbowArrow = (
- element?: ExcalidrawElement,
-): element is ExcalidrawElbowArrowElement => {
+export const isElbowArrow = <T extends ExcalidrawElement>(
+ element?: T,
+): element is T & ExcalidrawElbowArrowElement => {
return isArrowElement(element) && element.elbowed;
};
/**
* sharp or curved arrow, but not elbow
*/
-export const isSimpleArrow = (
- element?: ExcalidrawElement,
-): element is ExcalidrawArrowElement => {
+export const isSimpleArrow = <T extends ExcalidrawElement>(
+ element?: T,
+): element is T & ExcalidrawArrowElement => {
return isArrowElement(element) && !element.elbowed;
};
-export const isSharpArrow = (
- element?: ExcalidrawElement,
-): element is ExcalidrawArrowElement => {
+export const isSharpArrow = <T extends ExcalidrawElement>(
+ element?: T,
+): element is T & ExcalidrawArrowElement => {
return isArrowElement(element) && !element.elbowed && !element.roundness;
};
-export const isCurvedArrow = (
- element?: ExcalidrawElement,
-): element is ExcalidrawArrowElement => {
+export const isCurvedArrow = <T extends ExcalidrawElement>(
+ element?: T,
+): element is T & ExcalidrawArrowElement => {
return (
isArrowElement(element) && !element.elbowed && element.roundness !== null
);
@@ -157,10 +157,10 @@ export const isLinearElementType = (
);
};
-export const isBindingElement = (
- element?: ExcalidrawElement | null,
+export const isBindingElement = <T extends ExcalidrawElement>(
+ element?: T | null,
includeLocked = true,
-): element is ExcalidrawArrowElement => {
+): element is T & ExcalidrawArrowElement => {
return (
element != null &&
(!element.locked || includeLocked === true) &&
@@ -174,10 +174,10 @@ export const isBindingElementType = (
return elementType === "arrow";
};
-export const isBindableElement = (
- element: ExcalidrawElement | null | undefined,
+export const isBindableElement = <T extends ExcalidrawElement>(
+ element: T | null | undefined,
includeLocked = true,
-): element is ExcalidrawBindableElement => {
+): element is T & ExcalidrawBindableElement => {
return (
element != null &&
(!element.locked || includeLocked === true) &&
@@ -193,9 +193,9 @@ export const isBindableElement = (
);
};
-export const isRectanguloidElement = (
- element?: ExcalidrawElement | null,
-): element is ExcalidrawBindableElement => {
+export const isRectanguloidElement = <T extends ExcalidrawElement>(
+ element?: T | null,
+): element is T & ExcalidrawBindableElement => {
return (
element != null &&
(element.type === "rectangle" ||
@@ -211,9 +211,9 @@ export const isRectanguloidElement = (
// TODO: Remove this when proper distance calculation is introduced
// @see binding.ts:distanceToBindableElement()
-export const isRectangularElement = (
- element?: ExcalidrawElement | null,
-): element is ExcalidrawBindableElement => {
+export const isRectangularElement = <T extends ExcalidrawElement>(
+ element?: T | null,
+): element is T & ExcalidrawBindableElement => {
return (
element != null &&
(element.type === "rectangle" ||
@@ -227,10 +227,10 @@ export const isRectangularElement = (
);
};
-export const isTextBindableContainer = (
- element: ExcalidrawElement | null,
+export const isTextBindableContainer = <T extends ExcalidrawElement>(
+ element: T | null,
includeLocked = true,
-): element is ExcalidrawTextContainer => {
+): element is T & ExcalidrawTextContainer => {
return (
element != null &&
(!element.locked || includeLocked === true) &&
@@ -271,9 +271,9 @@ export const isExcalidrawElement = (
}
};
-export const isFlowchartNodeElement = (
- element: ExcalidrawElement,
-): element is ExcalidrawFlowchartNodeElement => {
+export const isFlowchartNodeElement = <T extends ExcalidrawElement>(
+ element: T,
+): element is T & ExcalidrawFlowchartNodeElement => {
return (
element.type === "rectangle" ||
element.type === "ellipse" ||
@@ -281,18 +281,19 @@ export const isFlowchartNodeElement = (
);
};
-export const hasBoundTextElement = (
- element: ExcalidrawElement | null,
-): element is MarkNonNullable<ExcalidrawBindableElement, "boundElements"> => {
+export const hasBoundTextElement = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T &
+ MarkNonNullable<ExcalidrawBindableElement, "boundElements"> => {
return (
isTextBindableContainer(element) &&
!!element.boundElements?.some(({ type }) => type === "text")
);
};
-export const isBoundToContainer = (
- element: ExcalidrawElement | null,
-): element is ExcalidrawTextElementWithContainer => {
+export const isBoundToContainer = <T extends ExcalidrawElement>(
+ element: T | null,
+): element is T & ExcalidrawTextElementWithContainer => {
return (
element !== null &&
"containerId" in element &&
diff --git a/packages/element/src/types.ts b/packages/element/src/types.ts
index 1797fbae9c..100b13db5b 100644
--- a/packages/element/src/types.ts
+++ b/packages/element/src/types.ts
@@ -227,7 +227,7 @@ export type Ordered<TElement extends ExcalidrawElement> = TElement & {
export type OrderedExcalidrawElement = Ordered<ExcalidrawElement>;
export type NonDeleted<TElement extends ExcalidrawElement> = TElement & {
- isDeleted: boolean;
+ isDeleted: false;
};
export type NonDeletedExcalidrawElement = NonDeleted<ExcalidrawElement>;
@@ -445,6 +445,10 @@ export type ElementsMapOrArray =
| readonly ExcalidrawElement[]
| Readonly<ElementsMap>;
+export type NonDeletedElementsMapOrArray =
+ | readonly NonDeletedExcalidrawElement[]
+ | Readonly<NonDeletedElementsMap | NonDeletedSceneElementsMap>;
+
export type ExcalidrawLinearElementSubType =
| "line"
| "sharpArrow"
diff --git a/packages/element/src/zindex.ts b/packages/element/src/zindex.ts
index d2b400e45f..0e5b66781f 100644
--- a/packages/element/src/zindex.ts
+++ b/packages/element/src/zindex.ts
@@ -12,6 +12,8 @@ import { getSelectedElements } from "./selection";
import { getBoundTextElement, getContainerElement } from "./textElement";
import { getHoveredElementForBinding } from "./collision";
+import { getNonDeletedElements } from ".";
+
import type { Scene } from "./Scene";
import type {
ExcalidrawArrowElement,
@@ -19,7 +21,6 @@ import type {
ExcalidrawFrameLikeElement,
NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
- Ordered,
OrderedExcalidrawElement,
} from "./types";
@@ -155,14 +156,19 @@ const getContiguousFrameRangeElements = (
export const moveArrowAboveBindable = (
point: GlobalPoint,
arrow: ExcalidrawArrowElement,
- elements: readonly Ordered<NonDeletedExcalidrawElement>[],
+ elements: readonly OrderedExcalidrawElement[],
elementsMap: NonDeletedSceneElementsMap,
scene: Scene,
hit?: NonDeletedExcalidrawElement,
): readonly OrderedExcalidrawElement[] => {
const hoveredElement = hit
? hit
- : getHoveredElementForBinding(point, elements, elementsMap);
+ : getHoveredElementForBinding(
+ point,
+ // SAFETY: callers that omit `hit` pass non-deleted elements
+ getNonDeletedElements(elements),
+ elementsMap,
+ );
if (!hoveredElement) {
return elements;
diff --git a/packages/element/tests/cropElement.test.tsx b/packages/element/tests/cropElement.test.tsx
index 73edb4c80c..6c03ec1265 100644
--- a/packages/element/tests/cropElement.test.tsx
+++ b/packages/element/tests/cropElement.test.tsx
@@ -26,7 +26,11 @@ import type { NormalizedZoomValue } from "@excalidraw/excalidraw/types";
import { duplicateElement } from "../src/duplicate";
-import type { ExcalidrawImageElement, ImageCrop } from "../src/types";
+import type {
+ ExcalidrawImageElement,
+ ImageCrop,
+ NonDeleted,
+} from "../src/types";
const { h } = window;
const mouse = new Pointer("mouse");
@@ -313,7 +317,7 @@ describe("Cropping and other features", async () => {
});
it("Exports should preserve crops", async () => {
- const image = h.elements[0] as ExcalidrawImageElement;
+ const image = h.elements[0] as NonDeleted<ExcalidrawImageElement>;
const initialWidth = image.width;
const initialHeight = image.height;
diff --git a/packages/element/tests/elbowArrow.test.tsx b/packages/element/tests/elbowArrow.test.tsx
index 2993e32158..bb8a4e7d75 100644
--- a/packages/element/tests/elbowArrow.test.tsx
+++ b/packages/element/tests/elbowArrow.test.tsx
@@ -23,6 +23,7 @@ import type {
ExcalidrawArrowElement,
ExcalidrawBindableElement,
ExcalidrawElbowArrowElement,
+ NonDeleted,
} from "../src/types";
const { h } = window;
@@ -141,7 +142,7 @@ describe("elbow arrow routing", () => {
const arrow = API.createElement({
type: "arrow",
elbowed: true,
- }) as ExcalidrawElbowArrowElement;
+ }) as NonDeleted<ExcalidrawElbowArrowElement>;
scene.insertElement(arrow);
h.app.scene.mutateElement(arrow, {
points: [
@@ -168,14 +169,14 @@ describe("elbow arrow routing", () => {
y: -150,
width: 100,
height: 100,
- }) as ExcalidrawBindableElement;
+ }) as NonDeleted<ExcalidrawBindableElement>;
const rectangle2 = API.createElement({
type: "rectangle",
x: 50,
y: 50,
width: 100,
height: 100,
- }) as ExcalidrawBindableElement;
+ }) as NonDeleted<ExcalidrawBindableElement>;
const arrow = API.createElement({
type: "arrow",
elbowed: true,
@@ -184,7 +185,7 @@ describe("elbow arrow routing", () => {
width: 90,
height: 200,
points: [pointFrom(0, 0), pointFrom(90, 200)],
- }) as ExcalidrawElbowArrowElement;
+ }) as NonDeleted<ExcalidrawElbowArrowElement>;
API.setElements([rectangle1, rectangle2, arrow]);
bindBindingElement(arrow, rectangle1, "orbit", "start", h.scene);
diff --git a/packages/element/tests/flowchart.test.tsx b/packages/element/tests/flowchart.test.tsx
index 0130fb4c8a..505cdd11db 100644
--- a/packages/element/tests/flowchart.test.tsx
+++ b/packages/element/tests/flowchart.test.tsx
@@ -9,6 +9,8 @@ import {
unmountComponent,
} from "@excalidraw/excalidraw/tests/test-utils";
+import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
+
unmountComponent();
const { h } = window;
@@ -109,7 +111,7 @@ describe("flow chart creation", () => {
expect(firstChildNode).not.toBe(null);
expect(firstChildNode.id).toBe(Object.keys(h.state.selectedElementIds)[0]);
- API.setSelectedElements([initialNode]);
+ API.setSelectedElements([initialNode] as NonDeletedExcalidrawElement[]);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.ARROW_RIGHT);
@@ -129,7 +131,7 @@ describe("flow chart creation", () => {
expect(secondChildNode).not.toBe(null);
expect(secondChildNode.id).toBe(Object.keys(h.state.selectedElementIds)[0]);
- API.setSelectedElements([initialNode]);
+ API.setSelectedElements([initialNode] as NonDeletedExcalidrawElement[]);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.ARROW_RIGHT);
@@ -376,7 +378,7 @@ describe("flow chart navigation", () => {
const predecessorToRightMostNode = h.elements[h.elements.length - 4];
expect(predecessorToRightMostNode.type).toBe("rectangle");
- API.setSelectedElements([rightMostNode]);
+ API.setSelectedElements([rightMostNode] as NonDeletedExcalidrawElement[]);
Keyboard.withModifierKeys({ alt: true }, () => {
Keyboard.keyPress(KEYS.ARROW_RIGHT);
});
@@ -385,7 +387,7 @@ describe("flow chart navigation", () => {
expect(h.state.selectedElementIds[predecessorToRightMostNode.id]).toBe(
true,
);
- API.setSelectedElements([rightMostNode]);
+ API.setSelectedElements([rightMostNode] as NonDeletedExcalidrawElement[]);
Keyboard.withModifierKeys({ alt: true }, () => {
Keyboard.keyPress(KEYS.ARROW_UP);
});
@@ -394,7 +396,7 @@ describe("flow chart navigation", () => {
expect(h.state.selectedElementIds[predecessorToRightMostNode.id]).toBe(
true,
);
- API.setSelectedElements([rightMostNode]);
+ API.setSelectedElements([rightMostNode] as NonDeletedExcalidrawElement[]);
Keyboard.withModifierKeys({ alt: true }, () => {
Keyboard.keyPress(KEYS.ARROW_DOWN);
});
diff --git a/packages/element/tests/frame.test.tsx b/packages/element/tests/frame.test.tsx
index 635a5bc2e9..22e406e732 100644
--- a/packages/element/tests/frame.test.tsx
+++ b/packages/element/tests/frame.test.tsx
@@ -19,6 +19,8 @@ import { elementOverlapsWithFrame } from "../src/frame";
import type {
ExcalidrawElement,
ExcalidrawFrameLikeElement,
+ NonDeleted,
+ NonDeletedExcalidrawElement,
} from "../src/types";
const { h } = window;
@@ -757,7 +759,7 @@ describe("adding elements to frames", () => {
});
API.setElements([rect2, frame, frameChild]);
- API.setSelectedElements([rect2]);
+ API.setSelectedElements([rect2] as NonDeletedExcalidrawElement[]);
API.updateElement(rect2, {
x: 10,
y: 10,
@@ -779,7 +781,7 @@ describe("adding elements to frames", () => {
newElement: h.state.newElement,
selectedElements: getSelectedElements(h.elements, h.state),
selectedElementsAreBeingDragged,
- frameToHighlight: frame as ExcalidrawFrameLikeElement,
+ frameToHighlight: frame as NonDeleted<ExcalidrawFrameLikeElement>,
})
.visibleElements.map((element) => element.id);
};
@@ -843,7 +845,7 @@ describe("adding elements to frames", () => {
newElement: h.state.newElement,
selectedElements: getSelectedElements(h.elements, h.state),
selectedElementsAreBeingDragged: true,
- frameToHighlight: frame as ExcalidrawFrameLikeElement,
+ frameToHighlight: frame as NonDeleted<ExcalidrawFrameLikeElement>,
})
.visibleElements.map((element) => element.id);
diff --git a/packages/element/tests/linearElementEditor.test.tsx b/packages/element/tests/linearElementEditor.test.tsx
index 97df0b32ce..3e01a18b33 100644
--- a/packages/element/tests/linearElementEditor.test.tsx
+++ b/packages/element/tests/linearElementEditor.test.tsx
@@ -43,6 +43,7 @@ import type {
ExcalidrawLinearElement,
ExcalidrawTextElementWithContainer,
FontString,
+ NonDeletedExcalidrawElement,
} from "../src/types";
const renderInteractiveScene = vi.spyOn(
@@ -130,7 +131,7 @@ describe("Test Linear Elements", () => {
selectProgrammatically = false,
) => {
if (selectProgrammatically) {
- API.setSelectedElements([line]);
+ API.setSelectedElements([line] as NonDeletedExcalidrawElement[]);
} else {
mouse.clickAt(p1[0], p1[1]);
}
@@ -991,7 +992,7 @@ describe("Test Linear Elements", () => {
}),
]);
const dragEndPositionOffset = [100, 100] as const;
- API.setSelectedElements([line]);
+ API.setSelectedElements([line] as NonDeletedExcalidrawElement[]);
enterLineEditingMode(line, true);
drag(
pointFrom(line.points[0][0] + line.x, line.points[0][1] + line.y),
@@ -1347,7 +1348,7 @@ describe("Test Linear Elements", () => {
const arrow = h.elements[0] as ExcalidrawLinearElement;
createBoundTextElement(DEFAULT_TEXT, arrow);
- API.setSelectedElements([arrow]);
+ API.setSelectedElements([arrow] as NonDeletedExcalidrawElement[]);
expect(queryByTestId(container, "align-top")).toBeNull();
expect(queryByTestId(container, "align-middle")).toBeNull();
@@ -1418,7 +1419,7 @@ describe("Test Linear Elements", () => {
const arrow = h.elements[0] as ExcalidrawLinearElement;
createBoundTextElement(DEFAULT_TEXT, arrow);
- API.setSelectedElements([arrow]);
+ API.setSelectedElements([arrow] as NonDeletedExcalidrawElement[]);
expect(queryByTestId(container, "align-left")).toBeNull();
expect(queryByTestId(container, "align-horizontal-center")).toBeNull();
@@ -1437,7 +1438,10 @@ describe("Test Linear Elements", () => {
API.setElements([h.elements[0], text]);
const container = h.elements[0];
- API.setSelectedElements([container, text]);
+ API.setSelectedElements([
+ container,
+ text,
+ ] as NonDeletedExcalidrawElement[]);
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 20,
@@ -1461,7 +1465,10 @@ describe("Test Linear Elements", () => {
);
mouse.down();
mouse.up();
- API.setSelectedElements([h.elements[0], h.elements[1]]);
+ API.setSelectedElements([
+ h.elements[0],
+ h.elements[1],
+ ] as NonDeletedExcalidrawElement[]);
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
diff --git a/packages/element/tests/resize.test.tsx b/packages/element/tests/resize.test.tsx
index 15e52dfa1b..10875ee634 100644
--- a/packages/element/tests/resize.test.tsx
+++ b/packages/element/tests/resize.test.tsx
@@ -27,6 +27,7 @@ import type {
ExcalidrawElbowArrowElement,
ExcalidrawFreeDrawElement,
ExcalidrawLinearElement,
+ NonDeleted,
} from "../src/types";
unmountComponent();
@@ -315,7 +316,7 @@ describe("line element", () => {
it("resizes", async () => {
UI.createElement("line", { points });
- const element = h.elements[0] as ExcalidrawLinearElement;
+ const element = h.elements[0] as NonDeleted<ExcalidrawLinearElement>;
const {
x: prevX,
@@ -352,7 +353,7 @@ describe("line element", () => {
it("flips while resizing", async () => {
UI.createElement("line", { points });
- const element = h.elements[0] as ExcalidrawLinearElement;
+ const element = h.elements[0] as NonDeleted<ExcalidrawLinearElement>;
const {
width: prevWidth,
@@ -406,7 +407,7 @@ describe("line element", () => {
pointFrom(-338.05644048727373, -180.4761618151104),
],
});
- const element = h.elements[0] as ExcalidrawLinearElement;
+ const element = h.elements[0] as NonDeleted<ExcalidrawLinearElement>;
const {
x: prevX,
diff --git a/packages/element/tests/typeChecks.test.ts b/packages/element/tests/typeChecks.test.ts
index 6be81aaa6d..0a2e81b9fc 100644
--- a/packages/element/tests/typeChecks.test.ts
+++ b/packages/element/tests/typeChecks.test.ts
@@ -1,6 +1,19 @@
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
-import { hasBoundTextElement } from "../src/typeChecks";
+import { newElementWith } from "../src/mutateElement";
+import {
+ hasBoundTextElement,
+ isLinearElement,
+ isTextElement,
+} from "../src/typeChecks";
+
+import type {
+ ExcalidrawElement,
+ ExcalidrawLinearElement,
+ ExcalidrawTextElement,
+ NonDeleted,
+ NonDeletedExcalidrawElement,
+} from "../src/types";
describe("Test TypeChecks", () => {
describe("Test hasBoundTextElement", () => {
@@ -65,3 +78,38 @@ describe("Test TypeChecks", () => {
).toBeFalsy();
});
});
+
+describe("Test NonDeleted type", () => {
+ it("should only allow `isDeleted: false` elements", () => {
+ const element = API.createElement({ type: "rectangle" });
+ const deletedElement = newElementWith(element as ExcalidrawElement, {
+ isDeleted: true,
+ });
+
+ // @ts-expect-error deleted elements are not assignable to NonDeleted
+ const nonDeleted: NonDeletedExcalidrawElement = deletedElement;
+
+ // runtime narrowing is still required to treat an element as non-deleted
+ // @ts-expect-error generic elements are not assignable to NonDeleted
+ const nonDeletedGeneric: NonDeletedExcalidrawElement =
+ deletedElement as ExcalidrawElement;
+
+ expect(nonDeleted.isDeleted).toBe(true);
+ expect(nonDeletedGeneric.isDeleted).toBe(true);
+ });
+
+ it("should be preserved by type guards", () => {
+ const elements: NonDeletedExcalidrawElement[] = [
+ API.createElement({ type: "text", text: "text" }),
+ API.createElement({ type: "arrow" }),
+ ];
+
+ const textElements: NonDeleted<ExcalidrawTextElement>[] =
+ elements.filter(isTextElement);
+ const linearElements: NonDeleted<ExcalidrawLinearElement>[] =
+ elements.filter(isLinearElement);
+
+ expect(textElements.length).toBe(1);
+ expect(linearElements.length).toBe(1);
+ });
+});
diff --git a/packages/element/tests/zindex.test.tsx b/packages/element/tests/zindex.test.tsx
index 1861bf5d8d..31dd32ad11 100644
--- a/packages/element/tests/zindex.test.tsx
+++ b/packages/element/tests/zindex.test.tsx
@@ -8,7 +8,7 @@ import {
actionDuplicateSelection,
} from "@excalidraw/excalidraw/actions";
-import { Excalidraw } from "@excalidraw/excalidraw";
+import { Excalidraw, getNonDeletedElements } from "@excalidraw/excalidraw";
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import {
@@ -116,7 +116,7 @@ const populateElements = (
h.setState({
...selectGroupsForSelectedElements(
{ ...h.state, ...appState, selectedElementIds },
- h.elements,
+ getNonDeletedElements(h.elements),
h.state,
null,
),
diff --git a/packages/excalidraw/actions/actionCanvas.tsx b/packages/excalidraw/actions/actionCanvas.tsx
index f6e6e88f41..69e2d5ba8c 100644
--- a/packages/excalidraw/actions/actionCanvas.tsx
+++ b/packages/excalidraw/actions/actionCanvas.tsx
@@ -16,6 +16,8 @@ import { getCommonBounds } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
+import type { ExcalidrawElement } from "@excalidraw/element/types";
+
import {
getDefaultAppState,
isEraserActive,
@@ -282,12 +284,13 @@ export const actionZoomToFitSelectionInViewport = register({
predicate: (elements, appState) => !appState.scrollConstraints,
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
+ const nonDeletedSelectedElements = getNonDeletedElements(
+ (selectedElements.length
+ ? selectedElements
+ : elements) as ExcalidrawElement[],
+ );
return zoomToFitBounds({
- bounds: getCommonBounds(
- getNonDeletedElements(
- selectedElements.length ? selectedElements : elements,
- ),
- ),
+ bounds: getCommonBounds(nonDeletedSelectedElements),
appState: {
...appState,
userToFollow: null,
@@ -314,12 +317,13 @@ export const actionZoomToFitSelection = register({
predicate: (elements, appState) => !appState.scrollConstraints,
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
+ const nonDeletedSelectedElements = getNonDeletedElements(
+ (selectedElements.length
+ ? selectedElements
+ : elements) as ExcalidrawElement[],
+ );
return zoomToFitBounds({
- bounds: getCommonBounds(
- getNonDeletedElements(
- selectedElements.length ? selectedElements : elements,
- ),
- ),
+ bounds: getCommonBounds(nonDeletedSelectedElements),
appState: {
...appState,
userToFollow: null,
diff --git a/packages/excalidraw/actions/actionDeleteSelected.tsx b/packages/excalidraw/actions/actionDeleteSelected.tsx
index c25712eb94..8112e1b9f3 100644
--- a/packages/excalidraw/actions/actionDeleteSelected.tsx
+++ b/packages/excalidraw/actions/actionDeleteSelected.tsx
@@ -178,7 +178,7 @@ const deleteSelectedElements = (
selectedElementIds,
editingGroupId: nextEditingGroupId,
},
- nextElements,
+ getNonDeletedElements(nextElements),
appState,
null,
),
diff --git a/packages/excalidraw/actions/actionElementLock.ts b/packages/excalidraw/actions/actionElementLock.ts
index aaecf1c4da..7be2f0876f 100644
--- a/packages/excalidraw/actions/actionElementLock.ts
+++ b/packages/excalidraw/actions/actionElementLock.ts
@@ -2,6 +2,7 @@ import { KEYS, arrayToMap, randomId } from "@excalidraw/common";
import {
elementsAreInSameGroup,
+ getNonDeletedElements,
newElementWith,
selectGroupsFromGivenElements,
} from "@excalidraw/element";
@@ -114,7 +115,10 @@ export const actionToggleElementLock = register({
);
const nextSelectedGroupIds = nextLockState
? {}
- : selectGroupsFromGivenElements(unlockedSelectedElements, appState);
+ : selectGroupsFromGivenElements(
+ getNonDeletedElements(unlockedSelectedElements),
+ appState,
+ );
const activeLockedId = nextLockState
? newGroupId
@@ -192,16 +196,17 @@ export const actionUnlockAllElements = register({
const unlockedElements = lockedElements.map(
(el) => nextElementsMap.get(el.id) || el,
);
+ const unlockedNonDeletedElements = getNonDeletedElements(unlockedElements);
return {
elements: nextElements,
appState: {
...appState,
selectedElementIds: Object.fromEntries(
- lockedElements.map((el) => [el.id, true]),
+ unlockedNonDeletedElements.map((el) => [el.id, true]),
),
selectedGroupIds: selectGroupsFromGivenElements(
- unlockedElements,
+ unlockedNonDeletedElements,
appState,
),
lockedMultiSelections: {},
diff --git a/packages/excalidraw/actions/actionLink.tsx b/packages/excalidraw/actions/actionLink.tsx
index 34b3326b57..a228f51d55 100644
--- a/packages/excalidraw/actions/actionLink.tsx
+++ b/packages/excalidraw/actions/actionLink.tsx
@@ -1,4 +1,7 @@
-import { isEmbeddableElement } from "@excalidraw/element";
+import {
+ getNonDeletedElements,
+ isEmbeddableElement,
+} from "@excalidraw/element";
import { KEYS } from "@excalidraw/common";
@@ -15,7 +18,8 @@ import { register } from "./register";
export const actionLink = register({
name: "hyperlink",
- label: (elements, appState) => getContextMenuLabel(elements, appState),
+ label: (elements, appState) =>
+ getContextMenuLabel(getNonDeletedElements(elements), appState),
icon: LinkIcon,
perform: (elements, appState) => {
if (appState.showHyperlinkPopup === "editor") {
@@ -45,7 +49,9 @@ export const actionLink = register({
<ToolButton
type="button"
icon={LinkIcon}
- aria-label={t(getContextMenuLabel(elements, appState))}
+ aria-label={t(
+ getContextMenuLabel(getNonDeletedElements(elements), appState),
+ )}
title={`${
isEmbeddableElement(elements[0])
? t("labels.link.labelEmbed")
diff --git a/packages/excalidraw/actions/actionProperties.tsx b/packages/excalidraw/actions/actionProperties.tsx
index c8341dfdfa..d807c42ca5 100644
--- a/packages/excalidraw/actions/actionProperties.tsx
+++ b/packages/excalidraw/actions/actionProperties.tsx
@@ -27,7 +27,11 @@ import {
type StrokeWidthKey,
} from "@excalidraw/common";
-import { canBecomePolygon, getNonDeletedElements } from "@excalidraw/element";
+import {
+ canBecomePolygon,
+ getNonDeletedElements,
+ isNonDeletedElement,
+} from "@excalidraw/element";
import {
bindBindingElement,
@@ -77,11 +81,13 @@ import type {
ExcalidrawTextElement,
FontFamilyValues,
StrokeVariability,
+ NonDeleted,
+ NonDeletedExcalidrawElement,
TextAlign,
VerticalAlign,
} from "@excalidraw/element/types";
-import type { Scene } from "@excalidraw/element";
+import type { ElementUpdate, Scene } from "@excalidraw/element";
import type { CaptureUpdateActionType } from "@excalidraw/element";
@@ -174,7 +180,7 @@ const getStylesPanelInfo = (app: AppClassProperties) => {
export const changeProperty = (
elements: readonly ExcalidrawElement[],
appState: AppState,
- callback: (element: ExcalidrawElement) => ExcalidrawElement,
+ callback: (element: NonDeletedExcalidrawElement) => ExcalidrawElement,
includeBoundText = false,
) => {
const selectedElementIds = arrayToMap(
@@ -188,7 +194,14 @@ export const changeProperty = (
selectedElementIds.get(element.id) ||
element.id === appState.editingTextElement?.id
) {
- return callback(element);
+ // selected & editing elements are non-deleted
+ if (!isNonDeletedElement(element)) {
+ // SAFETY: This should never happen, but log it just in case
+ console.error(
+ "[NONDELETED][INVARIANT] changeProperty(): skipping deleted selected/editing element",
+ );
+ }
+ return callback(element as NonDeletedExcalidrawElement);
}
return element;
});
@@ -1036,7 +1049,7 @@ export const actionChangeFontFamily = register<{
if (cachedElement) {
const newElement = newElementWith(element, {
...cachedElement,
- });
+ } as ElementUpdate<NonDeletedExcalidrawElement>);
return newElement;
}
@@ -2038,13 +2051,13 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
endBinding,
fixedSegments: null,
}),
- };
+ } as typeof newElement;
} else {
const elementsMap = app.scene.getNonDeletedElementsMap();
if (newElement.startBinding) {
const startElement = elementsMap.get(
newElement.startBinding.elementId,
- ) as ExcalidrawBindableElement;
+ ) as NonDeleted<ExcalidrawBindableElement>;
if (startElement) {
bindBindingElement(
newElement,
@@ -2058,7 +2071,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
if (newElement.endBinding) {
const endElement = elementsMap.get(
newElement.endBinding.elementId,
- ) as ExcalidrawBindableElement;
+ ) as NonDeleted<ExcalidrawBindableElement>;
if (endElement) {
bindBindingElement(
newElement,
@@ -2086,7 +2099,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
const selected = newElements.find((el) => el.id === selectedId);
if (selected) {
newState.selectedLinearElement = new LinearElementEditor(
- selected as ExcalidrawLinearElement,
+ selected as NonDeleted<ExcalidrawLinearElement>,
arrayToMap(elements),
);
}
diff --git a/packages/excalidraw/actions/actionSelectAll.ts b/packages/excalidraw/actions/actionSelectAll.ts
index 7157d76176..9e6a07ff5e 100644
--- a/packages/excalidraw/actions/actionSelectAll.ts
+++ b/packages/excalidraw/actions/actionSelectAll.ts
@@ -8,7 +8,11 @@ import { selectGroupsForSelectedElements } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
-import type { ExcalidrawElement } from "@excalidraw/element/types";
+import type {
+ ExcalidrawElement,
+ ExcalidrawLinearElement,
+ NonDeleted,
+} from "@excalidraw/element/types";
import { selectAllIcon } from "../components/icons";
@@ -53,7 +57,10 @@ export const actionSelectAll = register({
// single linear element selected
Object.keys(selectedElementIds).length === 1 &&
isLinearElement(elements[0])
- ? new LinearElementEditor(elements[0], arrayToMap(elements))
+ ? new LinearElementEditor(
+ elements[0] as NonDeleted<ExcalidrawLinearElement>,
+ arrayToMap(elements),
+ )
: null,
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
diff --git a/packages/excalidraw/actions/actionStyles.ts b/packages/excalidraw/actions/actionStyles.ts
index aa8bf41fc6..aa1dc78f00 100644
--- a/packages/excalidraw/actions/actionStyles.ts
+++ b/packages/excalidraw/actions/actionStyles.ts
@@ -121,7 +121,7 @@ export const actionPasteStyles = register({
const fontFamily =
(elementStylesToCopyFrom as ExcalidrawTextElement).fontFamily ||
DEFAULT_FONT_FAMILY;
- newElement = newElementWith(newElement, {
+ const newTextElement = newElementWith(newElement, {
fontSize,
fontFamily,
textAlign:
@@ -131,17 +131,16 @@ export const actionPasteStyles = register({
(elementStylesToCopyFrom as ExcalidrawTextElement).lineHeight ||
getLineHeight(fontFamily),
});
+ newElement = newTextElement;
let container = null;
- if (newElement.containerId) {
+ if (newTextElement.containerId) {
container =
selectedElements.find(
- (element) =>
- isTextElement(newElement) &&
- element.id === newElement.containerId,
+ (element) => element.id === newTextElement.containerId,
) || null;
}
- redrawTextBoundingBox(newElement, container, app.scene);
+ redrawTextBoundingBox(newTextElement, container, app.scene);
}
if (
diff --git a/packages/excalidraw/charts.test.ts b/packages/excalidraw/charts.test.ts
index 16e161ca40..f12fd5579b 100644
--- a/packages/excalidraw/charts.test.ts
+++ b/packages/excalidraw/charts.test.ts
@@ -7,6 +7,7 @@ import {
import type {
ExcalidrawLineElement,
ExcalidrawTextElement,
+ NonDeleted,
} from "@excalidraw/element/types";
import {
@@ -476,7 +477,7 @@ describe("charts", () => {
const multiElements = renderSpreadsheet("bar", multiSeries, 0, 0);
const getXAxisWidth = (elements: ReturnType<typeof renderSpreadsheet>) =>
elements!.find(
- (element): element is ExcalidrawLineElement =>
+ (element): element is NonDeleted<ExcalidrawLineElement> =>
element.type === "line" &&
element.strokeStyle === "solid" &&
element.points[0][1] === 0 &&
@@ -509,7 +510,7 @@ describe("charts", () => {
const multiElements = renderSpreadsheet("line", multiSeries, 0, 0);
const getXAxisWidth = (elements: ReturnType<typeof renderSpreadsheet>) =>
elements!.find(
- (element): element is ExcalidrawLineElement =>
+ (element): element is NonDeleted<ExcalidrawLineElement> =>
element.type === "line" &&
element.strokeStyle === "solid" &&
element.points[0][1] === 0 &&
@@ -539,13 +540,13 @@ describe("charts", () => {
const elements = renderSpreadsheet("bar", spreadsheet, 0, 0);
const longWordLabel = elements!.find(
- (element): element is ExcalidrawTextElement =>
+ (element): element is NonDeleted<ExcalidrawTextElement> =>
element.type === "text" &&
Math.abs(element.angle) > 0 &&
element.text.includes("..."),
);
const spacedLabels = elements!.filter(
- (element): element is ExcalidrawTextElement =>
+ (element): element is NonDeleted<ExcalidrawTextElement> =>
element.type === "text" &&
(element.originalText === "Data Flow" ||
element.originalText === "Logic Layer"),
@@ -587,7 +588,7 @@ describe("charts", () => {
const elements = renderSpreadsheet("bar", spreadsheet, 0, 0);
const axisLabels = elements!.filter(
- (element): element is ExcalidrawTextElement =>
+ (element): element is NonDeleted<ExcalidrawTextElement> =>
element.type === "text" && Math.abs(element.angle) > 0,
);
@@ -620,7 +621,7 @@ describe("charts", () => {
const elements = renderSpreadsheet("line", spreadsheet, 0, 0);
const seriesLines = elements!.filter(
- (element): element is ExcalidrawLineElement =>
+ (element): element is NonDeleted<ExcalidrawLineElement> =>
element.type === "line" && element.strokeWidth === 2,
);
const dots = elements!.filter(
@@ -689,7 +690,7 @@ describe("charts", () => {
const elements = renderSpreadsheet("line", spreadsheet, 0, 0, seed);
return elements!
.filter(
- (element): element is ExcalidrawLineElement =>
+ (element): element is NonDeleted<ExcalidrawLineElement> =>
element.type === "line" && element.strokeWidth === 2,
)
.map((line) => line.strokeColor);
@@ -759,7 +760,7 @@ describe("charts", () => {
const elements = renderSpreadsheet("line", spreadsheet, 0, 0);
const axisLabels = elements!.filter(
- (element): element is ExcalidrawTextElement =>
+ (element): element is NonDeleted<ExcalidrawTextElement> =>
element.type === "text" && Math.abs(element.angle) > 0,
);
@@ -793,7 +794,7 @@ describe("charts", () => {
const elements = renderSpreadsheet("radar", spreadsheet, 0, 0);
const seriesPolygons = elements!.filter(
- (element): element is ExcalidrawLineElement =>
+ (element): element is NonDeleted<ExcalidrawLineElement> =>
element.type === "line" &&
"polygon" in element &&
element.polygon === true &&
@@ -820,7 +821,7 @@ describe("charts", () => {
const elements = renderSpreadsheet("radar", spreadsheet, 0, 0);
const seriesPolygons = elements!.filter(
- (element): element is ExcalidrawLineElement =>
+ (element): element is NonDeleted<ExcalidrawLineElement> =>
element.type === "line" &&
"polygon" in element &&
element.polygon === true &&
@@ -880,7 +881,7 @@ describe("charts", () => {
const elements = renderSpreadsheet("radar", spreadsheet, 0, 0);
const seriesPolygons = elements!.filter(
- (element): element is ExcalidrawLineElement =>
+ (element): element is NonDeleted<ExcalidrawLineElement> =>
element.type === "line" &&
"polygon" in element &&
element.polygon === true &&
@@ -994,7 +995,7 @@ describe("charts", () => {
const topSpokeY = Math.min(
...elements!
.filter(
- (element): element is ExcalidrawLineElement =>
+ (element): element is NonDeleted<ExcalidrawLineElement> =>
element.type === "line" &&
"polygon" in element &&
!element.polygon &&
diff --git a/packages/excalidraw/clipboard.ts b/packages/excalidraw/clipboard.ts
index 6de0b12eab..5075343f65 100644
--- a/packages/excalidraw/clipboard.ts
+++ b/packages/excalidraw/clipboard.ts
@@ -22,6 +22,7 @@ import type { ValueOf } from "@excalidraw/common/utility-types";
import type { IMAGE_MIME_TYPES, STRING_MIME_TYPES } from "@excalidraw/common";
import type {
ExcalidrawElement,
+ ExcalidrawFrameLikeElement,
NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
@@ -147,7 +148,7 @@ export const serializeAsClipboardJSON = ({
files: BinaryFiles | null;
}) => {
const elementsMap = arrayToMap(elements);
- const framesToCopy = new Set(
+ const framesToCopy = new Set<ExcalidrawFrameLikeElement>(
elements.filter((element) => isFrameLikeElement(element)),
);
let foundFile = false;
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index cd6a3425a0..ae202a3a6f 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -232,7 +232,6 @@ import {
dragNewElement,
dragSelectedElements,
getDragOffsetXY,
- isNonDeletedElement,
Scene,
Store,
CaptureUpdateAction,
@@ -262,6 +261,7 @@ import {
getActiveTextElement,
isEligibleFrameChildType,
getBindingStrategyForDraggingBindingElementEndpoints,
+ isNonDeletedElement,
} from "@excalidraw/element";
import type { GlobalPoint, LocalPoint, Radians } from "@excalidraw/math";
@@ -2518,7 +2518,7 @@ class App extends React.Component<AppProps, AppState> {
public onExportImage = async (
type: keyof typeof EXPORT_IMAGE_TYPES,
elements: ExportedElements,
- opts: { exportingFrame: ExcalidrawFrameLikeElement | null },
+ opts: { exportingFrame: NonDeleted<ExcalidrawFrameLikeElement> | null },
) => {
trackEvent("export", type, "ui");
const fileHandle = await exportCanvas(
@@ -2596,7 +2596,7 @@ class App extends React.Component<AppProps, AppState> {
}
private async onMagicFrameGenerate(
- magicFrame: ExcalidrawMagicFrameElement,
+ magicFrame: Readonly<NonDeleted<ExcalidrawMagicFrameElement>>,
source: "button" | "upstream",
) {
const generateDiagramToCode = this.plugins.diagramToCode?.generate;
@@ -2710,7 +2710,9 @@ class App extends React.Component<AppProps, AppState> {
this.setActiveTool({ type: TOOL_TYPE.magicframe });
trackEvent("ai", "tool-select (empty-selection)", "d2c");
} else {
- const selectedMagicFrame: ExcalidrawMagicFrameElement | false =
+ const selectedMagicFrame:
+ | NonDeleted<ExcalidrawMagicFrameElement>
+ | false =
selectedElements.length === 1 &&
isMagicFrameElement(selectedElements[0]) &&
selectedElements[0];
@@ -2728,7 +2730,7 @@ class App extends React.Component<AppProps, AppState> {
trackEvent("ai", "tool-select (existing selection)", "d2c");
- let frame: ExcalidrawMagicFrameElement;
+ let frame: NonDeleted<ExcalidrawMagicFrameElement>;
if (selectedMagicFrame) {
// a single magicframe already selected -> use it
frame = selectedMagicFrame;
@@ -4057,7 +4059,10 @@ class App extends React.Component<AppProps, AppState> {
});
const prevElements = this.scene.getElementsIncludingDeleted();
- let nextElements = [...prevElements, ...duplicatedElements];
+ let nextElements: ExcalidrawElement[] = [
+ ...prevElements,
+ ...duplicatedElements,
+ ];
const mappedNewSceneElements = this.props.onDuplicate?.(
nextElements,
@@ -5671,7 +5676,7 @@ class App extends React.Component<AppProps, AppState> {
element,
elementsMap.get(
element.startBinding.elementId,
- ) as ExcalidrawBindableElement,
+ ) as NonDeleted<ExcalidrawBindableElement>,
"start",
elementsMap,
),
@@ -5686,7 +5691,7 @@ class App extends React.Component<AppProps, AppState> {
element,
elementsMap.get(
element.endBinding.elementId,
- ) as ExcalidrawBindableElement,
+ ) as NonDeleted<ExcalidrawBindableElement>,
"end",
elementsMap,
),
@@ -5951,7 +5956,7 @@ class App extends React.Component<AppProps, AppState> {
});
private handleTextWysiwyg(
- element: ExcalidrawTextElement,
+ element: NonDeleted<ExcalidrawTextElement>,
{
isExistingElement = false,
initialCaretSceneCoords = null,
@@ -5989,7 +5994,6 @@ class App extends React.Component<AppProps, AppState> {
};
textWysiwyg({
- id: element.id,
canvas: this.canvas,
getViewportCoords: (x, y) => {
const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
@@ -6110,7 +6114,7 @@ class App extends React.Component<AppProps, AppState> {
return getBoundTextElement(
selectedElement,
this.scene.getNonDeletedElementsMap(),
- );
+ ) as NonDeleted<ExcalidrawTextElement> | null;
}
private getSelectedTextEditingContainerAtPosition(
@@ -6284,7 +6288,7 @@ class App extends React.Component<AppProps, AppState> {
includeLockedElements?: boolean;
},
): NonDeleted<ExcalidrawElement>[] {
- const iframeLikes: Ordered<ExcalidrawIframeElement>[] = [];
+ const iframeLikes: Ordered<NonDeleted<ExcalidrawIframeElement>>[] = [];
const elementsMap = this.scene.getNonDeletedElementsMap();
@@ -6304,10 +6308,17 @@ class App extends React.Component<AppProps, AppState> {
.filter((element) => {
// hitting a frame's element from outside the frame is not considered a hit
const containingFrame = getContainingFrame(element, elementsMap);
+ if (containingFrame && !isNonDeletedElement(containingFrame)) {
+ console.error("[NONDELETED][INVARIANT] Containing frame is deleted");
+ }
return containingFrame &&
this.state.frameRendering.enabled &&
this.state.frameRendering.clip
- ? isCursorInFrame({ x, y }, containingFrame, elementsMap)
+ ? isCursorInFrame(
+ { x, y },
+ containingFrame as NonDeleted<ExcalidrawFrameLikeElement>,
+ elementsMap,
+ )
: true;
})
.filter((el) => {
@@ -6339,7 +6350,7 @@ class App extends React.Component<AppProps, AppState> {
private hitElement(
x: number,
y: number,
- element: ExcalidrawElement,
+ element: NonDeletedExcalidrawElement,
considerBoundingBox = true,
) {
// if the element is selected, then hit test is done against its bounding box
@@ -6943,7 +6954,7 @@ class App extends React.Component<AppProps, AppState> {
private getElementLinkAtPosition = (
scenePointer: Readonly<{ x: number; y: number }>,
hitElementMightBeLocked: NonDeletedExcalidrawElement | null,
- ): ExcalidrawElement | undefined => {
+ ): NonDeletedExcalidrawElement | undefined => {
if (hitElementMightBeLocked && hitElementMightBeLocked.locked) {
return undefined;
}
@@ -7066,7 +7077,7 @@ class App extends React.Component<AppProps, AppState> {
const framesUnderCursor = this.scene
.getNonDeletedFramesLikes()
.filter(
- (frame): frame is ExcalidrawFrameLikeElement =>
+ (frame) =>
!frame.locked && isCursorInFrame(sceneCoords, frame, elementsMap),
);
@@ -7698,7 +7709,7 @@ class App extends React.Component<AppProps, AppState> {
},
);
- let hitElement: ExcalidrawElement | null = null;
+ let hitElement: NonDeleted<ExcalidrawElement> | null = null;
if (hitElementMightBeLocked && hitElementMightBeLocked.locked) {
hitElement = null;
} else {
@@ -9284,7 +9295,7 @@ class App extends React.Component<AppProps, AppState> {
let container = this.getTextBindableContainerAtPosition(sceneX, sceneY);
if (hasBoundTextElement(element)) {
- container = element as ExcalidrawTextContainer;
+ container = element as NonDeleted<ExcalidrawTextContainer>;
sceneX = element.x + element.width / 2;
sceneY = element.y + element.height / 2;
}
@@ -9944,7 +9955,7 @@ class App extends React.Component<AppProps, AppState> {
private maybeCacheReferenceSnapPoints(
event: KeyboardModifiersObject,
- selectedElements: ExcalidrawElement[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
recomputeAnyways: boolean = false,
) {
if (
@@ -9968,7 +9979,7 @@ class App extends React.Component<AppProps, AppState> {
private maybeCacheVisibleGaps(
event: KeyboardModifiersObject,
- selectedElements: ExcalidrawElement[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
recomputeAnyways: boolean = false,
) {
if (
@@ -11518,9 +11529,7 @@ class App extends React.Component<AppProps, AppState> {
const selectedFrames = this.scene
.getSelectedElements(this.state)
- .filter((element): element is ExcalidrawFrameLikeElement =>
- isFrameLikeElement(element),
- );
+ .filter(isFrameLikeElement);
for (const frame of selectedFrames) {
nextElements = replaceAllElementsInFrame(
@@ -12143,7 +12152,7 @@ class App extends React.Component<AppProps, AppState> {
this.scene.getElement(imagePlaceholder.id) ?? imagePlaceholder;
return newElementWith(
- latestImageElement as InitializedExcalidrawImageElement,
+ latestImageElement as NonDeleted<InitializedExcalidrawImageElement>,
{
fileId,
},
@@ -12363,7 +12372,9 @@ class App extends React.Component<AppProps, AppState> {
this.setState({
errorMessage: error.message || t("errors.imageInsertError"),
});
- return newElementWith(placeholder, { isDeleted: true });
+ return newElementWith(placeholder as ExcalidrawImageElement, {
+ isDeleted: true,
+ });
}
}),
);
@@ -12787,7 +12798,7 @@ class App extends React.Component<AppProps, AppState> {
newElement as ExcalidrawFrameLikeElement,
this.state,
this.scene.getNonDeletedElementsMap(),
- ),
+ ) as NonDeletedExcalidrawElement[], // Obvious typecast, no need to runtime typecheck
});
}
};
@@ -12889,10 +12900,7 @@ class App extends React.Component<AppProps, AppState> {
event: MouseEvent | KeyboardEvent,
): boolean => {
const selectedElements = this.scene.getSelectedElements(this.state);
- const selectedFrames = selectedElements.filter(
- (element): element is ExcalidrawFrameLikeElement =>
- isFrameLikeElement(element),
- );
+ const selectedFrames = selectedElements.filter(isFrameLikeElement);
const transformHandleType = pointerDownState.resize.handleType;
@@ -12996,14 +13004,23 @@ class App extends React.Component<AppProps, AppState> {
pointerDownState.resize.center.y,
)
) {
- const elementsToHighlight = new Set<ExcalidrawElement>();
+ const elementsToHighlight = new Set<NonDeletedExcalidrawElement>();
selectedFrames.forEach((frame) => {
getElementsInResizingFrame(
this.scene.getNonDeletedElements(),
frame,
this.state,
this.scene.getNonDeletedElementsMap(),
- ).forEach((element) => elementsToHighlight.add(element));
+ ).forEach((element) => {
+ if (isNonDeletedElement(element)) {
+ elementsToHighlight.add(element);
+ } else {
+ // SAFETY: This should never happen, but log it just in case
+ console.error(
+ "[NONDELETED][INVARIANT] Skipped highlighting deleted element in resizing frame",
+ );
+ }
+ });
});
this.setState({
diff --git a/packages/excalidraw/components/ConvertElementTypePopup.tsx b/packages/excalidraw/components/ConvertElementTypePopup.tsx
index 5f02212012..910301288c 100644
--- a/packages/excalidraw/components/ConvertElementTypePopup.tsx
+++ b/packages/excalidraw/components/ConvertElementTypePopup.tsx
@@ -71,6 +71,8 @@ import type {
ExcalidrawTextContainer,
ExcalidrawTextElementWithContainer,
FixedSegment,
+ NonDeleted,
+ NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import type { Scene } from "@excalidraw/element";
@@ -190,7 +192,7 @@ const Panel = ({
elements,
}: {
app: App;
- elements: ExcalidrawElement[];
+ elements: readonly NonDeletedExcalidrawElement[];
}) => {
const conversionType = getConversionTypeFromElements(elements);
@@ -452,7 +454,7 @@ export const convertElementTypes = (
];
if (nextType && isConvertibleGenericType(nextType)) {
- const convertedElements: Record<string, ExcalidrawElement> = {};
+ const convertedElements: Record<string, NonDeletedExcalidrawElement> = {};
for (const element of convertibleGenericElements) {
const convertedElement = convertElementType(element, nextType, app);
@@ -505,9 +507,8 @@ export const convertElementTypes = (
}
if (conversionType === "linear") {
- const convertibleLinearElements = filterLinearConvertibleElements(
- selectedElements,
- ) as ExcalidrawLinearElement[];
+ const convertibleLinearElements =
+ filterLinearConvertibleElements(selectedElements);
if (!nextType) {
const commonSubType = reduceToCommonValue(
@@ -628,7 +629,7 @@ export const convertElementTypes = (
};
export const getConversionTypeFromElements = (
- elements: ExcalidrawElement[],
+ elements: readonly ExcalidrawElement[],
): ConversionType => {
if (elements.length === 0) {
return null;
@@ -667,17 +668,30 @@ const toCacheKey = (
return `${elementId}:${convertitleType}` as CacheKey;
};
-const filterGenericConvetibleElements = (elements: ExcalidrawElement[]) =>
+const filterGenericConvetibleElements = <T extends ExcalidrawElement>(
+ elements: readonly T[],
+) =>
elements.filter((element) => isConvertibleGenericType(element.type)) as Array<
- | ExcalidrawRectangleElement
- | ExcalidrawDiamondElement
- | ExcalidrawEllipseElement
+ T extends NonDeletedExcalidrawElement
+ ? NonDeleted<
+ | ExcalidrawRectangleElement
+ | ExcalidrawDiamondElement
+ | ExcalidrawEllipseElement
+ >
+ :
+ | ExcalidrawRectangleElement
+ | ExcalidrawDiamondElement
+ | ExcalidrawEllipseElement
>;
-const filterLinearConvertibleElements = (elements: ExcalidrawElement[]) =>
+const filterLinearConvertibleElements = <T extends ExcalidrawElement>(
+ elements: readonly T[],
+) =>
elements.filter((element) =>
isEligibleLinearElement(element),
- ) as ExcalidrawLinearElement[];
+ ) as (T extends NonDeletedExcalidrawElement
+ ? NonDeleted<ExcalidrawLinearElement>
+ : ExcalidrawLinearElement)[];
const THRESHOLD = 20;
const isVert = (a: LocalPoint, b: LocalPoint) => a[0] === b[0];
@@ -807,12 +821,15 @@ const sanitizePoints = (points: readonly LocalPoint[]): LocalPoint[] => {
* e.g. elbow arrow -> line
*/
const convertElementType = <
- TElement extends Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
+ TElement extends Exclude<
+ NonDeletedExcalidrawElement,
+ ExcalidrawSelectionElement
+ >,
>(
element: TElement,
targetType: ConvertibleTypes,
app: AppClassProperties,
-): ExcalidrawElement => {
+): NonDeletedExcalidrawElement => {
if (!isValidConversion(element.type, targetType)) {
if (!isProdEnv()) {
throw Error(`Invalid conversion from ${element.type} to ${targetType}.`);
diff --git a/packages/excalidraw/components/Stats/Angle.tsx b/packages/excalidraw/components/Stats/Angle.tsx
index c79e9bb3b1..9b88a98dfc 100644
--- a/packages/excalidraw/components/Stats/Angle.tsx
+++ b/packages/excalidraw/components/Stats/Angle.tsx
@@ -7,7 +7,7 @@ import { updateBindings } from "@excalidraw/element";
import type { Degrees } from "@excalidraw/math";
-import type { ExcalidrawElement } from "@excalidraw/element/types";
+import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import type { Scene } from "@excalidraw/element";
@@ -20,7 +20,7 @@ import type { DragInputCallbackType } from "./DragInput";
import type { AppState } from "../../types";
interface AngleProps {
- element: ExcalidrawElement;
+ element: NonDeletedExcalidrawElement;
scene: Scene;
appState: AppState;
property: "angle";
diff --git a/packages/excalidraw/components/Stats/Dimension.tsx b/packages/excalidraw/components/Stats/Dimension.tsx
index a83cf835fc..623d547797 100644
--- a/packages/excalidraw/components/Stats/Dimension.tsx
+++ b/packages/excalidraw/components/Stats/Dimension.tsx
@@ -3,6 +3,7 @@ import { clamp, round } from "@excalidraw/math";
import { MIN_WIDTH_OR_HEIGHT } from "@excalidraw/common";
import {
MINIMAL_CROP_SIZE,
+ getNonDeletedElements,
getUncroppedWidthAndHeight,
} from "@excalidraw/element";
import { resizeSingleElement } from "@excalidraw/element";
@@ -11,7 +12,10 @@ import { isFrameLikeElement } from "@excalidraw/element";
import { getElementsInResizingFrame } from "@excalidraw/element";
import { replaceAllElementsInFrame } from "@excalidraw/element";
-import type { ExcalidrawElement } from "@excalidraw/element/types";
+import type {
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
import type { Scene } from "@excalidraw/element";
@@ -26,7 +30,7 @@ import type { AppState } from "../../types";
interface DimensionDragInputProps {
property: "width" | "height";
- element: ExcalidrawElement;
+ element: NonDeletedExcalidrawElement;
scene: Scene;
appState: AppState;
}
@@ -263,11 +267,13 @@ const handleDimensionChange: DragInputCallbackType<
// Handle highlighting frame element candidates
if (isFrameLikeElement(latestElement)) {
- const nextElementsInFrame = getElementsInResizingFrame(
- scene.getElementsIncludingDeleted(),
- latestElement,
- originalAppState,
- scene.getNonDeletedElementsMap(),
+ const nextElementsInFrame = getNonDeletedElements(
+ getElementsInResizingFrame(
+ scene.getElementsIncludingDeleted(),
+ latestElement,
+ originalAppState,
+ scene.getNonDeletedElementsMap(),
+ ),
);
setAppState({
diff --git a/packages/excalidraw/components/Stats/DragInput.tsx b/packages/excalidraw/components/Stats/DragInput.tsx
index 259cb47180..6479dbb1c3 100644
--- a/packages/excalidraw/components/Stats/DragInput.tsx
+++ b/packages/excalidraw/components/Stats/DragInput.tsx
@@ -7,7 +7,11 @@ import { deepCopyElement } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
-import type { ElementsMap, ExcalidrawElement } from "@excalidraw/element/types";
+import type {
+ ElementsMap,
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
import type { Scene } from "@excalidraw/element";
@@ -23,7 +27,7 @@ import type { AppState } from "../../types";
export type DragInputCallbackType<
P extends StatsInputProperty,
- E = ExcalidrawElement,
+ E = NonDeletedExcalidrawElement,
> = (props: {
accumulatedChange: number;
instantChange: number;
diff --git a/packages/excalidraw/components/Stats/MultiAngle.tsx b/packages/excalidraw/components/Stats/MultiAngle.tsx
index 966425f3bf..e232f5ec12 100644
--- a/packages/excalidraw/components/Stats/MultiAngle.tsx
+++ b/packages/excalidraw/components/Stats/MultiAngle.tsx
@@ -7,7 +7,7 @@ import { isInGroup } from "@excalidraw/element";
import type { Degrees } from "@excalidraw/math";
-import type { ExcalidrawElement } from "@excalidraw/element/types";
+import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import type { Scene } from "@excalidraw/element";
@@ -20,7 +20,7 @@ import type { DragInputCallbackType } from "./DragInput";
import type { AppState } from "../../types";
interface MultiAngleProps {
- elements: readonly ExcalidrawElement[];
+ elements: readonly NonDeletedExcalidrawElement[];
scene: Scene;
appState: AppState;
property: "angle";
diff --git a/packages/excalidraw/components/Stats/MultiDimension.tsx b/packages/excalidraw/components/Stats/MultiDimension.tsx
index 5224928ce7..ec59bd568b 100644
--- a/packages/excalidraw/components/Stats/MultiDimension.tsx
+++ b/packages/excalidraw/components/Stats/MultiDimension.tsx
@@ -4,6 +4,7 @@ import { useMemo } from "react";
import { MIN_WIDTH_OR_HEIGHT } from "@excalidraw/common";
import {
getElementsInResizingFrame,
+ getNonDeletedElements,
isFrameLikeElement,
replaceAllElementsInFrame,
updateBoundElements,
@@ -20,7 +21,7 @@ import { getCommonBounds } from "@excalidraw/utils";
import type {
ElementsMap,
- ExcalidrawElement,
+ NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
} from "@excalidraw/element/types";
@@ -39,7 +40,7 @@ import type { AppState } from "../../types";
interface MultiDimensionProps {
property: "width" | "height";
- elements: readonly ExcalidrawElement[];
+ elements: readonly NonDeletedExcalidrawElement[];
elementsMap: NonDeletedSceneElementsMap;
atomicUnits: AtomicUnit[];
scene: Scene;
@@ -52,7 +53,7 @@ const getResizedUpdates = (
anchorX: number,
anchorY: number,
scale: number,
- origElement: ExcalidrawElement,
+ origElement: NonDeletedExcalidrawElement,
) => {
const offsetX = origElement.x - anchorX;
const offsetY = origElement.y - anchorY;
@@ -78,8 +79,8 @@ const resizeElementInGroup = (
anchorY: number,
property: MultiDimensionProps["property"],
scale: number,
- latestElement: ExcalidrawElement,
- origElement: ExcalidrawElement,
+ latestElement: NonDeletedExcalidrawElement,
+ origElement: NonDeletedExcalidrawElement,
originalElementsMap: ElementsMap,
scene: Scene,
) => {
@@ -117,8 +118,8 @@ const resizeGroup = (
aspectRatio: number,
anchor: GlobalPoint,
property: MultiDimensionProps["property"],
- latestElements: ExcalidrawElement[],
- originalElements: ExcalidrawElement[],
+ latestElements: NonDeletedExcalidrawElement[],
+ originalElements: NonDeletedExcalidrawElement[],
originalElementsMap: ElementsMap,
scene: Scene,
) => {
@@ -276,7 +277,7 @@ const handleDimensionChange: DragInputCallbackType<
const changeInWidth = property === "width" ? accumulatedChange : 0;
const changeInHeight = property === "height" ? accumulatedChange : 0;
- const elementsToHighlight: ExcalidrawElement[] = [];
+ const elementsToHighlight: NonDeletedExcalidrawElement[] = [];
for (const atomicUnit of atomicUnits) {
const elementsInUnit = getElementsInAtomicUnit(
@@ -372,11 +373,13 @@ const handleDimensionChange: DragInputCallbackType<
// Handle highlighting frame element candidates
if (isFrameLikeElement(latestElement)) {
- const nextElementsInFrame = getElementsInResizingFrame(
- scene.getElementsIncludingDeleted(),
- latestElement,
- originalAppState,
- scene.getNonDeletedElementsMap(),
+ const nextElementsInFrame = getNonDeletedElements(
+ getElementsInResizingFrame(
+ scene.getElementsIncludingDeleted(),
+ latestElement,
+ originalAppState,
+ scene.getNonDeletedElementsMap(),
+ ),
);
elementsToHighlight.push(...nextElementsInFrame);
diff --git a/packages/excalidraw/components/Stats/MultiPosition.tsx b/packages/excalidraw/components/Stats/MultiPosition.tsx
index 35f6cfb897..030e77694b 100644
--- a/packages/excalidraw/components/Stats/MultiPosition.tsx
+++ b/packages/excalidraw/components/Stats/MultiPosition.tsx
@@ -5,7 +5,11 @@ import { isTextElement } from "@excalidraw/element";
import { getCommonBounds } from "@excalidraw/element";
-import type { ElementsMap, ExcalidrawElement } from "@excalidraw/element/types";
+import type {
+ ElementsMap,
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
import type { Scene } from "@excalidraw/element";
@@ -24,7 +28,7 @@ import type { AppState } from "../../types";
interface MultiPositionProps {
property: "x" | "y";
- elements: readonly ExcalidrawElement[];
+ elements: readonly NonDeletedExcalidrawElement[];
elementsMap: ElementsMap;
atomicUnits: AtomicUnit[];
scene: Scene;
@@ -35,7 +39,7 @@ const moveElements = (
property: MultiPositionProps["property"],
changeInTopX: number,
changeInTopY: number,
- originalElements: readonly ExcalidrawElement[],
+ originalElements: readonly NonDeletedExcalidrawElement[],
originalElementsMap: ElementsMap,
scene: Scene,
appState: AppState,
@@ -74,7 +78,7 @@ const moveElements = (
const moveGroupTo = (
nextX: number,
nextY: number,
- originalElements: ExcalidrawElement[],
+ originalElements: readonly NonDeletedExcalidrawElement[],
originalElementsMap: ElementsMap,
scene: Scene,
appState: AppState,
diff --git a/packages/excalidraw/components/Stats/Position.tsx b/packages/excalidraw/components/Stats/Position.tsx
index 8b57183308..fde51de431 100644
--- a/packages/excalidraw/components/Stats/Position.tsx
+++ b/packages/excalidraw/components/Stats/Position.tsx
@@ -6,7 +6,10 @@ import {
} from "@excalidraw/element";
import { isImageElement } from "@excalidraw/element";
-import type { ElementsMap, ExcalidrawElement } from "@excalidraw/element/types";
+import type {
+ ElementsMap,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
import type { Scene } from "@excalidraw/element";
@@ -18,7 +21,7 @@ import type { AppState } from "../../types";
interface PositionProps {
property: "x" | "y";
- element: ExcalidrawElement;
+ element: NonDeletedExcalidrawElement;
elementsMap: ElementsMap;
scene: Scene;
appState: AppState;
@@ -169,13 +172,7 @@ const handlePositionChange: DragInputCallbackType<"x" | "y"> = ({
);
};
-const Position = ({
- property,
- element,
- elementsMap,
- scene,
- appState,
-}: PositionProps) => {
+const Position = ({ property, element, scene, appState }: PositionProps) => {
const [topLeftX, topLeftY] = pointRotateRads(
pointFrom(element.x, element.y),
pointFrom(element.x + element.width / 2, element.y + element.height / 2),
diff --git a/packages/excalidraw/components/Stats/stats.test.tsx b/packages/excalidraw/components/Stats/stats.test.tsx
index 24d739afa9..a146f9a476 100644
--- a/packages/excalidraw/components/Stats/stats.test.tsx
+++ b/packages/excalidraw/components/Stats/stats.test.tsx
@@ -15,6 +15,7 @@ import type {
ExcalidrawElement,
ExcalidrawLinearElement,
ExcalidrawTextElement,
+ NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import { Excalidraw, getCommonBounds } from "../..";
@@ -364,7 +365,7 @@ describe("stats for a non-generic element", () => {
Keyboard.exitTextEditor(editor);
const text = h.elements[0] as ExcalidrawTextElement;
- API.setSelectedElements([text]);
+ API.setSelectedElements([text] as NonDeletedExcalidrawElement[]);
elementStats = stats?.querySelector("#elementStats");
diff --git a/packages/excalidraw/components/Stats/utils.ts b/packages/excalidraw/components/Stats/utils.ts
index 7628261840..49b8405da4 100644
--- a/packages/excalidraw/components/Stats/utils.ts
+++ b/packages/excalidraw/components/Stats/utils.ts
@@ -2,6 +2,7 @@ import { pointFrom, pointRotateRads } from "@excalidraw/math";
import {
getBoundTextElement,
+ getNonDeletedElements,
isBindingElement,
unbindBindingElement,
} from "@excalidraw/element";
@@ -113,7 +114,7 @@ export const newOrigin = (
export const moveElement = (
newTopLeftX: number,
newTopLeftY: number,
- originalElement: ExcalidrawElement,
+ originalElement: NonDeletedExcalidrawElement,
scene: Scene,
appState: AppState,
originalElementsMap: ElementsMap,
@@ -225,7 +226,7 @@ export const moveElement = (
{ informMutation: shouldInformMutation, isDragging: false },
);
updateBindings(latestChildElement, scene, appState, {
- simultaneouslyUpdated: originalChildren,
+ simultaneouslyUpdated: getNonDeletedElements(originalChildren),
});
});
}
diff --git a/packages/excalidraw/components/UnlockPopup.tsx b/packages/excalidraw/components/UnlockPopup.tsx
index fe1f328fbb..6d9df22890 100644
--- a/packages/excalidraw/components/UnlockPopup.tsx
+++ b/packages/excalidraw/components/UnlockPopup.tsx
@@ -1,12 +1,15 @@
import {
getCommonBounds,
getElementsInGroup,
+ isNonDeletedElement,
selectGroupsFromGivenElements,
} from "@excalidraw/element";
import { sceneCoordsToViewportCoords } from "@excalidraw/common";
import { flushSync } from "react-dom";
+import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
+
import { actionToggleElementLock } from "../actions";
import { t } from "../i18n";
@@ -25,11 +28,24 @@ const UnlockPopup = ({
app: App;
activeLockedId: NonNullable<AppState["activeLockedId"]>;
}) => {
- const element = app.scene.getElement(activeLockedId);
+ const candidateElement = app.scene.getElement(activeLockedId);
+ // SAFETY: This should never happen, but log it just in case
+ if (candidateElement && !isNonDeletedElement(candidateElement)) {
+ console.error(
+ "[NONDELETED][INVARIANT] UnlockPopup: activeLockedId points to a deleted element",
+ );
+ }
+ const element: NonDeletedExcalidrawElement | null =
+ candidateElement && isNonDeletedElement(candidateElement)
+ ? candidateElement
+ : null;
const elements = element
? [element]
- : getElementsInGroup(app.scene.getNonDeletedElementsMap(), activeLockedId);
+ : getElementsInGroup<NonDeletedExcalidrawElement>(
+ app.scene.getNonDeletedElementsMap(),
+ activeLockedId,
+ );
if (elements.length === 0) {
return null;
diff --git a/packages/excalidraw/data/index.ts b/packages/excalidraw/data/index.ts
index d31ab931fd..eef9d286f7 100644
--- a/packages/excalidraw/data/index.ts
+++ b/packages/excalidraw/data/index.ts
@@ -18,6 +18,7 @@ import { getElementsOverlappingFrame } from "@excalidraw/element";
import type {
ExcalidrawElement,
ExcalidrawFrameLikeElement,
+ NonDeleted,
NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
@@ -45,18 +46,18 @@ export type ExportedElements = readonly NonDeletedExcalidrawElement[] & {
};
export const prepareElementsForExport = (
- elements: readonly ExcalidrawElement[],
+ allElements: readonly ExcalidrawElement[],
{ selectedElementIds }: Pick<AppState, "selectedElementIds">,
exportSelectionOnly: boolean,
) => {
- elements = getNonDeletedElements(elements);
+ const elements = getNonDeletedElements(allElements);
const elementsMap = arrayToMap(elements);
const isExportingSelection =
exportSelectionOnly &&
isSomeElementSelected(elements, { selectedElementIds });
- let exportingFrame: ExcalidrawFrameLikeElement | null = null;
+ let exportingFrame: NonDeleted<ExcalidrawFrameLikeElement> | null = null;
let exportedElements = isExportingSelection
? getSelectedElements(
elements,
@@ -68,14 +69,12 @@ export const prepareElementsForExport = (
: elements;
if (isExportingSelection) {
- if (
- exportedElements.length === 1 &&
- isFrameLikeElement(exportedElements[0])
- ) {
- exportingFrame = exportedElements[0];
+ const firstElement = exportedElements[0];
+ if (exportedElements.length === 1 && isFrameLikeElement(firstElement)) {
+ exportingFrame = firstElement;
exportedElements = getElementsOverlappingFrame(
elements,
- exportingFrame,
+ firstElement,
elementsMap,
);
} else if (exportedElements.length > 1) {
@@ -115,7 +114,7 @@ export const exportCanvas = async (
/** filename, if applicable */
name?: string;
fileHandle?: FileSystemFileHandle | null;
- exportingFrame: ExcalidrawFrameLikeElement | null;
+ exportingFrame: NonDeleted<ExcalidrawFrameLikeElement> | null;
},
) => {
if (elements.length === 0) {
diff --git a/packages/excalidraw/data/json.ts b/packages/excalidraw/data/json.ts
index fc34203262..a49d58cd02 100644
--- a/packages/excalidraw/data/json.ts
+++ b/packages/excalidraw/data/json.ts
@@ -5,7 +5,7 @@ import {
VERSIONS,
} from "@excalidraw/common";
-import type { ExcalidrawElement, NonDeleted } from "@excalidraw/element/types";
+import type { ExcalidrawElement } from "@excalidraw/element/types";
import type { MaybePromise } from "@excalidraw/common/utility-types";
@@ -23,7 +23,7 @@ import type {
} from "./types";
export type JSONExportData = {
- elements: readonly NonDeleted<ExcalidrawElement>[];
+ elements: readonly ExcalidrawElement[];
appState: AppState;
files: BinaryFiles;
};
diff --git a/packages/excalidraw/data/restore.ts b/packages/excalidraw/data/restore.ts
index c0b9e0b85f..5ec293d497 100644
--- a/packages/excalidraw/data/restore.ts
+++ b/packages/excalidraw/data/restore.ts
@@ -30,6 +30,7 @@ import {
isPointInElement,
isValidPolygon,
projectFixedPointOntoDiagonal,
+ isNonDeletedElement,
} from "@excalidraw/element";
import { normalizeFixedPoint } from "@excalidraw/element";
import {
@@ -72,6 +73,7 @@ import type {
ExcalidrawTextElement,
FixedPointBinding,
FontFamilyValues,
+ NonDeleted,
NonDeletedSceneElementsMap,
OrderedExcalidrawElement,
StrokeVariability,
@@ -344,6 +346,11 @@ const repairBinding = <T extends ExcalidrawArrowElement>(
const mode = isPointInElement(p, boundElement, elementsMap)
? "inside"
: "orbit";
+
+ if (!isNonDeletedElement(element)) {
+ console.error("[NONDELETED][INVARIANT] Restoring a deleted element");
+ }
+
const safeElement = {
...element,
startBinding: element.startBinding?.elementId
@@ -373,8 +380,8 @@ const repairBinding = <T extends ExcalidrawArrowElement>(
{ value: 1 as NormalizedZoomValue },
) || p;
const { fixedPoint } = calculateFixedPointForNonElbowArrowBinding(
- safeElement,
- boundElement,
+ safeElement as NonDeleted<ExcalidrawArrowElement>,
+ boundElement as NonDeleted<ExcalidrawBindableElement>,
startOrEnd,
elementsMap,
focusPoint,
@@ -1150,10 +1157,9 @@ export const restoreAppState = (
};
};
-const restoreLibraryItem = (libraryItem: LibraryItem) => {
- const elements = restoreElements(
- getNonDeletedElements(libraryItem.elements),
- null,
+const restoreLibraryItem = (libraryItem: LibraryItem): LibraryItem | null => {
+ const elements = getNonDeletedElements(
+ restoreElements(libraryItem.elements, null),
);
return elements.length ? { ...libraryItem, elements } : null;
};
diff --git a/packages/excalidraw/renderer/interactiveScene.ts b/packages/excalidraw/renderer/interactiveScene.ts
index e19df683db..bd0dc8d8ca 100644
--- a/packages/excalidraw/renderer/interactiveScene.ts
+++ b/packages/excalidraw/renderer/interactiveScene.ts
@@ -42,17 +42,14 @@ import {
isTextElement,
LinearElementEditor,
getActiveTextElement,
-} from "@excalidraw/element";
-
-import { renderSelectionElement } from "@excalidraw/element";
-
-import {
getElementsInGroup,
getSelectedGroupIds,
isSelectedViaGroup,
selectGroupsFromGivenElements,
} from "@excalidraw/element";
+import { renderSelectionElement } from "@excalidraw/element";
+
import { getCommonBounds, getElementAbsoluteCoords } from "@excalidraw/element";
import {
getGlobalFixedPointForBindableElement,
@@ -77,6 +74,7 @@ import type {
ExcalidrawTextElement,
GroupId,
NonDeleted,
+ NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
} from "@excalidraw/element/types";
@@ -1032,7 +1030,7 @@ const renderFrameHighlight = (
const renderElementsBoxHighlight = (
context: CanvasRenderingContext2D,
appState: InteractiveCanvasAppState,
- elements: NonDeleted<ExcalidrawElement>[],
+ elements: readonly NonDeletedExcalidrawElement[],
config?: { colors?: string[]; dashed?: boolean },
) => {
const { colors = ["rgb(0,118,255)"], dashed = false } = config || {};
@@ -1491,7 +1489,7 @@ const renderCropHandles = (
};
const renderTextBox = (
- text: NonDeleted<ExcalidrawTextElement>,
+ text: ExcalidrawTextElement,
context: CanvasRenderingContext2D,
appState: InteractiveCanvasAppState,
selectionColor: InteractiveCanvasRenderConfig["selectionColor"],
@@ -1515,7 +1513,7 @@ const renderTextBox = (
};
const renderResetAutoResizeHandle = (
- text: NonDeleted<ExcalidrawTextElement>,
+ text: ExcalidrawTextElement,
context: CanvasRenderingContext2D,
appState: InteractiveCanvasAppState,
selectionColor: InteractiveCanvasRenderConfig["selectionColor"],
@@ -1691,10 +1689,15 @@ const _renderInteractiveScene = ({
const elements = element
? [element]
: getElementsInGroup(allElementsMap, appState.activeLockedId);
- renderElementsBoxHighlight(context, appState, elements, {
- colors: ["#ced4da"],
- dashed: true,
- });
+ renderElementsBoxHighlight(
+ context,
+ appState,
+ elements as NonDeletedExcalidrawElement[], // We don't typecheck runtime because of performance
+ {
+ colors: ["#ced4da"],
+ dashed: true,
+ },
+ );
}
const isFrameSelected = selectedElements.some((element) =>
@@ -1780,7 +1783,7 @@ const _renderInteractiveScene = ({
renderLinearPointHandles(
context,
appState,
- selectedElements[0] as ExcalidrawLinearElement,
+ selectedElements[0] as NonDeleted<ExcalidrawLinearElement>,
elementsMap,
);
}
diff --git a/packages/excalidraw/renderer/staticSvgScene.ts b/packages/excalidraw/renderer/staticSvgScene.ts
index 94410e0e71..5f6d36daad 100644
--- a/packages/excalidraw/renderer/staticSvgScene.ts
+++ b/packages/excalidraw/renderer/staticSvgScene.ts
@@ -64,7 +64,7 @@ const roughSVGDrawWithPrecision = (
};
const maybeWrapNodesInFrameClipPath = (
- element: NonDeletedExcalidrawElement,
+ element: Readonly<NonDeletedExcalidrawElement>,
root: SVGElement,
nodes: SVGElement[],
frameRendering: AppState["frameRendering"],
@@ -85,7 +85,7 @@ const maybeWrapNodesInFrameClipPath = (
};
const renderElementToSvg = (
- element: NonDeletedExcalidrawElement,
+ element: Readonly<NonDeletedExcalidrawElement>,
elementsMap: RenderableElementsMap,
rsvg: RoughSVG,
svgRoot: SVGElement,
@@ -200,8 +200,7 @@ const renderElementToSvg = (
);
addToRoot(node, element);
- const label: ExcalidrawElement =
- createPlaceholderEmbeddableLabel(element);
+ const label = createPlaceholderEmbeddableLabel(element);
renderElementToSvg(
label,
elementsMap,
@@ -755,9 +754,9 @@ export const renderSceneToSvg = (
);
const boundTextElement = getBoundTextElement(element, elementsMap);
- if (boundTextElement) {
+ if (boundTextElement?.isDeleted === false) {
renderElementToSvg(
- boundTextElement,
+ boundTextElement as Readonly<NonDeletedExcalidrawElement>,
elementsMap,
rsvg,
svgRoot,
@@ -766,6 +765,11 @@ export const renderSceneToSvg = (
boundTextElement.y + renderConfig.offsetY,
renderConfig,
);
+ } else if (boundTextElement) {
+ // SAFETY: This should never happen, but log it just in case
+ console.error(
+ "[NONDELETED][INVARIANT] Skipped rendering deleted bound text element",
+ );
}
} catch (error: any) {
console.error(error);
diff --git a/packages/excalidraw/scene/export.ts b/packages/excalidraw/scene/export.ts
index eef553d4c7..9216e42722 100644
--- a/packages/excalidraw/scene/export.ts
+++ b/packages/excalidraw/scene/export.ts
@@ -42,9 +42,9 @@ import { newTextElement } from "@excalidraw/element";
import type { Bounds } from "@excalidraw/common";
import type {
- ExcalidrawElement,
ExcalidrawFrameLikeElement,
ExcalidrawTextElement,
+ NonDeleted,
NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
} from "@excalidraw/element/types";
@@ -62,7 +62,10 @@ import type { RenderableElementsMap } from "./types";
import type { AppState, BinaryFiles } from "../types";
-const truncateText = (element: ExcalidrawTextElement, maxWidth: number) => {
+const truncateText = (
+ element: NonDeleted<ExcalidrawTextElement>,
+ maxWidth: number,
+) => {
if (element.width <= maxWidth) {
return element;
}
@@ -106,18 +109,19 @@ const addFrameLabelsAsTextElements = (
const nextElements: NonDeletedExcalidrawElement[] = [];
for (const element of elements) {
if (isFrameLikeElement(element)) {
- let textElement: Mutable<ExcalidrawTextElement> = newTextElement({
- x: element.x,
- y: element.y - FRAME_STYLE.nameOffsetY,
- fontFamily: FONT_FAMILY.Helvetica,
- fontSize: FRAME_STYLE.nameFontSize,
- lineHeight:
- FRAME_STYLE.nameLineHeight as ExcalidrawTextElement["lineHeight"],
- strokeColor: opts.exportWithDarkMode
- ? FRAME_STYLE.nameColorDarkTheme
- : FRAME_STYLE.nameColorLightTheme,
- text: getFrameLikeTitle(element),
- });
+ let textElement: Mutable<NonDeleted<ExcalidrawTextElement>> =
+ newTextElement({
+ x: element.x,
+ y: element.y - FRAME_STYLE.nameOffsetY,
+ fontFamily: FONT_FAMILY.Helvetica,
+ fontSize: FRAME_STYLE.nameFontSize,
+ lineHeight:
+ FRAME_STYLE.nameLineHeight as ExcalidrawTextElement["lineHeight"],
+ strokeColor: opts.exportWithDarkMode
+ ? FRAME_STYLE.nameColorDarkTheme
+ : FRAME_STYLE.nameColorLightTheme,
+ text: getFrameLikeTitle(element),
+ });
textElement.y -= textElement.height;
textElement = truncateText(textElement, element.width);
@@ -149,12 +153,12 @@ const prepareElementsForRender = ({
frameRendering,
exportWithDarkMode,
}: {
- elements: readonly ExcalidrawElement[];
+ elements: readonly NonDeletedExcalidrawElement[];
exportingFrame: ExcalidrawFrameLikeElement | null | undefined;
frameRendering: AppState["frameRendering"];
exportWithDarkMode: AppState["exportWithDarkMode"];
}) => {
- let nextElements: readonly ExcalidrawElement[];
+ let nextElements: readonly NonDeletedExcalidrawElement[];
if (exportingFrame) {
nextElements = getElementsOverlappingFrame(
@@ -186,7 +190,7 @@ export const exportToCanvas = async (
exportBackground: boolean;
exportPadding?: number;
viewBackgroundColor: string;
- exportingFrame?: ExcalidrawFrameLikeElement | null;
+ exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;
},
createCanvas: (
width: number,
@@ -303,7 +307,7 @@ export const exportToSvg = async (
* if true, all embeddables passed in will be rendered when possible.
*/
renderEmbeddables?: boolean;
- exportingFrame?: ExcalidrawFrameLikeElement | null;
+ exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;
skipInliningFonts?: true;
reuseImages?: boolean;
},
diff --git a/packages/excalidraw/scene/types.ts b/packages/excalidraw/scene/types.ts
index db168ab225..d77fede4c9 100644
--- a/packages/excalidraw/scene/types.ts
+++ b/packages/excalidraw/scene/types.ts
@@ -111,7 +111,7 @@ export type InteractiveSceneRenderConfig = {
export type NewElementSceneRenderConfig = {
canvas: HTMLCanvasElement | null;
rc: RoughCanvas;
- newElement: ExcalidrawElement | null;
+ newElement: NonDeletedExcalidrawElement | null;
elementsMap: RenderableElementsMap;
allElementsMap: NonDeletedSceneElementsMap;
scale: number;
diff --git a/packages/excalidraw/snapping.ts b/packages/excalidraw/snapping.ts
index 6ea47e5bef..c0e22a99cb 100644
--- a/packages/excalidraw/snapping.ts
+++ b/packages/excalidraw/snapping.ts
@@ -166,7 +166,7 @@ export const isSnappingEnabled = ({
}: {
app: AppClassProperties;
event: KeyboardModifiersObject;
- selectedElements: NonDeletedExcalidrawElement[];
+ selectedElements: readonly NonDeletedExcalidrawElement[];
}) => {
if (event) {
// Allow snapping for lasso tool when dragging selected elements
@@ -196,7 +196,7 @@ export const areRoughlyEqual = (a: number, b: number, precision = 0.01) => {
};
export const getElementsCorners = (
- elements: ExcalidrawElement[],
+ elements: readonly NonDeletedExcalidrawElement[],
elementsMap: ElementsMap,
{
omitCenter,
@@ -314,7 +314,7 @@ export const getElementsCorners = (
const getReferenceElements = (
elements: readonly NonDeletedExcalidrawElement[],
- selectedElements: NonDeletedExcalidrawElement[],
+ selectedElements: readonly ExcalidrawElement[],
appState: AppState,
elementsMap: ElementsMap,
) =>
@@ -327,7 +327,7 @@ const getReferenceElements = (
export const getVisibleGaps = (
elements: readonly NonDeletedExcalidrawElement[],
- selectedElements: ExcalidrawElement[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
elementsMap: ElementsMap,
) => {
@@ -444,7 +444,7 @@ export const getVisibleGaps = (
};
const getGapSnaps = (
- selectedElements: ExcalidrawElement[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
dragOffset: Vector2D,
app: AppClassProperties,
event: KeyboardModifiersObject,
@@ -615,7 +615,7 @@ const getGapSnaps = (
export const getReferenceSnapPoints = (
elements: readonly NonDeletedExcalidrawElement[],
- selectedElements: ExcalidrawElement[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
elementsMap: ElementsMap,
) => {
@@ -634,7 +634,7 @@ export const getReferenceSnapPoints = (
};
const getPointSnaps = (
- selectedElements: ExcalidrawElement[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
selectionSnapPoints: GlobalPoint[],
app: AppClassProperties,
event: KeyboardModifiersObject,
@@ -913,7 +913,7 @@ const dedupeGapSnapLines = (gapSnapLines: GapSnapLine[]) => {
};
const createGapSnapLines = (
- selectedElements: ExcalidrawElement[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
dragOffset: Vector2D,
gapSnaps: GapSnap[],
): GapSnapLine[] => {
@@ -1107,9 +1107,9 @@ const createGapSnapLines = (
export const snapResizingElements = (
// use the latest elements to create snap lines
- selectedElements: ExcalidrawElement[],
+ selectedElements: readonly NonDeletedExcalidrawElement[],
// while using the original elements to appy dragOffset to calculate snaps
- selectedOriginalElements: ExcalidrawElement[],
+ selectedOriginalElements: readonly NonDeletedExcalidrawElement[],
app: AppClassProperties,
event: KeyboardModifiersObject,
dragOffset: Vector2D,
@@ -1244,7 +1244,7 @@ export const snapResizingElements = (
};
export const snapNewElement = (
- newElement: ExcalidrawElement,
+ newElement: NonDeletedExcalidrawElement,
app: AppClassProperties,
event: KeyboardModifiersObject,
origin: Vector2D,
@@ -1316,7 +1316,7 @@ export const snapNewElement = (
};
export const getSnapLinesAtPointer = (
- elements: readonly ExcalidrawElement[],
+ elements: readonly NonDeletedExcalidrawElement[],
app: AppClassProperties,
pointer: Vector2D,
event: KeyboardModifiersObject,
diff --git a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
index fc3fa4b8ba..9d99089d84 100644
--- a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
+++ b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
@@ -12768,8 +12768,8 @@ exports[`history > singleplayer undo/redo > should create entry when selecting f
"updated": 1,
"version": 4,
"width": 50,
- "x": 130,
- "y": -30,
+ "x": 40,
+ "y": -20,
}
`;
@@ -12910,8 +12910,8 @@ exports[`history > singleplayer undo/redo > should create entry when selecting f
"type": "freedraw",
"version": 4,
"width": 50,
- "x": 130,
- "y": -30,
+ "x": 40,
+ "y": -20,
},
"inserted": {
"isDeleted": true,
diff --git a/packages/excalidraw/tests/actionStyles.test.tsx b/packages/excalidraw/tests/actionStyles.test.tsx
index ce4ff46ec6..fc40cf4d6c 100644
--- a/packages/excalidraw/tests/actionStyles.test.tsx
+++ b/packages/excalidraw/tests/actionStyles.test.tsx
@@ -2,6 +2,8 @@ import React from "react";
import { CODES, STROKE_WIDTH } from "@excalidraw/common";
+import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
+
import { copiedStyles } from "../actions/actionStyles";
import { Excalidraw } from "../index";
import { API } from "../tests/helpers/api";
@@ -58,7 +60,7 @@ describe("actionStyles", () => {
mouse.reset();
- API.setSelectedElements([h.elements[1]]);
+ API.setSelectedElements([h.elements[1]] as NonDeletedExcalidrawElement[]);
Keyboard.withModifierKeys({ ctrl: true, alt: true }, () => {
Keyboard.codeDown(CODES.C);
@@ -68,7 +70,7 @@ describe("actionStyles", () => {
mouse.reset();
// Paste styles to first rectangle
- API.setSelectedElements([h.elements[0]]);
+ API.setSelectedElements([h.elements[0]] as NonDeletedExcalidrawElement[]);
Keyboard.withModifierKeys({ ctrl: true, alt: true }, () => {
Keyboard.codeDown(CODES.V);
});
diff --git a/packages/excalidraw/tests/data/restore.test.ts b/packages/excalidraw/tests/data/restore.test.ts
index b33f756511..310b001a73 100644
--- a/packages/excalidraw/tests/data/restore.test.ts
+++ b/packages/excalidraw/tests/data/restore.test.ts
@@ -673,7 +673,9 @@ describe("restoreElements", () => {
it("bump versions of local duplicate elements when supplied", () => {
const rectangle = API.createElement({ type: "rectangle" }); // version=1
const ellipse = API.createElement({ type: "ellipse" });
- const rectangle_modified = newElementWith(rectangle, { isDeleted: true }); // version=2
+ const rectangle_modified = newElementWith(rectangle as ExcalidrawElement, {
+ isDeleted: true,
+ }); // version=2
const restoredElements = restore.bumpElementVersions(
restore.restoreElements([rectangle, ellipse], null),
diff --git a/packages/excalidraw/tests/fixtures/diagramFixture.ts b/packages/excalidraw/tests/fixtures/diagramFixture.ts
index 8512fed36a..6c2c993cc5 100644
--- a/packages/excalidraw/tests/fixtures/diagramFixture.ts
+++ b/packages/excalidraw/tests/fixtures/diagramFixture.ts
@@ -1,5 +1,10 @@
import { VERSIONS } from "@excalidraw/common";
+import type {
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
+
import {
diamondFixture,
ellipseFixture,
@@ -20,13 +25,25 @@ export const diagramFixture = {
export const diagramFactory = ({
overrides = {},
- elementOverrides = {},
+ elementOverrides = {} as Partial<ExcalidrawElement>,
} = {}) => ({
...diagramFixture,
elements: [
- { ...diamondFixture, ...elementOverrides },
- { ...ellipseFixture, ...elementOverrides },
- { ...rectangleFixture, ...elementOverrides },
+ {
+ ...diamondFixture,
+ ...elementOverrides,
+ isDeleted: elementOverrides.isDeleted ?? false,
+ } as NonDeletedExcalidrawElement,
+ {
+ ...ellipseFixture,
+ ...elementOverrides,
+ isDeleted: elementOverrides.isDeleted ?? false,
+ } as NonDeletedExcalidrawElement,
+ {
+ ...rectangleFixture,
+ ...elementOverrides,
+ isDeleted: elementOverrides.isDeleted ?? false,
+ } as NonDeletedExcalidrawElement,
],
...overrides,
});
diff --git a/packages/excalidraw/tests/freedrawMode.test.tsx b/packages/excalidraw/tests/freedrawMode.test.tsx
index 150219b54e..36b50e6cc9 100644
--- a/packages/excalidraw/tests/freedrawMode.test.tsx
+++ b/packages/excalidraw/tests/freedrawMode.test.tsx
@@ -1,4 +1,7 @@
-import type { ExcalidrawFreeDrawElement } from "@excalidraw/element/types";
+import type {
+ ExcalidrawFreeDrawElement,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
import { Excalidraw } from "../index";
@@ -34,7 +37,7 @@ describe("freedraw mode action", () => {
it("toggling the radio updates both the selected element and the default", () => {
const element = UI.createElement("freedraw", { x: 0, y: 0 });
- API.setSelectedElements([element.get()]);
+ API.setSelectedElements([element.get()] as NonDeletedExcalidrawElement[]);
fireEvent.click(screen.getByTitle("Variable"));
expect(
diff --git a/packages/excalidraw/tests/helpers/api.ts b/packages/excalidraw/tests/helpers/api.ts
index 4faafcf82c..b3a857a4c3 100644
--- a/packages/excalidraw/tests/helpers/api.ts
+++ b/packages/excalidraw/tests/helpers/api.ts
@@ -43,6 +43,8 @@ import type {
ExcalidrawElbowArrowElement,
ExcalidrawArrowElement,
FixedSegment,
+ NonDeleted,
+ NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import type { Mutable } from "@excalidraw/common/utility-types";
@@ -84,7 +86,7 @@ export class API {
});
};
- static setSelectedElements = (elements: ExcalidrawElement[], editingGroupId?: string | null) => {
+ static setSelectedElements = (elements: NonDeletedExcalidrawElement[], editingGroupId?: string | null) => {
act(() => {
h.setState({
...selectGroupsForSelectedElements(
@@ -226,19 +228,21 @@ export class API {
: never;
elbowed?: boolean;
fixedSegments?: FixedSegment[] | null;
- }): T extends "arrow" | "line"
- ? ExcalidrawLinearElement
- : T extends "freedraw"
- ? ExcalidrawFreeDrawElement
- : T extends "text"
- ? ExcalidrawTextElement
- : T extends "image"
- ? ExcalidrawImageElement
- : T extends "frame"
- ? ExcalidrawFrameElement
- : T extends "magicframe"
- ? ExcalidrawMagicFrameElement
- : ExcalidrawGenericElement => {
+ }): NonDeleted<
+ T extends "arrow" | "line"
+ ? ExcalidrawLinearElement
+ : T extends "freedraw"
+ ? ExcalidrawFreeDrawElement
+ : T extends "text"
+ ? ExcalidrawTextElement
+ : T extends "image"
+ ? ExcalidrawImageElement
+ : T extends "frame"
+ ? ExcalidrawFrameElement
+ : T extends "magicframe"
+ ? ExcalidrawMagicFrameElement
+ : ExcalidrawGenericElement
+ > => {
let element: Mutable<ExcalidrawElement> = null!;
const appState = h?.state || getDefaultAppState();
diff --git a/packages/excalidraw/tests/history.test.tsx b/packages/excalidraw/tests/history.test.tsx
index 78b431b773..0c7514c972 100644
--- a/packages/excalidraw/tests/history.test.tsx
+++ b/packages/excalidraw/tests/history.test.tsx
@@ -1283,6 +1283,7 @@ describe("history", () => {
togglePopover("Stroke");
UI.clickOnTestId("color-red");
+ mouse.reset();
mouse.down(40, -20);
mouse.up(50, 10);
diff --git a/packages/excalidraw/tests/library.test.tsx b/packages/excalidraw/tests/library.test.tsx
index 7a8dab860f..067a4f23ce 100644
--- a/packages/excalidraw/tests/library.test.tsx
+++ b/packages/excalidraw/tests/library.test.tsx
@@ -6,7 +6,10 @@ import { MIME_TYPES, ORIG_ID } from "@excalidraw/common";
import { getCommonBoundingBox } from "@excalidraw/element";
-import type { ExcalidrawGenericElement } from "@excalidraw/element/types";
+import type {
+ ExcalidrawGenericElement,
+ NonDeleted,
+} from "@excalidraw/element/types";
import { parseLibraryJSON } from "../data/blob";
import { serializeLibraryAsJSON } from "../data/json";
@@ -274,7 +277,7 @@ describe("library menu", () => {
describe("distributeLibraryItemsOnSquareGrid()", () => {
it("should distribute items on a grid", async () => {
const createLibraryItem = (
- elements: ExcalidrawGenericElement[],
+ elements: NonDeleted<ExcalidrawGenericElement>[],
): LibraryItem => {
return {
id: `id-${Date.now()}`,
diff --git a/packages/excalidraw/tests/move.test.tsx b/packages/excalidraw/tests/move.test.tsx
index f03e7744f1..ae1db40fda 100644
--- a/packages/excalidraw/tests/move.test.tsx
+++ b/packages/excalidraw/tests/move.test.tsx
@@ -6,6 +6,7 @@ import "@excalidraw/utils/test-utils";
import type {
ExcalidrawArrowElement,
+ ExcalidrawBindableElement,
NonDeleted,
} from "@excalidraw/element/types";
@@ -84,14 +85,14 @@ describe("move element", () => {
// bind line to two rectangles
bindBindingElement(
arrow.get() as NonDeleted<ExcalidrawArrowElement>,
- rectA.get(),
+ rectA.get() as NonDeleted<ExcalidrawBindableElement>,
"orbit",
"start",
h.app.scene,
);
bindBindingElement(
arrow.get() as NonDeleted<ExcalidrawArrowElement>,
- rectB.get(),
+ rectB.get() as NonDeleted<ExcalidrawBindableElement>,
"orbit",
"end",
h.app.scene,
diff --git a/packages/excalidraw/tests/scene/export.test.ts b/packages/excalidraw/tests/scene/export.test.ts
index 2a00e7245a..3771d52229 100644
--- a/packages/excalidraw/tests/scene/export.test.ts
+++ b/packages/excalidraw/tests/scene/export.test.ts
@@ -11,6 +11,7 @@ import { pointFrom } from "@excalidraw/math";
import type {
ExcalidrawTextElement,
FractionalIndex,
+ NonDeleted,
NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
@@ -85,7 +86,7 @@ describe("exportToSvg", () => {
originalText:
"中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",
index: "a4" as FractionalIndex,
- } as ExcalidrawTextElement,
+ } as NonDeleted<ExcalidrawTextElement>,
],
DEFAULT_OPTIONS,
null,
@@ -190,7 +191,7 @@ describe("exportToSvg", () => {
it("with elements that have a link", async () => {
const svgElement = await exportUtils.exportToSvg(
- [rectangleWithLinkFixture],
+ [rectangleWithLinkFixture] as NonDeletedExcalidrawElement[],
DEFAULT_OPTIONS,
null,
);
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index 3e3bf45225..75624d2c74 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -370,7 +370,7 @@ export interface AppState {
clip: boolean;
};
editingFrame: string | null;
- elementsToHighlight: NonDeleted<ExcalidrawElement>[] | null;
+ elementsToHighlight: readonly NonDeletedExcalidrawElement[] | null;
/**
* set when a new text is created or when an existing text is being edited
*/
@@ -1128,7 +1128,7 @@ export type EmbedsValidationStatus = Map<
export type ElementsPendingErasure = Set<ExcalidrawElement["id"]>;
-export type PendingExcalidrawElements = ExcalidrawElement[];
+export type PendingExcalidrawElements = NonDeletedExcalidrawElement[];
/** Runtime gridSize value. Null indicates disabled grid. */
export type NullableGridSize =
@@ -1136,8 +1136,8 @@ export type NullableGridSize =
| null;
export type GenerateDiagramToCode = (props: {
- frame: ExcalidrawMagicFrameElement;
- children: readonly ExcalidrawElement[];
+ frame: NonDeleted<ExcalidrawMagicFrameElement>;
+ children: readonly NonDeletedExcalidrawElement[];
}) => MaybePromise<{ html: string }>;
export type Offsets = Partial<{
diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx
index f044553fd5..f8647419f3 100644
--- a/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx
+++ b/packages/excalidraw/wysiwyg/textWysiwyg.test.tsx
@@ -20,6 +20,7 @@ import {
import type {
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
+ NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import { Excalidraw } from "../index";
@@ -1011,7 +1012,7 @@ describe("textWysiwyg", () => {
width: 100,
height: 50,
});
- API.setSelectedElements([element]);
+ API.setSelectedElements([element] as NonDeletedExcalidrawElement[]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(1);
});
@@ -1052,7 +1053,10 @@ describe("textWysiwyg", () => {
expect(h.elements.length).toBe(2);
expect(h.elements[1].type).toBe("text");
- API.setSelectedElements([h.elements[0], h.elements[1]]);
+ API.setSelectedElements([
+ h.elements[0],
+ h.elements[1],
+ ] as NonDeletedExcalidrawElement[]);
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 20,
@@ -1710,7 +1714,7 @@ describe("textWysiwyg", () => {
"Excalidraw is an opensource virtual collaborative whiteboard",
);
- API.setSelectedElements([textElement]);
+ API.setSelectedElements([textElement] as NonDeletedExcalidrawElement[]);
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.tsx
index eeee206fa7..74bf7aebbb 100644
--- a/packages/excalidraw/wysiwyg/textWysiwyg.tsx
+++ b/packages/excalidraw/wysiwyg/textWysiwyg.tsx
@@ -47,10 +47,11 @@ import {
} from "@excalidraw/element";
import type {
- ExcalidrawElement,
ExcalidrawLinearElement,
ExcalidrawTextElementWithContainer,
ExcalidrawTextElement,
+ NonDeleted,
+ ExcalidrawTextContainer,
} from "@excalidraw/element/types";
import { actionSaveToActiveFile } from "../actions";
@@ -196,7 +197,6 @@ const getLineCaretOffsetFromNativeLayout = ({
type SubmitHandler = () => void;
export const textWysiwyg = ({
- id,
onChange,
onSubmit,
getViewportCoords,
@@ -207,7 +207,6 @@ export const textWysiwyg = ({
autoSelect = true,
initialCaretSceneCoords = null,
}: {
- id: ExcalidrawElement["id"];
/**
* textWysiwyg only deals with `originalText`
*
@@ -261,7 +260,9 @@ export const textWysiwyg = ({
LAST_THEME = app.state.theme;
const appState = app.state;
- const updatedTextElement = app.scene.getElement<ExcalidrawTextElement>(id);
+ const updatedTextElement = app.scene.getElement<
+ NonDeleted<ExcalidrawTextElement>
+ >(element.id);
if (!updatedTextElement) {
return;
@@ -271,10 +272,10 @@ export const textWysiwyg = ({
if (updatedTextElement && isTextElement(updatedTextElement)) {
let coordX = updatedTextElement.x;
let coordY = updatedTextElement.y;
- const container = getContainerElement(
- updatedTextElement,
- app.scene.getNonDeletedElementsMap(),
- );
+ const container = getContainerElement<
+ NonDeleted<ExcalidrawTextElement>,
+ NonDeleted<ExcalidrawTextContainer>
+ >(updatedTextElement, app.scene.getNonDeletedElementsMap());
let width = updatedTextElement.width;
diff --git a/packages/utils/src/export.ts b/packages/utils/src/export.ts
index e29e396300..6f7c8ad19c 100644
--- a/packages/utils/src/export.ts
+++ b/packages/utils/src/export.ts
@@ -6,6 +6,7 @@ import {
copyToClipboard,
} from "@excalidraw/excalidraw/clipboard";
import { encodePngMetadata } from "@excalidraw/excalidraw/data/image";
+import { getNonDeletedElements } from "@excalidraw/element";
import { serializeAsJSON } from "@excalidraw/excalidraw/data/json";
import {
restoreAppState,
@@ -17,20 +18,20 @@ import {
} from "@excalidraw/excalidraw/scene/export";
import type {
- ExcalidrawElement,
ExcalidrawFrameLikeElement,
NonDeleted,
+ NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import type { AppState, BinaryFiles } from "@excalidraw/excalidraw/types";
export { MIME_TYPES };
type ExportOpts = {
- elements: readonly NonDeleted<ExcalidrawElement>[];
+ elements: readonly NonDeletedExcalidrawElement[];
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
files: BinaryFiles | null;
maxWidthOrHeight?: number;
- exportingFrame?: ExcalidrawFrameLikeElement | null;
+ exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;
getDimensions?: (
width: number,
height: number,
@@ -48,9 +49,11 @@ export const exportToCanvas = ({
}: ExportOpts & {
exportPadding?: number;
}) => {
- const restoredElements = restoreElements(elements, null, {
- deleteInvisibleElements: true,
- });
+ const restoredElements = getNonDeletedElements(
+ restoreElements(elements, null, {
+ deleteInvisibleElements: true,
+ }),
+ );
const restoredAppState = restoreAppState(appState, null);
const { exportBackground, viewBackgroundColor } = restoredAppState;
@@ -178,9 +181,11 @@ export const exportToSvg = async ({
skipInliningFonts?: true;
reuseImages?: boolean;
}): Promise<SVGSVGElement> => {
- const restoredElements = restoreElements(elements, null, {
- deleteInvisibleElements: true,
- });
+ const restoredElements = getNonDeletedElements(
+ restoreElements(elements, null, {
+ deleteInvisibleElements: true,
+ }),
+ );
const restoredAppState = restoreAppState(appState, null);
const exportAppState = {
diff --git a/packages/utils/tests/export.test.ts b/packages/utils/tests/export.test.ts
index 47b9398ab7..a50b1bbeeb 100644
--- a/packages/utils/tests/export.test.ts
+++ b/packages/utils/tests/export.test.ts
@@ -91,10 +91,10 @@ describe("exportToSvg", () => {
expect(passedOptionsWhenDefault).toMatchSnapshot();
});
- // FIXME the utils.exportToSvg no longer filters out deleted elements.
- // It's already supposed to be passed non-deleted elements by we're not
- // type-checking for it correctly.
- it.skip("with deleted elements", async () => {
+ // Regression test: when all elements are deleted, exportToSvg should pass
+ // zero elements to the lower-level export (line 184-188 of export.ts calls
+ // getNonDeletedElements which filters them out).
+ it("with deleted elements", async () => {
await utils.exportToSvg({
...diagramFactory({
overrides: { appState: void 0 },
@@ -107,7 +107,9 @@ describe("exportToSvg", () => {
it("with exportPadding", async () => {
await utils.exportToSvg({
- ...diagramFactory({ overrides: { appState: { name: "diagram name" } } }),
+ ...diagramFactory({
+ overrides: { appState: { name: "diagram name" } },
+ }),
exportPadding: 0,
});