excalidraw/src/scene/globalScene.ts

56 lines
1.1 KiB
TypeScript
Raw Normal View History

import {
ExcalidrawElement,
NonDeletedExcalidrawElement,
} from "../element/types";
import { getNonDeletedElements } from "../element";
2020-03-15 10:06:41 -07:00
export interface SceneStateCallback {
(): void;
}
export interface SceneStateCallbackRemover {
(): void;
}
class GlobalScene {
2020-03-15 10:06:41 -07:00
private callbacks: Set<SceneStateCallback> = new Set();
constructor(private _elements: readonly ExcalidrawElement[] = []) {}
getElementsIncludingDeleted() {
2020-03-15 10:06:41 -07:00
return this._elements;
}
getElements(): readonly NonDeletedExcalidrawElement[] {
return getNonDeletedElements(this._elements);
}
2020-03-15 10:06:41 -07:00
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 GlobalScene();