view class doc
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784/// FOURJS_START_COPYRIGHT(D,2015)
/// Property of Four Js*
/// (c) Copyright Four Js 2015, 2023. All Rights Reserved.
/// * Trademark of Four Js Development Tools Europe Ltd
///   in the United States and elsewhere
///
/// This file can be modified by licensees according to the
/// product manual.
/// FOURJS_END_COPYRIGHT

'use strict';

modulum('SpinEditWidgetBase', ['FieldWidgetBase', 'WidgetFactory'],
  function(context, cls) {

    /**
     * SpinEdit widget Base class.
     * @class SpinEditWidgetBase
     * @memberOf classes
     * @extends classes.FieldWidgetBase
     * @publicdoc Widgets
     */
    cls.SpinEditWidgetBase = context.oo.Class(cls.FieldWidgetBase, function($super) {
      return /** @lends classes.SpinEditWidgetBase.prototype */ {
        __name: 'SpinEditWidgetBase',

        /**
         * Redefine where the data is located
         * @type {string}
         */
        __dataContentPlaceholderSelector: '.gbc_dataContentPlaceholder',

        /**
         * Up arrow element
         * @type {Element}
         */
        _upArrow: null,

        /**
         * Down arrow element
         * @type {Element}
         */
        _downArrow: null,

        /**
         * Maximum number of characters allowed. By default -1 indicates no limit.
         * @type {number}
         */
        _maxLength: -1,

        /**
         * Step of value increment/decrement.
         * @type {number}
         */
        _step: 1,

        /**
         * Minimum value of the spinedit
         * @type {?number}
         */
        _min: null,

        /**
         * Maximum value of the spinedit
         * @type {?number}
         */
        _max: null,

        /**
         * @type {boolean}
         */
        _canShowVirtualKeyboard: null,

        /**
         * True to always show the virtual keyboard on GMA
         * @type {boolean}
         */
        _showVirtualKeyboardOnFocus: null,

        /**
         * Handler for virtualKeyboardDisplayed event
         * @function
         */
        _virtualKeyboardDisplayedHandler: null,

        /**
         * Give the real widget readonly state (on mobile the widget is sometimes readonly only
         * to hide the virtual keyboard)
         * @type {boolean}
         */
        _realReadOnly: false,

        /**
         * Scroll attribute value
         * @type {boolean}
         */
        _scroll: null,

        /**
         * widget VM width
         * @type {number}
         */
        _vmWidth: 0,

        /**
         * @inheritDoc
         */
        _initLayout: function() {
          if (!this._ignoreLayout) {
            this._layoutInformation = new cls.LayoutInformation(this);
            this._layoutEngine = new cls.LeafLayoutEngine(this);
            this._layoutInformation.setSingleLineContentOnly(true);
          }
        },

        /**
         * @inheritDoc
         */
        _initElement: function() {
          $super._initElement.call(this);
          this._inputElement = this._element.getElementsByTagName('input')[0];
          this._upArrow = this._element.getElementsByClassName('up')[0];
          this._downArrow = this._element.getElementsByClassName('down')[0];

          this._inputElement.on('input.SpinEditWidget', this._onInput.bind(this));
          // Manage requestFocus during selection of text
          this._inputElement.on('mousedown.SpinEditWidget', cls.WidgetBase._onSelect.bind(this));

          // Manage virtual keyboard on Mobile
          this._canShowVirtualKeyboard = true;
          this._realReadOnly = false;

          // Manage virtual keyboard on Mobile
          if (context.__wrapper.isGMA()) {
            // On GMA skip the first VM Focus after a dialogType change.
            this._virtualKeyboardDisplayedHandler = this._appWidget.when(context.constants.widgetEvents.virtualKeyboardDisplayed,
              function() {
                this._canShowVirtualKeyboard = true;
              }.bind(this));
          }

          this._showVirtualKeyboardOnFocus = false;
        },

        /**
         * @inheritDoc
         */
        destroy: function() {
          this._inputElement.off('input.SpinEditWidget');
          this._inputElement.off('mousedown.SpinEditWidget');

          if (this._virtualKeyboardDisplayedHandler) {
            this._virtualKeyboardDisplayedHandler();
            this._virtualKeyboardDisplayedHandler = null;
          }

          $super.destroy.call(this);
        },

        /**
         * Process one key event
         * @param {Object} event
         * @param {string} keyString
         * @returns {boolean} true if key has been processed, false otherwise
         */
        _processKey: function(event, keyString) {
          var isModifier = cls.KeyboardHelper.isSpecialCommand(keyString);
          var isValid = !isModifier && cls.KeyboardHelper.isDecimal(event.gbcKey) && !this._isMaxLength();

          if (isValid) {
            var value = this._inputElement.value;
            var start = this._inputElement.selectionStart;
            var end = this._inputElement.selectionEnd;
            if (end !== start) {
              value = '';
            }
            isValid = cls.KeyboardHelper.validateNumber(value, start, event.gbcKey, this._min, this._max);
          }
          if (!isValid && !isModifier) {
            this._elementState.setRestored(true); //Cancel autonext
            event.preventCancelableDefault();
            return true;
          }
          return false;
        },

        /**
         * @inheritDoc
         */
        manageMouseClick: function(domEvent) {
          //On GMA remove the readonly to display the virtual keyboard
          if (this.getApplicationWidget() && context.__wrapper.isGMA()) {
            this._setInputReadOnly(this._realReadOnly || this._notEditable || !this._enabled);
            this.getApplicationWidget().virtualKeyboardIsDisplayed();
          }

          this._elementState.backupCursorPos(this._inputElement);
          this._onRequestFocus(domEvent); // request focus

          var target = domEvent.target;
          if (target.isElementOrChildOf(this._upArrow)) {
            this._onUpIcon(domEvent);
          } else if (target.isElementOrChildOf(this._downArrow)) {
            this._onDownIcon(domEvent);
          }

          return true;
        },

        /**
         * @inheritDoc
         */
        manageKeyUp: function(keyString, domKeyEvent) {
          $super.manageKeyUp.call(this, keyString, domKeyEvent);

          this._verifyWidgetValue(domKeyEvent);
          this.emit(context.constants.widgetEvents.change, true);
          this.emit(context.constants.widgetEvents.keyUp, domKeyEvent, true);
        },

        /**
         * @inheritDoc
         */
        setValue: function(value, fromVM) {
          $super.setValue.call(this, value, fromVM);
          this._inputElement.value = value;
          this._elementState.backup(this._inputElement);
          this.setAriaAttribute("valuenow", value);
        },

        /**
         * @inheritDoc
         */
        getValue: function() {
          var value = parseInt(this._inputElement.value, 10);
          var isDefined = Object.isNumber(value) && !Object.isNaN(value);
          return isDefined ? value : '';
        },

        /**
         * Handler called when arrow up icon has been touched/click
         * @param {UIEvent} evt - DOM event
         */
        _onUpIcon: function(evt) {
          if (this.isEnabled() && !this.isReadOnly()) {
            this._increase();
            this.emit(context.constants.widgetEvents.change, false, true);
          }
        },

        /**
         * Handler called when arrow down icon has been touched/click
         * @param {UIEvent} evt - DOM event
         */
        _onDownIcon: function(evt) {
          if (this.isEnabled() && !this.isReadOnly()) {
            this._decrease();
            this.emit(context.constants.widgetEvents.change, false, true);
          }
        },

        /**
         * Update value
         * @param {number} factor - value to add
         */
        _updateValue: function(factor) {
          if (factor > 0) {
            this._increase(factor);
          } else if (factor < 0) {
            this._decrease(Math.abs(factor));
          }
        },

        /**
         * @inheritDoc
         */
        validateValue: function() {
          var valid = true;
          if (this._min && this.getValue() < this._min) {
            valid = false;
          }
          if (this._max && this.getValue() > this._max) {
            valid = false;
          }
          return valid;
        },

        /**
         * Increase value
         * @param {number} [factor=1] - value to add (default is 1)
         */
        _increase: function(factor) {
          var curVal = parseInt(this.getValue() ? this.getValue() : this._oldValue, 10);
          if (this._max && curVal > this._max) {
            this.setValue(this._max);
          }
          if (this._min && curVal < this._min) {
            this.setValue(this._min);
          } else {
            var newVal = (this._step * (factor && Object.isNumber(factor) ? factor : 1));
            newVal = curVal ? newVal + curVal : newVal;
            if (Object.isNumber(this._max) && newVal > this._max) {
              newVal = this._max;
            }
            this.setEditing(this._oldValue !== newVal);
            this.setValue(newVal);
          }
        },

        /**
         * Decrease value
         * @param {number} [factor=1] - value to remove (default is 1)
         */
        _decrease: function(factor) {
          var curVal = parseInt(this.getValue() ? this.getValue() : this._oldValue, 10);
          if (this._min && curVal < this._min) {
            this.setValue(this._min);
          } else if (this._max && curVal > this._max) {
            this.setValue(this._max);
          } else {
            var newVal = (this._step * (factor && Object.isNumber(factor) ? factor : 1));
            newVal = curVal ? curVal - newVal : -newVal;
            if (Object.isNumber(this._min) && newVal < this._min) {
              newVal = this._min;
            }
            this.setEditing(this._oldValue !== newVal);
            this.setValue(newVal);
          }
        },

        /**
         * Define the minimum possible value
         * @param {number} min - the minimum value
         * @publicdoc
         */
        setMin: function(min) {
          if (Object.isNumber(min)) {
            this._min = min;
          }
          this.setAriaAttribute("valuemin", min);
        },

        /**
         * Get minimum possible value
         * @returns {number} the minimum value
         * @publicdoc
         */
        getMin: function() {
          return this._min;
        },

        /**
         * Define the maximum possible value
         * @param {number} max - the maximum value
         * @publicdoc
         */
        setMax: function(max) {
          if (Object.isNumber(max)) {
            this._max = max;
          }
          this.setAriaAttribute("valuemax", max);
        },

        /**
         * Get maximum possible value
         * @returns {number} the maximum value
         * @publicdoc
         */
        getMax: function() {
          return this._max;
        },

        /**
         * Define the spinedit step when increasing or decreasing value
         * @param {number} step - the step value
         * @publicdoc
         */
        setStep: function(step) {
          var s = step && parseInt(step, 10);
          if (!s || Number.isNaN(s)) {
            s = 1;
          }
          this._step = s;
        },

        /**
         * Get spinedit step when increasing or decreasing value
         * @returns {number} the step value
         * @publicdoc
         */
        getStep: function() {
          return this._step;
        },

        /**
         * Returns if max length of the widget has been reached
         * @returns {boolean} return true if max length is reached in input element
         */
        _isMaxLength: function() {
          return this._maxLength !== -1 && this._inputElement.value.length >= this._maxLength &&
            this._inputElement.selectionStart === this._inputElement.selectionEnd;
        },

        /**
         * Defines if we can take more char than the widget width
         * @param {boolean} scroll true if the widget can 'scroll' his content (take more char than the widget width)
         * @publicdoc
         */
        setScroll: function(scroll) {
          var scrollModified = this._scroll !== scroll;
          this._scroll = scroll;

          if (scrollModified && !this._scroll && this._dataTypeWithValueCheck && this._maxLength > 0) {
            var widgetText = this.getValue();
            var res = this._checkValue("", widgetText);
            if (res !== widgetText) {
              this.setValue(res);
            }
          }
        },

        /**
         * Set to true if we must ignore the scroll attribute
         * @param {boolean} checkDisplayValue
         */
        setDataTypeWithNoScroll: function(checkDisplayValue) {
          this._dataTypeWithNoScroll = checkDisplayValue;
        },

        /**
         * Define the maximum number of characters allowed
         * @param {number} maxlength - maximum number of characters allowed in the field
         * @publicdoc
         */
        setMaxLength: function(maxlength) {
          if (maxlength) {
            this._maxLength = maxlength;
          }
        },

        /**
         * Get the maximum number of characters allowed
         * @returns {number} the maximum number of characters allowed in the field
         * @publicdoc
         */
        getMaxLength: function() {
          return this._maxLength;
        },

        /**
         * @inheritDoc
         */
        setReadOnly: function(readonly) {
          this._realReadOnly = readonly;
          if (this._isReadOnly !== readonly) {
            $super.setReadOnly.call(this, readonly);
            this._setInputReadOnly(this._realReadOnly || this._notEditable || !this._enabled);
          }
        },

        /**
         * Set input readonly attribute if it doesn't have focus or is noentry.
         * @param {boolean} readonly - true to set the edit part as read-only, false otherwise
         */
        _setInputReadOnly: function(readonly) {
          if (readonly) {
            this._inputElement.setAttribute('readonly', 'readonly');
          } else {
            this._inputElement.removeAttribute('readonly');
          }
        },

        /**
         * @inheritDoc
         */
        setFocus: function(fromMouse) {
          $super.setFocus.call(this, fromMouse);

          if (context.__wrapper.isGMA() && !this._showVirtualKeyboardOnFocus) {
            if (this._canShowVirtualKeyboard) {
              this._setInputReadOnly(this._realReadOnly || this._notEditable || !this._enabled);
            } else {
              this._setInputReadOnly(true);
            }
          }

          this._inputElement.domFocus();
          $super.setFocus.call(this, fromMouse);
        },

        /**
         * @inheritDoc
         */
        setDialogType: function(dialogType) {
          var oldDialogType = this._dialogType;

          $super.setDialogType.call(this, dialogType);

          if (dialogType === 'Display' || dialogType === 'DisplayArray') {
            return;
          }

          this._canShowVirtualKeyboard = oldDialogType === this._dialogType;
        },

        /**
         * @inheritDoc
         */
        setTitle: function(title) {
          $super.setTitle.call(this, title);
          this._inputElement.setAttribute('title', title);
        },

        /**
         * @inheritDoc
         */
        getTitle: function() {
          return this._inputElement.getAttribute('title');
        },

        /** Place the cursor at the given position,
         * @param {number} cursor - first cursor position
         * @param {number=} cursor2 - second cursor position
         * @publicdoc
         */
        setCursors: function(cursor, cursor2) {
          if (!cursor2) {
            cursor2 = cursor;
          }
          if (cursor2 && cursor2 < 0) {
            cursor2 = ('' + this.getValue()).length;
          }
          this._inputElement.setCursorPosition(cursor, cursor2);
        },

        /**
         * Get cursors
         * @return {{start: number, end: number}} object with cursors
         * @publicdoc
         */
        getCursors: function() {
          var cursors = {
            start: 0,
            end: 0
          };
          if (this._inputElement && this._inputElement.value) {
            try {
              cursors.start = this._inputElement.selectionStart;
              cursors.end = this._inputElement.selectionEnd;
            } catch (ignore) {
              // Some input types don't allow cursor manipulation
            }
          }
          return cursors;
        },

        /**
         * @inheritDoc
         */
        setEnabled: function(enabled) {
          var oldEnabled = this._enabled;
          var bEnabled = Boolean(enabled);

          if (this._dialogType !== 'Display' && this._dialogType !== 'DisplayArray' && this._dialogType !== false) {
            this._canShowVirtualKeyboard = !enabled || oldEnabled === bEnabled;
          }

          $super.setEnabled.call(this, enabled);
          this._setInputReadOnly(!enabled);
        },

        /**
         * @inheritDoc
         */
        setFontWeight: function(weight) {
          this.setStyle('input', {
            'font-weight': weight
          });
        },

        /**
         * @inheritDoc
         */
        getFontWeight: function() {
          return this.getStyle('input', 'font-weight');
        },

        /**
         * @inheritDoc
         */
        setFontStyle: function(style) {
          this.setStyle('input', {
            'font-style': style
          });
        },

        /**
         * @inheritDoc
         */
        getFontStyle: function() {
          return this.getStyle('input', 'font-style');
        },

        /**
         * @inheritDoc
         */
        setTextAlign: function(align) {
          this.setStyle('input', {
            'text-align': align
          });
        },

        /**
         * Set Default TTF color
         * @param {string} color - rgb formatted or css name
         */
        setDefaultTTFColor: function(color) {
          this.setStyle(".gbc_SpinEditWidget_arrows", {
            'color': color
          });
        },

        /**
         * @inheritDoc
         */
        getTextAlign: function() {
          return this.getStyle('input', 'text-align');
        },

        /**
         * @inheritDoc
         */
        getTextDecoration: function() {
          return this.getStyle('input', 'text-decoration');
        },

        /**
         * @inheritDoc
         */
        setTextDecoration: function(decoration) {
          this.setStyle('input', {
            'text-decoration': decoration
          });
        },

        /**
         * overrided since aria-required is not valid on spinbutton role
         * @inheritDoc
         */
        setRequired: function(required) {
          $super.setRequired.call(this, required);
          this.setAriaAttribute("required", null);
        },

        /**
         * Widget VM width
         * @param {number} width
         */
        setVMWidth: function(width) {
          this._vmWidth = width;
        },

        /**
         * @return {boolean} true if we can trigger autonext event
         */
        canAutoNext: function() {
          var text = this.getValue().toString();

          if (this._maxLength > 0) {
            return text.length >= this._maxLength;
          }

          return false;
        },

        /**
         * Verify the display width, the max length and the encoding according to the char/byte length semantics,
         * the width/max length of the widget and vm encoding
         * @param {Object} domEvent
         * @private
         */
        _verifyWidgetValue: function(event) {
          //If restored no need to control it again.
          if (this._elementState.isRestored()) {
            return;
          }

          //Manage display char (full/half) and length semantics constraints
          var widgetText = this._elementState.getValue();
          var inputValue = this._inputElement.value;

          if (widgetText.length >= inputValue.length) {
            this._elementState.backup(this._inputElement);
            //Less char in edit so no need to verify autonext
            return;
          } else {
            var newPart = this._elementState.newPart(inputValue);
            //If you need to make some char replacement do something like:
            //newPart = newPart.replace(....)
            var res = '';
            //On mobile isComposing=1 even for regular char
            if (!window.isMobile() && event.isComposing) {
              //When composing we can use invalid char to create a valid one
              //No need to verify autonext
              return;
            } else {
              res = this._checkValue(widgetText, newPart.removeUnknownChar());
            }

            if (res !== newPart) {
              this._elementState.restore(this._inputElement, res);
              this.setValue(this._inputElement.value);
              //Set restored to true to not trigger the autonext
              this._elementState.setRestored(true);
              return;
            }
          }
        },

        /**
         * @inheritDoc
         */
        _onInput: function(event) {
          $super._onInput.call(this);

          //Keyboard events are managed by manageKeyUp method
          if (!this._processingKeyEvent) {
            this._verifyWidgetValue(event);
          }
        },

        /**
         * Fix the newTextPart according to byte/char length and display width
         * @param  {string} text - widget valid value
         * @param {string} newTextPart - new text part
         * @return {string} a valid newTextPart
         * @private
         */
        _checkValue: function(text, newTextPart) {
          if (this._dialogType !== 'Input' && this._dialogType !== 'InputArray') {
            return newTextPart;
          }

          newTextPart = this.checkValueDisplayWidth(text, newTextPart);

          return newTextPart;
        },

        /**
         * True if you want to  show the virtual keyboard on GMA
         * @param {boolean} show
         */
        setShowVirtualKeyboardOnFocus: function(show) {
          this._showVirtualKeyboardOnFocus = show;
        },

        /**
         * @inheritDoc
         */
        getClipboardValue: function(ignoreSelection) {
          if (ignoreSelection) {
            return this.getValue();
          }

          var txt = cls.ClipboardHelper.getSelection();

          return txt.length > 0 ? txt : null;
        },

        /**
         * @inheritDoc
         */
        getClipboardAuthorizedAction: function() {
          return {
            paste: false,
            copy: true,
            cut: false
          };
        }

      };
    });
  });