# all files / clique/model/ Selection.js

23.08% Statements 9/39
25% Branches 4/16
9.09% Functions 1/11
14.29% Lines 5/35
1 branch Ignored

    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
    791×
    1×

    1×

    1×

     import _ from 'underscore';
    import Backbone from 'backbone';

    const Selection = Backbone.Model.extend({
      initialize: function () {
        this.focalPoint = 0;
      },

      add: function (key) {
        this.set(key, key);
        if (this.size()) {
          this.trigger('focused', this.focused());
        }

        this.trigger('added', key);
      },

      remove: function (key) {
        var focused = this.focused() === key;

        this.unset(key);

        if (this.focalPoint >= this.size()) {
          this.focalPoint = Math.max(0, this.size() - 1);
          this.trigger('focused', this.focused());
        } else if (focused) {
          this.focusLeft();
        }

        this.trigger('removed', key);
      },

      items: function () {
        return _.keys(this.attributes);
      },

      focusKey: function (target) {
        var index = _.indexOf(this.items(), target);
        if (index === -1) {
          return false;
        }

        this.focus(index);
        return true;
      },

      focus: function (target) {
        this.focalPoint = target;
        if (this.focalPoint < 0) {
          while (this.focalPoint < 0) {
            this.focalPoint += this.size();
          }
        } else if (this.focalPoint >= this.size()) {
          this.focalPoint = this.focalPoint % this.size();
        }

        this.trigger('focused', this.focused());
      },

      focusLeft: function () {
        this.focus(this.focalPoint - 1);
      },

      focusRight: function () {
        this.focus(this.focalPoint + 1);
      },

      focused: function () {
        return this.items()[this.focalPoint];
      },

      size: function () {
        return _.size(this.attributes);
      }
    });

    export default Selection;