devextreme
Version:
JavaScript/TypeScript Component Suite for Responsive Web Development
452 lines (451 loc) • 14.8 kB
JavaScript
/**
* DevExtreme (esm/__internal/ui/number_box/number_box.base.js)
* Version: 26.1.6
* Build date: Fri Oct 16 2026
*
* Copyright (c) 2012 - 2026 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
import eventsEngine from "../../../common/core/events/core/events_engine";
import {
addNamespace,
getChar,
isCommandKeyPressed,
normalizeKeyName
} from "../../../common/core/events/utils/index";
import messageLocalization from "../../../common/core/localization/message";
import numberLocalization from "../../../common/core/localization/number";
import devices from "../../../core/devices";
import domAdapter from "../../../core/dom_adapter";
import $ from "../../../core/renderer";
import browser from "../../../core/utils/browser";
import {
applyServerDecimalSeparator
} from "../../../core/utils/common";
import {
Deferred
} from "../../../core/utils/deferred";
import {
fitIntoRange,
inRange
} from "../../../core/utils/math";
import {
isDefined
} from "../../../core/utils/type";
import {
getGlobalFormatByDataType
} from "../../core/global_format_config";
import TextEditor from "../../ui/text_box/text_editor";
import SpinButtons from "./number_box.spins";
export const WIDGET_CLASS = "dx-numberbox";
const FIREFOX_CONTROL_KEYS = ["tab", "del", "backspace", "leftArrow", "rightArrow", "home", "end", "enter"];
const FORCE_VALUECHANGE_EVENT_NAMESPACE = "NumberBoxForceValueChange";
const getSpinEvent = e => "event" in e ? e.event : e;
class NumberBoxBase extends TextEditor {
_supportedKeys() {
return Object.assign({}, super._supportedKeys(), {
upArrow: e => {
if (!isCommandKeyPressed(e)) {
e.preventDefault();
e.stopPropagation();
this._spinUpChangeHandler(e)
}
},
downArrow: e => {
if (!isCommandKeyPressed(e)) {
e.preventDefault();
e.stopPropagation();
this._spinDownChangeHandler(e)
}
},
enter: () => {}
})
}
_getDefaultOptions() {
return Object.assign({}, super._getDefaultOptions(), {
value: 0,
min: void 0,
max: void 0,
step: 1,
showSpinButtons: false,
useLargeSpinButtons: true,
mode: "text",
invalidValueMessage: messageLocalization.format("dxNumberBox-invalidValueMessage"),
buttons: void 0
})
}
_useTemplates() {
return false
}
_getDefaultButtons() {
return super._getDefaultButtons().concat([{
name: "spins",
Ctor: SpinButtons
}])
}
_isSupportInputMode() {
const version = parseFloat(browser.version ?? "");
const isSupportedChrome = !!browser.chrome && version >= 66;
const isSupportedSafari = !!browser.safari && version >= 12;
return isSupportedChrome || isSupportedSafari
}
_defaultOptionsRules() {
return super._defaultOptionsRules().concat([{
device: () => !!devices.real().generic && !devices.isSimulator(),
options: {
useLargeSpinButtons: false
}
}, {
device: () => "desktop" !== devices.real().deviceType && !this._isSupportInputMode(),
options: {
mode: "number"
}
}])
}
_initMarkup() {
this._renderSubmitElement();
this.$element().addClass(WIDGET_CLASS);
super._initMarkup();
this._toggleTabIndex()
}
_getDefaultAttributes() {
const attributes = super._getDefaultAttributes();
attributes.inputmode = "decimal";
return attributes
}
_renderContentImpl() {
const {
isValid: isValid,
value: value
} = this.option();
if (isValid) {
this._validateValue(value)
}
this.setAria("role", "spinbutton")
}
_renderSubmitElement() {
const {
value: value
} = this.option();
this._$submitElement = $("<input>").attr("type", "hidden").appendTo(this.$element());
this._setSubmitValue(value)
}
_setSubmitValue(value) {
this._getSubmitElement().val(applyServerDecimalSeparator(value))
}
_getSubmitElement() {
return this._$submitElement
}
_keyPressHandler(e) {
super._keyPressHandler();
const char = getChar(e);
const isInputCharValid = /[\d.,eE\-+]/.test(char);
if (!isInputCharValid) {
const keyName = normalizeKeyName(e);
if (isCommandKeyPressed(e) || keyName && FIREFOX_CONTROL_KEYS.includes(keyName)) {
return
}
e.preventDefault();
return
}
this._keyPressed = true
}
_hasMouseWheelHandler() {
return true
}
_onMouseWheel(e) {
this._spinValueChange(e.delta > 0 ? 1 : -1, e)
}
_renderValue() {
const inputValue = this._input().val();
const {
value: value
} = this.option();
if (!inputValue.length || Number(inputValue) !== value) {
this._forceValueRender();
this._toggleEmptinessEventHandler()
}
const valueText = isDefined(value) ? null : messageLocalization.format("dxNumberBox-noDataText");
this.setAria({
valuenow: value ?? "",
valuetext: valueText
});
this.option("text", this._input().val());
this._updateButtons();
return Deferred().resolve()
}
_forceValueRender() {
const {
value: value
} = this.option();
const formattedValue = isNaN(Number(value)) ? "" : this._applyDisplayValueFormatter(value);
this._renderDisplayText(formattedValue)
}
_applyDisplayValueFormatter(value) {
const {
format: format,
displayValueFormatter: displayValueFormatter
} = this.option();
if (!format) {
const globalNumberFormat = getGlobalFormatByDataType("number");
if (globalNumberFormat) {
return numberLocalization.format(Number(value), globalNumberFormat)
}
}
return null === displayValueFormatter || void 0 === displayValueFormatter ? void 0 : displayValueFormatter(value)
}
_renderProps() {
const {
min: min,
max: max,
step: step
} = this.option();
this._input().prop({
min: min,
max: max,
step: step
});
this.setAria({
valuemin: min ?? "",
valuemax: max ?? ""
})
}
_spinButtonsPointerDownHandler() {
const {
useLargeSpinButtons: useLargeSpinButtons
} = this.option();
const $input = this._input();
if (!useLargeSpinButtons && domAdapter.getActiveElement() !== $input[0]) {
eventsEngine.trigger($input, "focus")
}
}
_spinUpChangeHandler(e) {
const {
readOnly: readOnly
} = this.option();
if (!readOnly) {
this._spinValueChange(1, getSpinEvent(e))
}
}
_spinDownChangeHandler(e) {
const {
readOnly: readOnly
} = this.option();
if (!readOnly) {
this._spinValueChange(-1, getSpinEvent(e))
}
}
_spinValueChange(sign, dxEvent) {
const {
step: stepOption,
min: min,
max: max
} = this.option();
const step = parseFloat(String(stepOption));
if (0 === step) {
return
}
let value = parseFloat(String(this._normalizeInputValue())) || 0;
value = this._correctRounding(value, step * sign);
if (isDefined(min)) {
value = Math.max(min, value)
}
if (isDefined(max)) {
value = Math.min(max, value)
}
this._saveValueChangeEvent(dxEvent);
this.option("value", value)
}
_correctRounding(value, step) {
const regex = /[,.](.*)/;
const valueText = String(value);
const stepText = String(step);
const isFloatValue = regex.test(valueText);
const isFloatStep = regex.test(stepText);
if (isFloatValue || isFloatStep) {
var _regex$exec, _regex$exec2;
const valueAccuracy = isFloatValue ? (null === (_regex$exec = regex.exec(valueText)) || void 0 === _regex$exec ? void 0 : _regex$exec[0].length) ?? 0 : 0;
const stepAccuracy = isFloatStep ? (null === (_regex$exec2 = regex.exec(stepText)) || void 0 === _regex$exec2 ? void 0 : _regex$exec2[0].length) ?? 0 : 0;
const accuracy = Math.max(valueAccuracy, stepAccuracy);
return this._round(value + step, accuracy)
}
return value + step
}
_round(value) {
let precision = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
const multiplier = 10 ** precision;
return Math.round(value * multiplier) / multiplier
}
_renderValueChangeEvent() {
super._renderValueChangeEvent();
const forceValueChangeEvent = addNamespace("focusout", "NumberBoxForceValueChange");
eventsEngine.off(this.element(), forceValueChangeEvent);
eventsEngine.on(this.element(), forceValueChangeEvent, this._forceRefreshInputValue.bind(this))
}
_forceRefreshInputValue() {
const {
mode: mode,
value: value
} = this.option();
if ("number" === mode) {
return
}
const $input = this._input();
const formattedValue = this._applyDisplayValueFormatter(value);
$input.val(null);
$input.val(formattedValue)
}
_valueChangeEventHandler(e) {
const $input = this._input();
const inputValue = this._normalizeText();
const value = this._parseValue(inputValue);
const valueHasDigits = "." !== inputValue && "-" !== inputValue;
if (this._isValueValid() && !this._validateValue(value)) {
$input.val(this._applyDisplayValueFormatter(value));
return
}
if (valueHasDigits) {
super._valueChangeEventHandler(e, isNaN(Number(value)) ? null : value)
}
this._applyValueBoundaries(inputValue, value);
this.validationRequest.fire({
value: value,
editor: this
})
}
_applyValueBoundaries(inputValue, parsedValue) {
const isValueIncomplete = this._isValueIncomplete(inputValue);
const isValueCorrect = this._isValueInRange(Number(inputValue));
if (!isValueIncomplete && !isValueCorrect && null !== parsedValue) {
if (Number(inputValue) !== parsedValue) {
this._input().val(this._applyDisplayValueFormatter(parsedValue))
}
}
}
_replaceCommaWithPoint(value) {
return value.replace(",", ".")
}
_inputIsInvalid() {
const {
mode: mode
} = this.option();
const isNumberMode = "number" === mode;
const input = this._input().get(0);
return isNumberMode && !!(null !== input && void 0 !== input && input.validity.badInput)
}
_renderDisplayText(text) {
if (this._inputIsInvalid()) {
return
}
super._renderDisplayText(text)
}
_isValueIncomplete(value) {
return /(^-$)|(^-?\d*\.$)|(\d+e-?$)/i.test(value)
}
_isValueInRange(value) {
const {
min: min,
max: max
} = this.option();
return inRange(value, min, max)
}
_isNumber(value) {
return null !== this._parseValue(value)
}
_validateValue(value) {
const {
invalidValueMessage: invalidValueMessage
} = this.option();
const inputValue = this._normalizeText();
const isValueValid = this._isValueValid();
let isValid = true;
const isNumber = this._isNumber(inputValue);
if (isNaN(Number(value))) {
isValid = false
}
if (!value && isValueValid) {
isValid = true
} else if (!isNumber && !isValueValid) {
isValid = false
}
this.option({
isValid: isValid,
validationError: isValid ? null : {
editorSpecific: true,
message: invalidValueMessage
}
});
return isValid
}
_normalizeInputValue() {
return this._parseValue(this._normalizeText())
}
_normalizeText() {
const value = this._input().val().trim();
return this._replaceCommaWithPoint(value)
}
_parseValue(value) {
const {
min: min,
max: max
} = this.option();
const parsedValue = parseFloat(String(value ?? ""));
if (isNaN(parsedValue)) {
return null
}
return fitIntoRange(parsedValue, min, max)
}
_clearValue() {
if (this._inputIsInvalid()) {
this._input().val("");
this._validateValue()
}
super._clearValue()
}
clear() {
const {
value: value
} = this.option();
if (null === value) {
this.option("text", "");
if (this._input().length) {
this._renderValue()
}
} else {
this.option("value", null)
}
}
_optionChanged(args) {
switch (args.name) {
case "value": {
const value = args.value;
this._validateValue(value);
this._setSubmitValue(value);
super._optionChanged(args);
this._resumeValueChangeAction();
break
}
case "step":
this._renderProps();
break;
case "min":
case "max": {
const {
value: value
} = this.option();
this._renderProps();
this.option("value", this._parseValue(value));
break
}
case "showSpinButtons":
case "useLargeSpinButtons":
this._updateButtons(["spins"]);
break;
case "invalidValueMessage":
break;
default:
super._optionChanged(args)
}
}
}
export default NumberBoxBase;