Fire number-changed event whenever the user changed the value by interacting with it.

This commit is contained in:
trading_peter 2025-01-10 23:39:22 +01:00
parent df81d4f266
commit bd5d079ed6
2 changed files with 50 additions and 7 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@tp/tp-number-input",
"version": "1.0.2",
"version": "1.1.0",
"description": "",
"main": "tp-number-input.js",
"scripts": {

View File

@ -119,6 +119,7 @@ class TpNumberInput extends FormElement(EventHelpers(DomQuery(LitElement))) {
this.max = Number.MAX_SAFE_INTEGER;
this.fastInterval = 50;
this.superFastInterval = 100;
this._isConnected = false
}
firstUpdated() {
@ -129,6 +130,14 @@ class TpNumberInput extends FormElement(EventHelpers(DomQuery(LitElement))) {
this.listen(this.$.innerInput, 'keydown', '_onKey');
}
connectedCallback() {
super.connectedCallback();
// Set small timeout to ensure all initial updates have run
setTimeout(() => {
this._isConnected = true;
}, 0);
}
updated(changes) {
super.updated();
@ -291,8 +300,18 @@ class TpNumberInput extends FormElement(EventHelpers(DomQuery(LitElement))) {
}
_onKey(e) {
if(e.keyCode === 13) {
if (e.keyCode === 13) {
this._updateValue(parseInt(this.$.input.value, 10));
} else if (e.keyCode === 38) { // Arrow Up
e.preventDefault();
let val = parseInt(this.value, 10) || 0;
val = Math.min(this.max, val + this.step);
this._updateValue(val);
} else if (e.keyCode === 40) { // Arrow Down
e.preventDefault();
let val = parseInt(this.value, 10) || 0;
val = Math.max(this.min, val - this.step);
this._updateValue(val);
}
}
@ -319,9 +338,18 @@ class TpNumberInput extends FormElement(EventHelpers(DomQuery(LitElement))) {
_updateValue(val) {
if(this.timeMode) return;
const oldValue = this.value;
if(typeof this.specialMin === 'string' && val === this.specialMin) {
this.value = this.specialMin;
this.$.input.value = this.value;
if (oldValue !== this.value && this._isConnected) {
this.dispatchEvent(new CustomEvent('number-changed', {
detail: { value: this.value },
bubbles: true,
composed: true
}));
}
return;
}
@ -336,6 +364,13 @@ class TpNumberInput extends FormElement(EventHelpers(DomQuery(LitElement))) {
if((typeof this.specialMin === 'string' && val === this.specialMin) || (val < this.min && typeof this.specialMin === 'string')) {
this.value = this.specialMin;
this.$.input.value = this.value;
if (oldValue !== this.value && this._isConnected) {
this.dispatchEvent(new CustomEvent('number-changed', {
detail: { value: this.value },
bubbles: true,
composed: true
}));
}
return;
}
@ -343,6 +378,14 @@ class TpNumberInput extends FormElement(EventHelpers(DomQuery(LitElement))) {
val = Math.max(this.min, val);
this.value = this.ignoreSuffix ? val : (!!this.suffix ? val + this.suffix : val);
this.$.input.value = !!this.suffix ? val + this.suffix : val;
if (oldValue !== this.value && this._isConnected) {
this.dispatchEvent(new CustomEvent('number-changed', {
detail: { value: this.value },
bubbles: true,
composed: true
}));
}
}
}