89 lines
2.0 KiB
JavaScript
89 lines
2.0 KiB
JavaScript
import * as PIXI from "pixi.js";
|
|
import {Assets} from "pixi.js";
|
|
|
|
export const createElement = (displayObject, props, ...children) => {
|
|
if (!props) props = {};
|
|
if (!props.args) props.args = [];
|
|
|
|
const obj = new displayObject(...props.args)
|
|
|
|
if (props && props.ref) props.ref(obj);
|
|
|
|
children.forEach(child => addChild(obj, child));
|
|
|
|
obj.once('added', () => {
|
|
if (props) setProps(obj, props);
|
|
})
|
|
|
|
return obj
|
|
}
|
|
|
|
export const addChild = (parent, children) => {
|
|
if (Array.isArray(children))
|
|
children.forEach(nestedChild => {
|
|
addChild(parent, nestedChild)
|
|
});
|
|
|
|
else {
|
|
parent.addChild(children)
|
|
}
|
|
};
|
|
|
|
export function setProps(object, props) {
|
|
Object.keys(props).forEach(property => {
|
|
if (property === 'texture') {
|
|
object.texture = getTexture(props.texture);
|
|
return;
|
|
}
|
|
if (property === 'textures') {
|
|
object.textures = getTextures(props.textures)
|
|
return;
|
|
}
|
|
if (property === 'styles') {
|
|
applyStyles(object, props)
|
|
return;
|
|
}
|
|
if (property === 'position') {
|
|
object.position.set(...props.position)
|
|
return;
|
|
}
|
|
object[property] = props[property]
|
|
})
|
|
}
|
|
|
|
export function getTexture(texture) {
|
|
if (typeof texture === 'string') {
|
|
return Assets.get(texture)
|
|
}
|
|
if (texture instanceof PIXI.Texture) {
|
|
return texture;
|
|
}
|
|
return PIXI.Texture.WHITE
|
|
}
|
|
|
|
function getTextures(textures) {
|
|
return textures.map((texture) => getTexture(texture))
|
|
}
|
|
|
|
export function applyStyles(object, props) {
|
|
if (!object.styles) {
|
|
Object.defineProperty(object, 'styles', {
|
|
get: () => object._styles,
|
|
set: (value) => {
|
|
if (!object._styles) object._styles = {};
|
|
Object.assign(object._styles, value);
|
|
const styles = {}
|
|
for (const key in object._styles) {
|
|
if (typeof object._styles[key] === 'function') {
|
|
styles[key] = object._styles[key]();
|
|
} else {
|
|
styles[key] = object._styles[key];
|
|
}
|
|
}
|
|
setProps(object, styles)
|
|
}
|
|
})
|
|
}
|
|
object.styles = props.styles
|
|
}
|