remove most setState({}) (#959)

This commit is contained in:
Pete Hunt 2020-03-15 10:06:41 -07:00 committed by GitHub
parent e1e2249f57
commit 35ce1729cc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 149 additions and 95 deletions

View file

@ -1,17 +0,0 @@
import { ExcalidrawElement } from "../element/types";
class SceneState {
constructor(private _elements: readonly ExcalidrawElement[] = []) {}
getAllElements() {
return this._elements;
}
replaceAllElements(nextElements: readonly ExcalidrawElement[]) {
this._elements = nextElements;
}
}
export const createScene = () => {
return new SceneState();
};

47
src/scene/globalScene.ts Normal file
View file

@ -0,0 +1,47 @@
import { ExcalidrawElement } from "../element/types";
export interface SceneStateCallback {
(): void;
}
export interface SceneStateCallbackRemover {
(): void;
}
class SceneState {
private callbacks: Set<SceneStateCallback> = new Set();
constructor(private _elements: readonly ExcalidrawElement[] = []) {}
getAllElements() {
return this._elements;
}
replaceAllElements(nextElements: readonly ExcalidrawElement[]) {
this._elements = nextElements;
this.informMutation();
}
informMutation() {
for (const callback of Array.from(this.callbacks)) {
callback();
}
}
addCallback(cb: SceneStateCallback): SceneStateCallbackRemover {
if (this.callbacks.has(cb)) {
throw new Error();
}
this.callbacks.add(cb);
return () => {
if (!this.callbacks.has(cb)) {
throw new Error();
}
this.callbacks.delete(cb);
};
}
}
export const globalSceneState = new SceneState();

View file

@ -16,5 +16,5 @@ export {
getElementContainingPosition,
hasText,
} from "./comparisons";
export { createScene } from "./createScene";
export { getZoomOrigin, getNormalizedZoom } from "./zoom";
export { globalSceneState } from "./globalScene";