/
main.preact.js
89 lines (75 loc) · 2.23 KB
/
main.preact.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { h } from "preact";
import { useRef, useEffect, useCallback } from "preact/hooks";
import {
createRenderer,
component as baseComponent,
subscribeToAnimationFrame,
unsubscribeFromAnimationFrame,
} from "./main.js";
export * from "./main.js";
export const Canvas = ({ attributes, pixelRatio, debug, clearColor, ...rest }) => {
const ref = useRef();
useCanvas(ref, { attributes, pixelRatio, debug, clearColor });
return h("canvas", {
ref,
...rest,
});
};
export const useCanvas = (elementOrRef, config) => {
useEffect(() => {
const canvas = elementOrRef.current || elementOrRef;
const renderer = createRenderer(canvas, config);
return () => {
renderer.destroy();
};
}, [elementOrRef, ...Object.keys(config), ...Object.values(config)]);
};
export const component = (...args) => {
const elem = baseComponent(...args);
const WebGL2Component = ({ children = null, ...props }) => {
useComponent(elem, props);
return children;
};
return WebGL2Component;
};
export const useComponent = (component, props, enabled = true) => {
const ref = useRef({ ...props });
const { addInstance, deleteInstance, updateInstance } = component;
useEffect(() => {
if (enabled) {
const instance = ref.current;
addInstance(instance);
return () => deleteInstance(instance);
}
}, [enabled, addInstance, deleteInstance]);
const instance = ref.current;
const update = useCallback(
(name, value) => updateInstance(instance, name, value),
[instance, updateInstance]
);
// Update data from props
for (const key in props) {
const oldValue = instance[key];
const newValue = props[key];
if (key !== "children" && oldValue !== newValue) {
instance[key] = newValue;
update(
key,
ArrayBuffer.isView(newValue)
? newValue
: Array.isArray(newValue)
? new Float32Array(newValue)
: Float32Array.of(newValue)
);
}
}
return [instance, update];
};
export const useAnimationFrame = (callback, nthFrame = 1) => {
useEffect(() => {
if (callback) {
subscribeToAnimationFrame(callback, nthFrame);
return unsubscribeFromAnimationFrame(callback, nthFrame);
}
}, [callback, nthFrame]);
};