<commit_before>import { Loading } from 'element-ui'
import _ from 'lodash'
import { ShowDeleteConfirmDialog } from './Utils'

const PARAMS_PAGE_SIZE = 'pageSize'
const PARAMS_PAGE = 'page'
const PARAMS_SEARCH_TERM = 'term'
const PARAMS_SEARCH_PREFIX = 's--'
const PARAMS_SORT_COLUMN = 'sort'
const PARAMS_SORT_DIRECTION = 'dir'

export var mixin = {
  data: function () {
    return {
      pagination: {
        currentPage: 1,
        totalCount: 0,
        pageSize: 25,
        pageSizeList: [
          {
            label: 25,
            value: 25
          },
          {
            label: 50,
            value: 50
          },
          {
            label: 100,
            value: 100
          },
          {
            label: this.$i18n.t('scaffold.terms.page_size_all'),
            value: -1
          }
        ],
        $enableAddressBar: true    // true: 在浏览器地址栏保存 currentPage 和 pageSize
      },

      searchForm: {},

      tableData: [],
      selectedItems: [],
      datatablesParameters: {
        draw: 0,
        columns: [],
        order: [],
        start: 0,
        length: 25,
        search: {
          value: null,
          regex: false
        },
        _: null,
      },

      defaultSort: {prop: 'date', order: 'descending'},

      loading: null,
      _draw: null,

      autoload: true
    }
  },
  beforeMount: function () {
    if (this.pagination.$enableAddressBar) {
      this.pagination.currentPage = this.$route.query.hasOwnProperty(PARAMS_PAGE) ? parseInt(this.$route.query[PARAMS_PAGE]) : 1
      this.pagination.pageSize = this.$route.query.hasOwnProperty(PARAMS_PAGE_SIZE) ? parseInt(this.$route.query[PARAMS_PAGE_SIZE]) : 25
      if (this.$route.query.hasOwnProperty(PARAMS_SORT_COLUMN)) {
        this.defaultSort = {
          prop: this.$route.query[PARAMS_SORT_COLUMN],
          order: this.$route.query[PARAMS_SORT_DIRECTION]
        }
      }
    }
  },
  mounted: function () {
    this.initializeDataTablesParameters()
    if (!this.$route.query.hasOwnProperty(PARAMS_SORT_COLUMN) && this.autoload) {
      this.queryTableData()
    }
  },
  methods: {
    initializeDataTablesParameters: function () {
      let hasCreatedAt = false
      this.$refs.table.$children.forEach((column, index, columns) => {
        if (column.$options._componentTag !== 'el-table-column') {
          return
        }
        if (!column.columnConfig.property) {
          return
        }
        if (!hasCreatedAt && column.columnConfig.property === 'created_at') {
          hasCreatedAt = true
        }
        this.datatablesParameters.columns.push({
          data: column.columnConfig.property,
          name: column.columnConfig.property,
          searchable: column.$el.getAttribute('searchable') ? (column.$el.getAttribute('searchable').toLowerCase() === 'true') : true,
          orderable: column.columnConfig.sortable == 'custom' ? true : false,
          search: {
            value: null,
            regex: false,
            advance: {}
          },
        })
      })

      if (!hasCreatedAt) {
        this.datatablesParameters.columns.push({
          data: 'created_at',
          name: 'created_at',
          searchable: true,
          orderable: true,
          search: {
            value: null,
            regex: false,
            advance: {}
          },
        })
      }

      if (this.pagination.$enableAddressBar) {
        let hasSearchParams = false
        _.forEach(this.$route.query, (value, key) => {
          if (key.indexOf(PARAMS_SEARCH_PREFIX) !== -1) {
            this.searchForm[key.substr(PARAMS_SEARCH_PREFIX.length)] = value
            hasSearchParams = true
          }
        })
        if (hasSearchParams) {
          this.buildSearchParameters()
        }
        this.datatablesParameters.search.value = this.$route.query.hasOwnProperty(PARAMS_SEARCH_TERM) ? this.$route.query[PARAMS_SEARCH_TERM] : null
      }
      this.datatablesParameters.length = this.pagination.pageSize
      this.datatablesParameters.start = (this.pagination.currentPage - 1) * this.pagination.pageSize
    },
    showLoading: function (target) {
      this.loading = Loading.service({
        target: target,
        fullscreen: false,
        lock: false,
        text: this.$i18n.t('scaffold.terms.loading') + '...'
      })
    },
    hideLoading: function () {
      this.loading.close()
    },
    queryTableData: function () {
      if (this.loading && this.loading.visible) {
        return false
      }
      this.showLoading('.datatable-loading-section')
      axios.get(this.resource, {
        params: this.buildDataTablesParameters(),
        paramsSerializer: SerializerDatatablesParameters
      }).then(result => {
        if (this._draw == result.data.draw) {
          this.tableData = result.data.data
          this.pagination.totalCount = result.data.recordsFiltered
          this.hideLoading()
        }
      }).catch(result => {
        this.hideLoading()
      })
    },
    updateAddressBarParams: function () {
      if (this.pagination.$enableAddressBar) {
        let payload = JSON.parse(JSON.stringify(this.$route.query))
        let queries = {}
        if (arguments.length === 2) {
          queries[arguments[0]] = arguments[1]
        }
        else {
          queries = arguments[0]
        }
        _.forEach(queries, function (data, key) {
          if (data === null) {
            delete payload[key]
          }
          else {
            payload[key] = data
          }
        })
        this.$router.push({
          path: this.$route.path,
          query: payload
        })
      }
    },
    clearSearchFormAddressBarParams: function (searchPrefix) {
      let payload = JSON.parse(JSON.stringify(this.$route.query))
      _.forEach(payload, function (data, key) {
        if (key.indexOf(searchPrefix) !== -1) {
          delete payload[key]
        }
      })
      this.$router.push({
        path: this.$route.path,
        query: payload
      })
    },
    onPageSizeChange: function () {
      this.datatablesParameters.length = this.pagination.pageSize
      this.queryTableData()
      this.updateAddressBarParams(PARAMS_PAGE_SIZE, this.pagination.pageSize)
    },
    onPageChange: function (page) {
      this.pagination.currentPage = page
      this.datatablesParameters.start = (page - 1) * this.pagination.pageSize
      this.queryTableData()
      this.updateAddressBarParams(PARAMS_PAGE, this.pagination.currentPage)
    },
    onSortChange: function ({column, prop, order}) {
      if (order === null) {
        this.datatablesParameters.order = []
      }
      else {
        this.datatablesParameters.order = [{'column': prop, 'dir': (order == 'ascending' ? 'asc' : 'desc')}]
      }
      this.queryTableData()
      this.updateAddressBarParams({
        'sort': prop,
        'dir': order
      })
    },
    onAutoSearchChanged: _.debounce(function (newValue) {
      this.queryTableData()
      this.updateAddressBarParams(PARAMS_SEARCH_TERM, this.datatablesParameters.search.value)
    }, 500),
    onAutoSearchIconClick: function (newValue) {
      if (this.datatablesParameters.search.value) {
        this.datatablesParameters.search.value = null
        this.queryTableData()
        this.updateAddressBarParams(PARAMS_SEARCH_TERM, null)
      }
    },
    onSubmitSearch: function () {
      this.buildSearchParameters()
      this.queryTableData()
      this.updateAddressBarParams(PrefixObject(this.searchForm, PARAMS_SEARCH_PREFIX))
    },
    onResetSearch: function () {
      this.searchForm = {}
      this.$nextTick(this.onSubmitSearch)
      this.clearSearchFormAddressBarParams(PARAMS_SEARCH_PREFIX)
    },
    onSelectionChange: function (selection) {
      this.selectedItems = selection
    },
    _onDeleteClick: function ({url, data, confirmText, messageText}) {
      return ShowDeleteConfirmDialog(this, url, data, confirmText, messageText)
    },

    _onBundle: function (action, resourceUrl, options, items) {
      var selectedItems = JSON.parse(JSON.stringify(items ? items : this.selectedItems))
      return axios.post(resourceUrl ? resourceUrl : ( this.resource.substr(0, this.resource.indexOf('?')) + '/bundle'), {
        action: action,
        indexes: selectedItems.map((item) => item.id),
        options: options
      }).then(response => {
        if (response && response.status == 200) {
          return response
        }
        else {
          throw new Error(response.data)
        }
      }).catch(({response}) => {
        this.$message({
          type: 'error',
          message: response.data.message
        })
        throw response
      })
    },
    buildDataTablesParameters: function () {
      this.datatablesParameters.draw++
      this._draw = this.datatablesParameters.draw
      this.datatablesParameters._ = new Date().getTime()
      return this.datatablesParameters
    },
    buildSearchParameters: function () {
      var searchComponents = FindSearchComponents(this.$refs.searchForm)
      searchComponents.forEach(item => {
        // console.log('search',item.);
        var columnName = item.$el.getAttribute('column')
        var operator = item.$el.getAttribute('operator') ? item.$el.getAttribute('operator') : '='
        var value = this.searchForm[columnName]
        if (value === '' || value === null || value === undefined) {
          this.clearAdvanceSearchToColumn(columnName, operator)
        }
        else {
          switch (operator) {
            case 'range':
              if (value[0]) {
                this.applyAdvanceSearchToColumn(columnName, '>=', UnifiedValue(value[0]))
              }
              else {
                this.clearAdvanceSearchToColumn(columnName, '>=')
              }
              if (value[1]) {
                this.applyAdvanceSearchToColumn(columnName, '<=', UnifiedValue(value[1], true))
              }
              else {
                this.clearAdvanceSearchToColumn(columnName, '<=')
              }
              break
            case 'like':
              this.applyAdvanceSearchToColumn(columnName, operator, '%' + UnifiedValue(value) + '%')
              break
            default:
              // >, >=, =, <=, <
              this.applyAdvanceSearchToColumn(columnName, operator, UnifiedValue(value))
              break
          }
        }
      })
    },
    applyAdvanceSearchToColumn: function (columnName, operator, value) {
      var column = FindColumnConfigByName(this.datatablesParameters.columns, columnName)
      if (!column.hasOwnProperty('search')) {
        column.search = {advance: {}}
      }
      column.search.advance[operator] = value
    },
    clearAdvanceSearchToColumn: function (columnName, operator) {
      var column = FindColumnConfigByName(this.datatablesParameters.columns, columnName)
      if (operator) {
        delete column.search.advance[operator]
      }
      else {
        column.search.advance = {}
      }
    }
  }
}

function UnifiedValue (value, dayEnd) {
  var result = value
  if (_.isDate(value)) {
    result = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate()
    if (dayEnd) {
      result += ' 23:59:59'
    }
    else {
      result += ' ' + value.getHours() + ':' + value.getMinutes() + ':' + value.getSeconds()
    }
  }
  return result
}

function FindSearchComponents (inputComponent) {
  const CONTROLLERS = [
    'el-input', 'el-select', 'el-date-picker', 'el-time-picker', 'b-form-input'
  ]
  var components = []
  inputComponent.$children.forEach(component => {
    if (component.$el.hasAttribute('manual-search')) {
      // 当一个控件含有 manual-search 属性时， 不自动处理参数。 需要在 onSubmitSearch 函数中手工处理
      // Ignore.
    }
    else if (CONTROLLERS.indexOf(component.$options._componentTag) !== -1) {
      components.push(component)
    }
    else if (component.hasOwnProperty('$children')) {
      [].push.apply(components, FindSearchComponents(component))
    }
    else {
      // Ignore
    }
  })
  return components
}

function FindColumnConfigByName (columns, columnName) {
  var column = columns.find(column => {
    return column.name === columnName
  })
  if (!column) {
    throw new Error('Can\'t find column named \'' + columnName + '\'')
  }
  return column
}

function PrefixObject (params, prefix) {
  var result = {}
  _.forEach(params, function (val, key) {
    result[prefix + key] = val
  })
  return result
}

function SerializerDatatablesParameters (params) {
  var parameters = JSON.parse(JSON.stringify(params))
  delete parameters.order
  delete parameters.columns
  delete parameters.search
  params.columns.forEach((element, index) => {
    if (!element.data) {
      return
    }
    parameters['columns[' + index + '][data]'] = element.data
    parameters['columns[' + index + '][name]'] = element.name
    parameters['columns[' + index + '][searchable]'] = element.searchable
    parameters['columns[' + index + '][orderable]'] = element.orderable
    parameters['columns[' + index + '][search][value]'] = (element.search && element.search.value) ? element.search.value : null
    parameters['columns[' + index + '][search][regex]'] = (element.search && element.search.regex) ? element.search.regex : false
    if (element.search && element.search.hasOwnProperty('advance')) {
      for (var operator in element.search.advance) {
        if (element.search.advance.hasOwnProperty(operator)) {
          var value = element.search.advance[operator]
          if (Array.isArray(value)) {
            for (var valueIndex = 0; valueIndex < value.length; valueIndex++) {
              parameters['columns[' + index + '][search][advance][' + operator + '][' + valueIndex + ']'] = value[valueIndex]
            }
          } else {
            parameters['columns[' + index + '][search][advance][' + operator + ']'] = element.search.advance[operator]
          }
        }
      }
    }
  })
  params.order.forEach(function (element, index) {
    parameters['order[' + index + '][column]'] = isNaN(element.column) ? params.columns.findIndex(column => {
      return column.data === element.column
    }) : parseInt(element.column)
    parameters['order[' + index + '][dir]'] = element.dir ? element.dir : 'asc'
  })
  parameters['search[value]'] = params.search.value !== undefined ? params.search.value : null
  parameters['search[regex]'] = params.search.regex ? params.search.regex : false
  var parameterString = []
  for (var key in parameters) {
    if (parameters.hasOwnProperty(key)) {
      if ([undefined, null, ''].indexOf(parameters[key]) === -1) {
        parameterString.push(encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]))
      }
      else {
        parameterString.push(encodeURIComponent(key) + '=')
      }
    }
  }
  parameterString = parameterString.join('&')
  return parameterString
}
<commit_msg>Fixed list page order attribute.<commit_after>import { Loading } from 'element-ui'
import _ from 'lodash'
import { ShowDeleteConfirmDialog } from './Utils'

const PARAMS_PAGE_SIZE = 'pageSize'
const PARAMS_PAGE = 'page'
const PARAMS_SEARCH_TERM = 'term'
const PARAMS_SEARCH_PREFIX = 's--'
const PARAMS_SORT_COLUMN = 'sort'
const PARAMS_SORT_DIRECTION = 'dir'

export var mixin = {
  data: function () {
    return {
      pagination: {
        currentPage: 1,
        totalCount: 0,
        pageSize: 25,
        pageSizeList: [
          {
            label: 25,
            value: 25
          },
          {
            label: 50,
            value: 50
          },
          {
            label: 100,
            value: 100
          },
          {
            label: this.$i18n.t('scaffold.terms.page_size_all'),
            value: -1
          }
        ],
        $enableAddressBar: true    // true: 在浏览器地址栏保存 currentPage 和 pageSize
      },

      searchForm: {},

      tableData: [],
      selectedItems: [],
      datatablesParameters: {
        draw: 0,
        columns: [],
        order: [],
        start: 0,
        length: 25,
        search: {
          value: null,
          regex: false
        },
        _: null,
      },

      defaultSort: {prop: 'date', order: 'descending'},

      loading: null,
      _draw: null,

      autoload: true
    }
  },
  beforeMount: function () {
    if (this.pagination.$enableAddressBar) {
      this.pagination.currentPage = this.$route.query.hasOwnProperty(PARAMS_PAGE) ? parseInt(this.$route.query[PARAMS_PAGE]) : 1
      this.pagination.pageSize = this.$route.query.hasOwnProperty(PARAMS_PAGE_SIZE) ? parseInt(this.$route.query[PARAMS_PAGE_SIZE]) : 25
      if (this.$route.query.hasOwnProperty(PARAMS_SORT_COLUMN)) {
        this.defaultSort = {
          prop: this.$route.query[PARAMS_SORT_COLUMN],
          order: this.$route.query[PARAMS_SORT_DIRECTION]
        }
      }
    }
  },
  mounted: function () {
    this.initializeDataTablesParameters()
    if (!this.$route.query.hasOwnProperty(PARAMS_SORT_COLUMN) && this.autoload) {
      this.queryTableData()
    }
  },
  methods: {
    initializeDataTablesParameters: function () {
      let hasCreatedAt = false
      this.$refs.table.$children.forEach((column, index, columns) => {
        if (column.$options._componentTag !== 'el-table-column') {
          return
        }
        if (!column.columnConfig.property) {
          return
        }
        if (!hasCreatedAt && column.columnConfig.property === 'created_at') {
          hasCreatedAt = true
        }
        this.datatablesParameters.columns.push({
          data: column.columnConfig.property,
          name: column.columnConfig.property,
          searchable: column.$el.getAttribute('searchable') ? (column.$el.getAttribute('searchable').toLowerCase() === 'true') : true,
          orderable: column.columnConfig.sortable == 'custom' ? true : false,
          search: {
            value: null,
            regex: false,
            advance: {}
          },
        })
      })

      if (!hasCreatedAt) {
        this.datatablesParameters.columns.push({
          data: 'created_at',
          name: 'created_at',
          searchable: true,
          orderable: true,
          search: {
            value: null,
            regex: false,
            advance: {}
          },
        })
      }

      if (this.pagination.$enableAddressBar) {
        let hasSearchParams = false
        _.forEach(this.$route.query, (value, key) => {
          if (key.indexOf(PARAMS_SEARCH_PREFIX) !== -1) {
            this.searchForm[key.substr(PARAMS_SEARCH_PREFIX.length)] = value
            hasSearchParams = true
          }
        })
        if (hasSearchParams) {
          this.buildSearchParameters()
        }
        this.datatablesParameters.search.value = this.$route.query.hasOwnProperty(PARAMS_SEARCH_TERM) ? this.$route.query[PARAMS_SEARCH_TERM] : null
      }
      this.datatablesParameters.length = this.pagination.pageSize
      this.datatablesParameters.start = (this.pagination.currentPage - 1) * this.pagination.pageSize
    },
    showLoading: function (target) {
      this.loading = Loading.service({
        target: target,
        fullscreen: false,
        lock: false,
        text: this.$i18n.t('scaffold.terms.loading') + '...'
      })
    },
    hideLoading: function () {
      this.loading.close()
    },
    queryTableData: function () {
      if (this.loading && this.loading.visible) {
        return false
      }
      this.showLoading('.datatable-loading-section')
      axios.get(this.resource, {
        params: this.buildDataTablesParameters(),
        paramsSerializer: SerializerDatatablesParameters
      }).then(result => {
        if (this._draw == result.data.draw) {
          this.tableData = result.data.data
          this.pagination.totalCount = result.data.recordsFiltered
          this.hideLoading()
        }
      }).catch(result => {
        this.hideLoading()
      })
    },
    updateAddressBarParams: function () {
      if (this.pagination.$enableAddressBar) {
        let payload = JSON.parse(JSON.stringify(this.$route.query))
        let queries = {}
        if (arguments.length === 2) {
          queries[arguments[0]] = arguments[1]
        }
        else {
          queries = arguments[0]
        }
        _.forEach(queries, function (data, key) {
          if (data === null) {
            delete payload[key]
          }
          else {
            payload[key] = data
          }
        })
        this.$router.push({
          path: this.$route.path,
          query: payload
        })
      }
    },
    clearSearchFormAddressBarParams: function (searchPrefix) {
      let payload = JSON.parse(JSON.stringify(this.$route.query))
      _.forEach(payload, function (data, key) {
        if (key.indexOf(searchPrefix) !== -1) {
          delete payload[key]
        }
      })
      this.$router.push({
        path: this.$route.path,
        query: payload
      })
    },
    onPageSizeChange: function () {
      this.datatablesParameters.length = this.pagination.pageSize
      this.queryTableData()
      this.updateAddressBarParams(PARAMS_PAGE_SIZE, this.pagination.pageSize)
    },
    onPageChange: function (page) {
      this.pagination.currentPage = page
      this.datatablesParameters.start = (page - 1) * this.pagination.pageSize
      this.queryTableData()
      this.updateAddressBarParams(PARAMS_PAGE, this.pagination.currentPage)
    },
    onSortChange: function ({column, prop, order}) {
      if (order === null) {
        this.datatablesParameters.order = []
      }
      else {
        this.datatablesParameters.order = [{'column': prop, 'dir': (order == 'ascending' ? 'asc' : 'desc')}]
      }
      this.queryTableData()
      this.updateAddressBarParams({
        'sort': prop,
        'dir': order
      })
    },
    onAutoSearchChanged: _.debounce(function (newValue) {
      this.queryTableData()
      this.updateAddressBarParams(PARAMS_SEARCH_TERM, this.datatablesParameters.search.value)
    }, 500),
    onAutoSearchIconClick: function (newValue) {
      if (this.datatablesParameters.search.value) {
        this.datatablesParameters.search.value = null
        this.queryTableData()
        this.updateAddressBarParams(PARAMS_SEARCH_TERM, null)
      }
    },
    onSubmitSearch: function () {
      this.buildSearchParameters()
      this.queryTableData()
      this.updateAddressBarParams(PrefixObject(this.searchForm, PARAMS_SEARCH_PREFIX))
    },
    onResetSearch: function () {
      this.searchForm = {}
      this.$nextTick(this.onSubmitSearch)
      this.clearSearchFormAddressBarParams(PARAMS_SEARCH_PREFIX)
    },
    onSelectionChange: function (selection) {
      this.selectedItems = selection
    },
    _onDeleteClick: function ({url, data, confirmText, messageText}) {
      return ShowDeleteConfirmDialog(this, url, data, confirmText, messageText)
    },

    _onBundle: function (action, resourceUrl, options, items) {
      var selectedItems = JSON.parse(JSON.stringify(items ? items : this.selectedItems))
      return axios.post(resourceUrl ? resourceUrl : ( this.resource.substr(0, this.resource.indexOf('?')) + '/bundle'), {
        action: action,
        indexes: selectedItems.map((item) => item.id),
        options: options
      }).then(response => {
        if (response && response.status == 200) {
          return response
        }
        else {
          throw new Error(response.data)
        }
      }).catch(({response}) => {
        this.$message({
          type: 'error',
          message: response.data.message
        })
        throw response
      })
    },
    buildDataTablesParameters: function () {
      this.datatablesParameters.draw++
      this._draw = this.datatablesParameters.draw
      this.datatablesParameters._ = new Date().getTime()
      return this.datatablesParameters
    },
    buildSearchParameters: function () {
      var searchComponents = FindSearchComponents(this.$refs.searchForm)
      searchComponents.forEach(item => {
        // console.log('search',item.);
        var columnName = item.$el.getAttribute('column')
        var operator = item.$el.getAttribute('operator') ? item.$el.getAttribute('operator') : '='
        var value = this.searchForm[columnName]
        if (value === '' || value === null || value === undefined) {
          this.clearAdvanceSearchToColumn(columnName, operator)
        }
        else {
          switch (operator) {
            case 'range':
              if (value[0]) {
                this.applyAdvanceSearchToColumn(columnName, '>=', UnifiedValue(value[0]))
              }
              else {
                this.clearAdvanceSearchToColumn(columnName, '>=')
              }
              if (value[1]) {
                this.applyAdvanceSearchToColumn(columnName, '<=', UnifiedValue(value[1], true))
              }
              else {
                this.clearAdvanceSearchToColumn(columnName, '<=')
              }
              break
            case 'like':
              this.applyAdvanceSearchToColumn(columnName, operator, '%' + UnifiedValue(value) + '%')
              break
            default:
              // >, >=, =, <=, <
              this.applyAdvanceSearchToColumn(columnName, operator, UnifiedValue(value))
              break
          }
        }
      })
    },
    applyAdvanceSearchToColumn: function (columnName, operator, value) {
      var column = FindColumnConfigByName(this.datatablesParameters.columns, columnName)
      if (!column.hasOwnProperty('search')) {
        column.search = {advance: {}}
      }
      column.search.advance[operator] = value
    },
    clearAdvanceSearchToColumn: function (columnName, operator) {
      var column = FindColumnConfigByName(this.datatablesParameters.columns, columnName)
      if (operator) {
        delete column.search.advance[operator]
      }
      else {
        column.search.advance = {}
      }
    }
  }
}

function UnifiedValue (value, dayEnd) {
  var result = value
  if (_.isDate(value)) {
    result = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate()
    if (dayEnd) {
      result += ' 23:59:59'
    }
    else {
      result += ' ' + value.getHours() + ':' + value.getMinutes() + ':' + value.getSeconds()
    }
  }
  return result
}

function FindSearchComponents (inputComponent) {
  const CONTROLLERS = [
    'el-input', 'el-select', 'el-date-picker', 'el-time-picker', 'b-form-input'
  ]
  var components = []
  inputComponent.$children.forEach(component => {
    if (component.$el.hasAttribute('manual-search')) {
      // 当一个控件含有 manual-search 属性时， 不自动处理参数。 需要在 onSubmitSearch 函数中手工处理
      // Ignore.
    }
    else if (CONTROLLERS.indexOf(component.$options._componentTag) !== -1) {
      components.push(component)
    }
    else if (component.hasOwnProperty('$children')) {
      [].push.apply(components, FindSearchComponents(component))
    }
    else {
      // Ignore
    }
  })
  return components
}

function FindColumnConfigByName (columns, columnName) {
  var column = columns.find(column => {
    return column.name === columnName
  })
  if (!column) {
    throw new Error('Can\'t find column named \'' + columnName + '\'')
  }
  return column
}

function PrefixObject (params, prefix) {
  var result = {}
  _.forEach(params, function (val, key) {
    result[prefix + key] = val
  })
  return result
}

function SerializerDatatablesParameters (params) {
  var parameters = JSON.parse(JSON.stringify(params))
  delete parameters.order
  delete parameters.columns
  delete parameters.search
  var columnMaxIndex = 0;
  params.columns.forEach((element, index) => {
    if (!element.data) {
      return
    }
    columnMaxIndex++;
    parameters['columns[' + index + '][data]'] = element.data
    parameters['columns[' + index + '][name]'] = element.name
    parameters['columns[' + index + '][searchable]'] = element.searchable
    parameters['columns[' + index + '][orderable]'] = element.orderable
    parameters['columns[' + index + '][search][value]'] = (element.search && element.search.value) ? element.search.value : null
    parameters['columns[' + index + '][search][regex]'] = (element.search && element.search.regex) ? element.search.regex : false
    if (element.search && element.search.hasOwnProperty('advance')) {
      for (var operator in element.search.advance) {
        if (element.search.advance.hasOwnProperty(operator)) {
          var value = element.search.advance[operator]
          if (Array.isArray(value)) {
            for (var valueIndex = 0; valueIndex < value.length; valueIndex++) {
              parameters['columns[' + index + '][search][advance][' + operator + '][' + valueIndex + ']'] = value[valueIndex]
            }
          } else {
            parameters['columns[' + index + '][search][advance][' + operator + ']'] = element.search.advance[operator]
          }
        }
      }
    }
  })
  params.order.forEach(function (element, index) {
    var columnIndex = isNaN(element.column) ? params.columns.findIndex(column => {
        return column.data === element.column
    }) : parseInt(element.column)
    if(columnIndex === -1)
    {
      parameters['columns[' + columnMaxIndex + '][data]'] = element.column
      parameters['columns[' + columnMaxIndex + '][name]'] = element.column
      parameters['columns[' + columnMaxIndex + '][orderable]'] = true
      columnIndex = columnMaxIndex;
      columnMaxIndex++;
    }
    parameters['order[' + index + '][column]'] = columnIndex;
    parameters['order[' + index + '][dir]'] = element.dir ? element.dir : 'asc'
  })
  parameters['search[value]'] = params.search.value !== undefined ? params.search.value : null
  parameters['search[regex]'] = params.search.regex ? params.search.regex : false
  var parameterString = []
  for (var key in parameters) {
    if (parameters.hasOwnProperty(key)) {
      if ([undefined, null, ''].indexOf(parameters[key]) === -1) {
        parameterString.push(encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]))
      }
      else {
        parameterString.push(encodeURIComponent(key) + '=')
      }
    }
  }
  parameterString = parameterString.join('&')
  return parameterString
}
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import express from 'express';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux'
import { StaticRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config';

import routes from '../routes';
import configureStore from '../store';
import sagas from '../sagas';

export default class Renderer {

  app: express$Application;
  staticPath: string;
  serviceWorkerPath: string;
  uploadsPath: string;

  render: (req: $Request, res: $Response) => void;

  constructor(app: express$Application, staticPath: string, serviceWorkerPath: string, uploadsPath: string) {
    this.render = this.render.bind(this);

    this.app = app;
    this.staticPath = staticPath;
    this.serviceWorkerPath = serviceWorkerPath;
    this.uploadsPath = uploadsPath;
    this.middleware();
  }

  middleware(): void {
    this.app.use('/static', express.static(this.staticPath));
    this.app.use('/uploads', express.static(this.uploadsPath));
    this.app.use('/service-worker.js', express.static(this.serviceWorkerPath));
    this.app.use(this.render);
  }

  render(req: $Request, res: $Response): void {
    const store = configureStore();

    const component = (
      <Provider store={store}>
        <StaticRouter location={req.url} context={{}}>
          {renderRoutes(routes)}
        </StaticRouter>
      </Provider>
    );

    store.runSaga(sagas).done.then(() => {
      const content = renderToString(component);
      res.send(this.renderFullPage(content, store.getState()));
    });

    renderToString(component);
    store.close();
  }

  renderFullPage(body: string, preloadedState: Object): string {
    return `
      <!doctype html>
      <title>Artwork Manager ttt</title>
      <meta name="viewport" content="width=device-width,initial-scale=1" />
      <meta name="apple-mobile-web-app-capable" content="yes" />
      <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
      <link rel="manifest" href="/static/manifest.json" />
      <link rel="icon" sizes="192x192" href="/static/images/icons/192x192.png" />
      <link rel="apple-touch-icon" href="/static/images/icons/180x180.png" />
      <link rel="stylesheet" href="/static/app.css" />

${ body }

    `;
  }

}
<commit_msg>Modify title in HTML<commit_after>// @flow

import React from 'react';
import express from 'express';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux'
import { StaticRouter } from 'react-router-dom';
import { renderRoutes } from 'react-router-config';

import routes from '../routes';
import configureStore from '../store';
import sagas from '../sagas';

export default class Renderer {

  app: express$Application;
  staticPath: string;
  serviceWorkerPath: string;
  uploadsPath: string;

  render: (req: $Request, res: $Response) => void;

  constructor(app: express$Application, staticPath: string, serviceWorkerPath: string, uploadsPath: string) {
    this.render = this.render.bind(this);

    this.app = app;
    this.staticPath = staticPath;
    this.serviceWorkerPath = serviceWorkerPath;
    this.uploadsPath = uploadsPath;
    this.middleware();
  }

  middleware(): void {
    this.app.use('/static', express.static(this.staticPath));
    this.app.use('/uploads', express.static(this.uploadsPath));
    this.app.use('/service-worker.js', express.static(this.serviceWorkerPath));
    this.app.use(this.render);
  }

  render(req: $Request, res: $Response): void {
    const store = configureStore();

    const component = (
      <Provider store={store}>
        <StaticRouter location={req.url} context={{}}>
          {renderRoutes(routes)}
        </StaticRouter>
      </Provider>
    );

    store.runSaga(sagas).done.then(() => {
      const content = renderToString(component);
      res.send(this.renderFullPage(content, store.getState()));
    });

    renderToString(component);
    store.close();
  }

  renderFullPage(body: string, preloadedState: Object): string {
    return `
      <!doctype html>
      <title>Artwork Manager</title>
      <meta name="viewport" content="width=device-width,initial-scale=1" />
      <meta name="apple-mobile-web-app-capable" content="yes" />
      <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
      <link rel="manifest" href="/static/manifest.json" />
      <link rel="icon" sizes="192x192" href="/static/images/icons/192x192.png" />
      <link rel="apple-touch-icon" href="/static/images/icons/180x180.png" />
      <link rel="stylesheet" href="/static/app.css" />

${ body }

    `;
  }

}
<|endoftext|>


<commit_before>const test = require('ava')
const htmlmodule = require('../lib/htmlmodule')

test('HtmlA', t => t.is(htmlmodule.HtmlA.render().toString(), ''))
test('HtmlAbbr', t => t.is(htmlmodule.HtmlAbbr.render().toString(), ''))
test('HtmlAddress', t => t.is(htmlmodule.HtmlAddress.render().toString(), '<address></address>'))
test('HtmlArea', t => t.is(htmlmodule.HtmlArea.render().toString(), '<area>'))
test('HtmlArticle', t => t.is(htmlmodule.HtmlArticle.render().toString(), '

'))
test('HtmlAside', t => t.is(htmlmodule.HtmlAside.render().toString(), ''))
test('HtmlAudio', t => t.is(htmlmodule.HtmlAudio.render().toString(), '<audio></audio>'))
test('HtmlB', t => t.is(htmlmodule.HtmlB.render().toString(), ''))
test('HtmlBase', t => t.is(htmlmodule.HtmlBase.render().toString(), '<base>'))
test('HtmlBdi', t => t.is(htmlmodule.HtmlBdi.render().toString(), '<bdi></bdi>'))
test('HtmlBdo', t => t.is(htmlmodule.HtmlBdo.render().toString(), '<bdo></bdo>'))
test('HtmlBlockQuote', t => t.is(htmlmodule.HtmlBlockQuote.render().toString(), '

'))
test('HtmlBody', t => t.is(htmlmodule.HtmlBody.render().toString(), ''))
test('HtmlBr', t => t.is(htmlmodule.HtmlBr.render().toString(), '
'))
test('HtmlButton', t => t.is(htmlmodule.HtmlButton.render().toString(), '<button></button>'))
test('HtmlCanvas', t => t.is(htmlmodule.HtmlCanvas.render().toString(), '<canvas></canvas>'))
test('HtmlCaption', t => t.is(htmlmodule.HtmlCaption.render().toString(), '

'))
test('HtmlCite', t => t.is(htmlmodule.HtmlCite.render().toString(), ''))
test('HtmlCode', t => t.is(htmlmodule.HtmlCode.render().toString(), ''))
test('HtmlCol', t => t.is(htmlmodule.HtmlCol.render().toString(), '<col>'))
test('HtmlColGroup', t => t.is(htmlmodule.HtmlColGroup.render().toString(), '<colgroup></colgroup>'))
test('HtmlData', t => t.is(htmlmodule.HtmlData.render().toString(), '<data></data>'))
test('HtmlDataList', t => t.is(htmlmodule.HtmlDataList.render().toString(), '<datalist></datalist>'))
test('HtmlDd', t => t.is(htmlmodule.HtmlDd.render().toString(), '

'))
test('HtmlDel', t => t.is(htmlmodule.HtmlDel.render().toString(), ''))
test('HtmlDetails', t => t.is(htmlmodule.HtmlDetails.render().toString(), ''))
test('HtmlDfn', t => t.is(htmlmodule.HtmlDfn.render().toString(), '<dfn></dfn>'))
test('HtmlDialog', t => t.is(htmlmodule.HtmlDialog.render().toString(), '<dialog></dialog>'))
test('HtmlDiv', t => t.is(htmlmodule.HtmlDiv.render().toString(), '

'))
test('HtmlDl', t => t.is(htmlmodule.HtmlDl.render().toString(), '

'))
test('HtmlDt', t => t.is(htmlmodule.HtmlDt.render().toString(), '

'))
test('HtmlEm', t => t.is(htmlmodule.HtmlEm.render().toString(), ''))
test('HtmlEmbed', t => t.is(htmlmodule.HtmlEmbed.render().toString(), '<embed>'))
test('HtmlFieldSet', t => t.is(htmlmodule.HtmlFieldSet.render().toString(), '<fieldset></fieldset>'))
test('HtmlFigCaption', t => t.is(htmlmodule.HtmlFigCaption.render().toString(), '

'))
test('HtmlFigure', t => t.is(htmlmodule.HtmlFigure.render().toString(), '

'))
test('HtmlFooter', t => t.is(htmlmodule.HtmlFooter.render().toString(), ''))
test('HtmlForm', t => t.is(htmlmodule.HtmlForm.render().toString(), '<form></form>'))
test('HtmlH1', t => t.is(htmlmodule.HtmlH1.render().toString(), '

'))
test('HtmlH2', t => t.is(htmlmodule.HtmlH2.render().toString(), '

'))
test('HtmlH3', t => t.is(htmlmodule.HtmlH3.render().toString(), '

'))
test('HtmlH4', t => t.is(htmlmodule.HtmlH4.render().toString(), '

'))
test('HtmlH5', t => t.is(htmlmodule.HtmlH5.render().toString(), '

'))
test('HtmlH6', t => t.is(htmlmodule.HtmlH6.render().toString(), '

'))
test('HtmlHGroup', t => t.is(htmlmodule.HtmlHGroup.render().toString(), '<hgroup></hgroup>'))
test('HtmlHead', t => t.is(htmlmodule.HtmlHead.render().toString(), ''))
test('HtmlHeader', t => t.is(htmlmodule.HtmlHeader.render().toString(), ''))
test('HtmlHr', t => t.is(htmlmodule.HtmlHr.render().toString(), '
'))
test('HtmlHtml', t => t.is(htmlmodule.HtmlHtml.render().toString(), ''))
test('HtmlI', t => t.is(htmlmodule.HtmlI.render().toString(), ''))
test('HtmlIFrame', t => t.is(htmlmodule.HtmlIFrame.render().toString(), ''))
test('HtmlImg', t => t.is(htmlmodule.HtmlImg.render().toString(), ''))
test('HtmlInput', t => t.is(htmlmodule.HtmlInput.render().toString(), '<input>'))
test('HtmlIns', t => t.is(htmlmodule.HtmlIns.render().toString(), ''))
test('HtmlKbd', t => t.is(htmlmodule.HtmlKbd.render().toString(), ''))
test('HtmlLabel', t => t.is(htmlmodule.HtmlLabel.render().toString(), ''))
test('HtmlLegend', t => t.is(htmlmodule.HtmlLegend.render().toString(), '<legend></legend>'))
test('HtmlLi', t => t.is(htmlmodule.HtmlLi.render().toString(), '

'))
test('HtmlLink', t => t.is(htmlmodule.HtmlLink.render().toString(), '<link>'))
test('HtmlMain', t => t.is(htmlmodule.HtmlMain.render().toString(), ''))
test('HtmlMap', t => t.is(htmlmodule.HtmlMap.render().toString(), '<map></map>'))
test('HtmlMark', t => t.is(htmlmodule.HtmlMark.render().toString(), ''))
test('HtmlMenu', t => t.is(htmlmodule.HtmlMenu.render().toString(), '<menu></menu>'))
test('HtmlMeta', t => t.is(htmlmodule.HtmlMeta.render().toString(), '<meta>'))
test('HtmlMeter', t => t.is(htmlmodule.HtmlMeter.render().toString(), '<meter></meter>'))
test('HtmlNav', t => t.is(htmlmodule.HtmlNav.render().toString(), ''))
test('HtmlNoScript', t => t.is(htmlmodule.HtmlNoScript.render().toString(), ''))
test('HtmlObject', t => t.is(htmlmodule.HtmlObject.render().toString(), '<object></object>'))
test('HtmlOl', t => t.is(htmlmodule.HtmlOl.render().toString(), '

'))
test('HtmlOptGroup', t => t.is(htmlmodule.HtmlOptGroup.render().toString(), '<optgroup></optgroup>'))
test('HtmlOption', t => t.is(htmlmodule.HtmlOption.render().toString(), '<option></option>'))
test('HtmlOutput', t => t.is(htmlmodule.HtmlOutput.render().toString(), '<output></output>'))
test('HtmlP', t => t.is(htmlmodule.HtmlP.render().toString(), '

'))
test('HtmlPicture', t => t.is(htmlmodule.HtmlPicture.render().toString(), '<picture></picture>'))
test('HtmlPre', t => t.is(htmlmodule.HtmlPre.render().toString(), '

'))
test('HtmlProgress', t => t.is(htmlmodule.HtmlProgress.render().toString(), '<progress></progress>'))
test('HtmlQ', t => t.is(htmlmodule.HtmlQ.render().toString(), '<q></q>'))
test('HtmlRp', t => t.is(htmlmodule.HtmlRp.render().toString(), '<rp></rp>'))
test('HtmlRt', t => t.is(htmlmodule.HtmlRt.render().toString(), '<rt></rt>'))
test('HtmlRuby', t => t.is(htmlmodule.HtmlRuby.render().toString(), '<ruby></ruby>'))
test('HtmlS', t => t.is(htmlmodule.HtmlS.render().toString(), '<s></s>'))
test('HtmlSamp', t => t.is(htmlmodule.HtmlSamp.render().toString(), '<samp></samp>'))
test('HtmlScript', t => t.is(htmlmodule.HtmlScript.render().toString(), ''))
test('HtmlSection', t => t.is(htmlmodule.HtmlSection.render().toString(), '

'))
test('HtmlSelect', t => t.is(htmlmodule.HtmlSelect.render().toString(), '<select></select>'))
test('HtmlSmall', t => t.is(htmlmodule.HtmlSmall.render().toString(), ''))
test('HtmlSource', t => t.is(htmlmodule.HtmlSource.render().toString(), '<source>'))
test('HtmlSpan', t => t.is(htmlmodule.HtmlSpan.render().toString(), ''))
test('HtmlStrong', t => t.is(htmlmodule.HtmlStrong.render().toString(), ''))
test('HtmlStyle', t => t.is(htmlmodule.HtmlStyle.render().toString(), ''))
test('HtmlSub', t => t.is(htmlmodule.HtmlSub.render().toString(), ''))
test('HtmlSummary', t => t.is(htmlmodule.HtmlSummary.render().toString(), ''))
test('HtmlSup', t => t.is(htmlmodule.HtmlSup.render().toString(), ''))
test('HtmlTBody', t => t.is(htmlmodule.HtmlTBody.render().toString(), '

'))
test('HtmlTFoot', t => t.is(htmlmodule.HtmlTFoot.render().toString(), '

'))
test('HtmlTHead', t => t.is(htmlmodule.HtmlTHead.render().toString(), '

'))
test('HtmlTable', t => t.is(htmlmodule.HtmlTable.render().toString(), '

'))
test('HtmlTd', t => t.is(htmlmodule.HtmlTd.render().toString(), '	'))
test('HtmlTemplate', t => t.is(htmlmodule.HtmlTemplate.render().toString(), '<template></template>'))
test('HtmlTextArea', t => t.is(htmlmodule.HtmlTextArea.render().toString(), '<textarea></textarea>'))
test('HtmlTh', t => t.is(htmlmodule.HtmlTh.render().toString(), '	'))
test('HtmlTime', t => t.is(htmlmodule.HtmlTime.render().toString(), '<time></time>'))
test('HtmlTitle', t => t.is(htmlmodule.HtmlTitle.render().toString(), '<title></title>'))
test('HtmlTr', t => t.is(htmlmodule.HtmlTr.render().toString(), '

'))
test('HtmlTrack', t => t.is(htmlmodule.HtmlTrack.render().toString(), '<track>'))
test('HtmlU', t => t.is(htmlmodule.HtmlU.render().toString(), ''))
test('HtmlUl', t => t.is(htmlmodule.HtmlUl.render().toString(), '

'))
test('HtmlVar', t => t.is(htmlmodule.HtmlVar.render().toString(), '<var></var>'))
test('HtmlVideo', t => t.is(htmlmodule.HtmlVideo.render().toString(), '<video></video>'))
test('HtmlWbr', t => t.is(htmlmodule.HtmlWbr.render().toString(), '<wbr>'))
<commit_msg>Editing tests<commit_after>const test = require('ava')
const h = require('../lib/htmlmodule')

test('test #1', t => {
  t.is(h.HtmlA.render().toString(), '')
  t.is(h.HtmlAbbr.render().toString(), '')
  t.is(h.HtmlAddress.render().toString(), '<address></address>')
  t.is(h.HtmlArea.render().toString(), '<area>')
  t.is(h.HtmlArticle.render().toString(), '

')
  t.is(h.HtmlAside.render().toString(), '')
  t.is(h.HtmlAudio.render().toString(), '<audio></audio>')
  t.is(h.HtmlB.render().toString(), '')
  t.is(h.HtmlBase.render().toString(), '<base>')
  t.is(h.HtmlBdi.render().toString(), '<bdi></bdi>')
  t.is(h.HtmlBdo.render().toString(), '<bdo></bdo>')
  t.is(h.HtmlBlockQuote.render().toString(), '

')
  t.is(h.HtmlBody.render().toString(), '')
  t.is(h.HtmlBr.render().toString(), '
')
  t.is(h.HtmlButton.render().toString(), '<button></button>')
  t.is(h.HtmlCanvas.render().toString(), '<canvas></canvas>')
  t.is(h.HtmlCaption.render().toString(), '

')
  t.is(h.HtmlCite.render().toString(), '')
  t.is(h.HtmlCode.render().toString(), '')
  t.is(h.HtmlCol.render().toString(), '<col>')
  t.is(h.HtmlColGroup.render().toString(), '<colgroup></colgroup>')
  t.is(h.HtmlData.render().toString(), '<data></data>')
  t.is(h.HtmlDataList.render().toString(), '<datalist></datalist>')
  t.is(h.HtmlDd.render().toString(), '

')
  t.is(h.HtmlDel.render().toString(), '')
  t.is(h.HtmlDetails.render().toString(), '')
  t.is(h.HtmlDfn.render().toString(), '<dfn></dfn>')
  t.is(h.HtmlDialog.render().toString(), '<dialog></dialog>')
  t.is(h.HtmlDiv.render().toString(), '

')
  t.is(h.HtmlDl.render().toString(), '

')
  t.is(h.HtmlDt.render().toString(), '

')
  t.is(h.HtmlEm.render().toString(), '')
  t.is(h.HtmlEmbed.render().toString(), '<embed>')
  t.is(h.HtmlFieldSet.render().toString(), '<fieldset></fieldset>')
  t.is(h.HtmlFigCaption.render().toString(), '

')
  t.is(h.HtmlFigure.render().toString(), '

')
  t.is(h.HtmlFooter.render().toString(), '')
  t.is(h.HtmlForm.render().toString(), '<form></form>')
  t.is(h.HtmlH1.render().toString(), '

')
  t.is(h.HtmlH2.render().toString(), '

')
  t.is(h.HtmlH3.render().toString(), '

')
  t.is(h.HtmlH4.render().toString(), '

')
  t.is(h.HtmlH5.render().toString(), '

')
  t.is(h.HtmlH6.render().toString(), '

')
  t.is(h.HtmlHGroup.render().toString(), '<hgroup></hgroup>')
  t.is(h.HtmlHead.render().toString(), '')
  t.is(h.HtmlHeader.render().toString(), '')
  t.is(h.HtmlHr.render().toString(), '
')
  t.is(h.HtmlHtml.render().toString(), '')
  t.is(h.HtmlI.render().toString(), '')
  t.is(h.HtmlIFrame.render().toString(), '')
  t.is(h.HtmlImg.render().toString(), '')
  t.is(h.HtmlInput.render().toString(), '<input>')
  t.is(h.HtmlIns.render().toString(), '')
  t.is(h.HtmlKbd.render().toString(), '')
  t.is(h.HtmlLabel.render().toString(), '')
  t.is(h.HtmlLegend.render().toString(), '<legend></legend>')
  t.is(h.HtmlLi.render().toString(), '

')
  t.is(h.HtmlLink.render().toString(), '<link>')
  t.is(h.HtmlMain.render().toString(), '')
  t.is(h.HtmlMap.render().toString(), '<map></map>')
  t.is(h.HtmlMark.render().toString(), '')
  t.is(h.HtmlMenu.render().toString(), '<menu></menu>')
  t.is(h.HtmlMeta.render().toString(), '<meta>')
  t.is(h.HtmlMeter.render().toString(), '<meter></meter>')
  t.is(h.HtmlNav.render().toString(), '')
  t.is(h.HtmlNoScript.render().toString(), '')
  t.is(h.HtmlObject.render().toString(), '<object></object>')
  t.is(h.HtmlOl.render().toString(), '

')
  t.is(h.HtmlOptGroup.render().toString(), '<optgroup></optgroup>')
  t.is(h.HtmlOption.render().toString(), '<option></option>')
  t.is(h.HtmlOutput.render().toString(), '<output></output>')
  t.is(h.HtmlP.render().toString(), '

')
  t.is(h.HtmlPicture.render().toString(), '<picture></picture>')
  t.is(h.HtmlPre.render().toString(), '

')
  t.is(h.HtmlProgress.render().toString(), '<progress></progress>')
  t.is(h.HtmlQ.render().toString(), '<q></q>')
  t.is(h.HtmlRp.render().toString(), '<rp></rp>')
  t.is(h.HtmlRt.render().toString(), '<rt></rt>')
  t.is(h.HtmlRuby.render().toString(), '<ruby></ruby>')
  t.is(h.HtmlS.render().toString(), '<s></s>')
  t.is(h.HtmlSamp.render().toString(), '<samp></samp>')
  t.is(h.HtmlScript.render().toString(), '')
  t.is(h.HtmlSection.render().toString(), '

')
  t.is(h.HtmlSelect.render().toString(), '<select></select>')
  t.is(h.HtmlSmall.render().toString(), '')
  t.is(h.HtmlSource.render().toString(), '<source>')
  t.is(h.HtmlSpan.render().toString(), '')
  t.is(h.HtmlStrong.render().toString(), '')
  t.is(h.HtmlStyle.render().toString(), '')
  t.is(h.HtmlSub.render().toString(), '')
  t.is(h.HtmlSummary.render().toString(), '')
  t.is(h.HtmlSup.render().toString(), '')
  t.is(h.HtmlTBody.render().toString(), '

')
  t.is(h.HtmlTFoot.render().toString(), '

')
  t.is(h.HtmlTHead.render().toString(), '

')
  t.is(h.HtmlTable.render().toString(), '

')
  t.is(h.HtmlTd.render().toString(), '	')
  t.is(h.HtmlTemplate.render().toString(), '<template></template>')
  t.is(h.HtmlTextArea.render().toString(), '<textarea></textarea>')
  t.is(h.HtmlTh.render().toString(), '	')
  t.is(h.HtmlTime.render().toString(), '<time></time>')
  t.is(h.HtmlTitle.render().toString(), '<title></title>')
  t.is(h.HtmlTr.render().toString(), '

')
  t.is(h.HtmlTrack.render().toString(), '<track>')
  t.is(h.HtmlU.render().toString(), '')
  t.is(h.HtmlUl.render().toString(), '

')
  t.is(h.HtmlVar.render().toString(), '<var></var>')
  t.is(h.HtmlVideo.render().toString(), '<video></video>')
  t.is(h.HtmlWbr.render().toString(), '<wbr>')
})
<|endoftext|>


<commit_before>import React,{Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {folderAdd,folderItemDelete,tabAdd,modal} from "../actions/index";

class Sidebar extends Component {

    constructor(props){
        super(props);
        this.state = {};
        this.folderAddClickHandler = this.folderAddClickHandler.bind(this);
        this.folderClickHandler = this.folderClickHandler.bind(this);
        this.renderFolders = this.renderFolders.bind(this);
        this.renderItems = this.renderItems.bind(this);
        this.itemClickHandler = this.itemClickHandler.bind(this);
        this.itemClickDeleteHandler = this.itemClickDeleteHandler.bind(this);
    }

    folderAddClickHandler(e){
        this.props.modal("newFolder");
    }

    folderClickHandler(e){
        const folder = $(e.currentTarget);
        const folderList = folder.next(".items");
        folder.toggleClass("-active");
        if (folderList.is("ul")){
            folderList.toggleClass("-open");
        }
    }

    itemClickHandler(e){
        const item = $(e.currentTarget);
        const name = item.find(".name").text();
        this.props.tabAdd(name);
    }

    itemClickDeleteHandler(e){
        // alert("Item will be deleted");
        const item = $(e.currentTarget).closest(".item");
        const itemIndex = item.attr("data-id");
        const folder = item.closest(".folder");
        const folderIndex = folder.attr("data-id");
        this.props.folderItemDelete(folderIndex,itemIndex);
        e.stopPropagation();
        e.preventDefault();
    }

    itemClickEditHandler(e){
        alert("Item will be edited");
        e.stopPropagation();
        e.preventDefault();
    }

    renderItems(data,index){
        return(

{data.name}

{data.description}

{data.type}

                        <svg x="0px" y="0px" viewBox="0 0 469.331 469.331" width="100%" height="100%">
                            <path d="M438.931,30.403c-40.4-40.5-106.1-40.5-146.5,0l-268.6,268.5c-2.1,2.1-3.4,4.8-3.8,7.7l-19.9,147.4   c-0.6,4.2,0.9,8.4,3.8,11.3c2.5,2.5,6,4,9.5,4c0.6,0,1.2,0,1.8-0.1l88.8-12c7.4-1,12.6-7.8,11.6-15.2c-1-7.4-7.8-12.6-15.2-11.6   l-71.2,9.6l13.9-102.8l108.2,108.2c2.5,2.5,6,4,9.5,4s7-1.4,9.5-4l268.6-268.5c19.6-19.6,30.4-45.6,30.4-73.3   S458.531,49.903,438.931,30.403z M297.631,63.403l45.1,45.1l-245.1,245.1l-45.1-45.1L297.631,63.403z M160.931,416.803l-44.1-44.1   l245.1-245.1l44.1,44.1L160.931,416.803z M424.831,152.403l-107.9-107.9c13.7-11.3,30.8-17.5,48.8-17.5c20.5,0,39.7,8,54.2,22.4   s22.4,33.7,22.4,54.2C442.331,121.703,436.131,138.703,424.831,152.403z"/>
                        </svg>

                        <svg x="0px" y="0px" viewBox="0 0 774.266 774.266" width="100%" height="100%">
                            <g>
                                <path d="M640.35,91.169H536.971V23.991C536.971,10.469,526.064,0,512.543,0c-1.312,0-2.187,0.438-2.614,0.875    C509.491,0.438,508.616,0,508.179,0H265.212h-1.74h-1.75c-13.521,0-23.99,10.469-23.99,23.991v67.179H133.916    c-29.667,0-52.783,23.116-52.783,52.783v38.387v47.981h45.803v491.6c0,29.668,22.679,52.346,52.346,52.346h415.703    c29.667,0,52.782-22.678,52.782-52.346v-491.6h45.366v-47.981v-38.387C693.133,114.286,670.008,91.169,640.35,91.169z     M285.713,47.981h202.84v43.188h-202.84V47.981z M599.349,721.922c0,3.061-1.312,4.363-4.364,4.363H179.282    c-3.052,0-4.364-1.303-4.364-4.363V230.32h424.431V721.922z M644.715,182.339H129.551v-38.387c0-3.053,1.312-4.802,4.364-4.802    H640.35c3.053,0,4.365,1.749,4.365,4.802V182.339z"/>
                                <rect x="475.031" y="286.593" width="48.418" height="396.942" />
                                <rect x="363.361" y="286.593" width="48.418" height="396.942" />
                                <rect x="251.69" y="286.593" width="48.418" height="396.942" />
                            </g>
                        </svg>

        )
    }

    renderFolders(data,index){

        var items = ('items' in data)? data.items : [];

        return(

{data.name}

{items.length + " Itens"}

                    {items.map(this.renderItems)}

        );
    }

    render() {
        return (

                        Requesto

                        {this.props.folders.map(this.renderFolders)}

                        <svg className="icon  icon--plus" viewBox="0 0 5 5" xmlns="http://www.w3.org/2000/svg">
                            <path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" />
                        </svg>

        );
    }
}

function mapStateToProps({folders}){
    return {folders};
}

function mapDispatchToProps(dispatch){
    return bindActionCreators({folderAdd,folderItemDelete,tabAdd,modal},dispatch);
}

export default connect (mapStateToProps,mapDispatchToProps)(Sidebar);
<commit_msg>add folder delete action<commit_after>import React,{Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {folderAdd,folderDelete,folderItemDelete,tabAdd,modal} from "../actions/index";

class Sidebar extends Component {

    constructor(props){
        super(props);
        this.state = {};
        this.folderAddClickHandler = this.folderAddClickHandler.bind(this);
        this.folderClickHandler = this.folderClickHandler.bind(this);
        this.folderOnContextHandler = this.folderOnContextHandler.bind(this);
        this.itemClickHandler = this.itemClickHandler.bind(this);
        this.itemClickDeleteHandler = this.itemClickDeleteHandler.bind(this);
        this.renderItems = this.renderItems.bind(this);
        this.renderFolders = this.renderFolders.bind(this);
    }

    folderAddClickHandler(e){
        this.props.modal("newFolder");
    }

    folderClickHandler(e){
        const folder = $(e.currentTarget);
        const folderList = folder.next(".items");
        folder.toggleClass("-active");
        if (folderList.is("ul")){
            folderList.toggleClass("-open");
        }
    }

    folderOnContextHandler(e){
        const folder = e.target.getAttribute("data-id");
        if (confirm("Are you sure?")) this.props.folderDelete(folder);
        e.stopPropagation();
        e.preventDefault();
        return false;
    }

    itemClickHandler(e){
        const item = $(e.currentTarget);
        const name = item.find(".name").text();
        this.props.tabAdd(name);
    }

    itemClickDeleteHandler(e){
        // alert("Item will be deleted");
        const item = $(e.currentTarget).closest(".item");
        const itemIndex = item.attr("data-id");
        const folder = item.closest(".folder");
        const folderIndex = folder.attr("data-id");
        this.props.folderItemDelete(folderIndex,itemIndex);
        e.stopPropagation();
        e.preventDefault();
    }

    itemClickEditHandler(e){
        alert("Item will be edited");
        e.stopPropagation();
        e.preventDefault();
    }

    renderItems(data,index){
        return(

{data.name}

{data.description}

{data.type}

                        <svg x="0px" y="0px" viewBox="0 0 469.331 469.331" width="100%" height="100%">
                            <path d="M438.931,30.403c-40.4-40.5-106.1-40.5-146.5,0l-268.6,268.5c-2.1,2.1-3.4,4.8-3.8,7.7l-19.9,147.4   c-0.6,4.2,0.9,8.4,3.8,11.3c2.5,2.5,6,4,9.5,4c0.6,0,1.2,0,1.8-0.1l88.8-12c7.4-1,12.6-7.8,11.6-15.2c-1-7.4-7.8-12.6-15.2-11.6   l-71.2,9.6l13.9-102.8l108.2,108.2c2.5,2.5,6,4,9.5,4s7-1.4,9.5-4l268.6-268.5c19.6-19.6,30.4-45.6,30.4-73.3   S458.531,49.903,438.931,30.403z M297.631,63.403l45.1,45.1l-245.1,245.1l-45.1-45.1L297.631,63.403z M160.931,416.803l-44.1-44.1   l245.1-245.1l44.1,44.1L160.931,416.803z M424.831,152.403l-107.9-107.9c13.7-11.3,30.8-17.5,48.8-17.5c20.5,0,39.7,8,54.2,22.4   s22.4,33.7,22.4,54.2C442.331,121.703,436.131,138.703,424.831,152.403z"/>
                        </svg>

                        <svg x="0px" y="0px" viewBox="0 0 774.266 774.266" width="100%" height="100%">
                            <g>
                                <path d="M640.35,91.169H536.971V23.991C536.971,10.469,526.064,0,512.543,0c-1.312,0-2.187,0.438-2.614,0.875    C509.491,0.438,508.616,0,508.179,0H265.212h-1.74h-1.75c-13.521,0-23.99,10.469-23.99,23.991v67.179H133.916    c-29.667,0-52.783,23.116-52.783,52.783v38.387v47.981h45.803v491.6c0,29.668,22.679,52.346,52.346,52.346h415.703    c29.667,0,52.782-22.678,52.782-52.346v-491.6h45.366v-47.981v-38.387C693.133,114.286,670.008,91.169,640.35,91.169z     M285.713,47.981h202.84v43.188h-202.84V47.981z M599.349,721.922c0,3.061-1.312,4.363-4.364,4.363H179.282    c-3.052,0-4.364-1.303-4.364-4.363V230.32h424.431V721.922z M644.715,182.339H129.551v-38.387c0-3.053,1.312-4.802,4.364-4.802    H640.35c3.053,0,4.365,1.749,4.365,4.802V182.339z"/>
                                <rect x="475.031" y="286.593" width="48.418" height="396.942" />
                                <rect x="363.361" y="286.593" width="48.418" height="396.942" />
                                <rect x="251.69" y="286.593" width="48.418" height="396.942" />
                            </g>
                        </svg>

        )
    }

    renderFolders(data,index){

        var items = ('items' in data)? data.items : [];

        return(

{data.name}

{items.length + " Itens"}

                    {items.map(this.renderItems)}

        );
    }

    render() {
        return (

                        Requesto

                        {this.props.folders.map(this.renderFolders)}

                        <svg className="icon  icon--plus" viewBox="0 0 5 5" xmlns="http://www.w3.org/2000/svg">
                            <path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" />
                        </svg>

        );
    }
}

function mapStateToProps({folders}){
    return {folders};
}

function mapDispatchToProps(dispatch){
    return bindActionCreators({folderAdd,folderDelete,folderItemDelete,tabAdd,modal},dispatch);
}

export default connect (mapStateToProps,mapDispatchToProps)(Sidebar);
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.factories')
    .factory('cvEvaluator', function (cvModel, jobDescriptionModel) {
        var EDU_WEIGHT = 0.20, ESS_SKILL_WEIGHT = 0.20, PREF_SKILL_WEIGHT = 0.20,
            EXP_WEIGHT = 0.20, LANG_WEIGHT = 0.20;

        var evaluateAllCv = function () {
            var allCv = cvModel.get_all_stemmed();
            var jobDesc = jobDescriptionModel.get_stemmed();

            var rankedCvs = [];
            allCv.forEach(function (cv) {
                console.log("CV: ", cv.id);

                var educationScore = calcEducationScore(cv.education, jobDesc.education);
                console.log("education: ", educationScore);

                var essSkillsScore = calcSkillsScore(cv, jobDesc.essentialSkills);
                console.log("essential skills: ", essSkillsScore);

                var prefSkillsScore = calcSkillsScore(cv, jobDesc.preferredSkills);
                console.log("preferred skills: ", prefSkillsScore);

                var expScore = calcExpScore(cv.experience, jobDesc.experience);
                console.log("experience: ", expScore);

                var languageScore = calcLanguageScore(cv.languages, jobDesc.languages);
                console.log("language: ", languageScore);

                var result = {
                    id: cv.id,
                    education: educationScore,
                    essSkills: essSkillsScore,
                    prefSkills: prefSkillsScore,
                    experience: expScore,
                    language: languageScore
                };
                console.log(result);
                rankedCvs.push(result);
            });

            //TODO: to not store results into storage access, return to filter
//            storageAccess.storeResults(rankedCvs);
            console.log("ranked CVS", rankedCvs);
            return rankedCvs;
        };

        /* EDUCATION SCORING */
        // Initial score based on number of matching keywords
        // Then compare, if degree less than minimum, return 0, else 100
        function calcEducationScore(cvEdu, jdEdu) {
            var eduCount = findMatchingWords(cvEdu.keywords, jdEdu.keywords);

            // if user has no degree level or course preference
            if(jdEdu.degree == 0 && jdEdu.keywords.length == 0) {
                return 100;
            } else if(jdEdu.degree == 0) {
                return eduCount/jdEdu.keywords.length * 100;
            } else if(jdEdu.keywords.length == 0) {
                return cvEdu.degree >= jdEdu.degree ? 100 : 0;
            } else {
                return ((cvEdu.degree >= jdEdu.degree ? 100 : 0) + eduCount/jdEdu.keywords.length*100) / 2;
            }
        }

        /* SKILLS SCORING */
        // The score is the percentage number of skill keywords matched with weightage of each category matching
        function calcSkillsScore(cv, jdSkills) {
            if (jdSkills.length == 0) {
                return 100;
            }
            var SKILLS_WEIGHT = 3, EXP_WEIGHT = 1.5, INTEREST_WEIGHT = 0.5;
            var WEIGHT_NORM = SKILLS_WEIGHT + EXP_WEIGHT + INTEREST_WEIGHT;

            var skillCount = findMatchingWords(cv.skill, jdSkills);

            var expCount = findMatchingWords(cv.experience, jdSkills);

            var interestCount = findMatchingWords(cv.interest, jdSkills);

            var totalScore = (skillCount * SKILLS_WEIGHT + expCount * EXP_WEIGHT + interestCount * INTEREST_WEIGHT) /
                (jdSkills.length * WEIGHT_NORM) * 100;
            return totalScore > 100 ? 100 : totalScore;
        }

        /* EXPERIENCE SCORING */
        // Returns 100% if attained minimum
        // If experience lesser than requirement return 0
        function calcExpScore(cvExp, jdExp) {
            var EXP_NORMAL = 100;

            if(cvExp < jdExp)
                return 0;
            else
                return EXP_NORMAL;
        }

        /* LANGUAGE SCORING */
        // The score is the percentage number of language keywords matched
        function calcLanguageScore(cvLang, jdLang) {
            if(jdLang.length == 0) {
                return 100;
            }

            var count = 0;
            cvLang.forEach(function (lang) {
                for(var i=0; i<jdLang.length; i++) {
                    if(lang.name === jdLang[i].name) {
                        count++;
                        break;
                    }
                }
            });

            return count/jdLang.length * 100;
        }

        //returns number of matched words
        function findMatchingWords(source1, source2) {
            var results = [];

            for (var i = 0; i < source1.length; i++) {
                //for each word, check the entire wordsOfSource2?
                var hasKeyWord = function (keyWord) {
                    return source1[i].toLowerCase().indexOf(keyWord.toLowerCase()) >= 0;
                };
                var matchedWords = source2.filter(hasKeyWord);
                results = results.concat(matchedWords);
            }
            /**
             * uniqueArray = a.filter(function(item, pos) {
                    return a.indexOf(item) == pos;
                })
             */
            console.log("matched results", results);
            return results.length;
        }

        return {
            calcEducationScore: calcEducationScore,
            calcSkillsScore: calcSkillsScore,
            calcExpScore: calcExpScore,
            calcLanguageScore: calcLanguageScore,
        }
    });<commit_msg>CV Evaluator: Cleanup, since it doesn't evaluate the entire CV anymore<commit_after>'use strict';

angular.module('myApp.factories')
    .factory('cvEvaluator', function () {

        /* EDUCATION SCORING */
        // Initial score based on number of matching keywords
        // Then compare, if degree less than minimum, return 0, else 100
        function calcEducationScore(cvEdu, jdEdu) {
            var eduCount = findMatchingWords(cvEdu.keywords, jdEdu.keywords);

            // if user has no degree level or course preference
            if(jdEdu.degree == 0 && jdEdu.keywords.length == 0) {
                return 100;
            } else if(jdEdu.degree == 0) {
                return eduCount/jdEdu.keywords.length * 100;
            } else if(jdEdu.keywords.length == 0) {
                return cvEdu.degree >= jdEdu.degree ? 100 : 0;
            } else {
                return ((cvEdu.degree >= jdEdu.degree ? 100 : 0) + eduCount/jdEdu.keywords.length*100) / 2;
            }
        }

        /* SKILLS SCORING */
        // The score is the percentage number of skill keywords matched with weightage of each category matching
        function calcSkillsScore(cv, jdSkills) {
            if (jdSkills.length == 0) {
                return 100;
            }
            var SKILLS_WEIGHT = 3, EXP_WEIGHT = 1.5, INTEREST_WEIGHT = 0.5;
            var WEIGHT_NORM = SKILLS_WEIGHT + EXP_WEIGHT + INTEREST_WEIGHT;

            var skillCount = findMatchingWords(cv.skill, jdSkills);

            var expCount = findMatchingWords(cv.experience, jdSkills);

            var interestCount = findMatchingWords(cv.interest, jdSkills);

            var totalScore = (skillCount * SKILLS_WEIGHT + expCount * EXP_WEIGHT + interestCount * INTEREST_WEIGHT) /
                (jdSkills.length * WEIGHT_NORM) * 100;
            return totalScore > 100 ? 100 : totalScore;
        }

        /* EXPERIENCE SCORING */
        // Returns 100% if attained minimum
        // If experience lesser than requirement return 0
        function calcExpScore(cvExp, jdExp) {
            var EXP_NORMAL = 100;

            if(cvExp < jdExp)
                return 0;
            else
                return EXP_NORMAL;
        }

        /* LANGUAGE SCORING */
        // The score is the percentage number of language keywords matched
        function calcLanguageScore(cvLang, jdLang) {
            if(jdLang.length == 0) {
                return 100;
            }

            var count = 0;
            cvLang.forEach(function (lang) {
                for(var i=0; i<jdLang.length; i++) {
                    if(lang.name === jdLang[i].name) {
                        count++;
                        break;
                    }
                }
            });

            return count/jdLang.length * 100;
        }

        //returns number of matched words
        function findMatchingWords(source1, source2) {
            var results = [];

            for (var i = 0; i < source1.length; i++) {
                //for each word, check the entire wordsOfSource2?
                var hasKeyWord = function (keyWord) {
                    return source1[i].toLowerCase().indexOf(keyWord.toLowerCase()) >= 0;
                };
                var matchedWords = source2.filter(hasKeyWord);
                results = results.concat(matchedWords);
            }
            /**
             * uniqueArray = a.filter(function(item, pos) {
                    return a.indexOf(item) == pos;
                })
             */
            console.log("matched results", results);
            return results.length;
        }

        return {
            calcEducationScore: calcEducationScore,
            calcSkillsScore: calcSkillsScore,
            calcExpScore: calcExpScore,
            calcLanguageScore: calcLanguageScore
        }
    });<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { injectIntl } from 'react-intl';
import Isvg from 'react-inlinesvg';
import makeSelectWhatsHappening from './selectors';
import BellIcon from 'assets/images/icons/bell.svg';
import { createStructuredSelector } from 'reselect';
import styled from 'styled-components';

const CounterArea = styled.div`
  color: white;
  text-align: center;
  width: 20px;
  font-size: 12px;
  position: relative;

  span {
    z-index: 100;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    font-weight: 800;
  }

  &::after {
    content: ' ';
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 50;
    width: 100%;
    padding-bottom: 100%;
    background: black;
    border-radius: 50%;
    transform: translate(-50%, -50%);
  }

`;

class Counter extends React.PureComponent {

  constructor(props) {
    super();
  }

  render() {

    const { data, lastViewed } = this.props.WhatsHappening;
    const { locale } = this.props.intl;
    if (!data || data === undefined) return null;

    const unseenCount = data.filter(item=> {
          const dateTime = new Date(item.date);
          return dateTime > lastViewed;
      });

    // if (unseenCount.length == 0) return null;

    return (
      <CounterArea>{unseenCount.length}</CounterArea>
    )
  }
}

const mapStateToProps = createStructuredSelector({
  WhatsHappening: makeSelectWhatsHappening(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(Counter));
<commit_msg>Revert back the counter<commit_after>import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { injectIntl } from 'react-intl';
import Isvg from 'react-inlinesvg';
import makeSelectWhatsHappening from './selectors';
import BellIcon from 'assets/images/icons/bell.svg';
import { createStructuredSelector } from 'reselect';
import styled from 'styled-components';

const CounterArea = styled.div`
  color: white;
  text-align: center;
  width: 20px;
  font-size: 12px;
  position: relative;

  span {
    z-index: 100;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    font-weight: 800;
  }

  &::after {
    content: ' ';
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 50;
    width: 100%;
    padding-bottom: 100%;
    background: black;
    border-radius: 50%;
    transform: translate(-50%, -50%);
  }

`;

class Counter extends React.PureComponent {

  constructor(props) {
    super();
  }

  render() {

    const { data, lastViewed } = this.props.WhatsHappening;
    const { locale } = this.props.intl;
    if (!data || data === undefined) return null;

    const unseenCount = data.filter(item=> {
          const dateTime = new Date(item.date);
          return dateTime > lastViewed;
      });

    if (unseenCount.length == 0) return null;

    return (
      <CounterArea>{unseenCount.length}</CounterArea>
    )
  }
}

const mapStateToProps = createStructuredSelector({
  WhatsHappening: makeSelectWhatsHappening(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(Counter));
<|endoftext|>


<commit_before>"use strict";
const imported = require("../data/import.js");
let helper = require("../helper.js");

describe("starting OAUTH integration tests", () => {

	let controller, service;

	before((done) => {
		let rootPath = process.cwd();
		imported(rootPath + "/test/data/soajs_profile.js", rootPath + "/test/data/integration/", (err, msg) => {
			if (err) {
				console.log(err);
			}
			if (msg) {
				console.log(msg);
			}
			console.log("Starting Controller and OAUTH service");
			controller = require("soajs.controller");
			setTimeout(function () {

				service = helper.requireModule('./_index.js');
				service.runService(() => {
					setTimeout(function () {
						done();
					}, 5000);
				});

			}, 5000);
		});
	});

	it("loading tests", (done) => {
		require('./index/index');
		require('./oauth/index');
		done();
	});

	it("loading ldap test", (done) => {
		require('./ldap/index.js');
		done();
	});
});<commit_msg>enhanced integration test<commit_after>"use strict";
const imported = require("../data/import.js");
let helper = require("../helper.js");

describe("starting OAUTH integration tests", () => {

	let controller, service;

	before((done) => {
		let rootPath = process.cwd();
		imported(rootPath + "/test/data/soajs_profile.js", rootPath + "/test/data/integration/", (err, msg) => {
			if (err) {
				console.log(err);
			}
			if (msg) {
				console.log(msg);
			}
			console.log("Starting Controller ...");
			controller = require("soajs.controller/_index.js");
			controller.runService(() => {
				console.log("Starting OAUTH ...");
				service = helper.requireModule('./_index.js');
				service.runService(() => {
					setTimeout(function () {
						done();
					}, 5000);
				});
			});
		});
	});

	it("loading tests", (done) => {
		require('./index/index');
		require('./oauth/index');
		done();
	});

	it("loading ldap test", (done) => {
		require('./ldap/index.js');
		done();
	});
});<|endoftext|>


<commit_before>const chai = require('chai');
const assert = chai.assert;

var isColliding = require('../app/lib/collision/is-colliding');
const Skier = require('../app/lib/skier');
const Tree = require('../app/lib/tree');

describe('isColliding', function() {
  beforeEach(function () {
    this.canvas = document.createElement('canvas');
    this.canvas.width = 600;
    this.canvas.height = 500;
    this.context = this.canvas.getContext('2d');
  });

  it('should report if there is a collision', function() {
    var skier = new Skier({ canvas: this.canvas, context: this.context });
    var obstacle = new Tree({ canvas: this.canvas, context: this.context });
    skier.x = 50; skier.y = 50;
    obstacle.x = 50; obstacle.y = 50;

    assert.strictEqual(skier.crashed, false);

    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, true);
  });

  it('should report if there is no collision', function() {
    var skier = new Skier({ canvas: this.canvas, context: this.context });
    var obstacle = new Tree({ canvas: this.canvas, context: this.context });
    skier.x = 50; skier.y = 50;
    obstacle.x = 50; obstacle.y = 30;
    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, false);
  });

  it('should report based on the skiers width', function() {
    var skier = new Skier({ canvas: this.canvas, context: this.context });
    var obstacle = new Tree({ canvas: this.canvas, context: this.context });
    skier.x = 50; skier.y = 50;
    obstacle.x = 50; obstacle.y = skier.y - skier.width - 5;
    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, false);

    obstacle.y = skier.y - skier.width;
    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, false);

    obstacle.y = skier.y - skier.width + 1;
    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, true);
  });
});
<commit_msg>Fix collision test<commit_after>const chai = require('chai');
const assert = chai.assert;

var isColliding = require('../app/lib/collision/is-colliding');
const Skier = require('../app/lib/skier');
const Tree = require('../app/lib/tree');

describe('isColliding', function() {
  beforeEach(function () {
    this.canvas = document.createElement('canvas');
    this.canvas.width = 600;
    this.canvas.height = 500;
    this.context = this.canvas.getContext('2d');
  });

  it('should report if there is a collision', function() {
    var skier = new Skier({ canvas: this.canvas, context: this.context });
    var obstacle = new Tree({ canvas: this.canvas, context: this.context });
    skier.x = 50; skier.y = 50;
    obstacle.x = 50; obstacle.y = 50;

    assert.strictEqual(skier.crashed, false);

    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, true);
  });

  it('should report if there is no collision', function() {
    var skier = new Skier({ canvas: this.canvas, context: this.context });
    var obstacle = new Tree({ canvas: this.canvas, context: this.context });
    skier.x = 50; skier.y = 50;
    obstacle.x = 50; obstacle.y = 30;
    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, false);
  });

  it('should report based on the skiers width', function() {
    var skier = new Skier({ canvas: this.canvas, context: this.context });
    var obstacle = new Tree({ canvas: this.canvas, context: this.context });
    skier.x = 50; skier.y = 50;
    obstacle.x = 50; obstacle.y = skier.y - skier.width - 5;
    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, false);

    obstacle.y = skier.y - skier.width;
    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, false);

    obstacle.y = skier.y - skier.width + 2;
    isColliding(skier, obstacle);

    assert.strictEqual(skier.crashed, true);
  });
});
<|endoftext|>


<commit_before>'use strict';

describe('job packager', function(){
  var JobPackager = require('../src/job_packager');
  var errors = require('../src/errors');
  var utils = require('../src/utils');

  var parts = 4;

  var code = function (a) { return a + 1; };
  var elements = new Uint32Array([1,2,3,4,5,6,7,8]);
  var operationFilter = 'filter';
  var operationMap = 'map';
  var operationReduce = 'reduce';
  var packager = new JobPackager(parts, elements);
  var invalidOperation = 'add';
  var packages = packager.generatePackages([{ code: code, name: operationFilter}]);
  var ctxPackages = packager.generatePackages([{ code: code, name: operationFilter}], {name: 'pjs'});

  it('should not support empty initialization', function () {
    expect(function () {
      var p = new JobPackager();
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should not support empty elements initialization', function () {
    expect(function () {
      var p = new JobPackager(parts);
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should not support empty operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages();
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should not support invalid operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages([{code: code, name: invalidOperation}]);
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should support valid map operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages([{code: code, name: operationMap}]);
    }).to.not.throw(errors.InvalidArgumentsError);
  });

  it('should support valid reduce operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages([{ code: code, name: operationReduce }]);
    }).to.not.throw(errors.InvalidArgumentsError);
  });

  it('should support valid filter operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages([{ code: code, name: operationFilter}]);
    }).to.not.throw(errors.InvalidArgumentsError);
  });

  it('should generate ' + parts + ' packages', function () {
    expect(packages).to.not.be.undefined;
    expect(packages.length).to.equal(parts);
  });

  it('should return a package for each valid index', function () {
    var invalidIndex = parts;
    var negativeIndex = -1;

    for (var i = 0; i < parts; i++) {
      expect(packages[i]).to.not.be.undefined;
    }
    expect(packages[invalidIndex]).to.be.undefined;
    expect(packages[negativeIndex]).to.be.undefined;
  });

  it('should track order on all packages', function () {
    packages.forEach(function (jobPackage, index) {
      expect(jobPackage.index).to.equal(index);
    });
  });

  it('should generate packaged code on all packages', function () {
    packages.forEach(function (jobPackage) {
      expect(jobPackage.operations).to.not.have.length(0);
      jobPackage.operations.forEach(function(op){
        expect(op.code).to.not.be.undefined;
      });
    });
  });

  it('should generate packaged buffer on all packages', function () {
    packages.forEach(function (jobPackage) {
      expect(jobPackage.buffer).to.not.be.undefined;
    });
  });

  it('should not generate packaged context on all packages', function () {
    packages.forEach(function (jobPackage) {
      expect(jobPackage.ctx).to.be.undefined;
    });
  });

  it('should generate packaged context on all packages', function () {
    ctxPackages.forEach(function (jobPackage) {
      expect(jobPackage.ctx).to.not.be.undefined;
      expect(jobPackage.ctx.name).to.equal('pjs');
    });
  });

  it('should track elements type on all packages', function () {
    packages.forEach(function (jobPackage, index) {
      expect(jobPackage.elementsType).to.equal(utils.getTypedArrayType(elements));
    });
  });

  it('should track filter operation on all packages', function () {
    packages.forEach(function (jobPackage, index) {
      expect(jobPackage.operations).to.not.have.length(0);
      jobPackage.operations.forEach(function(op){
        expect(op.name).to.equal(operationFilter);
      });
    });
  });

  it('should track map operation on all packages', function () {
    var mapPackager = new JobPackager(parts, elements);
    var mapPackages = mapPackager.generatePackages([ { code: code, name: operationMap }]);
    mapPackages.forEach(function (jobPackage, index) {
      expect(jobPackage.operations).to.not.have.length(0);
      jobPackage.operations.forEach(function(op){
        expect(op.name).to.equal(operationMap);
      });
    });
  });

  it('should track reduce operation on all packages', function () {
    var mapPackager = new JobPackager(parts, elements);
    var mapPackages = mapPackager.generatePackages([{ code: code, name: operationReduce }]);
    mapPackages.forEach(function (jobPackage, index) {
      expect(jobPackage.operations).to.not.have.length(0);
      jobPackage.operations.forEach(function(op){
        expect(op.name).to.equal(operationReduce);
      });
    });
  });

  it('should not package elements buffer on the packages', function () {
    packages.forEach(function (jobPackage) {
      expect(jobPackage.buffer).to.not.equal(elements.buffer);
    });
  });

  it('should not lose or duplicate data on packaged buffers', function () {
    var elementsConstructor = elements.constructor;

    var index = 0;
    packages.forEach(function (jobPackage) {
      var packagedElements = new elementsConstructor(jobPackage.buffer);
      for (var i = 0; i < packagedElements.length; i++, index++) {
        expect(packagedElements[i]).to.equal(elements[index]);
      }
    });
    expect(index).to.equal(elements.length);
  });

});<commit_msg>[6.2] fixes broken test.<commit_after>'use strict';

describe('job packager', function(){
  var JobPackager = require('../src/job_packager');
  var errors = require('../src/errors');
  var utils = require('../src/utils');

  var parts = 4;

  var code = function (a) { return a + 1; };
  var elements = new Uint32Array([1,2,3,4,5,6,7,8]);
  var operationFilter = 'filter';
  var operationMap = 'map';
  var operationReduce = 'reduce';
  var packager = new JobPackager(parts, elements);
  var invalidOperation = 'add';
  var packages = packager.generatePackages([{ code: code, name: operationFilter}]);
  var ctxPackages = packager.generatePackages([{ code: code, name: operationFilter}], {name: 'pjs'});

  it('should not support empty initialization', function () {
    expect(function () {
      var p = new JobPackager();
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should not support empty elements initialization', function () {
    expect(function () {
      var p = new JobPackager(parts);
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should not support empty operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages();
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should not support invalid operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages([{code: code, name: invalidOperation}]);
    }).to.throw(errors.InvalidArgumentsError);
  });

  it('should support valid map operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages([{code: code, name: operationMap}]);
    }).to.not.throw(errors.InvalidArgumentsError);
  });

  it('should support valid reduce operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages([{ code: code, name: operationReduce }]);
    }).to.not.throw(errors.InvalidArgumentsError);
  });

  it('should support valid filter operation for package generation', function () {
    expect(function () {
      var p = new JobPackager(parts, elements);
      var ps = p.generatePackages([{ code: code, name: operationFilter}]);
    }).to.not.throw(errors.InvalidArgumentsError);
  });

  it('should generate ' + parts + ' packages', function () {
    expect(packages).to.not.be.undefined;
    expect(packages.length).to.equal(parts);
  });

  it('should return a package for each valid index', function () {
    var invalidIndex = parts;
    var negativeIndex = -1;

    for (var i = 0; i < parts; i++) {
      expect(packages[i]).to.not.be.undefined;
    }
    expect(packages[invalidIndex]).to.be.undefined;
    expect(packages[negativeIndex]).to.be.undefined;
  });

  it('should track order on all packages', function () {
    packages.forEach(function (jobPackage, index) {
      expect(jobPackage.index).to.equal(index);
    });
  });

  it('should generate packaged code on all packages', function () {
    packages.forEach(function (jobPackage) {
      expect(jobPackage.operations).to.not.have.length(0);
      jobPackage.operations.forEach(function(op){
        expect(op.code).to.not.be.undefined;
      });
    });
  });

  it('should generate packaged buffer on all packages', function () {
    packages.forEach(function (jobPackage) {
      expect(jobPackage.buffer).to.not.be.undefined;
    });
  });

  it('should not generate packaged context on all packages', function () {
    packages.forEach(function (jobPackage) {
      expect(jobPackage.ctx).to.be.undefined;
    });
  });

  it('should generate packaged context on all packages', function () {
    ctxPackages.forEach(function (jobPackage) {
      expect(jobPackage.ctx).to.not.be.undefined;
      var jobCtx = JSON.parse(jobPackage.ctx);
      expect(jobCtx.name).to.equal('pjs');
    });
  });

  it('should track elements type on all packages', function () {
    packages.forEach(function (jobPackage, index) {
      expect(jobPackage.elementsType).to.equal(utils.getTypedArrayType(elements));
    });
  });

  it('should track filter operation on all packages', function () {
    packages.forEach(function (jobPackage, index) {
      expect(jobPackage.operations).to.not.have.length(0);
      jobPackage.operations.forEach(function(op){
        expect(op.name).to.equal(operationFilter);
      });
    });
  });

  it('should track map operation on all packages', function () {
    var mapPackager = new JobPackager(parts, elements);
    var mapPackages = mapPackager.generatePackages([ { code: code, name: operationMap }]);
    mapPackages.forEach(function (jobPackage, index) {
      expect(jobPackage.operations).to.not.have.length(0);
      jobPackage.operations.forEach(function(op){
        expect(op.name).to.equal(operationMap);
      });
    });
  });

  it('should track reduce operation on all packages', function () {
    var mapPackager = new JobPackager(parts, elements);
    var mapPackages = mapPackager.generatePackages([{ code: code, name: operationReduce }]);
    mapPackages.forEach(function (jobPackage, index) {
      expect(jobPackage.operations).to.not.have.length(0);
      jobPackage.operations.forEach(function(op){
        expect(op.name).to.equal(operationReduce);
      });
    });
  });

  it('should not package elements buffer on the packages', function () {
    packages.forEach(function (jobPackage) {
      expect(jobPackage.buffer).to.not.equal(elements.buffer);
    });
  });

  it('should not lose or duplicate data on packaged buffers', function () {
    var elementsConstructor = elements.constructor;

    var index = 0;
    packages.forEach(function (jobPackage) {
      var packagedElements = new elementsConstructor(jobPackage.buffer);
      for (var i = 0; i < packagedElements.length; i++, index++) {
        expect(packagedElements[i]).to.equal(elements[index]);
      }
    });
    expect(index).to.equal(elements.length);
  });

});<|endoftext|>


<commit_before>import chai, { expect } from 'chai';
import spies from 'chai-spies';
import React from 'react';

import { getRenderedDOM } from 'test/helpers/render';

import State from 'lib/state';
import DataInit from 'lib/data-init';
import DataWatcher from 'lib/data-watcher';

chai.use(spies);

describe('data-watcher', function() {
    it('exists', function() {
        expect(DataWatcher).to.exist;
    });

    describe('data dependencies', function() {
        beforeEach(function() {
            const propsSpy = chai.spy(function() {});
            const nestedPath = [ 'foo', 'bar' ];

            this.propsSpy = propsSpy;

            class Component extends React.Component {
                render() {
                    Object.keys(this.props).forEach(key => {
                        propsSpy(this.props[key]);
                    });

                    return null;
                }
            }

            this.state = new State({
                one: {
                    test: 'hey',
                    test2: 'what\'s'
                },
                two: {
                    test: 'dude',
                    test2: 'up'
                }
            }, {
                asynchronous: false
            });

            this.nestedPath = nestedPath;

            this.dataFactory = chai.spy(() => ({
                one: [ 'one', nestedPath ],
                two: [ 'two', nestedPath ]
            }));

            this.renderedOutput = getRenderedDOM(
                DataInit(this.state)(
                    DataWatcher(this.dataFactory)(Component)
                )
            );
        });

        // todo check more complex scenarious
        it('should update data in nested dependencies', function() {
            this.state.setIn(this.nestedPath, 'test');

            expect(this.propsSpy).to.be.called.with('hey');
            expect(this.propsSpy).to.be.called.with('dude');

            this.state.setIn(this.nestedPath, 'test2');
            expect(this.propsSpy).to.be.called.with('what\'s');
            expect(this.propsSpy).to.be.called.with('up');
        });

        // todo fix
        // it('should not cause memory leak when more than one nested dependencies', function() {
        //     this.state.setIn(this.nestedPath, 'test');
        //
        //     expect(this.dataFactory).to.be.called.exactly(2);
        // });
    });
});
<commit_msg>:space_invader: add test for props-based nested dependencies<commit_after>import chai, { expect } from 'chai';
import spies from 'chai-spies';
import React from 'react';

import { getRenderedDOM } from 'test/helpers/render';

import State from 'lib/state';
import DataInit from 'lib/data-init';
import DataWatcher from 'lib/data-watcher';

chai.use(spies);

describe('data-watcher', function() {
    it('exists', function() {
        expect(DataWatcher).to.exist;
    });

    describe('data dependencies', function() {
        beforeEach(function() {
            const propsSpy = chai.spy(function() {});
            const nestedPath = [ 'foo', 'bar' ];

            this.propsSpy = propsSpy;

            class Component extends React.Component {
                render() {
                    Object.keys(this.props).forEach(key => {
                        propsSpy(this.props[key]);
                    });

                    return null;
                }
            }

            this.state = new State({
                one: {
                    test: 'hey',
                    test2: 'what\'s'
                },
                two: {
                    test: 'dude',
                    test2: 'up'
                },
                three: {
                    test3: 'hooray!'
                },
                foo: {
                    magic: {
                        bar: 'test3'
                    }
                }
            }, {
                asynchronous: false
            });

            this.nestedPath = nestedPath;

            this.dataFactory = chai.spy(props => ({
                one: [ 'one', nestedPath ],
                two: [ 'two', nestedPath ],
                complex: [ 'three', [ 'foo', props.stuff, 'bar' ] ]
            }));

            this.renderMock = function(props) {
                getRenderedDOM(
                    DataInit(this.state)(
                        DataWatcher(this.dataFactory)(Component)
                    ),
                    props
                );
            };
        });

        it('should update data in nested dependencies', function() {
            this.renderMock();

            this.state.setIn(this.nestedPath, 'test');

            expect(this.propsSpy).to.be.called.with('hey');
            expect(this.propsSpy).to.be.called.with('dude');

            this.state.setIn(this.nestedPath, 'test2');
            expect(this.propsSpy).to.be.called.with('what\'s');
            expect(this.propsSpy).to.be.called.with('up');
        });

        // todo fix https://github.com/mistadikay/doob/issues/12?
        it('should update data in props-based nested dependencies', function() {
            this.renderMock({ stuff: 'magic' });

            expect(this.propsSpy).to.be.called.with('hooray!');
        });

        // todo fix https://github.com/mistadikay/doob/issues/11
        // it('should not cause memory leak when more than one nested dependencies', function() {
        //     this.renderMock();
        //     this.state.setIn(this.nestedPath, 'test');
        //
        //     expect(this.dataFactory).to.be.called.exactly(2);
        // });
    });
});
<|endoftext|>


<commit_before>'use strict';

var Provider = require('../../lib/provider');

describe('Provider Class', function () {

  it('should export Provider constructor', function () {
    expect(Provider).to.be.a('function');
  });

});<commit_msg>test: Added provider spec<commit_after>'use strict';

var Provider = require('../../lib/provider');

describe('Provider module', function () {

  it('should export Provider constructor', function () {
    expect(Provider).to.be.a('function');
  });

});

describe('Provider class', function () {
  var provider = new Provider();

  describe('#name', function () {
    it('should set `name` property as type String', function () {
      expect(provider.name).to.be.a('string');
    });
    it('should set `name` property as `unknown`', function () {
      expect(provider.name).equal('unknown');
    });
  });

  describe('#validate', function () {
    it('should have `validate` method', function () {
      expect(provider.validate).to.be.a('function');
    });

    it('should not throw error without callback', function () {
      provider.validate('12341234');
    });

    it('should call callback with error when validate method fails', function (done) {
      provider.validate(null, function (e, isValid) {
        expect(e).instanceOf(Error);
        expect(isValid).to.be.a('undefined');
        done();
      });
    });

    it('should validate string value `123456789`', function (done) {
      provider.validate('123456789', function (e, isValid) {
        expect(isValid).equal(true);
        done();
      });
    });

    it('should validate number value 123456789', function (done) {
      provider.validate(123456789, function (e, isValid) {
        expect(isValid).equal(true);
        done();
      });
    });
  });

  describe('#fetch', function () {
    it('should have `fetch` method', function () {
      expect(provider.fetch).to.be.a('function');
    });

    it('should not throw error without callback', function () {
      provider.fetch('12341234');
    });

    it('should call callback with error because it is not implemented', function (done) {
      provider.fetch('123456789', function (e) {
        expect(e).instanceOf(Error);
        expect(e.message).equal('not implemented');
        done();
      })
    });
  });

  describe('#parse', function () {
    it('should have `parse` method', function () {
      expect(provider.parse).to.be.a('function');
    });

    it('should not throw error without callback', function () {
      provider.parse('12341234');
    });

    it('should call callback with error because it is not implemented', function (done) {
      provider.parse('123456789', function (e) {
        expect(e).instanceOf(Error);
        expect(e.message).equal('not implemented');
        done();
      })
    });
  });

  describe('#execute', function () {
    it('should have `execute` method', function () {
      expect(provider.execute).to.be.a('function');
    });

    it('should not throw error without callback', function () {
      provider.execute('12341234');
    });

    it('should call callback with error when validate method fails', function (done) {
      provider.execute({}, function (e) {
        expect(e).instanceOf(Error);
        done();
      });
    });

    it('should call validate', function (done) {
      provider.execute('wrong\ntext', function (e) {
        expect(e).instanceOf(Error);
        expect(e.message).equal('invalid tracking');
        done();
      });
    });

    it('should call fetch', function (done) {
      provider.execute('123456789', function (e) {
        expect(e).instanceOf(Error);
        expect(e.message).equal('not implemented');
        done();
      });
    });
  });
});<|endoftext|>