@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
104 lines (78 loc) • 2.69 kB
JavaScript
import { clamp01 } from "../../../src/core/math/clamp01.js";
import { CSS_ABSOLUTE_POSITIONING } from "../../../src/view/CSS_ABSOLUTE_POSITIONING.js";
import EmptyView from "../../../src/view/elements/EmptyView.js";
export class SplitView extends EmptyView {
#direction = 'x';
#child_a = new EmptyView();
#child_b = new EmptyView();
#fraction = 0.5;
#round_split_to_nearest_integer = true
static from({ a, b, type = 'x', fraction = 0.5 }) {
const r = new SplitView();
r.direction = type;
r.fraction = fraction;
r.childA = a;
r.childB = b;
return r;
}
constructor() {
super();
this.addChild(this.#child_a);
this.addChild(this.#child_b);
this.layout();
this.bindSignal(this.size.onChanged, this.layout, this);
this.on.linked.add(this.layout, this);
}
set fraction(v) {
this.#fraction = v;
this.layout();
}
set direction(v) {
if (!['x', 'y'].includes(v)) {
throw new Error(`Invalid direction '${v}', valid values are 'x' and 'y'`);
}
this.#direction = v;
this.layout();
}
set childA(v) {
this.removeChild(this.#child_a);
this.#child_a = v;
this.addChild(v);
this.layout();
}
set childB(v) {
this.removeChild(this.#child_b);
this.#child_b = v;
this.addChild(v);
this.layout();
}
layout() {
const size = this.size;
const f = clamp01(this.#fraction);
this.#child_a.css(CSS_ABSOLUTE_POSITIONING);
this.#child_b.css(CSS_ABSOLUTE_POSITIONING);
const width = size.x;
const height = size.y;
if (this.#direction === 'x') {
let first = width*f;
if(this.#round_split_to_nearest_integer){
first = Math.round(first);
}
const second = width - first;
this.#child_a.size.set(first, height);
this.#child_b.size.set(second, height);
this.#child_a.position.set(0, 0);
this.#child_b.position.set(first, 0);
} else {
let first = height*f;
if(this.#round_split_to_nearest_integer){
first = Math.round(first);
}
const second = width - first;
this.#child_a.size.set(width, first);
this.#child_b.size.set(width, second);
this.#child_a.position.set(0, 0);
this.#child_b.position.set(0, first);
}
}
}