refactor(canvas): use deferred promise instead of sleep

This commit is contained in:
Elian Doran 2025-06-11 13:41:54 +03:00
parent 0da05a7dbe
commit 9d296dd692
No known key found for this signature in database

View File

@ -3,7 +3,6 @@ import { Excalidraw, getSceneVersion, exportToSvg } from "@excalidraw/excalidraw
import { createElement, render } from "preact/compat"; import { createElement, render } from "preact/compat";
import { AppState, BinaryFileData, ExcalidrawImperativeAPI, ExcalidrawProps, LibraryItem, SceneData } from "@excalidraw/excalidraw/types"; import { AppState, BinaryFileData, ExcalidrawImperativeAPI, ExcalidrawProps, LibraryItem, SceneData } from "@excalidraw/excalidraw/types";
import type { ComponentType } from "preact"; import type { ComponentType } from "preact";
import utils from "../../services/utils";
import { Theme } from "@excalidraw/excalidraw/element/types"; import { Theme } from "@excalidraw/excalidraw/element/types";
/** Indicates that it is fresh. excalidraw scene version is always >0 */ /** Indicates that it is fresh. excalidraw scene version is always >0 */
@ -14,10 +13,12 @@ export default class Canvas {
private currentSceneVersion: number; private currentSceneVersion: number;
private opts: ExcalidrawProps; private opts: ExcalidrawProps;
private excalidrawApi!: ExcalidrawImperativeAPI; private excalidrawApi!: ExcalidrawImperativeAPI;
private initializedPromise: JQuery.Deferred<void>;
constructor(opts: ExcalidrawProps) { constructor(opts: ExcalidrawProps) {
this.opts = opts; this.opts = opts;
this.currentSceneVersion = SCENE_VERSION_INITIAL; this.currentSceneVersion = SCENE_VERSION_INITIAL;
this.initializedPromise = $.Deferred();
} }
renderCanvas(targetEl: HTMLElement) { renderCanvas(targetEl: HTMLElement) {
@ -25,14 +26,14 @@ export default class Canvas {
...this.opts, ...this.opts,
excalidrawAPI: (api: ExcalidrawImperativeAPI) => { excalidrawAPI: (api: ExcalidrawImperativeAPI) => {
this.excalidrawApi = api; this.excalidrawApi = api;
this.initializedPromise.resolve();
}, },
}), targetEl); }), targetEl);
} }
async waitForApiToBecomeAvailable() { async waitForApiToBecomeAvailable() {
while (!this.excalidrawApi) { while (!this.excalidrawApi) {
console.log("excalidrawApi not yet loaded, sleep 200ms..."); await this.initializedPromise;
await utils.sleep(200);
} }
} }