All files selection.js

100% Statements 32/32
100% Branches 4/4
100% Functions 9/9
100% Lines 32/32
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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106                                      42x 42x 42x 42x       98x         98x 98x 98x       14x         14x 14x 14x       5x         5x 5x 5x       1x         1x 1x 1x       28x         28x 28x 28x       188x       146x 144x   146x 58x         146x     146x 142x              
import Emitter from 'component-emitter'
import { flow } from 'lodash/fp'
 
import {
  init,
  setItems,
  replace,
  toggle,
  remove,
  removeAll,
  rangeTo,
  getSelection,
  getChangedSelection,
  getChangedDeselection,
} from './operations'
 
class Selection extends Emitter {
 
  constructor(iterable) {
    super()
    this.iterable = iterable
    this.state = init()
    this._updateSelectedItems()
  }
 
  toggle(item) {
    this.state = flow(
      setItems(this.iterable),
      toggle(item)
    )(this.state)
 
    this._updateSelectedItems()
    this._notifyChangedItems()
    this._emitChangeEvent()
  }
 
  replace(item) {
    this.state = flow(
      setItems(this.iterable),
      replace(item)
    )(this.state)
 
    this._updateSelectedItems()
    this._notifyChangedItems()
    this._emitChangeEvent()
  }
 
  remove(items) {
    this.state = flow(
      setItems(this.iterable),
      remove(items)
    )(this.state)
 
    this._updateSelectedItems()
    this._notifyChangedItems()
    this._emitChangeEvent()
  }
 
  removeAll() {
    this.state = flow(
      setItems(this.iterable),
      removeAll()
    )(this.state)
 
    this._updateSelectedItems()
    this._notifyChangedItems()
    this._emitChangeEvent()
  }
 
  rangeTo(endItem) {
    this.state = flow(
      setItems(this.iterable),
      rangeTo(endItem)
    )(this.state)
 
    this._updateSelectedItems()
    this._notifyChangedItems()
    this._emitChangeEvent()
  }
 
  _updateSelectedItems() {
    this.selectedItems = getSelection(this.state)
  }
 
  _notifyChangedItems() {
    for (const item of getChangedSelection(this.state)) {
      item.select()
    }
    for (const item of getChangedDeselection(this.state)) {
      item.deselect()
    }
  }
 
  _emitChangeEvent() {
    const change = (getChangedSelection(this.state).length > 0) ||
      (getChangedDeselection(this.state).length > 0)
 
    if (change) {
      this.emit('change', this.selectedItems.slice())
    }
  }
 
}
 
export { Selection }