Matteo Scandolo | bba1d78 | 2016-07-12 15:56:23 -0700 | [diff] [blame] | 1 | (function () { |
| 2 | angular.module('xos.dashboardManager') |
| 3 | .directive('userDashboards', function(){ |
| 4 | return { |
| 5 | restrict: 'E', |
| 6 | scope: {}, |
| 7 | bindToController: true, |
| 8 | controllerAs: 'vm', |
| 9 | templateUrl: 'templates/user-dashboards.tpl.html', |
| 10 | controller: function($q, _, UserDashboards, Dashboards){ |
| 11 | |
| 12 | // retrieving user list |
| 13 | $q.all([ |
| 14 | UserDashboards.query().$promise, |
| 15 | Dashboards.query({enabled: 'False'}).$promise, |
| 16 | ]) |
| 17 | .then((res) => { |
| 18 | let [dashboards, disabled] = res; |
| 19 | this.disabled = disabled; |
| 20 | this.list = { |
| 21 | enabled: _.filter(dashboards, {shown: true}), |
| 22 | disabled: _.filter(dashboards, {shown: false}) |
| 23 | }; |
| 24 | }) |
| 25 | .catch((e) => { |
| 26 | throw new Error(e); |
| 27 | }); |
| 28 | |
| 29 | this.removeFromList = (listName, itemId) => { |
| 30 | _.remove(this.list[listName], {id: itemId}); |
| 31 | }; |
| 32 | |
| 33 | this.addToList = (listName, item) => { |
| 34 | this.list[listName].push(item) |
| 35 | }; |
| 36 | |
| 37 | this.isInList = (listName, item) => { |
| 38 | return _.find(this.list[listName], item); |
| 39 | }; |
| 40 | |
| 41 | this.reorderList = (list, newPos, oldPos, item) => { |
| 42 | |
| 43 | let listToOrder = _.filter(list, i => { |
| 44 | // if is the item, skip it, it is already updated |
| 45 | if(i.id === item.id){ |
| 46 | return false; |
| 47 | } |
| 48 | if(i.order < oldPos){ |
| 49 | return true; |
| 50 | } |
| 51 | if(i.order >= newPos){ |
| 52 | return true; |
| 53 | } |
| 54 | return false; |
| 55 | }); |
| 56 | |
| 57 | listToOrder = listToOrder.map(i => { |
| 58 | i.order++; |
| 59 | return i; |
| 60 | }) |
| 61 | }; |
| 62 | |
| 63 | this.addedToList = (event, index, item, external, list) => { |
| 64 | let originalPosition; |
| 65 | |
| 66 | // load the item in the list |
| 67 | let itemInList = this.isInList(list, item); |
| 68 | if(itemInList){ |
| 69 | // if is in the list update it |
| 70 | originalPosition = item.order; |
| 71 | itemInList.order = index; |
| 72 | item.order = index; |
| 73 | } |
| 74 | else { |
| 75 | // create a new one |
| 76 | item.order = this.list[list].length; |
| 77 | item.shown = !item.shown; |
| 78 | } |
| 79 | |
| 80 | const otherList = list === 'enabled' ? 'disabled' : 'enabled'; |
| 81 | |
| 82 | UserDashboards.update(item).$promise |
| 83 | .then((item) => { |
| 84 | if(!itemInList){ |
| 85 | // if it is not in the list, update both lists |
| 86 | this.addToList(list, item); |
| 87 | this.removeFromList(otherList, item.id); |
| 88 | } |
| 89 | else { |
| 90 | // reorder |
| 91 | this.reorderList(this.list[list], index, originalPosition, item); |
| 92 | } |
| 93 | }); |
| 94 | } |
| 95 | } |
| 96 | }; |
| 97 | }); |
| 98 | })(); |