|
| 1 | +import Ember from 'ember'; |
| 2 | +import layout from '../templates/components/materialize-selectable-item-group'; |
| 3 | + |
| 4 | +var get = Ember.get, |
| 5 | + map = Ember.EnumerableUtils.map, |
| 6 | + indexOf = Ember.EnumerableUtils.indexOf; |
| 7 | + |
| 8 | +export default Ember.Component.extend({ |
| 9 | + content: null, |
| 10 | + selection: null, |
| 11 | + layout: layout, |
| 12 | + optionValuePath: 'content', |
| 13 | + optionLabelPath: 'content', |
| 14 | + multiple: false, |
| 15 | + __materializeSelectableItemGroup: true, |
| 16 | + |
| 17 | + init() { |
| 18 | + this._super(...arguments); |
| 19 | + if (this.get('selection') === null && !!this.get('multiple')) { |
| 20 | + this.set('selection', Ember.A()); |
| 21 | + } |
| 22 | + }, |
| 23 | + |
| 24 | + isValueSelected(value) { |
| 25 | + if (this.get('multiple')) { |
| 26 | + return indexOf(this.get('selection'), value) >= 0; |
| 27 | + } |
| 28 | + else { |
| 29 | + return this.get('selection') === value; |
| 30 | + } |
| 31 | + }, |
| 32 | + |
| 33 | + setValueSelection(value, select) { |
| 34 | + if (select) { |
| 35 | + return this.addToSelection(value); |
| 36 | + } |
| 37 | + else { |
| 38 | + return this.removeFromSelection(value); |
| 39 | + } |
| 40 | + }, |
| 41 | + |
| 42 | + addToSelection(value) { |
| 43 | + if (this.get('multiple')) { |
| 44 | + this.get('selection').addObject(value); |
| 45 | + } |
| 46 | + else { |
| 47 | + this.set('selection', value); |
| 48 | + } |
| 49 | + }, |
| 50 | + |
| 51 | + removeFromSelection(value) { |
| 52 | + if (this.get('multiple')) { |
| 53 | + this.get('selection').removeObject(value); |
| 54 | + } |
| 55 | + else { |
| 56 | + throw new Error('removeFromSelection is not supported in single-selection mode'); |
| 57 | + } |
| 58 | + }, |
| 59 | + |
| 60 | + _valuePath: Ember.computed('optionValuePath', function () { |
| 61 | + var optionValuePath = get(this, 'optionValuePath'); |
| 62 | + return optionValuePath.replace(/^content\.?/, ''); |
| 63 | + }), |
| 64 | + |
| 65 | + _labelPath: Ember.computed('optionLabelPath', function () { |
| 66 | + var optionLabelPath = get(this, 'optionLabelPath'); |
| 67 | + return optionLabelPath.replace(/^content\.?/, ''); |
| 68 | + }), |
| 69 | + |
| 70 | + _content: Ember.computed('content.[]', '_valuePath', '_labelPath',function () { |
| 71 | + var valuePath = get(this, '_valuePath'); |
| 72 | + var labelPath = get(this, '_labelPath'); |
| 73 | + var content = get(this, 'content') || Ember.A([]); |
| 74 | + |
| 75 | + if (valuePath && labelPath) { |
| 76 | + return Ember.A(map(content, function (el) { return {value: get(el, valuePath), label: get(el, labelPath)}; })); |
| 77 | + } else { |
| 78 | + return Ember.A(map(content, function (el) { return {value: el, label: el}; })); |
| 79 | + } |
| 80 | + }) |
| 81 | +}); |
0 commit comments