Blame view

scripts/FeedController.js 10.5 KB
684d730ca   Andrew Buss   refactor; trying ...
1
  angular.module('flashy.FeedController', ['ui.router', 'ngAnimate']).
9c420b35c   Rachel Lee   Separating all cu...
2

688e5fe71   Andrew Buss   properly initiali...
3
      controller('FeedController', function($scope, $rootScope, $stateParams, $state, $http, $window, $timeout, UserService) {
bbba33088   Andrew Buss   Added addclass st...
4
          console.log('Hello from feed');
107013870   Andrew Buss   ui tweaks, check ...
5
6
          sectionId = parseInt($stateParams.sectionId);
          if (!UserService.isInSection(sectionId)) {
3fdc86f6c   Andrew Buss   fix off-by-one; d...
7
              console.log('user is not enrolled in ' + sectionId);
107013870   Andrew Buss   ui tweaks, check ...
8
9
              return $state.go('addclass');
          }
20f4dcac7   Andrew Buss   class name at top...
10
          $rootScope.currentSection = $rootScope.SectionResource.get({sectionId: sectionId});
7cf67e561   Andrew Buss   merge proper
11
          $rootScope.debug_flashcard = false;
fe2c7edc6   Andrew Buss   fix flashcard sca...
12
          $scope.cards = false;
fe2c7edc6   Andrew Buss   fix flashcard sca...
13
14
          $scope.cardCols = []; // organized data
          $scope.numCols = 0;
7cf67e561   Andrew Buss   merge proper
15
          $scope.cardTable = {}; // look up table of cards, {'colNum':col, 'obj':card}
107013870   Andrew Buss   ui tweaks, check ...
16

fe2c7edc6   Andrew Buss   fix flashcard sca...
17
18
19
20
          function calculate_cols() {
              var avail = $window.innerWidth - 17;
              return Math.max(1, Math.floor(avail / 250));
          }
684d730ca   Andrew Buss   refactor; trying ...
21
22
          $scope.refreshColumnWidth = function() {
              console.log('refreshing column width');
fe2c7edc6   Andrew Buss   fix flashcard sca...
23
24
25
26
              avail = $window.innerWidth - 17;
              width = Math.floor(avail / Math.floor(avail / 250));
              $('.cardColumn').css({
                  width: width + 'px',
9822fe0ff   Andrew Buss   to properly apply...
27
                  'font-size': 100 * width / 250 + '%'
fe2c7edc6   Andrew Buss   fix flashcard sca...
28
29
              });
              $('.cardColumn .card.flashy').css({
9822fe0ff   Andrew Buss   to properly apply...
30
                  width: width - 12 + 'px',
fe2c7edc6   Andrew Buss   fix flashcard sca...
31
32
                  height: (width * 3 / 5) + 'px'
              });
684d730ca   Andrew Buss   refactor; trying ...
33
          };
fe2c7edc6   Andrew Buss   fix flashcard sca...
34

688e5fe71   Andrew Buss   properly initiali...
35
          $scope.refreshLayout = function() {
9822fe0ff   Andrew Buss   to properly apply...
36
              // check if we actually need to refresh the whole layout
684d730ca   Andrew Buss   refactor; trying ...
37
              if (calculate_cols() == $scope.numCols) return $scope.refreshColumnWidth();
fe2c7edc6   Andrew Buss   fix flashcard sca...
38
39
              $scope.numCols = calculate_cols();
              console.log('refreshing layout for ' + $scope.numCols + ' columns');
212592d24   Andrew Buss   re-add userservice
40
              $scope.cardCols = [];
688e5fe71   Andrew Buss   properly initiali...
41
42
43
              var cols = [];
              for (i = 0; i < $scope.numCols; i++) cols.push([]);
              $scope.cards.forEach(function(card, i) {
9822fe0ff   Andrew Buss   to properly apply...
44
                  cols[i % $scope.numCols].push(card);
7cf67e561   Andrew Buss   merge proper
45
                  $scope.cardTable[card.id] = {'colNum': (i % $scope.numCols), 'obj': card};
9822fe0ff   Andrew Buss   to properly apply...
46
47
              });
              // wait until the next digest cycle to update cardCols
684d730ca   Andrew Buss   refactor; trying ...
48

688e5fe71   Andrew Buss   properly initiali...
49
              $timeout(function() {
9822fe0ff   Andrew Buss   to properly apply...
50
                  $scope.cardCols = cols;
684d730ca   Andrew Buss   refactor; trying ...
51
                  $timeout($scope.refreshColumnWidth);
9822fe0ff   Andrew Buss   to properly apply...
52
              });
684d730ca   Andrew Buss   refactor; trying ...
53

fe2c7edc6   Andrew Buss   fix flashcard sca...
54
          };
212592d24   Andrew Buss   re-add userservice
55

fe2c7edc6   Andrew Buss   fix flashcard sca...
56
          angular.element($window).bind('resize', $scope.refreshLayout);
688e5fe71   Andrew Buss   properly initiali...
57
          $scope.refreshCards = function() {
5ce17b918   Tetranoir   feed controller, ...
58
              $http.get('/api/sections/' + sectionId + '/feed/').
688e5fe71   Andrew Buss   properly initiali...
59
                  success(function(data) {
5ce17b918   Tetranoir   feed controller, ...
60
                      console.log(data);
9822fe0ff   Andrew Buss   to properly apply...
61
                      $scope.cards = data;
425c32c56   Tetranoir   columns basically...
62
                      $scope.refreshLayout();
5ce17b918   Tetranoir   feed controller, ...
63
64
                      console.log('success in refresh cards...');
                  }).
688e5fe71   Andrew Buss   properly initiali...
65
                  error(function(err) {
5ce17b918   Tetranoir   feed controller, ...
66
                      console.log('refresh fail');
107013870   Andrew Buss   ui tweaks, check ...
67
                      console.log(err);
5ce17b918   Tetranoir   feed controller, ...
68
69
                  });
          };
fe2c7edc6   Andrew Buss   fix flashcard sca...
70

688e5fe71   Andrew Buss   properly initiali...
71
          $scope.add = function(card) {
c6ac1ffcf   Andrew Buss   refactor; $timeou...
72
              var colNum = 0;
fcda9ffd2   Tetranoir   feed controller a...
73
              var lowestCol = $scope.cardCols[0];
7cf67e561   Andrew Buss   merge proper
74
              var lowestColNum = 0;
c6ac1ffcf   Andrew Buss   refactor; $timeou...
75
              while (colNum < $scope.numCols) {
a3d433600   Tetranoir   enter and leave a...
76
                  if ($scope.cardCols[colNum].length == 0) {
879bcc09b   Andrew Buss   don't unpull befo...
77
78
                      lowestCol = $scope.cardCols[colNum];
                      break;
fcda9ffd2   Tetranoir   feed controller a...
79
                  } else if ($scope.cardCols[colNum].length < lowestCol.length) {
879bcc09b   Andrew Buss   don't unpull befo...
80
                      lowestCol = $scope.cardCols[colNum];
7cf67e561   Andrew Buss   merge proper
81
                      lowestColNum = colNum;
879bcc09b   Andrew Buss   don't unpull befo...
82
83
                      lowestColLen = $scope.cardCols[colNum].length;
                  }
c6ac1ffcf   Andrew Buss   refactor; $timeou...
84
85
                  colNum++;
              }
c6ac1ffcf   Andrew Buss   refactor; $timeou...
86
              console.log(card);
684d730ca   Andrew Buss   refactor; trying ...
87
              $scope.cards.push(data);
c6ac1ffcf   Andrew Buss   refactor; $timeou...
88
              $timeout(function() {
a3d433600   Tetranoir   enter and leave a...
89
                  lowestCol.unshift(card);
7cf67e561   Andrew Buss   merge proper
90
                  $scope.cardTable[card.id] = {'colNum': lowestColNum, 'obj': card};
0c1e87578   Andrew Buss   refresh css when ...
91
                  $timeout($scope.refreshColumnWidth);
c6ac1ffcf   Andrew Buss   refactor; $timeou...
92
              });
fe2c7edc6   Andrew Buss   fix flashcard sca...
93
          };
0700ad8bb   Andrew Buss   change verify ema...
94

7cf67e561   Andrew Buss   merge proper
95
96
97
98
99
100
101
102
103
          $scope.sortAdd = function(card, array) {
              console.log('sort add');
              array.forEach(function(ele, i, ary) {
                  if (ele.score <= card.score) {
                      ary.splice(i, 0, card);
                      return;
                  }
              });
          };
fe2c7edc6   Andrew Buss   fix flashcard sca...
104

688e5fe71   Andrew Buss   properly initiali...
105
          $scope.hide = function(card) {
fe2c7edc6   Andrew Buss   fix flashcard sca...
106
              console.log('hiding card');
fe2c7edc6   Andrew Buss   fix flashcard sca...
107
              var found = -1;
7cf67e561   Andrew Buss   merge proper
108
109
110
111
112
113
114
              col = $scope.cardTable[card.id].colNum;
              found = $scope.cardCols[col].indexOf(card);
              if (found != -1) {
                  $scope.cardCols[col].splice(found, 1);
                  console.log('card hidden');
                  return col;
              }
fe2c7edc6   Andrew Buss   fix flashcard sca...
115
116
              console.log('Error finding card to hide:');
              console.log(card);
7cf67e561   Andrew Buss   merge proper
117
118
              return -1;
          };
0c65d0c07   Andrew Buss   try to fix behavi...
119

a82dd4015   Tetranoir   fixed abuss merge...
120
121
122
123
124
125
126
127
128
129
130
  		$scope.update = function(id, new_score) {
  			card = $scope.cardTable[id].obj;
  			if (Math.abs(new_score - card.score) < .0001) {
  				console.log('score same, no update required');
  				return;
  			}
  			console.log('updating');
  			console.log(card);
  			var column = $scope.cardCols[$scope.cardTable[id].colNum];
  			var found = column.indexOf(card);
  			var i = 0;
0c65d0c07   Andrew Buss   try to fix behavi...
131
  			for (; i < column.length; i++)
a82dd4015   Tetranoir   fixed abuss merge...
132
133
  				if (column[i].score <= new_score) break;
  			card.score = new_score;
322f74111   Tetranoir   angular digest cy...
134
135
136
  			if ($scope.$$phase) { // most of the time it is "$digest"
  				column.splice(i, 0, column.splice(found, 1)[0]);
  			} else {
96194a354   Tetranoir   oops, fixed broke...
137
  				$scope.$apply(column.splice(i, 0, column.splice(found, 1)[0]));
322f74111   Tetranoir   angular digest cy...
138
  			}
a82dd4015   Tetranoir   fixed abuss merge...
139
  		};
fe2c7edc6   Andrew Buss   fix flashcard sca...
140

235b8e0ec   Andrew Buss   realtime is hard,...
141
142
143
144
145
146
147
148
          var loc = window.location, new_uri;
          if (loc.protocol === 'https:') {
              new_uri = 'wss:';
          } else {
              new_uri = 'ws:';
          }
          new_uri += '//' + loc.host;
          var ws = new WebSocket(new_uri + '/ws/feed/' + sectionId + '?subscribe-broadcast');
688e5fe71   Andrew Buss   properly initiali...
149
          ws.onopen = function() {
235b8e0ec   Andrew Buss   realtime is hard,...
150
151
              console.log('websocket connected');
          };
688e5fe71   Andrew Buss   properly initiali...
152
          ws.onmessage = function(e) {
7cf67e561   Andrew Buss   merge proper
153
              data = JSON.parse(e.data);
235b8e0ec   Andrew Buss   realtime is hard,...
154
              console.log('got websocket message ' + e.data);
7cf67e561   Andrew Buss   merge proper
155
              console.log(data);
f71cb843b   Andrew Buss   tweaks; email ver...
156
              if (data.event_type == 'new_card') {
425c32c56   Tetranoir   columns basically...
157
                  $scope.add(data.flashcard);
517adf2f1   Tetranoir   listening for sco...
158
              } else if (data.event_type == 'score_change') {
7cf67e561   Andrew Buss   merge proper
159
160
                  $scope.update(data.flashcard_id, data.new_score);
              }
235b8e0ec   Andrew Buss   realtime is hard,...
161
          };
688e5fe71   Andrew Buss   properly initiali...
162
          ws.onerror = function(e) {
235b8e0ec   Andrew Buss   realtime is hard,...
163
164
              console.error(e);
          };
688e5fe71   Andrew Buss   properly initiali...
165
          ws.onclose = function(e) {
235b8e0ec   Andrew Buss   realtime is hard,...
166
167
              console.log('connection closed');
          };
107013870   Andrew Buss   ui tweaks, check ...
168
169
170
  
          var resetModal = function() {
              $('#new-card-input').html('');
065f0cdac   Tetranoir   node.data error a...
171
              $('#newCard').closeModal(modal_options);
107013870   Andrew Buss   ui tweaks, check ...
172
          };
688e5fe71   Andrew Buss   properly initiali...
173
          $scope.pushCard = function() {
efc77eb59   Andrew Buss   blanks kinda work
174
175
              var i = 0;
              var blanks = [];
688e5fe71   Andrew Buss   properly initiali...
176
              $('#new-card-input')[0].childNodes.forEach(function(node) {
107013870   Andrew Buss   ui tweaks, check ...
177
178
179
180
                  if (typeof node.data == 'undefined') {
                      console.log('undefined node');
                      return resetModal();
                  }
efc77eb59   Andrew Buss   blanks kinda work
181
182
183
184
185
186
187
188
189
190
                  node = $(node)[0];
                  console.log(node);
                  if (node.tagName == 'B') {
                      text = $(node).text();
                      blanks.push([i, i + text.length]);
                      i += text.length;
                  } else {
                      i += node.data.length;
                  }
              });
1167ab44a   Rachel Lee   Feed submit is go...
191
              var myCard = {
065f0cdac   Tetranoir   node.data error a...
192
                  'text': $('#new-card-input').text().trim(),
5227ae123   Andrew Buss   rejoice; now we c...
193
                  'mask': blanks,
20771fdcb   Andrew Buss   push sorta works
194
                  section: sectionId
2f199068c   Andrew Buss   focus input on ca...
195
              };
107013870   Andrew Buss   ui tweaks, check ...
196
197
198
199
              if (myCard.text == '') {
                  console.log('blank flashcard not pushed:' + myCard.text);
                  return resetModal();
              }
1167ab44a   Rachel Lee   Feed submit is go...
200
              $http.post('/api/flashcards/', myCard).
688e5fe71   Andrew Buss   properly initiali...
201
                  success(function(data) {
065f0cdac   Tetranoir   node.data error a...
202
                      console.log('flashcard pushed: ' + myCard.text);
f71cb843b   Andrew Buss   tweaks; email ver...
203
204
205
                      if (!UserService.hasVerifiedEmail()) {
                          Materialize.toast("<p>Thanks for contributing! However, others won't see your card until you verify your email address<p>", 4000);
                      }
684d730ca   Andrew Buss   refactor; trying ...
206

8fa323ef6   Andrew Buss   more on userservi...
207
                  }).
688e5fe71   Andrew Buss   properly initiali...
208
                  error(function(error) {
807399a02   Andrew Buss   push dialog hopef...
209
                      console.log('something went wrong pushing a card!');
8fa323ef6   Andrew Buss   more on userservi...
210
                  });
107013870   Andrew Buss   ui tweaks, check ...
211
              return resetModal();
32b3331d8   Melody   Fixed fancy butto...
212
          };
2ad496102   Rachel Lee   Tweaking hotkey a...
213
          /* Key bindings for the whole feed window. Hotkey it up! */
b83f46393   Andrew Buss   only listen for c...
214
          var listenForC = true;
807399a02   Andrew Buss   push dialog hopef...
215
216
217
218
219
220
221
222
223
  
          // Need to pass these options into openmodal and leanmodal,
          // otherwise the ready handler doesn't get called
  
          modal_options = {
              dismissible: true, // Modal can be dismissed by clicking outside of the modal
              opacity: 0, // Opacity of modal background
              in_duration: 300, // Transition in duration
              out_duration: 200, // Transition out duration
688e5fe71   Andrew Buss   properly initiali...
224
              ready: function() {
807399a02   Andrew Buss   push dialog hopef...
225
226
227
228
                  listenForC = false;
                  console.log('modal OPENING');
                  $('#new-card-input').focus();
              },
688e5fe71   Andrew Buss   properly initiali...
229
              complete: function() {
807399a02   Andrew Buss   push dialog hopef...
230
231
232
233
234
                  listenForC = true;
                  console.log('modal done, closing');
                  $('#new-card-input').blur();
              }
          };
688e5fe71   Andrew Buss   properly initiali...
235
          $(document).keydown(function(e) {
456616544   Rachel Lee   Hotkeyed compose ...
236
              var keyed = e.which;
c6ac1ffcf   Andrew Buss   refactor; $timeou...
237
              if (keyed == 67 && listenForC) { // "c" for compose
807399a02   Andrew Buss   push dialog hopef...
238
239
                  $('#newCard').openModal(modal_options);
                  e.preventDefault();
b83f46393   Andrew Buss   only listen for c...
240
241
                  listenForC = false;
                  return false;
c6ac1ffcf   Andrew Buss   refactor; $timeou...
242
              } else if (keyed == 27) { // clear on ESC
2ad496102   Rachel Lee   Tweaking hotkey a...
243
244
                  listenForC = true;
                  document.getElementById('new-card-input').value = '';
456616544   Rachel Lee   Hotkeyed compose ...
245
246
              }
          });
688e5fe71   Andrew Buss   properly initiali...
247
          $(document).ready(function() {
f71cb843b   Andrew Buss   tweaks; email ver...
248
              $('.tooltipped').tooltip({delay: 50});
8fa323ef6   Andrew Buss   more on userservi...
249
              // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
807399a02   Andrew Buss   push dialog hopef...
250
              $('.modal-trigger').leanModal(modal_options);
688e5fe71   Andrew Buss   properly initiali...
251
              $('#new-card-input').on('keydown', function(e) {
efc77eb59   Andrew Buss   blanks kinda work
252
253
254
                  if (e.which == 13) {
                      e.preventDefault();
                      $scope.pushCard();
c6ac1ffcf   Andrew Buss   refactor; $timeou...
255
                      listenForC = true;
efc77eb59   Andrew Buss   blanks kinda work
256
257
258
                      return false;
                  }
              });
688e5fe71   Andrew Buss   properly initiali...
259
              $('button#blank-selected').click(function() {
efc77eb59   Andrew Buss   blanks kinda work
260
261
                  console.log(window.getSelection());
                  document.execCommand('bold');
f6cd8fce8   Andrew Buss   get current selec...
262
              });
34a342819   Melody   Nicer new flashca...
263
          });
c6ac1ffcf   Andrew Buss   refactor; $timeou...
264
          $scope.refreshCards();
688e5fe71   Andrew Buss   properly initiali...
265
          $scope.$on('$destroy', function() {
235b8e0ec   Andrew Buss   realtime is hard,...
266
              ws.close();
dc71f53b1   Andrew Buss   dropdown for clas...
267
              $rootScope.currentSection = {};
323c738e1   Andrew Buss   stop listening fo...
268
269
              $(document).off('keydown');
          });
684d730ca   Andrew Buss   refactor; trying ...
270
271
272
273
274
275
276
277
278
          $scope.shuffleCards = function() {
              $timeout(function() {
                  (function(o) {
                      for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
                      return o;
                  })($scope.cardCols[0]);
              });
          };
          window.feedscope = $scope;
f0541be90   Andrew Buss   navbar icons!
279
      });