bg2e-js 2.2.12 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bg2e-js",
3
- "version": "2.2.12",
3
+ "version": "2.3.0",
4
4
  "description": "a graphics engine for productivity applications",
5
5
  "main": "./dist/bg2e-js.js",
6
6
  "types": "./src/index.ts",
@@ -0,0 +1,60 @@
1
+ import { useEffect, useMemo, useRef, useState } from "react";
2
+
3
+ import Canvas from "../app/Canvas";
4
+ import MainLoop from "../app/MainLoop";
5
+ import type AppController from "../app/AppController";
6
+ import Renderer from "../render/Renderer";
7
+
8
+ const mainLoopByCanvas = new WeakMap<HTMLCanvasElement, MainLoop>();
9
+
10
+ function resolveCanvas(canvas: string | HTMLCanvasElement): HTMLCanvasElement | null {
11
+ if (typeof canvas === "string") {
12
+ return document.querySelector(canvas);
13
+ } else {
14
+ return canvas;
15
+ }
16
+ }
17
+
18
+ export default function useBg2e(target: string | HTMLCanvasElement, renderer: Renderer, appController: AppController) {
19
+ const canvas = useMemo(() => {
20
+ if (typeof document === "undefined") return null; // SSR guard
21
+ return resolveCanvas(target);
22
+ }, [target]);
23
+ const mainLoopRef = useRef<MainLoop | null>(null);
24
+ const createdRef = useRef(false);
25
+
26
+ const [, forceUpdate] = useState(0);
27
+
28
+ useEffect(() => {
29
+ createdRef.current = false;
30
+
31
+ if (!canvas) {
32
+ mainLoopRef.current = null;
33
+ forceUpdate((x) => x + 1);
34
+ return;
35
+ }
36
+
37
+ const existing = mainLoopByCanvas.get(canvas);
38
+ if (existing) {
39
+ mainLoopRef.current = existing;
40
+ forceUpdate((x) => x + 1);
41
+ return;
42
+ }
43
+
44
+ const bg2Canvas = new Canvas(canvas, renderer);
45
+ const mainLoop = new MainLoop(bg2Canvas, appController);
46
+
47
+ mainLoop.run(); // Background execution
48
+
49
+ mainLoopByCanvas.set(canvas, mainLoop);
50
+ mainLoopRef.current = mainLoop;
51
+ createdRef.current = true;
52
+
53
+ forceUpdate((x) => x + 1);
54
+ }, []);
55
+
56
+ return {
57
+ mainLoop: mainLoopRef.current,
58
+ canvas
59
+ }
60
+ }