Add additional transforms (#899)

This commit is contained in:
toasted-nutbread 2020-10-08 17:38:18 -04:00 committed by GitHub
parent 05e51a950e
commit 41ead7a90a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 14 deletions

View File

@ -34,7 +34,9 @@ class GenericSettingController {
['setDocumentAttribute', this._setDocumentAttribute.bind(this)], ['setDocumentAttribute', this._setDocumentAttribute.bind(this)],
['setRelativeAttribute', this._setRelativeAttribute.bind(this)], ['setRelativeAttribute', this._setRelativeAttribute.bind(this)],
['splitTags', this._splitTags.bind(this)], ['splitTags', this._splitTags.bind(this)],
['joinTags', this._joinTags.bind(this)] ['joinTags', this._joinTags.bind(this)],
['toNumber', this._toNumber.bind(this)],
['toString', this._toString.bind(this)]
]); ]);
} }
@ -156,4 +158,12 @@ class GenericSettingController {
} }
return node; return node;
} }
_toNumber(value, metadata, element) {
return DOMDataBinder.convertToNumber(value, element.dataset);
}
_toString(value) {
return `${value}`;
}
} }

View File

@ -317,7 +317,7 @@ class DOMDataBinder {
case 'text': case 'text':
return `${element.value}`; return `${element.value}`;
case 'number': case 'number':
return this._getInputNumberValue(element); return DOMDataBinder.convertToNumber(element.value, element);
} }
break; break;
case 'TEXTAREA': case 'TEXTAREA':
@ -327,26 +327,29 @@ class DOMDataBinder {
return null; return null;
} }
_getInputNumberValue(element) { // Utilities
let value = parseFloat(element.value);
static convertToNumber(value, constraints) {
value = parseFloat(value);
if (!Number.isFinite(value)) { return 0; } if (!Number.isFinite(value)) { return 0; }
let {min, max, step} = element; let {min, max, step} = constraints;
min = this._stringValueToNumberOrNull(min); min = DOMDataBinder.convertToNumberOrNull(min);
max = this._stringValueToNumberOrNull(max); max = DOMDataBinder.convertToNumberOrNull(max);
step = this._stringValueToNumberOrNull(step); step = DOMDataBinder.convertToNumberOrNull(step);
if (typeof min === 'number') { value = Math.max(value, min); } if (typeof min === 'number') { value = Math.max(value, min); }
if (typeof max === 'number') { value = Math.min(value, max); } if (typeof max === 'number') { value = Math.min(value, max); }
if (typeof step === 'number' && step !== 0) { value = Math.round(value / step) * step; } if (typeof step === 'number' && step !== 0) { value = Math.round(value / step) * step; }
return value; return value;
} }
_stringValueToNumberOrNull(value) { static convertToNumberOrNull(value) {
if (typeof value !== 'string' || value.length === 0) { if (typeof value !== 'number') {
return null; if (typeof value !== 'string' || value.length === 0) {
return null;
}
value = parseFloat(value);
} }
return !Number.isNaN(value) ? value : null;
const number = parseFloat(value);
return !Number.isNaN(number) ? number : null;
} }
} }