excalidraw/src/element/mutateElement.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

import { ExcalidrawElement } from "./types";
2020-03-14 20:46:57 -07:00
import { randomSeed } from "roughjs/bin/math";
import { invalidateShapeForElement } from "../renderer/renderElement";
2020-03-15 10:06:41 -07:00
import { globalSceneState } from "../scene";
2020-03-17 11:01:11 -07:00
import { getSizeFromPoints } from "../points";
type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
Partial<TElement>,
"id" | "seed"
>;
2020-03-09 23:37:42 -07:00
// This function tracks updates of text elements for the purposes for collaboration.
// The version is used to compare updates when more than one user is working in
2020-03-16 19:07:47 -07:00
// the same drawing. Note: this will trigger the component to update. Make sure you
// are calling it either from a React event handler or within unstable_batchedUpdates().
export function mutateElement<TElement extends Mutable<ExcalidrawElement>>(
element: TElement,
updates: ElementUpdate<TElement>,
) {
// casting to any because can't use `in` operator
// (see https://github.com/microsoft/TypeScript/issues/21732)
const { points } = updates as any;
if (typeof points !== "undefined") {
updates = { ...getSizeFromPoints(points), ...updates };
2020-03-17 11:01:11 -07:00
}
for (const key in updates) {
const value = (updates as any)[key];
if (typeof value !== "undefined") {
// @ts-ignore
element[key] = value;
}
2020-03-14 20:46:57 -07:00
}
if (
typeof updates.height !== "undefined" ||
typeof updates.width !== "undefined" ||
typeof points !== "undefined"
) {
invalidateShapeForElement(element);
}
element.version++;
element.versionNonce = randomSeed();
2020-03-15 10:06:41 -07:00
globalSceneState.informMutation();
}
export function newElementWith<TElement extends ExcalidrawElement>(
element: TElement,
updates: ElementUpdate<TElement>,
): TElement {
2020-03-14 20:46:57 -07:00
return {
...element,
version: element.version + 1,
versionNonce: randomSeed(),
...updates,
2020-03-14 20:46:57 -07:00
};
}