diff --git a/.eslintrc.json b/.eslintrc.json index bffd928f54..4cfddffa0d 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -57,6 +57,7 @@ "lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }], "max-classes-per-file": ["error", 3], "max-params": ["error", 4], + "no-else-return": "error", "no-eval": "error", "no-implicit-coercion": ["error", { "allow": ["!!"] }], "no-promise-executor-return": "error", @@ -66,7 +67,9 @@ "no-sync": "off", "no-throw-literal": "error", "no-useless-return": "error", + "prefer-const": ["error", { "ignoreReadBeforeAssign": true }], "prefer-exponentiation-operator": "error", + "prefer-object-spread": "error", "prefer-rest-params": "error", "prefer-spread": "error", "space-in-parens": ["error", "never"], diff --git a/packages/board/src/vaadin-board-row.js b/packages/board/src/vaadin-board-row.js index 6b213769c1..feda7e8113 100644 --- a/packages/board/src/vaadin-board-row.js +++ b/packages/board/src/vaadin-board-row.js @@ -203,7 +203,7 @@ class BoardRow extends ElementMixin(mixinBehaviors([IronResizableBehavior], Poly _removeExtraNodesFromDOM(boardCols, nodes) { let isErrorReported = false; let spaceLeft = 4; - let returnNodes = []; + const returnNodes = []; nodes.forEach((node, i) => { spaceLeft = spaceLeft - boardCols[i]; if (spaceLeft < 0) { @@ -253,7 +253,7 @@ class BoardRow extends ElementMixin(mixinBehaviors([IronResizableBehavior], Poly const boardCols = this._parseBoardCols(filteredNodes); const colsInRow = boardCols.reduce((a, b) => a + b, 0); this._removeExtraNodesFromDOM(boardCols, filteredNodes).forEach((e, i) => { - let newFlexBasis = this._calculateFlexBasis(boardCols[i], width, colsInRow, breakpoints); + const newFlexBasis = this._calculateFlexBasis(boardCols[i], width, colsInRow, breakpoints); if (forceResize || !this._oldFlexBasis[i] || this._oldFlexBasis[i] != newFlexBasis) { this._oldFlexBasis[i] = newFlexBasis; e.style.flexBasis = newFlexBasis; diff --git a/packages/charts/src/vaadin-chart-series.js b/packages/charts/src/vaadin-chart-series.js index 88fd54ed4d..70fe81ba7b 100644 --- a/packages/charts/src/vaadin-chart-series.js +++ b/packages/charts/src/vaadin-chart-series.js @@ -371,7 +371,7 @@ class ChartSeries extends PolymerElement { if (parent && parent instanceof Chart) { if (unit && !parent.__getAxis(unit)) { const title = { title: { text: unit } }; - parent.__addAxis(Object.assign({ id: unit, axisGenerated: true }, title)); + parent.__addAxis({ id: unit, axisGenerated: true, ...title }); } series.update({ yAxis: unit || 0 }); diff --git a/packages/charts/src/vaadin-chart.js b/packages/charts/src/vaadin-chart.js index 94334fc86a..606a2d16ff 100644 --- a/packages/charts/src/vaadin-chart.js +++ b/packages/charts/src/vaadin-chart.js @@ -526,7 +526,7 @@ class Chart extends ElementMixin(ThemableMixin(PolymerElement)) { return; } - const options = Object.assign({}, this.options, this._jsonConfigurationBuffer); + const options = { ...this.options, ...this._jsonConfigurationBuffer }; this._jsonConfigurationBuffer = null; this.__initChart(options); this.__addChildObserver(); @@ -540,7 +540,7 @@ class Chart extends ElementMixin(ThemableMixin(PolymerElement)) { * @return {!Options} */ get options() { - const options = Object.assign({}, this._baseConfig); + const options = { ...this._baseConfig }; deepMerge(options, this.additionalOptions); if (this.type) { @@ -635,7 +635,7 @@ class Chart extends ElementMixin(ThemableMixin(PolymerElement)) { if (this.chart3d) { options.chart = options.chart || {}; - options.chart.options3d = Object.assign({}, this._baseChart3d, options.chart.options3d); + options.chart.options3d = { ...this._baseChart3d, ...options.chart.options3d }; } return options; @@ -1146,7 +1146,7 @@ class Chart extends ElementMixin(ThemableMixin(PolymerElement)) { } if (resetConfiguration) { - const initialOptions = Object.assign({}, this.options, this._jsonConfigurationBuffer); + const initialOptions = { ...this.options, ...this._jsonConfigurationBuffer }; this.__initChart(initialOptions); @@ -1610,12 +1610,11 @@ class Chart extends ElementMixin(ThemableMixin(PolymerElement)) { if (chart3d) { config.update({ chart: { - options3d: Object.assign( - {}, - this._baseChart3d, - this.additionalOptions && this.additionalOptions.chart && this.additionalOptions.chart.options3d, - { enabled: true } - ) + options3d: { + ...this._baseChart3d, + ...(this.additionalOptions && this.additionalOptions.chart && this.additionalOptions.chart.options3d), + enabled: true + } } }); } else { diff --git a/packages/combo-box/src/vaadin-combo-box-data-provider-mixin.js b/packages/combo-box/src/vaadin-combo-box-data-provider-mixin.js index 44774b6a93..d21ef75b09 100644 --- a/packages/combo-box/src/vaadin-combo-box-data-provider-mixin.js +++ b/packages/combo-box/src/vaadin-combo-box-data-provider-mixin.js @@ -158,9 +158,8 @@ export const ComboBoxDataProviderMixin = (superClass) => const loadedItem = this.filteredItems[page * this.pageSize]; if (loadedItem !== undefined) { return loadedItem instanceof ComboBoxPlaceholder; - } else { - return this.size === undefined; } + return this.size === undefined; } /** @private */ diff --git a/packages/combo-box/src/vaadin-combo-box-light.js b/packages/combo-box/src/vaadin-combo-box-light.js index b38cca5a1f..d9f8ad6ed2 100644 --- a/packages/combo-box/src/vaadin-combo-box-light.js +++ b/packages/combo-box/src/vaadin-combo-box-light.js @@ -133,9 +133,8 @@ class ComboBoxLight extends ComboBoxDataProviderMixin(ComboBoxMixin(ThemableMixi checkValidity() { if (this.inputElement.validate) { return this.inputElement.validate(); - } else { - return super.checkValidity(); } + return super.checkValidity(); } /** diff --git a/packages/combo-box/src/vaadin-combo-box-scroller.js b/packages/combo-box/src/vaadin-combo-box-scroller.js index be35c6567a..b83a7cfca6 100644 --- a/packages/combo-box/src/vaadin-combo-box-scroller.js +++ b/packages/combo-box/src/vaadin-combo-box-scroller.js @@ -221,9 +221,8 @@ export class ComboBoxScroller extends PolymerElement { return false; } else if (itemIdPath && item !== undefined && selectedItem !== undefined) { return this.get(itemIdPath, item) === this.get(itemIdPath, selectedItem); - } else { - return item === selectedItem; } + return item === selectedItem; } /** @private */ diff --git a/packages/combo-box/test/combo-box-light.test.js b/packages/combo-box/test/combo-box-light.test.js index 4e3db15cac..ae93fe75e0 100644 --- a/packages/combo-box/test/combo-box-light.test.js +++ b/packages/combo-box/test/combo-box-light.test.js @@ -294,7 +294,7 @@ describe('custom buttons', () => { const y = Math.ceil(rect.top); // Get the element which would be targeted, when the user // tries to click on this position - let target = elementFromPointDeep(x, y, elem.ownerDocument); + const target = elementFromPointDeep(x, y, elem.ownerDocument); if (!target) { return; } diff --git a/packages/component-base/src/async.js b/packages/component-base/src/async.js index 797bddf4e1..1af65518c9 100644 --- a/packages/component-base/src/async.js +++ b/packages/component-base/src/async.js @@ -23,17 +23,17 @@ // Microtask implemented using Mutation Observer let microtaskCurrHandle = 0; let microtaskLastHandle = 0; -let microtaskCallbacks = []; +const microtaskCallbacks = []; let microtaskNodeContent = 0; let microtaskScheduled = false; -let microtaskNode = document.createTextNode(''); +const microtaskNode = document.createTextNode(''); new window.MutationObserver(microtaskFlush).observe(microtaskNode, { characterData: true }); function microtaskFlush() { microtaskScheduled = false; const len = microtaskCallbacks.length; for (let i = 0; i < len; i++) { - let cb = microtaskCallbacks[i]; + const cb = microtaskCallbacks[i]; if (cb) { try { cb(); diff --git a/packages/component-base/src/focus-utils.js b/packages/component-base/src/focus-utils.js index 15291db4be..a8d8408d73 100644 --- a/packages/component-base/src/focus-utils.js +++ b/packages/component-base/src/focus-utils.js @@ -217,7 +217,7 @@ export function isElementFocused(element) { * @return {HTMLElement[]} */ export function getFocusableElements(element) { - let focusableElements = []; + const focusableElements = []; const needsSortByTabIndex = collectFocusableNodes(element, focusableElements); // If there is at least one element with tabindex > 0, we need to sort // the final array by tabindex.≈ diff --git a/packages/component-base/src/gestures.js b/packages/component-base/src/gestures.js index 5e3cc5a3b5..906717676c 100644 --- a/packages/component-base/src/gestures.js +++ b/packages/component-base/src/gestures.js @@ -29,22 +29,22 @@ const cancelSyntheticClickEvents = true; const wrap = (node) => node; // detect native touch action support -let HAS_NATIVE_TA = typeof document.head.style.touchAction === 'string'; -let GESTURE_KEY = '__polymerGestures'; -let HANDLED_OBJ = '__polymerGesturesHandled'; -let TOUCH_ACTION = '__polymerGesturesTouchAction'; +const HAS_NATIVE_TA = typeof document.head.style.touchAction === 'string'; +const GESTURE_KEY = '__polymerGestures'; +const HANDLED_OBJ = '__polymerGesturesHandled'; +const TOUCH_ACTION = '__polymerGesturesTouchAction'; // radius for tap and track -let TAP_DISTANCE = 25; -let TRACK_DISTANCE = 5; +const TAP_DISTANCE = 25; +const TRACK_DISTANCE = 5; // number of last N track positions to keep -let TRACK_LENGTH = 2; +const TRACK_LENGTH = 2; // Disabling "mouse" handlers for 2500ms is enough -let MOUSE_TIMEOUT = 2500; -let MOUSE_EVENTS = ['mousedown', 'mousemove', 'mouseup', 'click']; +const MOUSE_TIMEOUT = 2500; +const MOUSE_EVENTS = ['mousedown', 'mousemove', 'mouseup', 'click']; // an array of bitmask values for mapping MouseEvent.which to MouseEvent.buttons -let MOUSE_WHICH_TO_BUTTONS = [0, 1, 4, 2]; -let MOUSE_HAS_BUTTONS = (function () { +const MOUSE_WHICH_TO_BUTTONS = [0, 1, 4, 2]; +const MOUSE_HAS_BUTTONS = (function () { try { return new MouseEvent('test', { buttons: 1 }).buttons === 1; } catch (e) { @@ -65,7 +65,7 @@ function isMouseEvent(name) { let supportsPassive = false; (function () { try { - let opts = Object.defineProperty({}, 'passive', { + const opts = Object.defineProperty({}, 'passive', { // eslint-disable-next-line getter-return get() { supportsPassive = true; @@ -94,7 +94,7 @@ function PASSIVE_TOUCH(eventName) { } // Check for touch-only devices -let IS_TOUCH_ONLY = navigator.userAgent.match(/iP(?:[oa]d|hone)|Android/); +const IS_TOUCH_ONLY = navigator.userAgent.match(/iP(?:[oa]d|hone)|Android/); // keep track of any labels hit by the mouseCanceller /** @type {!Array} */ @@ -146,10 +146,10 @@ function matchingLabels(el) { // as the mouseCancellor code will handle ancstor labels if (!labels.length) { labels = []; - let root = el.getRootNode(); + const root = el.getRootNode(); // if there is an id on `el`, check for all labels with a matching `for` attribute if (el.id) { - let matching = root.querySelectorAll(`label[for = ${el.id}]`); + const matching = root.querySelectorAll(`label[for = ${el.id}]`); for (let i = 0; i < matching.length; i++) { labels.push(/** @type {!HTMLLabelElement} */ (matching[i])); } @@ -168,7 +168,7 @@ function mouseCanceller(mouseEvent) { // if mouseEvent did not come from a device that fires touch events, // it was made by a real mouse and should be counted // http://wicg.github.io/InputDeviceCapabilities/#dom-inputdevicecapabilities-firestouchevents - let sc = mouseEvent.sourceCapabilities; + const sc = mouseEvent.sourceCapabilities; if (sc && !sc.firesTouchEvents) { return; } @@ -177,13 +177,13 @@ function mouseCanceller(mouseEvent) { // disable "ghost clicks" if (mouseEvent.type === 'click') { let clickFromLabel = false; - let path = getComposedPath(mouseEvent); + const path = getComposedPath(mouseEvent); for (let i = 0; i < path.length; i++) { if (path[i].nodeType === Node.ELEMENT_NODE) { if (path[i].localName === 'label') { clickedLabels.push(/** @type {!HTMLLabelElement} */ (path[i])); } else if (canBeLabelled(/** @type {!HTMLElement} */ (path[i]))) { - let ownerLabels = matchingLabels(/** @type {!HTMLElement} */ (path[i])); + const ownerLabels = matchingLabels(/** @type {!HTMLElement} */ (path[i])); // check if one of the clicked labels is labelling this element for (let j = 0; j < ownerLabels.length; j++) { clickFromLabel = clickFromLabel || clickedLabels.indexOf(ownerLabels[j]) > -1; @@ -209,7 +209,7 @@ function mouseCanceller(mouseEvent) { * @return {void} */ function setupTeardownMouseCanceller(setup) { - let events = IS_TOUCH_ONLY ? ['click'] : MOUSE_EVENTS; + const events = IS_TOUCH_ONLY ? ['click'] : MOUSE_EVENTS; for (let i = 0, en; i < events.length; i++) { en = events[i]; if (setup) { @@ -229,7 +229,7 @@ function ignoreMouse(e) { if (!POINTERSTATE.mouse.mouseIgnoreJob) { setupTeardownMouseCanceller(true); } - let unset = () => { + const unset = () => { setupTeardownMouseCanceller(); POINTERSTATE.mouse.target = null; POINTERSTATE.mouse.mouseIgnoreJob = null; @@ -247,7 +247,7 @@ function ignoreMouse(e) { * @return {boolean} has left mouse button down */ function hasLeftMouseButton(ev) { - let type = ev.type; + const type = ev.type; // exit early if the event is not a mouse event if (!isMouseEvent(type)) { return false; @@ -262,12 +262,11 @@ function hasLeftMouseButton(ev) { } // buttons is a bitmask, check that the left button bit is set (1) return Boolean(buttons & 1); - } else { - // allow undefined for testing events - let button = ev.button === undefined ? 0 : ev.button; - // ev.button is 0 in mousedown/mouseup/click for left button activation - return button === 0; } + // allow undefined for testing events + const button = ev.button === undefined ? 0 : ev.button; + // ev.button is 0 in mousedown/mouseup/click for left button activation + return button === 0; } function isSyntheticClick(ev) { @@ -279,15 +278,15 @@ function isSyntheticClick(ev) { // in the worst case, check that the x/y position of the click is within // the bounding box of the target of the event // Thanks IE 10 >:( - let t = _findOriginalTarget(ev); + const t = _findOriginalTarget(ev); // make sure the target of the event is an element so we can use getBoundingClientRect, // if not, just assume it is a synthetic click if (!t.nodeType || /** @type {Element} */ (t).nodeType !== Node.ELEMENT_NODE) { return true; } - let bcr = /** @type {Element} */ (t).getBoundingClientRect(); + const bcr = /** @type {Element} */ (t).getBoundingClientRect(); // use page x/y to account for scrolling - let x = ev.pageX, + const x = ev.pageX, y = ev.pageY; // ev is a synthetic click if the position is outside the bounding box of the target return !(x >= bcr.left && x <= bcr.right && y >= bcr.top && y <= bcr.bottom); @@ -310,7 +309,7 @@ let POINTERSTATE = { function firstTouchAction(ev) { let ta = 'auto'; - let path = getComposedPath(ev); + const path = getComposedPath(ev); for (let i = 0, n; i < path.length; i++) { n = path[i]; if (n[TOUCH_ACTION]) { @@ -376,7 +375,7 @@ export function deepTargetFind(x, y) { // if there is not a shadowroot, exit the loop while (next && next.shadowRoot && !window.ShadyDOM) { // if there is a node at x/y in the shadowroot, look deeper - let oldNext = next; + const oldNext = next; next = next.shadowRoot.elementFromPoint(x, y); // on Safari, elementFromPoint may return the shadowRoot host if (oldNext === next) { @@ -408,14 +407,13 @@ function _findOriginalTarget(ev) { * @return {void} */ function _handleNative(ev) { - let handled; - let type = ev.type; - let node = ev.currentTarget; - let gobj = node[GESTURE_KEY]; + const type = ev.type; + const node = ev.currentTarget; + const gobj = node[GESTURE_KEY]; if (!gobj) { return; } - let gs = gobj[type]; + const gs = gobj[type]; if (!gs) { return; } @@ -423,7 +421,7 @@ function _handleNative(ev) { ev[HANDLED_OBJ] = {}; if (type.slice(0, 5) === 'touch') { // ev = /** @type {TouchEvent} */ (ev); // eslint-disable-line no-self-assign - let t = ev.changedTouches[0]; + const t = ev.changedTouches[0]; if (type === 'touchstart') { // only handle the first finger if (ev.touches.length === 1) { @@ -440,7 +438,7 @@ function _handleNative(ev) { } } } - handled = ev[HANDLED_OBJ]; + const handled = ev[HANDLED_OBJ]; // used to ignore synthetic mouse events if (handled.skip) { return; @@ -470,8 +468,8 @@ function _handleNative(ev) { * @return {void} */ function _handleTouchAction(ev) { - let t = ev.changedTouches[0]; - let type = ev.type; + const t = ev.changedTouches[0]; + const type = ev.type; if (type === 'touchstart') { POINTERSTATE.touch.x = t.clientX; POINTERSTATE.touch.y = t.clientY; @@ -481,10 +479,10 @@ function _handleTouchAction(ev) { return; } POINTERSTATE.touch.scrollDecided = true; - let ta = firstTouchAction(ev); + const ta = firstTouchAction(ev); let shouldPrevent = false; - let dx = Math.abs(POINTERSTATE.touch.x - t.clientX); - let dy = Math.abs(POINTERSTATE.touch.y - t.clientY); + const dx = Math.abs(POINTERSTATE.touch.x - t.clientX); + const dy = Math.abs(POINTERSTATE.touch.y - t.clientY); if (!ev.cancelable) { // scrolling is happening } else if (ta === 'none') { @@ -545,9 +543,9 @@ export function removeListener(node, evType, handler) { * @return {void} */ function _add(node, evType, handler) { - let recognizer = gestures[evType]; - let deps = recognizer.deps; - let name = recognizer.name; + const recognizer = gestures[evType]; + const deps = recognizer.deps; + const name = recognizer.name; let gobj = node[GESTURE_KEY]; if (!gobj) { node[GESTURE_KEY] = gobj = {}; @@ -584,10 +582,10 @@ function _add(node, evType, handler) { * @return {void} */ function _remove(node, evType, handler) { - let recognizer = gestures[evType]; - let deps = recognizer.deps; - let name = recognizer.name; - let gobj = node[GESTURE_KEY]; + const recognizer = gestures[evType]; + const deps = recognizer.deps; + const name = recognizer.name; + const gobj = node[GESTURE_KEY]; if (gobj) { for (let i = 0, dep, gd; i < deps.length; i++) { dep = deps[i]; @@ -669,12 +667,12 @@ export function setTouchAction(node, value) { * @return {void} */ function _fire(target, type, detail) { - let ev = new Event(type, { bubbles: true, cancelable: true, composed: true }); + const ev = new Event(type, { bubbles: true, cancelable: true, composed: true }); ev.detail = detail; wrap(/** @type {!Node} */ (target)).dispatchEvent(ev); // forward `preventDefault` in a clean way if (ev.defaultPrevented) { - let preventer = detail.preventer || detail.sourceEvent; + const preventer = detail.preventer || detail.sourceEvent; if (preventer && preventer.preventDefault) { preventer.preventDefault(); } @@ -688,7 +686,7 @@ function _fire(target, type, detail) { * @return {void} */ export function prevent(evName) { - let recognizer = _findRecognizerByEvent(evName); + const recognizer = _findRecognizerByEvent(evName); if (recognizer.info) { recognizer.info.prevent = true; } @@ -740,16 +738,16 @@ register({ if (!hasLeftMouseButton(e)) { return; } - let t = _findOriginalTarget(e); + const t = _findOriginalTarget(e); // eslint-disable-next-line @typescript-eslint/no-this-alias - let self = this; - let movefn = (e) => { + const self = this; + const movefn = (e) => { if (!hasLeftMouseButton(e)) { downupFire('up', t, e); untrackDocument(self.info); } }; - let upfn = (e) => { + const upfn = (e) => { if (hasLeftMouseButton(e)) { downupFire('up', t, e); } @@ -851,11 +849,11 @@ register({ if (!hasLeftMouseButton(e)) { return; } - let t = _findOriginalTarget(e); + const t = _findOriginalTarget(e); // eslint-disable-next-line @typescript-eslint/no-this-alias - let self = this; - let movefn = (e) => { - let x = e.clientX, + const self = this; + const movefn = (e) => { + const x = e.clientX, y = e.clientY; if (trackHasMovedEnough(self.info, x, y)) { // first move is 'start', subsequent moves are 'move', mouseup is 'end' @@ -876,7 +874,7 @@ register({ self.info.started = true; } }; - let upfn = (e) => { + const upfn = (e) => { if (self.info.started) { movefn(e); } @@ -896,7 +894,7 @@ register({ * @return {void} */ touchstart: function (e) { - let ct = e.changedTouches[0]; + const ct = e.changedTouches[0]; this.info.x = ct.clientX; this.info.y = ct.clientY; }, @@ -907,9 +905,9 @@ register({ * @return {void} */ touchmove: function (e) { - let t = _findOriginalTarget(e); - let ct = e.changedTouches[0]; - let x = ct.clientX, + const t = _findOriginalTarget(e); + const ct = e.changedTouches[0]; + const x = ct.clientX, y = ct.clientY; if (trackHasMovedEnough(this.info, x, y)) { if (this.info.state === 'start') { @@ -929,8 +927,8 @@ register({ * @return {void} */ touchend: function (e) { - let t = _findOriginalTarget(e); - let ct = e.changedTouches[0]; + const t = _findOriginalTarget(e); + const ct = e.changedTouches[0]; // only trackend if track was started and not aborted if (this.info.started) { // reset started state on up @@ -954,8 +952,8 @@ function trackHasMovedEnough(info, x, y) { if (info.started) { return true; } - let dx = Math.abs(info.x - x); - let dy = Math.abs(info.y - y); + const dx = Math.abs(info.x - x); + const dy = Math.abs(info.y - y); return dx >= TRACK_DISTANCE || dy >= TRACK_DISTANCE; } @@ -969,10 +967,10 @@ function trackFire(info, target, touch) { if (!target) { return; } - let secondlast = info.moves[info.moves.length - 2]; - let lastmove = info.moves[info.moves.length - 1]; - let dx = lastmove.x - info.x; - let dy = lastmove.y - info.y; + const secondlast = info.moves[info.moves.length - 2]; + const lastmove = info.moves[info.moves.length - 1]; + const dx = lastmove.x - info.x; + const dy = lastmove.y - info.y; let ddx, ddy = 0; if (secondlast) { @@ -1069,10 +1067,10 @@ register({ * @return {void} */ function trackForward(info, e, preventer) { - let dx = Math.abs(e.clientX - info.x); - let dy = Math.abs(e.clientY - info.y); + const dx = Math.abs(e.clientX - info.x); + const dy = Math.abs(e.clientY - info.y); // find original target from `preventer` for TouchEvents, or `e` for MouseEvents - let t = _findOriginalTarget(preventer || e); + const t = _findOriginalTarget(preventer || e); if (!t || (canBeDisabled[/** @type {!HTMLElement} */ (t).localName] && t.hasAttribute('disabled'))) { return; } diff --git a/packages/context-menu/src/vaadin-context-menu.js b/packages/context-menu/src/vaadin-context-menu.js index 62f49e9ad9..052f576230 100644 --- a/packages/context-menu/src/vaadin-context-menu.js +++ b/packages/context-menu/src/vaadin-context-menu.js @@ -487,9 +487,8 @@ class ContextMenu extends ElementMixin(ThemePropertyMixin(ItemsMixin(PolymerElem return Array.prototype.filter.call(targets, (el) => { return e.composedPath().indexOf(el) > -1; })[0]; - } else { - return e.target; } + return e.target; } /** @@ -572,7 +571,7 @@ class ContextMenu extends ElementMixin(ThemePropertyMixin(ItemsMixin(PolymerElem // in the `vaadin-overlay-change` which guarantees that overlay is ready. // The valus represent an anchor position on the page where the contextmenu // event took place. - let x = this.__x; + const x = this.__x; const y = this.__y; // Select one overlay corner and move to the event x/y position. @@ -634,10 +633,9 @@ class ContextMenu extends ElementMixin(ThemePropertyMixin(ItemsMixin(PolymerElem // Native keyboard event const rect = event.target.getBoundingClientRect(); return coord === 'x' ? rect.left : rect.top + rect.height; - } else { - // Native mouse or touch event - return position; } + // Native mouse or touch event + return position; } } diff --git a/packages/context-menu/test/items.test.js b/packages/context-menu/test/items.test.js index b178bce769..1fae524acc 100644 --- a/packages/context-menu/test/items.test.js +++ b/packages/context-menu/test/items.test.js @@ -617,7 +617,7 @@ describe('items', () => { rootMenu.items[1].theme = ['bar-1', 'bar-2', 'bar-3']; await updateItemsAndReopen(); - let rootItems = getMenuItems(); + const rootItems = getMenuItems(); expect(rootItems[1].getAttribute('theme')).to.equal('bar-1 bar-2 bar-3'); }); }); diff --git a/packages/crud/src/vaadin-crud.js b/packages/crud/src/vaadin-crud.js index 2d6a4a9422..56c2a1578a 100644 --- a/packages/crud/src/vaadin-crud.js +++ b/packages/crud/src/vaadin-crud.js @@ -1173,7 +1173,7 @@ class Crud extends SlotMixin(ElementMixin(ThemableMixin(PolymerElement))) { return; } - const item = Object.assign({}, this.editedItem); + const item = { ...this.editedItem }; this._fields.forEach((e) => { const path = e.path || e.getAttribute('path'); path && this.__set(path, e.value, item); diff --git a/packages/crud/test/crud.test.js b/packages/crud/test/crud.test.js index 55037712da..896c2ac92f 100644 --- a/packages/crud/test/crud.test.js +++ b/packages/crud/test/crud.test.js @@ -56,7 +56,7 @@ describe('crud', () => { it('should be able to internationalize via `i18n` property', async () => { expect(crud.$.new.textContent).to.be.equal('New item'); - crud.i18n = Object.assign({}, crud.i18n, { newItem: 'Nueva entidad', editLabel: 'Editar entidad' }); + crud.i18n = { ...crud.i18n, newItem: 'Nueva entidad', editLabel: 'Editar entidad' }; await nextRender(crud._grid); expect(crud.$.new.textContent).to.be.equal('Nueva entidad'); expect(crud._grid.querySelector('vaadin-crud-edit-column').ariaLabel).to.be.equal('Editar entidad'); @@ -616,7 +616,7 @@ describe('crud', () => { it('on save should keep item unmodified if default prevented', () => { listenOnce(crud, 'save', (e) => e.preventDefault()); - const originalItem = Object.assign({}, crud.items[0]); + const originalItem = { ...crud.items[0] }; edit(crud.items[0]); crud._fields[0].value = 'Modified'; change(crud._form); @@ -626,7 +626,7 @@ describe('crud', () => { }); it('on save should modify item if not default prevented', () => { - const originalItem = Object.assign({}, crud.items[0]); + const originalItem = { ...crud.items[0] }; edit(crud.items[0]); crud._fields[0].value = 'Modified'; change(crud._form); diff --git a/packages/date-picker/src/vaadin-date-picker-overlay-content.js b/packages/date-picker/src/vaadin-date-picker-overlay-content.js index 216b937bb0..9c6afc9915 100644 --- a/packages/date-picker/src/vaadin-date-picker-overlay-content.js +++ b/packages/date-picker/src/vaadin-date-picker-overlay-content.js @@ -478,9 +478,8 @@ class DatePickerOverlayContent extends ThemableMixin(DirMixin(PolymerElement)) { _formatDisplayed(date, formatDate, label) { if (date) { return formatDate(extractDateParts(date)); - } else { - return label; } + return label; } _onTodayTap() { diff --git a/packages/date-time-picker/src/vaadin-date-time-picker.js b/packages/date-time-picker/src/vaadin-date-time-picker.js index 7af7d65fc9..027a17c031 100644 --- a/packages/date-time-picker/src/vaadin-date-time-picker.js +++ b/packages/date-time-picker/src/vaadin-date-time-picker.js @@ -326,7 +326,7 @@ class DateTimePicker extends FieldMixin(SlotMixin(DisabledMixin(ThemableMixin(El */ i18n: { type: Object, - value: () => Object.assign({}, datePickerI18nDefaults, timePickerI18nDefaults) + value: () => ({ ...datePickerI18nDefaults, ...timePickerI18nDefaults }) } }; } diff --git a/packages/dialog/src/vaadin-dialog.js b/packages/dialog/src/vaadin-dialog.js index 8b2b4289cb..f00fad6a7b 100644 --- a/packages/dialog/src/vaadin-dialog.js +++ b/packages/dialog/src/vaadin-dialog.js @@ -73,7 +73,7 @@ export class DialogOverlay extends mixinBehaviors(IronResizableBehavior, Overlay */ setBounds(bounds) { const overlay = this.$.overlay; - const parsedBounds = Object.assign({}, bounds); + const parsedBounds = { ...bounds }; if (overlay.style.position !== 'absolute') { overlay.style.position = 'absolute'; diff --git a/packages/field-base/src/input-constraints-mixin.js b/packages/field-base/src/input-constraints-mixin.js index e73a972cb6..074af4286f 100644 --- a/packages/field-base/src/input-constraints-mixin.js +++ b/packages/field-base/src/input-constraints-mixin.js @@ -49,9 +49,8 @@ export const InputConstraintsMixin = dedupingMixin( checkValidity() { if (this.inputElement && this._hasValidConstraints(this.constructor.constraints.map((c) => this[c]))) { return this.inputElement.checkValidity(); - } else { - return !this.invalid; } + return !this.invalid; } /** diff --git a/packages/grid-pro/test/edit-column-renderer.test.js b/packages/grid-pro/test/edit-column-renderer.test.js index 9739696c3a..5e9725d051 100644 --- a/packages/grid-pro/test/edit-column-renderer.test.js +++ b/packages/grid-pro/test/edit-column-renderer.test.js @@ -229,7 +229,7 @@ describe('edit column renderer', () => { it('should close editor and update value when scrolling edited cell out of view', () => { grid.items = null; - grid.items = Array.from({ length: 30 }, () => Object.assign({}, createItems()[0])); + grid.items = Array.from({ length: 30 }, () => ({ ...createItems()[0] })); flushGrid(grid); cell = getContainerCell(grid.$.items, 0, 0); diff --git a/packages/grid-pro/test/visual/users.js b/packages/grid-pro/test/visual/users.js index 7231a34a95..f72f3f8436 100644 --- a/packages/grid-pro/test/visual/users.js +++ b/packages/grid-pro/test/visual/users.js @@ -146,7 +146,7 @@ function capitalize(lower) { } const users = data.map((item) => { - const user = Object.assign({}, item); + const user = { ...item }; user.name.first = capitalize(user.name.first); user.name.last = capitalize(user.name.last); user.location.city = capitalize(user.location.city); diff --git a/packages/grid/src/array-data-provider.js b/packages/grid/src/array-data-provider.js index 19b6e316f2..41e960605b 100644 --- a/packages/grid/src/array-data-provider.js +++ b/packages/grid/src/array-data-provider.js @@ -22,7 +22,7 @@ function checkPaths(arrayToCheck, action, items) { let result = true; - for (let i in arrayToCheck) { + for (const i in arrayToCheck) { const path = arrayToCheck[i].path; // skip simple paths @@ -73,9 +73,8 @@ function normalizeEmptyValue(value) { return ''; } else if (isNaN(value)) { return value.toString(); - } else { - return value; } + return value; } /** diff --git a/packages/grid/src/vaadin-grid-column-reordering-mixin.js b/packages/grid/src/vaadin-grid-column-reordering-mixin.js index 56ce3a4784..3b8581a59d 100644 --- a/packages/grid/src/vaadin-grid-column-reordering-mixin.js +++ b/packages/grid/src/vaadin-grid-column-reordering-mixin.js @@ -338,9 +338,8 @@ export const ColumnReorderingMixin = (superClass) => const targetRect = targetCell.getBoundingClientRect(); if (targetRect.left > sourceCellRect.left) { return clientX > targetRect.right - sourceCellRect.width; - } else { - return clientX < targetRect.left + sourceCellRect.width; } + return clientX < targetRect.left + sourceCellRect.width; } /** @@ -370,9 +369,8 @@ export const ColumnReorderingMixin = (superClass) => } if (candidate.parentElement === draggedColumn.parentElement) { return candidate; - } else { - return targetCell._column; } + return targetCell._column; } } diff --git a/packages/grid/src/vaadin-grid-column.js b/packages/grid/src/vaadin-grid-column.js index 0e76dd93f7..94f4b296b9 100644 --- a/packages/grid/src/vaadin-grid-column.js +++ b/packages/grid/src/vaadin-grid-column.js @@ -30,9 +30,8 @@ export const ColumnBaseMixin = (superClass) => const parent = this.parentNode; if (parent && parent.localName === 'vaadin-grid-column-group') { return parent.resizable || false; - } else { - return false; } + return false; } }, diff --git a/packages/grid/src/vaadin-grid-dynamic-columns-mixin.js b/packages/grid/src/vaadin-grid-dynamic-columns-mixin.js index d4c690735e..cd189dbea8 100644 --- a/packages/grid/src/vaadin-grid-dynamic-columns-mixin.js +++ b/packages/grid/src/vaadin-grid-dynamic-columns-mixin.js @@ -54,9 +54,8 @@ export const DynamicColumnsMixin = (superClass) => .map((col) => { if (col.localName === 'vaadin-grid-column-group') { return this._getChildColumns(col); - } else { - return [col]; } + return [col]; }) .reduce((prev, curr) => { return prev.concat(curr); diff --git a/packages/grid/src/vaadin-grid-keyboard-navigation-mixin.js b/packages/grid/src/vaadin-grid-keyboard-navigation-mixin.js index 50435d66bf..ef09f4c543 100644 --- a/packages/grid/src/vaadin-grid-keyboard-navigation-mixin.js +++ b/packages/grid/src/vaadin-grid-keyboard-navigation-mixin.js @@ -300,13 +300,12 @@ export const KeyboardNavigationMixin = (superClass) => // "If focus is on a collapsed row, expands the row." this.expandItem(activeRow._item); return; - } else { - // "If focus is on an expanded row or is on a row that does not have child rows, - // moves focus to the first cell in the row." - this.__rowFocusMode = false; - this._onCellNavigation(activeRow.firstElementChild, 0, 0); - return; } + // "If focus is on an expanded row or is on a row that does not have child rows, + // moves focus to the first cell in the row." + this.__rowFocusMode = false; + this._onCellNavigation(activeRow.firstElementChild, 0, 0); + return; } } else if (key === backwardsKey) { // "Left Arrow:" @@ -358,9 +357,8 @@ export const KeyboardNavigationMixin = (superClass) => // Body rows have index property, otherwise DOM child index of the row is used. if (rowGroup === this.$.items) { return bodyFallbackIndex !== undefined ? bodyFallbackIndex : row.index; - } else { - return this.__getIndexOfChildElement(row); } + return this.__getIndexOfChildElement(row); } /** @@ -396,51 +394,47 @@ export const KeyboardNavigationMixin = (superClass) => this.toggleAttribute('navigating', true); return { dstRow: activeRowGroup.children[dstRowIndex] }; - } else { - // Navigating body rows - - let dstIsRowDetails = false; - if (activeCell) { - const isRowDetails = this.__isDetailsCell(activeCell); - // Row details navigation logic - if (activeRowGroup === this.$.items) { - const item = activeRow._item; - const dstItem = this._cache.getItemForIndex(dstRowIndex); - // Should we navigate to row details? - if (isRowDetails) { - dstIsRowDetails = dy === 0; - } else { - dstIsRowDetails = - (dy === 1 && this._isDetailsOpened(item)) || - (dy === -1 && dstRowIndex !== currentRowIndex && this._isDetailsOpened(dstItem)); - } - // Should we navigate between details and regular cells of the same row? - if ( - dstIsRowDetails !== isRowDetails && - ((dy === 1 && dstIsRowDetails) || (dy === -1 && !dstIsRowDetails)) - ) { - dstRowIndex = currentRowIndex; - } + } + // Navigating body rows + + let dstIsRowDetails = false; + if (activeCell) { + const isRowDetails = this.__isDetailsCell(activeCell); + // Row details navigation logic + if (activeRowGroup === this.$.items) { + const item = activeRow._item; + const dstItem = this._cache.getItemForIndex(dstRowIndex); + // Should we navigate to row details? + if (isRowDetails) { + dstIsRowDetails = dy === 0; + } else { + dstIsRowDetails = + (dy === 1 && this._isDetailsOpened(item)) || + (dy === -1 && dstRowIndex !== currentRowIndex && this._isDetailsOpened(dstItem)); + } + // Should we navigate between details and regular cells of the same row? + if (dstIsRowDetails !== isRowDetails && ((dy === 1 && dstIsRowDetails) || (dy === -1 && !dstIsRowDetails))) { + dstRowIndex = currentRowIndex; } } + } - // Ensure correct vertical scroll position, destination row is visible - this._ensureScrolledToIndex(dstRowIndex); + // Ensure correct vertical scroll position, destination row is visible + this._ensureScrolledToIndex(dstRowIndex); - // When scrolling with repeated keydown, sometimes FocusEvent listeners - // are too late to update _focusedItemIndex. Ensure next keydown - // listener invocation gets updated _focusedItemIndex value. - this._focusedItemIndex = dstRowIndex; + // When scrolling with repeated keydown, sometimes FocusEvent listeners + // are too late to update _focusedItemIndex. Ensure next keydown + // listener invocation gets updated _focusedItemIndex value. + this._focusedItemIndex = dstRowIndex; - // This has to be set after scrolling, otherwise it can be removed by - // `_preventScrollerRotatingCellFocus(row, index)` during scrolling. - this.toggleAttribute('navigating', true); + // This has to be set after scrolling, otherwise it can be removed by + // `_preventScrollerRotatingCellFocus(row, index)` during scrolling. + this.toggleAttribute('navigating', true); - return { - dstRow: [...activeRowGroup.children].find((el) => !el.hidden && el.index === dstRowIndex), - dstIsRowDetails - }; - } + return { + dstRow: [...activeRowGroup.children].find((el) => !el.hidden && el.index === dstRowIndex), + dstIsRowDetails + }; } /** diff --git a/packages/grid/test/column-groups.test.js b/packages/grid/test/column-groups.test.js index 42381d0040..3c82565641 100644 --- a/packages/grid/test/column-groups.test.js +++ b/packages/grid/test/column-groups.test.js @@ -466,8 +466,8 @@ describe('column groups', () => { }); it('should correctly set column order', async () => { - let col19 = grid.querySelector('#col19'); - let col20 = grid.querySelector('#col20'); + const col19 = grid.querySelector('#col19'); + const col20 = grid.querySelector('#col20'); await nextFrame(); expect(col19._order).to.be.lessThan(col20._order); }); @@ -493,8 +493,8 @@ describe('column groups', () => { }); it('should correctly set column order when we have more than 100 columns', async () => { - let col99 = grid.querySelector('#col99'); - let col100 = grid.querySelector('#col100'); + const col99 = grid.querySelector('#col99'); + const col100 = grid.querySelector('#col100'); await nextFrame(); expect(col99._order).to.be.lessThan(col100._order); }); diff --git a/packages/grid/test/helpers.js b/packages/grid/test/helpers.js index 6d15422697..7eae489618 100644 --- a/packages/grid/test/helpers.js +++ b/packages/grid/test/helpers.js @@ -227,7 +227,7 @@ export const makeSoloTouchEvent = (type, xy, node) => { changedTouches: touches }; const event = new CustomEvent(type, { bubbles: true, cancelable: true }); - for (let property in touchEventInit) { + for (const property in touchEventInit) { event[property] = touchEventInit[property]; } node.dispatchEvent(event); diff --git a/packages/grid/test/keyboard-navigation-row-focus.test.js b/packages/grid/test/keyboard-navigation-row-focus.test.js index 0a89a0c58e..aa95249955 100644 --- a/packages/grid/test/keyboard-navigation-row-focus.test.js +++ b/packages/grid/test/keyboard-navigation-row-focus.test.js @@ -96,9 +96,8 @@ function getFocusedCellIndex() { const focusedCell = grid.shadowRoot.activeElement; if (focusedCell instanceof HTMLTableCellElement) { return Array.from(focusedCell.parentNode.children).indexOf(focusedCell); - } else { - return -1; } + return -1; } function getFocusedRowIndex() { diff --git a/packages/grid/test/visual/users.js b/packages/grid/test/visual/users.js index e4f4105201..57fa232b6c 100644 --- a/packages/grid/test/visual/users.js +++ b/packages/grid/test/visual/users.js @@ -2806,7 +2806,7 @@ function capitalize(lower) { } const users = data.map((item) => { - const user = Object.assign({}, item); + const user = { ...item }; user.name.first = capitalize(user.name.first); user.name.last = capitalize(user.name.last); user.location.city = capitalize(user.location.city); diff --git a/packages/login/test/login-form.test.js b/packages/login/test/login-form.test.js index ddb0310489..95fd4ceba5 100644 --- a/packages/login/test/login-form.test.js +++ b/packages/login/test/login-form.test.js @@ -112,10 +112,11 @@ describe('login form', () => { expect(additionalInformation.textContent).to.be.equal(''); expect(formWrapper.$.forgotPasswordButton.textContent).to.be.equal(login.i18n.form.forgotPassword); - const i18n = Object.assign({}, login.i18n, { + const i18n = { + ...login.i18n, additionalInformation: 'Mais informações', form: { forgotPassword: 'Esqueci a senha' } - }); + }; login.i18n = i18n; expect(additionalInformation.textContent).to.be.equal(login.i18n.additionalInformation); expect(formWrapper.$.forgotPasswordButton.textContent).to.be.equal(login.i18n.form.forgotPassword); diff --git a/packages/login/test/login-overlay.test.js b/packages/login/test/login-overlay.test.js index 0ad9a1ae39..eeea2aece5 100644 --- a/packages/login/test/login-overlay.test.js +++ b/packages/login/test/login-overlay.test.js @@ -155,9 +155,7 @@ describe('title and description', () => { }); it('should update title and description when i18n.header updated', () => { - const i18n = Object.assign({}, overlay.i18n, { - header: { title: 'The newest title', description: 'The newest description' } - }); + const i18n = { ...overlay.i18n, header: { title: 'The newest title', description: 'The newest description' } }; overlay.i18n = i18n; expect(headerElement.textContent).to.be.equal('The newest title'); diff --git a/packages/menu-bar/src/vaadin-menu-bar-buttons-mixin.js b/packages/menu-bar/src/vaadin-menu-bar-buttons-mixin.js index 9980c35200..186e95b00a 100644 --- a/packages/menu-bar/src/vaadin-menu-bar-buttons-mixin.js +++ b/packages/menu-bar/src/vaadin-menu-bar-buttons-mixin.js @@ -181,7 +181,7 @@ export const ButtonsMixin = (superClass) => const button = document.createElement('vaadin-menu-bar-button'); button.setAttribute('part', 'menu-bar-button'); - const itemCopy = Object.assign({}, item); + const itemCopy = { ...item }; button.item = itemCopy; if (item.component) { diff --git a/packages/message-list/test/message-list.test.js b/packages/message-list/test/message-list.test.js index 786da98564..66ee9fe22a 100644 --- a/packages/message-list/test/message-list.test.js +++ b/packages/message-list/test/message-list.test.js @@ -18,7 +18,7 @@ describe('message-list', () => { let messageList, messages; beforeEach(() => { - let root = document.documentElement; + const root = document.documentElement; root.style.setProperty('--vaadin-user-color-1', 'purple'); root.style.setProperty('--vaadin-user-color-2', 'blue'); diff --git a/packages/notification/src/vaadin-notification.js b/packages/notification/src/vaadin-notification.js index ba65262a42..6edc5c7438 100644 --- a/packages/notification/src/vaadin-notification.js +++ b/packages/notification/src/vaadin-notification.js @@ -490,11 +490,10 @@ class Notification extends ThemePropertyMixin(ElementMixin(PolymerElement)) { return Notification._createAndShowNotification((root) => { render(contents, root); }, options); - } else { - return Notification._createAndShowNotification((root) => { - root.innerText = contents; - }, options); } + return Notification._createAndShowNotification((root) => { + root.innerText = contents; + }, options); } /** @private */ diff --git a/packages/number-field/src/vaadin-number-field.js b/packages/number-field/src/vaadin-number-field.js index a13e180acb..91e691f679 100644 --- a/packages/number-field/src/vaadin-number-field.js +++ b/packages/number-field/src/vaadin-number-field.js @@ -348,9 +348,8 @@ export class NumberField extends InputFieldMixin(SlotStylesMixin(ThemableMixin(E return (currentValue - margin + step) / multiplier; } else if (incr < 0) { return (currentValue - (margin || step)) / multiplier; - } else { - return currentValue / multiplier; } + return currentValue / multiplier; } /** @private */ @@ -373,9 +372,8 @@ export class NumberField extends InputFieldMixin(SlotStylesMixin(ThemableMixin(E return this.min == null || this._getIncrement(incr, value) >= this.min; } else if (incr > 0) { return this.max == null || this._getIncrement(incr, value) <= this.max; - } else { - return this._getIncrement(incr, value) <= this.max && this._getIncrement(incr, value) >= this.min; } + return this._getIncrement(incr, value) <= this.max && this._getIncrement(incr, value) >= this.min; } /** @private */ @@ -470,9 +468,8 @@ export class NumberField extends InputFieldMixin(SlotStylesMixin(ThemableMixin(E (this.required || this.min !== undefined || this.max !== undefined || this.__validateByStep) ) { return this.inputElement.checkValidity(); - } else { - return !this.invalid; } + return !this.invalid; } } diff --git a/packages/upload/src/vaadin-upload.js b/packages/upload/src/vaadin-upload.js index 0fb119cd5d..2768961930 100644 --- a/packages/upload/src/vaadin-upload.js +++ b/packages/upload/src/vaadin-upload.js @@ -748,7 +748,7 @@ class Upload extends ElementMixin(ThemableMixin(PolymerElement)) { /** @private */ _notifyFileChanges(file) { var p = 'files.' + this.files.indexOf(file) + '.'; - for (let i in file) { + for (const i in file) { // eslint-disable-next-line no-prototype-builtins if (file.hasOwnProperty(i)) { this.notifyPath(p + i, file[i]); diff --git a/packages/vaadin-themable-mixin/test/lit-setup.js b/packages/vaadin-themable-mixin/test/lit-setup.js index 96144af527..b4b6a54ca4 100644 --- a/packages/vaadin-themable-mixin/test/lit-setup.js +++ b/packages/vaadin-themable-mixin/test/lit-setup.js @@ -22,9 +22,8 @@ window.defineCustomElementFunction = (name, parentName, content, styles) => { const template = document.createElement('template'); template.innerHTML = content; return template.content; - } else { - return super.render(); } + return super.render(); } } diff --git a/packages/vaadin-themable-mixin/test/register-styles.test.js b/packages/vaadin-themable-mixin/test/register-styles.test.js index 941d5f541e..81c8b50ab2 100644 --- a/packages/vaadin-themable-mixin/test/register-styles.test.js +++ b/packages/vaadin-themable-mixin/test/register-styles.test.js @@ -6,7 +6,7 @@ import { ThemableMixin } from '../vaadin-themable-mixin.js'; let attachedInstances = []; -let define = +const define = window.defineCustomElementFunction || ((name) => { customElements.define( diff --git a/packages/vaadin-themable-mixin/test/themable-mixin.test.js b/packages/vaadin-themable-mixin/test/themable-mixin.test.js index 5a745c50dd..6ac1f45234 100644 --- a/packages/vaadin-themable-mixin/test/themable-mixin.test.js +++ b/packages/vaadin-themable-mixin/test/themable-mixin.test.js @@ -3,13 +3,13 @@ import { fixtureSync, nextFrame } from '@vaadin/testing-helpers'; import { PolymerElement } from '@polymer/polymer/polymer-element.js'; import { css, registerStyles, ThemableMixin, unsafeCSS } from '../vaadin-themable-mixin.js'; -let createStyles = +const createStyles = window.createStylesFunction || ((moduleId, themeFor, styles) => { registerStyles(themeFor, styles, { moduleId }); }); -let defineCustomElement = +const defineCustomElement = window.defineCustomElementFunction || ((name, parentName, content, styles) => { const parentElement = parentName ? customElements.get(parentName) : PolymerElement; @@ -27,9 +27,8 @@ let defineCustomElement = const template = document.createElement('template'); template.innerHTML = content; return template; - } else { - return super.template; } + return super.template; } } diff --git a/packages/vaadin-themable-mixin/vaadin-themable-mixin.js b/packages/vaadin-themable-mixin/vaadin-themable-mixin.js index 55a1259ff5..7df0f254ee 100644 --- a/packages/vaadin-themable-mixin/vaadin-themable-mixin.js +++ b/packages/vaadin-themable-mixin/vaadin-themable-mixin.js @@ -65,9 +65,8 @@ export function registerStyles(themeFor, styles, options = {}) { function getAllThemes() { if (window.Vaadin && window.Vaadin.styleModules) { return window.Vaadin.styleModules.getAllThemes(); - } else { - return themeRegistry; } + return themeRegistry; } /** @@ -108,10 +107,9 @@ function flattenStyles(styles = []) { return [styles].flat(Infinity).filter((style) => { if (style instanceof CSSResult) { return true; - } else { - console.warn('An item in styles is not of type CSSResult. Use `unsafeCSS` or `css`.'); - return false; } + console.warn('An item in styles is not of type CSSResult. Use `unsafeCSS` or `css`.'); + return false; }); } @@ -170,10 +168,9 @@ function getThemes(tagName) { if (themes.length > 0) { return themes; - } else { - // No theme modules found, return the default module if it exists - return getAllThemes().filter((theme) => theme.moduleId === defaultModuleName); } + // No theme modules found, return the default module if it exists + return getAllThemes().filter((theme) => theme.moduleId === defaultModuleName); } /** diff --git a/scripts/cherryPick.js b/scripts/cherryPick.js index 8ca712f42e..445fe4cade 100644 --- a/scripts/cherryPick.js +++ b/scripts/cherryPick.js @@ -15,12 +15,12 @@ const axios = require('axios'); const https = require('https'); const exec = require('util').promisify(require('child_process').exec); -let arrPR = []; -let arrTitle = []; -let arrURL = []; -let arrSHA = []; -let arrBranch = []; -let arrUser = []; +const arrPR = []; +const arrTitle = []; +const arrURL = []; +const arrSHA = []; +const arrBranch = []; +const arrUser = []; const repo = 'vaadin/web-components'; const token = process.env['GITHUB_TOKEN']; @@ -30,7 +30,7 @@ if (!token) { } async function getAllCommits() { - let url = `https://api.github.com/repos/${repo}/pulls?state=closed&sort=updated&direction=desc&per_page=100`; + const url = `https://api.github.com/repos/${repo}/pulls?state=closed&sort=updated&direction=desc&per_page=100`; try { const options = { headers: { @@ -56,10 +56,10 @@ async function getAllCommits() { } function filterCommits(commits) { - for (let commit of commits) { + for (const commit of commits) { let target = false; let picked = false; - for (let label of commit.labels) { + for (const label of commit.labels) { if (label.name.includes('target/')) { target = true; } @@ -69,7 +69,7 @@ function filterCommits(commits) { } if (target === true && picked === false) { commit.labels.forEach((label) => { - let branch = /target\/(.*)/.exec(label.name); + const branch = /target\/(.*)/.exec(label.name); if (branch) { console.log(commit.number, commit.user.login, commit.url, commit.merge_commit_sha, branch[1]); arrPR.push(commit.number); @@ -86,7 +86,7 @@ function filterCommits(commits) { async function cherryPickCommits() { for (let i = arrPR.length - 1; i >= 0; i--) { - let branchName = `cherry-pick-${arrPR[i]}-to-${arrBranch[i]}-${Date.now()}`; + const branchName = `cherry-pick-${arrPR[i]}-to-${arrBranch[i]}-${Date.now()}`; await exec('git checkout master'); await exec('git pull'); @@ -121,7 +121,7 @@ async function cherryPickCommits() { } async function labelCommit(url, label) { - let issueURL = url.replace('pulls', 'issues') + '/labels'; + const issueURL = url.replace('pulls', 'issues') + '/labels'; const options = { headers: { 'User-Agent': 'Vaadin Cherry Pick', @@ -133,7 +133,7 @@ async function labelCommit(url, label) { } async function postComment(url, userName, branch, message) { - let issueURL = url.replace('pulls', 'issues') + '/comments'; + const issueURL = url.replace('pulls', 'issues') + '/comments'; const options = { headers: { 'User-Agent': 'Vaadin Cherry Pick', @@ -184,7 +184,7 @@ async function createPR(title, head, base) { } async function main() { - let allCommits = await getAllCommits(); + const allCommits = await getAllCommits(); filterCommits(allCommits); await cherryPickCommits(); } diff --git a/scripts/generateReleaseNotes.js b/scripts/generateReleaseNotes.js index f2d0b60504..4b953ee2bf 100644 --- a/scripts/generateReleaseNotes.js +++ b/scripts/generateReleaseNotes.js @@ -64,7 +64,7 @@ async function getReleases() { // Parse git log string and return an array of parsed commits as a JS object. function parseLog(log) { - let commits = []; + const commits = []; let commit, pos, result; log.split('\n').forEach((line) => { switch (pos) { @@ -99,7 +99,7 @@ function parseLog(log) { case 'body': result = /^ +([A-Z][\w-]+): +(.*)$/.exec(line); if (result) { - let k = result[1].toLowerCase(); + const k = result[1].toLowerCase(); if (k == 'warranty') { commit.bfp = true; } @@ -247,10 +247,10 @@ function logCommitsByComponent(commits) { let log = ''; let indent = ''; - let search = ','; - let replacement = '`,`'; - let componentsTitle = k.split(search).join(replacement); - let components = `\`${componentsTitle}\``; + const search = ','; + const replacement = '`,`'; + const componentsTitle = k.split(search).join(replacement); + const components = `\`${componentsTitle}\``; log += `- ${components}\n`; indent = ' '; diff --git a/scripts/transferFlowIssues.js b/scripts/transferFlowIssues.js index 63562d02c9..6af7f4dfe8 100644 --- a/scripts/transferFlowIssues.js +++ b/scripts/transferFlowIssues.js @@ -51,9 +51,8 @@ async function getZenHubWorkspaceName(workspace_id, repo_id) { const idx = workspaces.findIndex((workspace) => workspace.id === workspace_id); if (idx > -1) { return workspaces[idx].name; - } else { - throw new Error(`Cannot find ZenHub workspace with ID ${workspace_id} for the repo with ID ${repo_id}`); } + throw new Error(`Cannot find ZenHub workspace with ID ${workspace_id} for the repo with ID ${repo_id}`); })(workspace_id, repo_id) ); } @@ -114,9 +113,9 @@ async function createLabelInRepo(label, repo) { async function transferIssue(issue, targetRepo) { if (DRY_RUN) { return { ...issue }; - } else { - const response = await octokit.graphql( - `mutation TransferIssue($issueNodeId: ID!, $targetRepoNodeId: ID!, $clientMutationId: String) { + } + const response = await octokit.graphql( + `mutation TransferIssue($issueNodeId: ID!, $targetRepoNodeId: ID!, $clientMutationId: String) { transferIssue(input: { clientMutationId: $clientMutationId, issueId: $issueNodeId, @@ -134,46 +133,43 @@ async function transferIssue(issue, targetRepo) { } } }`, - { - clientMutationId: issue.url, - issueNodeId: issue.node_id, - targetRepoNodeId: targetRepo.node_id - } - ); - return response.transferIssue.issue; - } + { + clientMutationId: issue.url, + issueNodeId: issue.node_id, + targetRepoNodeId: targetRepo.node_id + } + ); + return response.transferIssue.issue; } async function transferLabels(labels, issue) { if (DRY_RUN) { return [...labels]; - } else { - const { data } = await octokit.rest.issues.addLabels({ - owner: issue.repository.owner.login, - repo: issue.repository.name, - issue_number: issue.number, - labels: labels.map((label) => label.name) - }); - return data; } + const { data } = await octokit.rest.issues.addLabels({ + owner: issue.repository.owner.login, + repo: issue.repository.name, + issue_number: issue.number, + labels: labels.map((label) => label.name) + }); + return data; } async function transferZhPipelines(pipelines, issue) { if (DRY_RUN) { return Promise.resolve(); - } else { - await Promise.all( - pipelines.map(async (pipeline) => { - zhApi.post( - `/p2/workspaces/${pipeline.workspace_id}/repositories/${issue.repository.databaseId}/issues/${issue.number}/moves`, - { - pipeline_id: pipeline.pipeline_id, - position: 'bottom' - } - ); - }) - ); } + await Promise.all( + pipelines.map(async (pipeline) => { + zhApi.post( + `/p2/workspaces/${pipeline.workspace_id}/repositories/${issue.repository.databaseId}/issues/${issue.number}/moves`, + { + pipeline_id: pipeline.pipeline_id, + position: 'bottom' + } + ); + }) + ); } async function makeRepoLabelsMap(repo) { diff --git a/scripts/transferIssues.js b/scripts/transferIssues.js index 84947d7c1d..4d45f09e37 100644 --- a/scripts/transferIssues.js +++ b/scripts/transferIssues.js @@ -111,9 +111,8 @@ async function getZenHubWorkspaceName(workspace_id, repo_id) { const idx = workspaces.findIndex((workspace) => workspace.id === workspace_id); if (idx > -1) { return workspaces[idx].name; - } else { - throw new Error(`Cannot find ZenHub workspace with ID ${workspace_id} for the repo with ID ${repo_id}`); } + throw new Error(`Cannot find ZenHub workspace with ID ${workspace_id} for the repo with ID ${repo_id}`); })(workspace_id, repo_id) ); } @@ -174,9 +173,9 @@ async function createLabelInRepo(label, repo) { async function transferIssue(issue, targetRepo) { if (DRY_RUN) { return { ...issue }; - } else { - const response = await octokit.graphql( - `mutation TransferIssue($issueNodeId: ID!, $targetRepoNodeId: ID!, $clientMutationId: String) { + } + const response = await octokit.graphql( + `mutation TransferIssue($issueNodeId: ID!, $targetRepoNodeId: ID!, $clientMutationId: String) { transferIssue(input: { clientMutationId: $clientMutationId, issueId: $issueNodeId, @@ -194,46 +193,43 @@ async function transferIssue(issue, targetRepo) { } } }`, - { - clientMutationId: issue.url, - issueNodeId: issue.node_id, - targetRepoNodeId: targetRepo.node_id - } - ); - return response.transferIssue.issue; - } + { + clientMutationId: issue.url, + issueNodeId: issue.node_id, + targetRepoNodeId: targetRepo.node_id + } + ); + return response.transferIssue.issue; } async function transferLabels(labels, issue) { if (DRY_RUN) { return [...labels]; - } else { - const { data } = await octokit.rest.issues.addLabels({ - owner: issue.repository.owner.login, - repo: issue.repository.name, - issue_number: issue.number, - labels: labels.map((label) => label.name) - }); - return data; } + const { data } = await octokit.rest.issues.addLabels({ + owner: issue.repository.owner.login, + repo: issue.repository.name, + issue_number: issue.number, + labels: labels.map((label) => label.name) + }); + return data; } async function transferZhPipelines(pipelines, issue) { if (DRY_RUN) { return Promise.resolve(); - } else { - await Promise.all( - pipelines.map(async (pipeline) => { - zhApi.post( - `/p2/workspaces/${pipeline.workspace_id}/repositories/${issue.repository.databaseId}/issues/${issue.number}/moves`, - { - pipeline_id: pipeline.pipeline_id, - position: 'bottom' - } - ); - }) - ); } + await Promise.all( + pipelines.map(async (pipeline) => { + zhApi.post( + `/p2/workspaces/${pipeline.workspace_id}/repositories/${issue.repository.databaseId}/issues/${issue.number}/moves`, + { + pipeline_id: pipeline.pipeline_id, + position: 'bottom' + } + ); + }) + ); } async function makeRepoLabelsMap(repo) {