pvbemu/app/toolkit/Component.js

93 lines
2.5 KiB
JavaScript

"use strict";
// Base features for all components
Toolkit.Component = class Component {
// Object constructor
constructor(application, tagname) {
// Configure instance fields
this.application = application;
this.containers = [ this ];
this.element = document.createElement(tagname);
this.id = this.element.id = Toolkit.id();
this.parent = null;
this.properties = {};
this.resizeListeners = [];
// Configure component
this.element.component = this;
}
///////////////////////////// Public Methods //////////////////////////////
// Add a callback for resize events
addResizeListener(listener) {
if (this.resizeListeners.indexOf(listener) != -1)
return;
if (this.resizeListeners.length == 0)
new ResizeObserver(()=>this.onresize()).observe(this.element);
this.resizeListeners.push(listener);
}
// Remove the component from its parent
remove() {
this.parent && this.parent.remove(this);
}
// Retrieve the bounding box of the element
getBounds() {
return this.element.getBoundingClientRect();
}
// Specify the height of the element
setHeight(height) {
if (height === null)
this.element.style.removeProperty("height");
else this.element.style.height = height;
}
// Specify the width of the element
setWidth(width) {
if (width === null)
this.element.style.removeProperty("width");
else this.element.style.width = width;
}
///////////////////////////// Package Methods /////////////////////////////
// Determine whether this component contains another
contains(comp) {
if (comp == null)
return false;
if (comp instanceof Toolkit.Component)
comp = comp.element;
for (let cont of this.containers)
if ((cont instanceof Toolkit.Component ? cont.element : cont)
.contains(comp)) return true;
return false;
}
// Notify of a change to component focus
focusChanged(from, to) {
if (this.parent != null)
this.parent.focusChanged(from, to);
}
///////////////////////////// Private Methods /////////////////////////////
// Resize event handler
onresize() {
let bounds = this.getBounds();
for (let listener of this.resizeListeners)
listener(bounds, this);
}
};