106 lines
3.1 KiB
JavaScript
106 lines
3.1 KiB
JavaScript
import UI from "../ui.js";
|
|
|
|
class NumericBox extends UI {
|
|
constructor(width, height) {
|
|
super(document.createElement("div"), width, height);
|
|
|
|
this._valid = false;
|
|
this._value = true;
|
|
|
|
this._createInput();
|
|
this._bindEvents();
|
|
}
|
|
destructor() {
|
|
this._input.removeEventListener("keyPress", this._boundKeyPress);
|
|
this._input.removeEventListener("input", this._boundInput);
|
|
delete this._boundKeyPress;
|
|
delete this._boundInput;
|
|
delete this._input;
|
|
|
|
super.destructor();
|
|
}
|
|
get value() {
|
|
if (this._valid) {
|
|
return this._value;
|
|
} else {
|
|
throw new Error("An attempt to get value of invalid NumericBox");
|
|
}
|
|
}
|
|
setValue(value) {
|
|
let val = parseFloat(value);
|
|
this._value = val;
|
|
|
|
this._input.value = val.toString();
|
|
this._valid = true;
|
|
}
|
|
_bindEvents() {
|
|
this._boundInput = this._onInput.bind(this);
|
|
this._boundKeyPress = this._onKeyPress.bind(this);
|
|
|
|
this._input.addEventListener("keyPress", this._boundKeyPress);
|
|
this._input.addEventListener("input", this._boundInput);
|
|
}
|
|
_createInput() {
|
|
this._input = document.createElement("div");
|
|
this._input.classList.add("numericBox");
|
|
|
|
this.element.appendChild(this._input);
|
|
}
|
|
_onInput(e) {
|
|
let oldVal = this._value;
|
|
let newVal = this._input.value;
|
|
|
|
if (newVal === "" || newVal === "-" || newVal === ".") {
|
|
if (newVal === ".") {
|
|
this.setValue(0);
|
|
this._input.value += '.';
|
|
} else {
|
|
this._input.value = newVal;
|
|
this._value = null;
|
|
this._valid = false;
|
|
}
|
|
} else if (!newVal.match(/^\-?[0-9]+(\.[0-9]*)?$/)) {
|
|
if (oldVal === null) {
|
|
this._input.value = "";
|
|
this._valid = false;
|
|
this._value = null;
|
|
} else {
|
|
this.setValue(oldVal);
|
|
}
|
|
} else {
|
|
let dotIndex = newVal.indexOf('.');
|
|
if (newVal[newVal.length-1] === '.') {
|
|
this.setValue(parseFloat(newVal));
|
|
this._input.value += '.';
|
|
} else if (dotIndex > 0 && newVal[newVal.length-1] === "0") {
|
|
this.setValue(parseFloat(newVal));
|
|
this._input.value = newVal;
|
|
} else {
|
|
this.setValue(parseFloat(newVal));
|
|
}
|
|
}
|
|
}
|
|
_onKeyPress(e) {
|
|
switch (e.charCode) {
|
|
case 45: // "-"
|
|
case 1102:
|
|
case 46: // "."
|
|
case 48: //zero
|
|
case 49: //other digits
|
|
case 50:
|
|
case 51:
|
|
case 52:
|
|
case 53:
|
|
case 54:
|
|
case 55:
|
|
case 56:
|
|
case 57:
|
|
break;
|
|
default:
|
|
e.preventDefault();
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
export default NumericBox; |