pvbemu/app/toolkit/TextBox.js

146 lines
3.6 KiB
JavaScript

import { Component } from /**/"./Component.js";
let Toolkit;
///////////////////////////////////////////////////////////////////////////////
// TextBox //
///////////////////////////////////////////////////////////////////////////////
// Text entry field
class TextBox extends Component {
static Component = Component;
///////////////////////// Initialization Methods //////////////////////////
constructor(gui, options) {
super(gui, options, {
className: "tk tk-textbox",
tagName : "input"
});
this.element.type = "text";
this.setAttribute("spellcheck", "false");
// Configure instance fields
this.isEnabled = null;
this.maxLength = null;
this.pattern = null;
// Configure component
options = options || {};
this.setEnabled(!("enabled" in options) || options.enabled);
if ("maxLength" in options)
this.setMaxLength(options.maxLength);
if ("pattern" in options)
this.setPattern(options.pattern);
this.setText (options.text);
// Configure event handlers
this.addEventListener("blur" , e=>this.commit ( ));
this.addEventListener("pointerdown", e=>e.stopPropagation( ));
this.addEventListener("keydown" , e=>this.onKeyDown (e));
}
///////////////////////////// Event Handlers //////////////////////////////
// Key press
onKeyDown(e) {
// Processing by key
switch (e.key) {
case "ArrowLeft":
case "ArrowRight":
e.stopPropagation();
return;
case "Enter":
this.commit();
break;
default: return;
}
// Configure event
e.stopPropagation();
e.preventDefault();
}
///////////////////////////// Public Methods //////////////////////////////
// Programmatically commit the text box
commit() {
this.event("action");
}
// Retrieve the control's value
getText() {
return this.element.value;
}
// Specify whether the button can be activated
setEnabled(enabled) {
this.isEnabled = enabled = !!enabled;
this.setAttribute("disabled", enabled ? null : "true");
}
// Specify the maximum length of the text
setMaxLength(length) {
// Remove limitation
if (length === null) {
this.maxLength = null;
this.setAttribute("maxlength", null);
return;
}
// Error checking
if (typeof length != "number" || isNaN(length))
return;
// Range checking
length = Math.floor(length);
if (length < 0)
return;
// Configure component
this.maxLength = length;
this.setAttribute("maxlength", length);
}
// Specify a regex pattern for valid text characters
setPattern(pattern) {
/*
Disabled because user agents may not prevent invalid input
// Error checking
if (pattern && typeof pattern != "string")
return;
// Configure component
this.pattern = pattern = pattern || null;
this.setAttribute("pattern", pattern);
*/
}
// Specify the widget's display text
setText(text = "") {
this.element.value = text.toString();
}
///////////////////////////// Package Methods /////////////////////////////
// Update the global Toolkit object
static setToolkit(toolkit) {
Toolkit = toolkit;
}
}
export { TextBox };