Abstract away or eliminate most of the mutation of the Elements array (#955)

This commit is contained in:
Pete Hunt 2020-03-14 21:48:51 -07:00 committed by GitHub
parent 05af9f04ed
commit e1e2249f57
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 293 additions and 272 deletions

View file

@ -1,5 +1,6 @@
import { ExcalidrawElement, ExcalidrawTextElement } from "./types";
import { ExcalidrawElement } from "./types";
import { randomSeed } from "roughjs/bin/math";
import { invalidateShapeForElement } from "../renderer/renderElement";
type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
Partial<TElement>,
@ -9,45 +10,35 @@ type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
// 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
// the same drawing.
export function mutateElement(
element: ExcalidrawElement,
updates?: ElementUpdate<ExcalidrawElement>,
export function mutateElement<TElement extends ExcalidrawElement>(
element: TElement,
updates: ElementUpdate<TElement>,
) {
if (updates) {
Object.assign(element, updates);
const mutableElement = element as any;
for (const key in updates) {
const value = (updates as any)[key];
if (typeof value !== "undefined") {
mutableElement[key] = value;
}
}
(element as any).version++;
(element as any).versionNonce = randomSeed();
if (
typeof updates.height !== "undefined" ||
typeof updates.width !== "undefined" ||
typeof updates.points !== "undefined"
) {
invalidateShapeForElement(element);
}
mutableElement.version++;
mutableElement.versionNonce = randomSeed();
}
export function newElementWith(
element: ExcalidrawElement,
updates: ElementUpdate<ExcalidrawElement>,
): ExcalidrawElement {
return {
...element,
...updates,
version: element.version + 1,
versionNonce: randomSeed(),
};
}
// 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
// the same document.
export function mutateTextElement(
element: ExcalidrawTextElement,
updates: ElementUpdate<ExcalidrawTextElement>,
): void {
Object.assign(element, updates);
(element as any).version++;
(element as any).versionNonce = randomSeed();
}
export function newTextElementWith(
element: ExcalidrawTextElement,
updates: ElementUpdate<ExcalidrawTextElement>,
): ExcalidrawTextElement {
export function newElementWith<TElement extends ExcalidrawElement>(
element: TElement,
updates: ElementUpdate<TElement>,
): TElement {
return {
...element,
...updates,