pvbemu/web/toolkit/Button.js

120 lines
3.0 KiB
JavaScript

let register = Toolkit => Toolkit.Button =
// Push button
class Button extends Toolkit.Component {
///////////////////////// Initialization Methods //////////////////////////
constructor(app, options = {}) {
super(app, options = Object.assign({
class : "tk button",
role : "button",
tabIndex: "0"
}, options));
// Configure options
if ("disabled" in options)
this.disabled = options.disabled;
this.doNotFocus = !("doNotFocus" in options) || options.doNotFocus;
// Display text
this.content = new Toolkit.Label(app);
this.add(this.content);
// Event handlers
this.addEventListener("keydown" , e=>this.onKeyDown (e));
this.addEventListener("pointerdown", e=>this.onPointerDown(e));
this.addEventListener("pointermove", e=>this.onPointerMove(e));
this.addEventListener("pointerup" , e=>this.onPointerUp (e));
}
///////////////////////////// Event Handlers //////////////////////////////
// Key press
onKeyDown(e) {
if (
!(e.altKey || e.ctrlKey || e.shiftKey || this.disabled) &&
(e.key == " " || e.key == "Enter")
) this.activate();
}
// Pointer down
onPointerDown(e) {
// Gain focus
if (
!this.doNotFocus &&
this.isFocusable() &&
this.element != document.activeElement
) this.element.focus();
else e.preventDefault();
// Do not drag
if (
e.button != 0 ||
this.disabled ||
this.element.hasPointerCapture(e.pointerId)
) return;
// Begin dragging
this.element.setPointerCapture(e.pointerId);
this.element.classList.add("pushed");
Toolkit.handle(e);
}
// Pointer move
onPointerMove(e) {
// Do not drag
if (!this.element.hasPointerCapture(e.pointerId))
return;
// Process dragging
this.element.classList[this.isWithin(e) ? "add" : "remove"]("pushed");
Toolkit.handle(e);
}
// Pointer up
onPointerUp(e) {
// Do not activate
if (e.button != 0 || !this.element.hasPointerCapture(e.pointerId))
return;
// End dragging
this.element.releasePointerCapture(e.pointerId);
this.element.classList.remove("pushed");
Toolkit.handle(e);
// Activate the button if applicable
if (this.isWithin(e))
this.activate();
}
///////////////////////////// Public Methods //////////////////////////////
// Simulate a click on the button
activate() {
if (!this.disabled)
this.element.dispatchEvent(new Event("action"));
}
///////////////////////////// Package Methods /////////////////////////////
// Update localization strings
localize() {
this.localizeText(this.content);
this.localizeLabel();
this.localizeTitle();
}
}
export { register };