All files action.js

82.76% Statements 24/29
68.75% Branches 11/16
100% Functions 7/7
82.76% Lines 24/29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86    2x       7x       3x   3x 3x 2x 2x       3x 3x               1x         2x             1x 1x         1x       1x 2x 1x 1x 1x       1x   1x                       1x 2x 1x                      
import debug from 'debug'
 
var log = debug('ddf.action')
 
class Action {
  constructor(conditions) {
    this.conditions = conditions || []
  }
 
  execute(field) {
    let method = 'apply'
 
    for (var i=0; i<this.conditions.length; i++) {
      if (!this.conditions[i].validate(field.form)) {
        method = 'unapply'
        break
      }
    }
 
    log(this, '.', method, '(', field, ')')
    this[method](field)
  }
}
 
// Remove a field from a form.
class Remove extends Action {
  // Hide the field.
  apply(field) {
    field.hide()
  }
 
  // Show the field.
  unapply(field) {
    field.show()
  }
}
 
// Remove given choices from a field.
class RemoveChoices extends Action {
  constructor(conditions, choices) {
    super(conditions)
    this.choices = choices
  }
 
  // Hide options which are not in this.choices from a field.
  apply(field) {
    Iif (this.choices.indexOf(field.value) >= 0) {
      field.valueReset()
    }
 
    for (let i=0; i < field.element.options.length; i++) {
      if (this.choices.indexOf(field.element.options[i].value) >= 0) {
        let option = field.element.options[i]
        option.classList.add('ddf-hide')
        option.selected = false
      }
    }
 
    Eif (!field.multiple) {
      // If selected value was removed, empty the field
      Iif (this.choices.indexOf(field.value) >= 0) {
        let empty = field.element.querySelector('option[value=""]')
        if (empty === undefined) {
          field.element.prepend('<option value=""></option>')
        }
        field.value = ''
      }
    }
  }
 
  // Show options which are not in this.choices from a field.
  unapply(field) {
    for (let i=0; i < field.element.options.length; i++) {
      if (!this.choices.indexOf(field.element.options[i].value)) {
        field.element.options[i].classList.remove('ddf-hide')
      }
    }
  }
}
 
export {
  Action,
  Remove,
  RemoveChoices
}