Browse Source

Fix eslint warning and error

zhixin 7 years ago
parent
commit
03b43d509e

+ 71 - 6
.eslintrc.js

@@ -1,7 +1,72 @@
 module.exports = {
-    "extends": "standard",
-    "globals": {
-      "jQuery": true,
-      "$": true
-    }
-};
+  'root': true,
+  'env': {
+    'browser': true,
+    'node': true
+  },
+  'parserOptions': {
+    'parser': 'babel-eslint',
+    'ecmaVersion': 2017,
+    'sourceType': 'module'
+  },
+  'extends': [
+    'eslint:recommended'
+  ],
+  'rules': {
+    'indent': ['error',
+      2,
+      {
+        'SwitchCase': 1,
+        'MemberExpression': 1,
+        'ArrayExpression': 1,
+        'FunctionDeclaration': {'parameters': 'first'},
+        'CallExpression': {'arguments': 1},
+        'ImportDeclaration': 'first',
+        'ObjectExpression': 1
+      }
+    ],
+    'linebreak-style': 'off',
+    'quotes': ['error', 'single'],
+    'semi': ['error', 'never'],
+    'semi-style': ['error', 'last'],
+    'semi-spacing': ['error', {'before': false, 'after': true}],
+    'camelcase': 'off',
+    'default-case': 'error',
+    'no-new-func': 'error',
+    'no-void': 'error',
+    'array-bracket-spacing': ['error', 'never'],
+    'no-tabs': 'error',
+    'one-var': ['error', 'never'],
+    'prefer-const': 'error',
+    'no-trailing-spaces': 'error',
+    'operator-assignment': ['error', 'always'],
+    'dot-location': ['error', 'property'],
+    'no-console': ['error', { allow: ['log', 'info', 'warn', 'error'] }],
+    'no-else-return': ['error', {allowElseIf: false}],
+    'no-case-declarations': 'off',
+    'no-unused-vars': 'off',
+    'no-multi-spaces': 'error',
+    'valid-jsdoc': 'warn',
+    'eqeqeq': 'error',
+    'guard-for-in': 'warn',
+    'no-multi-str': 'error',
+    'no-return-await': 'error',
+    'no-return-assign': 'error',
+    'no-throw-literal': 'error',
+    'no-undef-init': 'error',
+    'no-use-before-define': 'warn',
+    'key-spacing': ['error', {'beforeColon': false, 'afterColon': true, 'mode': 'strict'}],
+    'keyword-spacing': ['error', {'before': true, 'after': true}],
+    'space-before-blocks': ['error', {'functions': 'always', 'keywords': 'always', 'classes': 'always'}],
+    'spaced-comment': ['error', 'always'],
+    'space-infix-ops': 'error',
+    'arrow-spacing': ['error', { 'before': true, 'after': true }],
+    'no-useless-constructor': 'warn',
+    'comma-dangle': ['error', 'never'],
+    'no-param-reassign': 'warn'
+  },
+  'globals': {
+    '$': true,
+    'jQuery': true
+  }
+}

+ 1 - 7
package.json

@@ -13,19 +13,13 @@
     "babel-preset-stage-0": "^6.24.1",
     "cssmin-cli": "^0.0.5",
     "eslint": "^4.19.1",
-    "eslint-config-standard": "^11.0.0",
-    "eslint-plugin-import": "^2.9.0",
-    "eslint-plugin-node": "^6.0.1",
-    "eslint-plugin-promise": "^3.7.0",
-    "eslint-plugin-standard": "^3.0.1",
     "headr": "^0.0.4",
     "npm-run-all": "^4.1.5",
     "opencollective": "^1.0.3"
   },
   "scripts": {
     "postinstall": "opencollective postinstall || exit 0",
-    "lint:js": "eslint src/bootstrap-table.js src/extensions/export/bootstrap-table-export.js src/extensions/toolbar/bootstrap-table-toolbar.js",
-    "lint": "run-p lint:*",
+    "lint": "eslint src/bootstrap-table.js src/extensions/export src/extensions/editable src/extensions/toolbar",
     "js:build:min": "NODE_ENV=production babel src -d dist -q && find dist -name '*.js' | sed -e 'p;s/.js/.min.js/' | xargs -n2 mv",
     "js:build:base": "babel src -d dist -q",
     "js:build:concat": "babel src/locale -o dist/bootstrap-table-locale-all.js && NODE_ENV=production babel src/locale -o dist/bootstrap-table-locale-all.min.js",

+ 74 - 93
src/bootstrap-table.js

@@ -17,7 +17,9 @@
     if (rawVersion !== undefined) {
       bootstrapVersion = parseInt(rawVersion, 10)
     }
-  } catch (e) {}
+  } catch (e) {
+    // ignore
+  }
 
   const bootstrap = {
     3: {
@@ -74,11 +76,11 @@
     bootstrapVersion,
 
     // it only does '%s', and return '' when arguments are undefined
-    sprintf (str, ...args) {
+    sprintf (_str, ...args) {
       let flag = true
       let i = 0
 
-      str = str.replace(/%s/g, () => {
+      const str = _str.replace(/%s/g, () => {
         const arg = args[i++]
 
         if (typeof arg === 'undefined') {
@@ -91,7 +93,7 @@
     },
 
     getFieldTitle (list, value) {
-      for (let item of list) {
+      for (const item of list) {
         if (item.field === value) {
           return item.title
         }
@@ -143,15 +145,13 @@
       if (this.cachedWidth === null) {
         const $inner = $('<div/>').addClass('fixed-table-scroll-inner')
         const $outer = $('<div/>').addClass('fixed-table-scroll-outer')
-        let w1
-        let w2
 
         $outer.append($inner)
         $('body').append($outer)
 
-        w1 = $inner[0].offsetWidth
+        const w1 = $inner[0].offsetWidth
         $outer.css('overflow', 'scroll')
-        w2 = $inner[0].offsetWidth
+        let w2 = $inner[0].offsetWidth
 
         if (w1 === w2) {
           w2 = $outer[0].clientWidth
@@ -230,10 +230,10 @@
     },
 
     getRealDataAttr (dataAttr) {
-      for (const attr in dataAttr) {
+      for (const [attr, value] of Object.entries(dataAttr)) {
         const auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase()
         if (auxAttr !== attr) {
-          dataAttr[auxAttr] = dataAttr[attr]
+          dataAttr[auxAttr] = value
           delete dataAttr[attr]
         }
       }
@@ -684,8 +684,8 @@
       Utils.setFieldIndex(this.options.columns)
 
       this.options.columns.forEach((columns, i) => {
-        columns.forEach((column, j) => {
-          column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column)
+        columns.forEach((_column, j) => {
+          const column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, _column)
 
           if (typeof column.fieldIndex !== 'undefined') {
             this.columns[column.fieldIndex] = column
@@ -710,12 +710,15 @@
         row._class = $(el).attr('class')
         row._data = Utils.getRealDataAttr($(el).data())
 
-        $(el).find('>td').each((x, el) => {
+        $(el).find('>td').each((_x, el) => {
           const cspan = +$(el).attr('colspan') || 1
           const rspan = +$(el).attr('rowspan') || 1
+          let x = _x
 
           // skip already occupied cells in current row
-          for (; m[y] && m[y][x]; x++) {}
+          for (; m[y] && m[y][x]; x++) {
+            // ignore
+          }
 
           // mark matrix elements occupied by current cell with true
           for (let tx = x; tx < x + cspan; tx++) {
@@ -924,10 +927,6 @@
       }
     }
 
-    /**
-     * @param data
-     * @param type: append / prepend
-     */
     initData (data, type) {
       if (type === 'append') {
         this.options.data = this.options.data.concat(data)
@@ -1299,7 +1298,7 @@
               value = item
               const props = key.split('.')
               for (let i = 0; i < props.length; i++) {
-                if (value[props[i]] != null) {
+                if (value[props[i]] !== null) {
                   value = value[props[i]]
                 }
               }
@@ -1334,9 +1333,9 @@
       if (!this.options.pagination) {
         this.$pagination.hide()
         return
-      } else {
-        this.$pagination.show()
       }
+      this.$pagination.show()
+
 
       const html = []
       let $allSelected = false
@@ -1412,7 +1411,7 @@
             .replace(/ /g, '').split(',')
 
           pageList = []
-          for (let value of list) {
+          for (const value of list) {
             pageList.push(
               (value.toUpperCase() === this.options.formatAllRows().toUpperCase() ||
               value.toUpperCase() === 'UNLIMITED')
@@ -1634,7 +1633,6 @@
     }
 
     initRow (item, i, data, parentDom) {
-      let key
       const html = []
       let style = {}
       const csses = []
@@ -1649,8 +1647,8 @@
       style = Utils.calculateObjectValue(this.options, this.options.rowStyle, [item, i], style)
 
       if (style && style.css) {
-        for (key in style.css) {
-          csses.push(`${key}: ${style.css[key]}`)
+        for (const [key, value] of Object.entries(style.css)) {
+          csses.push(`${key}: ${value}`)
         }
       }
 
@@ -1658,8 +1656,8 @@
         this.options.rowAttributes, [item, i], attributes)
 
       if (attributes) {
-        for (key in attributes) {
-          htmlAttributes.push(`${key}="${Utils.escapeHTML(attributes[key])}"`)
+        for (const [key, value] of Object.entries(attributes)) {
+          htmlAttributes.push(`${key}="${Utils.escapeHTML(value)}"`)
         }
       }
 
@@ -1760,8 +1758,8 @@
         }
         if (cellStyle.css) {
           const csses_ = []
-          for (const key in cellStyle.css) {
-            csses_.push(`${key}: ${cellStyle.css[key]}`)
+          for (const [key, value] of Object.entries(cellStyle.css)) {
+            csses_.push(`${key}: ${value}`)
           }
           style_ = ` style="${csses_.concat(this.header.styles[j]).join('; ')}"`
         }
@@ -1940,7 +1938,8 @@
         this.check_($this.prop('checked'), $this.data('index'))
       })
 
-      this.header.events.forEach((events, i) => {
+      this.header.events.forEach((_events, i) => {
+        let events = _events
         if (!events) {
           return
         }
@@ -1960,21 +1959,20 @@
           fieldIndex += 1
         }
 
-        for (const key in events) {
+        for (const [key, event] of Object.entries(events)) {
           this.$body.find('>tr:not(.no-records-found)').each((i, tr) => {
             const $tr = $(tr)
             const $td = $tr.find(this.options.cardView ? '.card-view' : 'td').eq(fieldIndex)
             const index = key.indexOf(' ')
             const name = key.substring(0, index)
             const el = key.substring(index + 1)
-            const func = events[key]
 
             $td.find(el).off(name).on(name, e => {
               const index = $tr.data('index')
               const row = this.data[index]
               const value = row[field]
 
-              func.apply(this, [e, value, row, index])
+              event.apply(this, [e, value, row, index])
             })
           })
         }
@@ -1996,8 +1994,6 @@
         sortOrder: this.options.sortOrder
       }
 
-      let request
-
       if (this.header.sortNames[index]) {
         params.sortName = this.header.sortNames[index]
       }
@@ -2046,7 +2042,7 @@
       if (!silent) {
         this.$tableLoading.show()
       }
-      request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
+      const request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
         type: this.options.method,
         url: url || this.options.url,
         data: this.options.contentType === 'application/json' && this.options.method === 'post'
@@ -2054,8 +2050,9 @@
         cache: this.options.cache,
         contentType: this.options.contentType,
         dataType: this.options.dataType,
-        success: res => {
-          res = Utils.calculateObjectValue(this.options, this.options.responseHandler, [res], res)
+        success: _res => {
+          const res = Utils.calculateObjectValue(this.options,
+            this.options.responseHandler, [_res], _res)
 
           this.load(res)
           this.trigger('load-success', res)
@@ -2122,7 +2119,7 @@
     }
 
     resetRows () {
-      for (let row of this.data) {
+      for (const row of this.data) {
         this.$selectAll.prop('checked', false)
         this.$selectItem.prop('checked', false)
         if (this.header.stateField) {
@@ -2132,8 +2129,8 @@
       this.initHiddenRows()
     }
 
-    trigger (name, ...args) {
-      name += '.bs.table'
+    trigger (_name, ...args) {
+      const name = `${_name}.bs.table`
       this.options[BootstrapTable.EVENTS[name]].apply(this.options, args)
       this.$el.trigger($.Event(name), args)
 
@@ -2149,24 +2146,19 @@
     }
 
     fitHeader () {
-      let fixedBody
-      let scrollWidth
-      let focused
-      let focusedTemp
-
       if (this.$el.is(':hidden')) {
         this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), 100)
         return
       }
-      fixedBody = this.$tableBody.get(0)
+      const fixedBody = this.$tableBody.get(0)
 
-      scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
+      const scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
       fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight()
         ? Utils.getScrollBarWidth() : 0
 
       this.$el.css('margin-top', -this.$header.outerHeight())
 
-      focused = $(':focus')
+      const focused = $(':focus')
       if (focused.length > 0) {
         const $th = focused.parents('th')
         if ($th.length > 0) {
@@ -2188,7 +2180,7 @@
         .html('').attr('class', this.$el.attr('class'))
         .append(this.$header_)
 
-      focusedTemp = $('.focus-temp:visible:eq(0)')
+      const focusedTemp = $('.focus-temp:visible:eq(0)')
       if (focusedTemp.length > 0) {
         focusedTemp.focus()
         this.$header.find('.focus-temp').removeClass('focus-temp')
@@ -2242,11 +2234,8 @@
         html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>')
       }
 
-      for (let column of this.columns) {
-        let key
-
-        let // footer align style
-          falign = ''
+      for (const column of this.columns) {
+        let falign = ''
 
         let valign = ''
         const csses = []
@@ -2267,8 +2256,8 @@
         style = Utils.calculateObjectValue(null, this.options.footerStyle)
 
         if (style && style.css) {
-          for (key in style.css) {
-            csses.push(`${key}: ${style.css[key]}`)
+          for (const [key, value] of Object.keys(style.css)) {
+            csses.push(`${key}: ${value}`)
           }
         }
 
@@ -2291,25 +2280,21 @@
     }
 
     fitFooter () {
-      let $footerTd
-      let elWidth
-      let scrollWidth
-
       clearTimeout(this.timeoutFooter_)
       if (this.$el.is(':hidden')) {
         this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100)
         return
       }
 
-      elWidth = this.$el.css('width')
-      scrollWidth = elWidth > this.$tableBody.width() ? Utils.getScrollBarWidth() : 0
+      const elWidth = this.$el.css('width')
+      const scrollWidth = elWidth > this.$tableBody.width() ? Utils.getScrollBarWidth() : 0
 
       this.$tableFooter.css({
         'margin-right': scrollWidth
       }).find('table').css('width', elWidth)
         .attr('class', this.$el.attr('class'))
 
-      $footerTd = this.$tableFooter.find('td')
+      const $footerTd = this.$tableFooter.find('td')
 
       this.$body.find('>tr:first-child:not(.no-records-found) > *').each((i, el) => {
         const $this = $(el)
@@ -2362,7 +2347,7 @@
     getVisibleFields () {
       const visibleFields = []
 
-      for (let field of this.header.fields) {
+      for (const field of this.header.fields) {
         const column = this.columns[this.fieldsColumnsIndex[field]]
 
         if (!column.visible) {
@@ -2437,8 +2422,9 @@
       return data
     }
 
-    load (data) {
+    load (_data) {
       let fixedScroll = false
+      let data = _data
 
       // #431: support pagination
       if (this.options.pagination && this.options.sidePagination === 'server') {
@@ -2512,9 +2498,10 @@
       }
     }
 
-    getRowByUniqueId (id) {
+    getRowByUniqueId (_id) {
       const uniqueId = this.options.uniqueId
       const len = this.options.data.length
+      let id = _id
       let dataRow = null
       let i
       let row
@@ -2568,16 +2555,14 @@
     }
 
     updateByUniqueId (params) {
-      const allParams = Array.isArray(params) ? params : [ params ]
-
-      for (let params of allParams) {
-        let rowId
+      const allParams = Array.isArray(params) ? params : [params]
 
+      for (const params of allParams) {
         if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
           continue
         }
 
-        rowId = this.options.data.indexOf(this.getRowByUniqueId(params.id))
+        const rowId = this.options.data.indexOf(this.getRowByUniqueId(params.id))
 
         if (rowId === -1) {
           continue
@@ -2622,9 +2607,9 @@
     }
 
     updateRow (params) {
-      const allParams = Array.isArray(params) ? params : [ params ]
+      const allParams = Array.isArray(params) ? params : [params]
 
-      for (let params of allParams) {
+      for (const params of allParams) {
         if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
           continue
         }
@@ -2651,7 +2636,6 @@
 
     toggleRow (params, visible) {
       let row
-      let index
 
       if (params.hasOwnProperty('index')) {
         row = this.getData()[params.index]
@@ -2663,7 +2647,7 @@
         return
       }
 
-      index = this.hiddenRows.indexOf(row)
+      const index = this.hiddenRows.indexOf(row)
 
       if (!visible && index === -1) {
         this.hiddenRows.push(row)
@@ -2677,7 +2661,7 @@
       const data = this.getData()
       const rows = []
 
-      for (let row of data) {
+      for (const row of data) {
         if (this.hiddenRows.includes(row)) {
           rows.push(row)
         }
@@ -2694,13 +2678,12 @@
       let i
       let j
       const $tr = this.$body.find('>tr')
-      let $td
 
       if (this.options.detailView && !this.options.cardView) {
         col += 1
       }
 
-      $td = $tr.eq(row).find('>td').eq(col)
+      const $td = $tr.eq(row).find('>td').eq(col)
 
       if (row < 0 || col < 0 || row >= this.data.length) {
         return
@@ -2736,12 +2719,10 @@
         !params.hasOwnProperty('value')) {
         return
       }
-      const allParams = Array.isArray(params) ? params : [ params ]
+      const allParams = Array.isArray(params) ? params : [params]
 
       allParams.forEach(({id, field, value}) => {
-        let rowId
-
-        rowId = this.options.data.indexOf(this.getRowByUniqueId(id))
+        const rowId = this.options.data.indexOf(this.getRowByUniqueId(id))
 
         if (rowId === -1) {
           return
@@ -2821,7 +2802,7 @@
       const row = this.data[index]
 
       if ($el.is(':radio') || this.options.singleSelect) {
-        for (let r of this.options.data) {
+        for (const r of this.options.data) {
           r[this.header.stateField] = false
         }
         this.$selectItem.filter(':checked').not($el).prop('checked', false)
@@ -2937,7 +2918,7 @@
     }
 
     toggleAllColumns (visible) {
-      for (let column of this.columns) {
+      for (const column of this.columns) {
         column.visible = visible
       }
 
@@ -2969,16 +2950,16 @@
       this.updatePagination()
     }
 
-    scrollTo (value) {
-      if (typeof value === 'string') {
-        value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0
-      }
-      if (typeof value === 'number') {
-        this.$tableBody.scrollTop(value)
-      }
-      if (typeof value === 'undefined') {
+    scrollTo (_value) {
+      if (typeof _value === 'undefined') {
         return this.$tableBody.scrollTop()
       }
+
+      let value = 0
+      if (typeof _value === 'string' && _value === 'bottom') {
+        value = this.$tableBody[0].scrollHeight
+      }
+      this.$tableBody.scrollTop(value)
     }
 
     getScrollPosition () {

+ 1 - 1
src/extensions/export/bootstrap-table-export.js

@@ -100,7 +100,7 @@
         const types = exportTypes.slice(1, -1).replace(/ /g, '').split(',')
         exportTypes = types.map(t => t.slice(1, -1))
       }
-      for (let type of exportTypes) {
+      for (const type of exportTypes) {
         if (TYPE_NAME.hasOwnProperty(type)) {
           $menu.append(Utils.sprintf(bootstrap.html.dropitem, type, TYPE_NAME[type]))
         }

+ 5 - 4
src/extensions/toolbar/bootstrap-table-toolbar.js

@@ -157,7 +157,7 @@
       const o = this.options
       const html = [`<form class="form-horizontal" id="${o.idForm}" action="${o.actionForm}">`]
 
-      for (let column of this.columns) {
+      for (const column of this.columns) {
         if (!column.checkbox && column.visible && column.searchable) {
           html.push(`
             <div class="form-group row">
@@ -185,11 +185,12 @@
       const fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial
 
       this.data = fp ? $.grep(this.data, (item, i) => {
-        for (const key in fp) {
-          const fval = fp[key].toLowerCase()
+        for (const [key, v] of Object.entries(fp)) {
+          const fval = v.toLowerCase()
           let value = item[key]
           const index = this.header.fields.indexOf(key)
-          value = Utils.calculateObjectValue(this.header, this.header.formatters[index], [value, item, i], value)
+          value = Utils.calculateObjectValue(this.header,
+            this.header.formatters[index], [value, item, i], value)
 
           if (
             !(index !== -1 &&