]> git.proxmox.com Git - proxmox-widget-toolkit.git/blobdiff - src/Toolkit.js
api-viewer: eslint fixes, code cleanups
[proxmox-widget-toolkit.git] / src / Toolkit.js
index f7060366b53ef1644c8c216431d3ee9daadccca9..a08af4ef9a7926ecca06b036e313d4bf9bddea3a 100644 (file)
@@ -3,11 +3,6 @@
  // do not send '_dc' parameter
 Ext.Ajax.disableCaching = false;
 
-// FIXME: HACK! Makes scrolling in number spinner work again. fixed in ExtJS >= 6.1
-if (Ext.isFirefox) {
-    Ext.$eventNameMap.DOMMouseScroll = 'DOMMouseScroll';
-}
-
 // custom Vtypes
 Ext.apply(Ext.form.field.VTypes, {
     IPAddress: function(v) {
@@ -152,8 +147,7 @@ Ext.apply(Ext.form.field.VTypes, {
                Proxmox.Utils.HostPortBrackets_match.test(v) ||
                Proxmox.Utils.IP6_dotnotation_match.test(v);
     },
-
-    HostPortText: gettext('Not a valid hosts'),
+    HostPortText: gettext('Host/IP address or optional port is invalid'),
 
     HostList: function(v) {
        let list = v.split(/[ ,;]+/);
@@ -183,88 +177,10 @@ Ext.apply(Ext.form.field.VTypes, {
     },
 
     passwordText: gettext('Passwords do not match'),
-});
-
-// Firefox 52+ Touchscreen bug
-// see https://www.sencha.com/forum/showthread.php?336762-Examples-don-t-work-in-Firefox-52-touchscreen/page2
-// and https://bugzilla.proxmox.com/show_bug.cgi?id=1223
-Ext.define('EXTJS_23846.Element', {
-    override: 'Ext.dom.Element',
-}, function(Element) {
-    let supports = Ext.supports,
-        proto = Element.prototype,
-        eventMap = proto.eventMap,
-        additiveEvents = proto.additiveEvents;
-
-    if (Ext.os.is.Desktop && supports.TouchEvents && !supports.PointerEvents) {
-        eventMap.touchstart = 'mousedown';
-        eventMap.touchmove = 'mousemove';
-        eventMap.touchend = 'mouseup';
-        eventMap.touchcancel = 'mouseup';
-
-        additiveEvents.mousedown = 'mousedown';
-        additiveEvents.mousemove = 'mousemove';
-        additiveEvents.mouseup = 'mouseup';
-        additiveEvents.touchstart = 'touchstart';
-        additiveEvents.touchmove = 'touchmove';
-        additiveEvents.touchend = 'touchend';
-        additiveEvents.touchcancel = 'touchcancel';
-
-        additiveEvents.pointerdown = 'mousedown';
-        additiveEvents.pointermove = 'mousemove';
-        additiveEvents.pointerup = 'mouseup';
-        additiveEvents.pointercancel = 'mouseup';
-    }
-});
-
-Ext.define('EXTJS_23846.Gesture', {
-    override: 'Ext.event.publisher.Gesture',
-}, function(Gesture) {
-    let gestures = Gesture.instance;
 
-    if (Ext.supports.TouchEvents && !Ext.isWebKit && Ext.os.is.Desktop) {
-        gestures.handledDomEvents.push('mousedown', 'mousemove', 'mouseup');
-        gestures.registerEvents();
-    }
-});
-
-Ext.define('EXTJS_18900.Pie', {
-    override: 'Ext.chart.series.Pie',
-
-    // from 6.0.2
-    betweenAngle: function(x, a, b) {
-        let pp = Math.PI * 2,
-            offset = this.rotationOffset;
-
-        if (a === b) {
-            return false;
-        }
-
-        if (!this.getClockwise()) {
-            x *= -1;
-            a *= -1;
-            b *= -1;
-            a -= offset;
-            b -= offset;
-        } else {
-            a += offset;
-            b += offset;
-        }
-
-        x -= a;
-        b -= a;
-
-        // Normalize, so that both x and b are in the [0,360) interval.
-        x %= pp;
-        b %= pp;
-        x += pp;
-        b += pp;
-        x %= pp;
-        b %= pp;
-
-        // Because 360 * n angles will be normalized to 0,
-        // we need to treat b === 0 as a special case.
-        return x < b || b === 0;
+    email: function(value) {
+       let emailre = /^[\w+~-]+(\.[\w+~-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/;
+       return emailre.test(value);
     },
 });
 
@@ -307,20 +223,6 @@ Ext.define('Proxmox.UnderlayPool', {
     },
 });
 
-// 'Enter' in Textareas and aria multiline fields should not activate the
-// defaultbutton, fixed in extjs 6.0.2
-Ext.define('PVE.panel.Panel', {
-    override: 'Ext.panel.Panel',
-
-    fireDefaultButton: function(e) {
-       if (e.target.getAttribute('aria-multiline') === 'true' ||
-           e.target.tagName === "TEXTAREA") {
-           return true;
-       }
-       return this.callParent(arguments);
-    },
-});
-
 // if the order of the values are not the same in originalValue and value
 // extjs will not overwrite value, but marks the field dirty and thus
 // the reset button will be enabled (but clicking it changes nothing)
@@ -381,58 +283,105 @@ Ext.define(null, {
     jumpToFocus: false,
 
     saveFocusState: function() {
-       let me = this,
+       var me = this,
            store = me.dataSource,
            actionableMode = me.actionableMode,
            navModel = me.getNavigationModel(),
            focusPosition = actionableMode ? me.actionPosition : navModel.getPosition(true),
-           refocusRow, refocusCol;
-
-       if (focusPosition) {
+           activeElement = Ext.fly(Ext.Element.getActiveElement()),
+           focusCell = focusPosition && focusPosition.view === me &&
+           Ext.fly(focusPosition.getCell(true)),
+           refocusRow, refocusCol, record;
+
+       // The navModel may return a position that is in a locked partner, so check that
+       // the focusPosition's cell contains the focus before going forward.
+       // The skipSaveFocusState is set by Actionables which actively control
+       // focus destination. See CellEditing#activateCell.
+       if (!me.skipSaveFocusState && focusCell && focusCell.contains(activeElement)) {
            // Separate this from the instance that the nav model is using.
            focusPosition = focusPosition.clone();
 
-           // Exit actionable mode.
-           // We must inform any Actionables that they must relinquish control.
-           // Tabbability must be reset.
-           if (actionableMode) {
-               me.ownerGrid.setActionableMode(false);
+           // While we deactivate the focused element, suspend focus processing on it.
+           activeElement.suspendFocusEvents();
+
+           // Suspend actionable mode.
+           // Each Actionable must silently save its state ready to resume when focus
+           // can be restored but should only do that if the activeElement is not the cell itself,
+           // this happens when the grid is refreshed while one of the actionables is being
+           // deactivated (e.g. Calling  view refresh inside CellEditor 'edit' event listener).
+           if (actionableMode && focusCell.dom !== activeElement.dom) {
+               me.suspendActionableMode();
+           } else {
+               // Clear position, otherwise the setPosition on the other side
+               // will be rejected as a no-op if the resumption position is logically
+               // equivalent.
+               actionableMode = false;
+               navModel.setPosition();
            }
 
-           // Blur the focused descendant, but do not trigger focusLeave.
-           me.el.dom.focus();
+           // Do not leave the element in tht state in case refresh fails, and restoration
+           // closure not called.
+           activeElement.resumeFocusEvents();
 
-           // Exiting actionable mode navigates to the owning cell, so in either focus mode we must
-           // clear the navigation position
-           navModel.setPosition();
+           // if the store is expanding or collapsing, we should never scroll the view.
+           if (store.isExpandingOrCollapsing) {
+               return Ext.emptyFn;
+           }
 
            // The following function will attempt to refocus back in the same mode to the same cell
-           // as it was at before based upon the previous record (if it's still inthe store), or the row index.
+           // as it was at before based upon the previous record (if it's still in the store),
+           // or the row index.
            return function() {
+               var all;
+
+               // May have changed due to reconfigure
+               store = me.dataSource;
+
                // If we still have data, attempt to refocus in the same mode.
                if (store.getCount()) {
-                   // Adjust expectations of where we are able to refocus according to what kind of destruction
-                   // might have been wrought on this view's DOM during focus save.
-                   refocusRow = Math.min(focusPosition.rowIdx, me.all.getCount() - 1);
-                   refocusCol = Math.min(focusPosition.colIdx,
-                                         me.getVisibleColumnManager().getColumns().length - 1);
-                   refocusRow = store.contains(focusPosition.record) ? focusPosition.record : refocusRow;
-                   focusPosition = new Ext.grid.CellContext(me).setPosition(refocusRow, refocusCol);
-
-                   if (actionableMode) {
-                       me.ownerGrid.setActionableMode(true, focusPosition);
-                   } else {
-                       me.cellFocused = true;
-
-                       // we sometimes want to scroll back to where we were
-                       let x = me.getScrollX();
-                       let y = me.getScrollY();
-
-                       // Pass "preventNavigation" as true so that that does not cause selection.
-                       navModel.setPosition(focusPosition, null, null, null, true);
-
-                       if (!me.jumpToFocus) {
-                           me.scrollTo(x, y);
+                   all = me.all;
+
+                   // Adjust expectations of where we are able to refocus according to
+                   // what kind of destruction might have been wrought on this view's DOM
+                   // during focus save.
+                   refocusRow =
+                       Math.min(Math.max(focusPosition.rowIdx, all.startIndex), all.endIndex);
+
+                   refocusCol = Math.min(
+                       focusPosition.colIdx,
+                       me.getVisibleColumnManager().getColumns().length - 1,
+                   );
+
+                   record = focusPosition.record;
+
+                   focusPosition = new Ext.grid.CellContext(me).setPosition(
+                       record && store.contains(record) && !record.isCollapsedPlaceholder
+                       ? record
+                       : refocusRow,
+                       refocusCol,
+                   );
+
+                   // Maybe there are no cells. eg: all groups collapsed.
+                   if (focusPosition.getCell(true)) {
+                       if (actionableMode) {
+                           me.resumeActionableMode(focusPosition);
+                       } else {
+                           // we sometimes want to scroll back to where we are
+
+                           let x = me.getScrollX();
+                           let y = me.getScrollY();
+
+                           // Pass "preventNavigation" as true
+                           // so that that does not cause selection.
+                           navModel.setPosition(focusPosition, null, null, null, true);
+
+                           if (!navModel.getPosition()) {
+                               focusPosition.column.focus();
+                           }
+
+                           if (!me.jumpToFocus) {
+                               me.scrollTo(x, y);
+                           }
                        }
                    }
                } else { // No rows - focus associated column header
@@ -444,13 +393,6 @@ Ext.define(null, {
     },
 });
 
-// should be fixed with ExtJS 6.0.2, see:
-// https://www.sencha.com/forum/showthread.php?307244-Bug-with-datefield-in-window-with-scroll
-Ext.define('Proxmox.Datepicker', {
-    override: 'Ext.picker.Date',
-    hideMode: 'visibility',
-});
-
 // ExtJS 6.0.1 has no setSubmitValue() (although you find it in the docs).
 // Note: this.submitValue is a boolean flag, whereas getSubmitValue() returns
 // data to be submitted.
@@ -462,29 +404,96 @@ Ext.define('Proxmox.form.field.Text', {
     },
 });
 
-// this should be fixed with ExtJS 6.0.2
-// make mousescrolling work in firefox in the containers overflowhandler
+// make mousescrolling work in firefox in the containers overflowhandler,
+// by using only the 'wheel' event not 'mousewheel'(fixed in 7.3)
+// also reverse the scrolldirection (fixed in 7.3)
+// and reduce the default increment
 Ext.define(null, {
     override: 'Ext.layout.container.boxOverflow.Scroller',
 
-    createWheelListener: function() {
-       let me = this;
-       if (Ext.isFirefox) {
-           me.wheelListener = me.layout.innerCt.on('wheel', me.onMouseWheelFirefox, me, { destroyable: true });
+    wheelIncrement: 1,
+
+    getWheelDelta: function(e) {
+       return -e.getWheelDelta(e);
+    },
+
+    onOwnerRender: function(owner) {
+       var me = this,
+           scrollable = {
+               isBoxOverflowScroller: true,
+               x: false,
+               y: false,
+               listeners: {
+                   scrollend: this.onScrollEnd,
+                   scope: this,
+               },
+           };
+
+       // If no obstrusive scrollbars, allow natural scrolling on mobile touch devices
+       if (!Ext.scrollbar.width() && !Ext.platformTags.desktop) {
+           scrollable[owner.layout.horizontal ? 'x' : 'y'] = true;
        } else {
-           me.wheelListener = me.layout.innerCt.on('mousewheel', me.onMouseWheel, me, { destroyable: true });
+           me.wheelListener = me.layout.innerCt.on(
+               'wheel', me.onMouseWheel, me, { destroyable: true },
+           );
        }
-    },
 
-    // special wheel handler for firefox. differs from the default onMouseWheel
-    // handler by using deltaY instead of wheelDeltaY and no normalizing,
-    // because it is already
-    onMouseWheelFirefox: function(e) {
-       e.stopEvent();
-       let delta = e.browserEvent.deltaY || 0;
-       this.scrollBy(delta * this.wheelIncrement, false);
+       owner.setScrollable(scrollable);
     },
+});
+
+// extj 6.7 reversed mousewheel direction... (fixed in 7.3)
+// https://forum.sencha.com/forum/showthread.php?472517-Mousewheel-scroll-direction-in-numberfield-with-spinners
+// alse use the 'wheel' event instead of 'mousewheel' (fixed in 7.3)
+Ext.define('Proxmox.form.field.Spinner', {
+    override: 'Ext.form.field.Spinner',
+
+    onRender: function() {
+       var me = this,
+           spinnerTrigger = me.getTrigger('spinner');
+
+       me.callParent();
+
+       // Init up/down arrow keys
+       if (me.keyNavEnabled) {
+           me.spinnerKeyNav = new Ext.util.KeyNav({
+               target: me.inputEl,
+               scope: me,
+               up: me.spinUp,
+               down: me.spinDown,
+           });
+
+           me.inputEl.on({
+               keyup: me.onInputElKeyUp,
+               scope: me,
+           });
+       }
+
+       // Init mouse wheel
+       if (me.mouseWheelEnabled) {
+           me.mon(me.bodyEl, 'wheel', me.onMouseWheel, me);
+       }
 
+       // in v4 spinUpEl/spinDownEl were childEls, now they are children of the trigger.
+       // create references for compatibility
+       me.spinUpEl = spinnerTrigger.upEl;
+       me.spinDownEl = spinnerTrigger.downEl;
+    },
+
+    onMouseWheel: function(e) {
+       var me = this,
+           delta;
+       if (me.hasFocus) {
+           delta = e.getWheelDelta();
+           if (delta > 0) {
+               me.spinDown();
+           } else if (delta < 0) {
+               me.spinUp();
+           }
+           e.stopEvent();
+           me.onSpinEnd();
+       }
+    },
 });
 
 // add '@' to the valid id
@@ -493,11 +502,178 @@ Ext.define('Proxmox.validIdReOverride', {
     validIdRe: /^[a-z_][a-z0-9\-_@]*$/i,
 });
 
+Ext.define('Proxmox.selection.CheckboxModel', {
+    override: 'Ext.selection.CheckboxModel',
+
+    // [P] use whole checkbox cell to multiselect, not only the checkbox
+    checkSelector: '.x-grid-cell-row-checker',
+
+    // TODO: remove all optimizations below to an override for parent 'Ext.selection.Model' ??
+
+    // [ P: optimized to remove all records at once as single remove is O(n^3) slow ]
+    // records can be an index, a record or an array of records
+    doDeselect: function(records, suppressEvent) {
+        var me = this,
+            selected = me.selected,
+            i = 0,
+            len, record,
+            commit;
+        if (me.locked || !me.store) {
+            return false;
+        }
+        if (typeof records === "number") {
+            // No matching record, jump out
+            record = me.store.getAt(records);
+            if (!record) {
+                return false;
+            }
+            records = [
+                record,
+            ];
+        } else if (!Ext.isArray(records)) {
+            records = [
+                records,
+            ];
+        }
+       // [P] a beforedeselection, triggered by me.onSelectChange below, can block removal by
+       // returning false, thus the original implementation removed only here in the commit fn,
+       // which has an abysmal performance O(n^3). As blocking removal is not the norm, go do the
+       // reverse, record blocked records and remove them from the to-be-removed array before
+       // applying it. A FF86 i9-9900K on 10k records goes from >40s to ~33ms for >90% deselection
+       let committed = false;
+       commit = function() {
+           committed = true;
+           if (record === me.selectionStart) {
+               me.selectionStart = null;
+           }
+       };
+       let removalBlocked = [];
+        len = records.length;
+        me.suspendChanges();
+        for (; i < len; i++) {
+            record = records[i];
+            if (me.isSelected(record)) {
+               committed = false;
+                me.onSelectChange(record, false, suppressEvent, commit);
+               if (!committed) {
+                   removalBlocked.push(record);
+               }
+                if (me.destroyed) {
+                    return false;
+                }
+            }
+        }
+       if (removalBlocked.length > 0) {
+           records.remove(removalBlocked);
+       }
+       selected.remove(records); // [P] FAST(er)
+       me.lastSelected = selected.last();
+        me.resumeChanges();
+        // fire selchange if there was a change and there is no suppressEvent flag
+       me.maybeFireSelectionChange(records.length > 0 && !suppressEvent);
+       return records.length;
+    },
+
+
+    doMultiSelect: function(records, keepExisting, suppressEvent) {
+        var me = this,
+            selected = me.selected,
+            change = false,
+            result, i, len, record, commit;
+
+        if (me.locked) {
+            return;
+        }
+
+        records = !Ext.isArray(records) ? [records] : records;
+        len = records.length;
+        if (!keepExisting && selected.getCount() > 0) {
+            result = me.deselectDuringSelect(records, suppressEvent);
+            if (me.destroyed) {
+                return;
+            }
+            if (result[0]) {
+                // We had a failure during selection, so jump out
+                // Fire selection change if we did deselect anything
+                me.maybeFireSelectionChange(result[1] > 0 && !suppressEvent);
+                return;
+            } else {
+                // Means something has been deselected, so we've had a change
+                change = result[1] > 0;
+            }
+        }
+
+       let gotBlocked, blockedRecords = [];
+        commit = function() {
+            if (!selected.getCount()) {
+                me.selectionStart = record;
+            }
+           gotBlocked = false;
+            change = true;
+        };
+
+        for (i = 0; i < len; i++) {
+            record = records[i];
+            if (me.isSelected(record)) {
+                continue;
+            }
+
+           gotBlocked = true;
+            me.onSelectChange(record, true, suppressEvent, commit);
+            if (me.destroyed) {
+                return;
+            }
+           if (gotBlocked) {
+               blockedRecords.push(record);
+           }
+        }
+       if (blockedRecords.length > 0) {
+           records.remove(blockedRecords);
+       }
+        selected.add(records);
+        me.lastSelected = record;
+
+        // fire selchange if there was a change and there is no suppressEvent flag
+        me.maybeFireSelectionChange(change && !suppressEvent);
+    },
+    deselectDuringSelect: function(toSelect, suppressEvent) {
+        var me = this,
+            selected = me.selected.getRange(),
+            changed = 0,
+            failed = false;
+        // Prevent selection change events from firing, will happen during select
+        me.suspendChanges();
+        me.deselectingDuringSelect = true;
+       let toDeselect = selected.filter(item => !Ext.Array.contains(toSelect, item));
+       if (toDeselect.length > 0) {
+           changed = me.doDeselect(toDeselect, suppressEvent);
+           if (!changed) {
+               failed = true;
+            }
+            if (me.destroyed) {
+                failed = true;
+                changed = 0;
+            }
+        }
+        me.deselectingDuringSelect = false;
+        me.resumeChanges();
+        return [
+            failed,
+            changed,
+        ];
+    },
+});
+
+// stop nulling of properties
+Ext.define('Proxmox.Component', {
+    override: 'Ext.Component',
+    clearPropertiesOnDestroy: false,
+});
+
 // force alert boxes to be rendered with an Error Icon
 // since Ext.Msg is an object and not a prototype, we need to override it
 // after the framework has been initiated
 Ext.onReady(function() {
-/*jslint confusion: true */
     Ext.override(Ext.Msg, {
        alert: function(title, message, fn, scope) { // eslint-disable-line consistent-return
            if (Ext.isString(title)) {
@@ -514,7 +690,6 @@ Ext.onReady(function() {
            }
        },
     });
-/*jslint confusion: false */
 });
 Ext.define('Ext.ux.IFrame', {
     extend: 'Ext.Component',
@@ -615,7 +790,6 @@ Ext.define('Ext.ux.IFrame', {
                 // the event reaches listeners on elements like the document body. The effected
                 // mechanisms that depend on this bubbling behavior are listed to the right
                 // of the event.
-               /*jslint nomen: true*/
                 Ext.get(doc).on(
                     me._docListeners = {
                         mousedown: fn, // menu dismisal (MenuManager) and Window onMouseDown (toFront)
@@ -626,7 +800,6 @@ Ext.define('Ext.ux.IFrame', {
                         scope: me,
                     },
                 );
-               /*jslint nomen: false*/
             } catch (e) {
                 // cannot do this xss
             }