UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

123 lines (95 loc) 2.91 kB
import LabelView from '../../common/LabelView.js'; import domify from "../../DOM.js"; import View from '../../View.js'; import ImageView from "../image/ImageView.js"; class ButtonView extends View { /** * * @param {string} [tag] * @param {function} action * @param {string|ObservedString} [name] * @param {string} [icon] URL * @param {string[]} [classList] * @param {object} [css] * @constructor */ constructor({ tag = 'div', action, name, icon = undefined, classList = [], css }) { super(); if (typeof action !== "function") { throw new Error("Action must be a function"); } const dRoot = domify(tag); this.el = dRoot.el; //add background and foreground elements for styling purposes const dForeground = domify(); dForeground.addClass('foreground'); const dBackground = domify(); dBackground.addClass('background'); dRoot.append(dForeground); dRoot.append(dBackground); dRoot.addClass('ui-button-view'); if (css !== undefined) { this.css(css); } this.addClasses(classList); this.el.addEventListener('click', (event) => { if (this.__enabled) { const p = action(event); if (p instanceof Promise) { // async resolution, wait until done, disable button for now this.enabled = false; p.finally(() => { // restore this.enabled = true; }); } } else { console.warn('Button is disabled, no action'); } }); if (name !== undefined) { const vName = new LabelView(name); this.addChild(vName); this.size.onChanged.add(function (x, y) { vName.size.set(x, y); }); } if (icon !== undefined && icon !== null) { const vIcon = new ImageView(icon); this.addChild(vIcon); } /** * * @type {boolean} * @private */ this.__enabled = true; } /** * * @param {boolean} v */ set enabled(v) { if (this.__enabled === v) { return; } this.__enabled = v; this.setClass('enabled', v); this.setClass('disabled', !v); } /** * * @return {boolean} */ get enabled() { return this.__enabled; } } export default ButtonView;