excalidraw/src/element/mutateElement.ts

53 lines
1.5 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";
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 ExcalidrawElement>(
element: TElement,
updates: ElementUpdate<TElement>,
) {
const mutableElement = element as any;
for (const key in updates) {
const value = (updates as any)[key];
if (typeof value !== "undefined") {
mutableElement[key] = value;
}
2020-03-14 20:46:57 -07:00
}
if (
typeof updates.height !== "undefined" ||
typeof updates.width !== "undefined" ||
typeof updates.points !== "undefined"
) {
invalidateShapeForElement(element);
}
mutableElement.version++;
mutableElement.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,
...updates,
version: element.version + 1,
versionNonce: randomSeed(),
};
}