Commit 2d0860665d2e1eb100b13fc280db9a453a2ccb69

Authored by Andrew Buss

Merge branch 'master' of git.ucsd.edu:110swag/flashy-frontend

Showing 1 changed file Inline Diff

scripts/FeedController.js View file @ 2d08606
angular.module('flashy.FeedController', ['ui.router', 'ngAnimate']). 1 1 angular.module('flashy.FeedController', ['ui.router', 'ngAnimate']).
2 2
controller('FeedController', function($scope, $rootScope, $stateParams, $state, $http, $window, $timeout, UserService) { 3 3 controller('FeedController', function($scope, $rootScope, $stateParams, $state, $http, $window, $timeout, UserService) {
console.log('Hello from feed'); 4 4 console.log('Hello from feed');
sectionId = parseInt($stateParams.sectionId); 5 5 sectionId = parseInt($stateParams.sectionId);
if (!UserService.isInSection(sectionId)) { 6 6 if (!UserService.isInSection(sectionId)) {
console.log('user is not enrolled in ' + sectionId); 7 7 console.log('user is not enrolled in ' + sectionId);
return $state.go('addclass'); 8 8 return $state.go('addclass');
} 9 9 }
$rootScope.currentSection = $rootScope.SectionResource.get({sectionId: sectionId}); 10 10 $rootScope.currentSection = $rootScope.SectionResource.get({sectionId: sectionId});
$rootScope.debug_flashcard = false; 11 11 $rootScope.debug_flashcard = false;
$scope.cards = false; 12 12 $scope.cards = false;
$scope.cardCols = []; // organized data 13 13 $scope.cardCols = []; // organized data
$scope.numCols = 0; 14 14 $scope.numCols = 0;
$scope.cardTable = {}; // look up table of cards, {'colNum':col, 'obj':card} 15 15 $scope.cardTable = {}; // look up table of cards, {'colNum':col, 'obj':card}
16 16
function calculate_cols() { 17 17 function calculate_cols() {
var avail = $window.innerWidth - 17; 18 18 var avail = $window.innerWidth - 17;
return Math.max(1, Math.floor(avail / 250)); 19 19 return Math.max(1, Math.floor(avail / 250));
} 20 20 }
21 21
$scope.refreshColumnWidth = function() { 22 22 $scope.refreshColumnWidth = function() {
console.log('refreshing column width'); 23 23 console.log('refreshing column width');
avail = $window.innerWidth - 17; 24 24 avail = $window.innerWidth - 17;
width = Math.floor(avail / Math.floor(avail / 250)); 25 25 width = Math.floor(avail / Math.floor(avail / 250));
$('.cardColumn').css({ 26 26 $('.cardColumn').css({
width: width + 'px', 27 27 width: width + 'px',
'font-size': 100 * width / 250 + '%' 28 28 'font-size': 100 * width / 250 + '%'
}); 29 29 });
$('.cardColumn .card.flashy').css({ 30 30 $('.cardColumn .card.flashy').css({
width: width - 12 + 'px', 31 31 width: width - 12 + 'px',
height: (width * 3 / 5) + 'px' 32 32 height: (width * 3 / 5) + 'px'
}); 33 33 });
}; 34 34 };
35 35
$scope.refreshLayout = function() { 36 36 $scope.refreshLayout = function() {
// check if we actually need to refresh the whole layout 37 37 // check if we actually need to refresh the whole layout
if (calculate_cols() == $scope.numCols) return $scope.refreshColumnWidth(); 38 38 if (calculate_cols() == $scope.numCols) return $scope.refreshColumnWidth();
$scope.numCols = calculate_cols(); 39 39 $scope.numCols = calculate_cols();
console.log('refreshing layout for ' + $scope.numCols + ' columns'); 40 40 console.log('refreshing layout for ' + $scope.numCols + ' columns');
$scope.cardCols = []; 41 41 $scope.cardCols = [];
var cols = []; 42 42 var cols = [];
for (i = 0; i < $scope.numCols; i++) cols.push([]); 43 43 for (i = 0; i < $scope.numCols; i++) cols.push([]);
$scope.cards.forEach(function(card, i) { 44 44 $scope.cards.forEach(function(card, i) {
cols[i % $scope.numCols].push(card); 45 45 cols[i % $scope.numCols].push(card);
$scope.cardTable[card.id] = {'colNum': (i % $scope.numCols), 'obj': card}; 46 46 $scope.cardTable[card.id] = {'colNum': (i % $scope.numCols), 'obj': card};
}); 47 47 });
// wait until the next digest cycle to update cardCols 48 48 // wait until the next digest cycle to update cardCols
49 49
$timeout(function() { 50 50 $timeout(function() {
$scope.cardCols = cols; 51 51 $scope.cardCols = cols;
$timeout($scope.refreshColumnWidth); 52 52 $timeout($scope.refreshColumnWidth);
}); 53 53 });
54 54
}; 55 55 };
56 56
angular.element($window).bind('resize', $scope.refreshLayout); 57 57 angular.element($window).bind('resize', $scope.refreshLayout);
58 58
$scope.refreshCards = function() { 59 59 $scope.refreshCards = function() {
$http.get('/api/sections/' + sectionId + '/feed/'). 60 60 $http.get('/api/sections/' + sectionId + '/feed/').
success(function(data) { 61 61 success(function(data) {
console.log(data); 62 62 console.log(data);
$scope.cards = data; 63 63 $scope.cards = data;
$scope.refreshLayout(); 64 64 $scope.refreshLayout();
console.log('success in refresh cards...'); 65 65 console.log('success in refresh cards...');
}). 66 66 }).
error(function(err) { 67 67 error(function(err) {
console.log('refresh fail'); 68 68 console.log('refresh fail');
console.log(err); 69 69 console.log(err);
}); 70 70 });
}; 71 71 };
72 72
$scope.add = function(card) { 73 73 $scope.add = function(card) {
var colNum = 0; 74 74 var colNum = 0;
var lowestCol = $scope.cardCols[0]; 75 75 var lowestCol = $scope.cardCols[0];
var lowestColNum = 0; 76 76 var lowestColNum = 0;
while (colNum < $scope.numCols) { 77 77 while (colNum < $scope.numCols) {
if ($scope.cardCols[colNum].length == 0) { 78 78 if ($scope.cardCols[colNum].length == 0) {
lowestCol = $scope.cardCols[colNum]; 79 79 lowestCol = $scope.cardCols[colNum];
break; 80 80 break;
} else if ($scope.cardCols[colNum].length < lowestCol.length) { 81 81 } else if ($scope.cardCols[colNum].length < lowestCol.length) {
lowestCol = $scope.cardCols[colNum]; 82 82 lowestCol = $scope.cardCols[colNum];
lowestColNum = colNum; 83 83 lowestColNum = colNum;
lowestColLen = $scope.cardCols[colNum].length; 84 84 lowestColLen = $scope.cardCols[colNum].length;
} 85 85 }
colNum++; 86 86 colNum++;
} 87 87 }
console.log(card); 88 88 console.log(card);
$scope.cards.push(data); 89 89 $scope.cards.push(data);
$timeout(function() { 90 90 $timeout(function() {
lowestCol.unshift(card); 91 91 lowestCol.unshift(card);
$scope.cardTable[card.id] = {'colNum': lowestColNum, 'obj': card}; 92 92 $scope.cardTable[card.id] = {'colNum': lowestColNum, 'obj': card};
$timeout($scope.refreshColumnWidth); 93 93 $timeout($scope.refreshColumnWidth);
}); 94 94 });
}; 95 95 };
96 96
$scope.sortAdd = function(card, array) { 97 97 $scope.sortAdd = function(card, array) {
console.log('sort add'); 98 98 console.log('sort add');
array.forEach(function(ele, i, ary) { 99 99 array.forEach(function(ele, i, ary) {
if (ele.score <= card.score) { 100 100 if (ele.score <= card.score) {
ary.splice(i, 0, card); 101 101 ary.splice(i, 0, card);
return; 102 102 return;
} 103 103 }
}); 104 104 });
}; 105 105 };
106 106
$scope.hide = function(card) { 107 107 $scope.hide = function(card) {
console.log('hiding card'); 108 108 console.log('hiding card');
var found = -1; 109 109 var found = -1;
col = $scope.cardTable[card.id].colNum; 110 110 col = $scope.cardTable[card.id].colNum;
found = $scope.cardCols[col].indexOf(card); 111 111 found = $scope.cardCols[col].indexOf(card);
if (found != -1) { 112 112 if (found != -1) {
$scope.cardCols[col].splice(found, 1); 113 113 $scope.cardCols[col].splice(found, 1);
console.log('card hidden'); 114 114 console.log('card hidden');
return col; 115 115 return col;
} 116 116 }
console.log('Error finding card to hide:'); 117 117 console.log('Error finding card to hide:');
console.log(card); 118 118 console.log(card);
return -1; 119 119 return -1;
}; 120 120 };
121 121
$scope.update = function(id, new_score) { 122 122 $scope.update = function(id, new_score) {
card = $scope.cardTable[id].obj; 123 123 card = $scope.cardTable[id].obj;
if (Math.abs(new_score - card.score) < .0001) { 124 124 if (Math.abs(new_score - card.score) < .0001) {
console.log('score same, no update required'); 125 125 console.log('score same, no update required');
return; 126 126 return;
} 127 127 }
console.log('updating'); 128 128 console.log('updating');
console.log(card); 129 129 console.log(card);
var column = $scope.cardCols[$scope.cardTable[id].colNum]; 130 130 var column = $scope.cardCols[$scope.cardTable[id].colNum];
var found = column.indexOf(card); 131 131 var found = column.indexOf(card);
var i = 0; 132 132 var i = 0;
for (; i < column.length; i++) 133 133 for (; i < column.length; i++)
if (column[i].score <= new_score) break; 134 134 if (column[i].score <= new_score) break;
card.score = new_score; 135 135 card.score = new_score;
column.splice(i, 0, column.splice(found, 1)[0]); 136 136 if ($scope.$$phase) { // most of the time it is "$digest"
137 column.splice(i, 0, column.splice(found, 1)[0]);
138 } else {
139 $scope.$apply(column.splice(i, 0, column.splice(found, 1)[0]));
140 }
}; 137 141 };
138 142
var loc = window.location, new_uri; 139 143 var loc = window.location, new_uri;
if (loc.protocol === 'https:') { 140 144 if (loc.protocol === 'https:') {
new_uri = 'wss:'; 141 145 new_uri = 'wss:';
} else { 142 146 } else {
new_uri = 'ws:'; 143 147 new_uri = 'ws:';
} 144 148 }
new_uri += '//' + loc.host; 145 149 new_uri += '//' + loc.host;
var ws = new WebSocket(new_uri + '/ws/feed/' + sectionId + '?subscribe-broadcast'); 146 150 var ws = new WebSocket(new_uri + '/ws/feed/' + sectionId + '?subscribe-broadcast');
147 151
ws.onopen = function() { 148 152 ws.onopen = function() {
console.log('websocket connected'); 149 153 console.log('websocket connected');
}; 150 154 };
ws.onmessage = function(e) { 151 155 ws.onmessage = function(e) {
data = JSON.parse(e.data); 152 156 data = JSON.parse(e.data);
console.log('got websocket message ' + e.data); 153 157 console.log('got websocket message ' + e.data);
console.log(data); 154 158 console.log(data);
if (data.event_type == 'new_card') { 155 159 if (data.event_type == 'new_card') {
$scope.add(data.flashcard); 156 160 $scope.add(data.flashcard);
} else if (data.event_type == 'score_change') { 157 161 } else if (data.event_type == 'score_change') {
$scope.update(data.flashcard_id, data.new_score); 158 162 $scope.update(data.flashcard_id, data.new_score);
} 159 163 }
}; 160 164 };
ws.onerror = function(e) { 161 165 ws.onerror = function(e) {
console.error(e); 162 166 console.error(e);
}; 163 167 };
ws.onclose = function(e) { 164 168 ws.onclose = function(e) {
console.log('connection closed'); 165 169 console.log('connection closed');
}; 166 170 };
167 171
var resetModal = function() { 168 172 var resetModal = function() {
$('#new-card-input').html(''); 169 173 $('#new-card-input').html('');
$('#newCard').closeModal(modal_options); 170 174 $('#newCard').closeModal(modal_options);
}; 171 175 };
172 176
$scope.pushCard = function() { 173 177 $scope.pushCard = function() {
var i = 0; 174 178 var i = 0;
var blanks = []; 175 179 var blanks = [];
$('#new-card-input')[0].childNodes.forEach(function(node) { 176 180 $('#new-card-input')[0].childNodes.forEach(function(node) {
if (typeof node.data == 'undefined') { 177 181 if (typeof node.data == 'undefined') {
console.log('undefined node'); 178 182 console.log('undefined node');
return resetModal(); 179 183 return resetModal();
} 180 184 }
node = $(node)[0]; 181 185 node = $(node)[0];
console.log(node); 182 186 console.log(node);
if (node.tagName == 'B') { 183 187 if (node.tagName == 'B') {
text = $(node).text(); 184 188 text = $(node).text();
blanks.push([i, i + text.length]); 185 189 blanks.push([i, i + text.length]);
i += text.length; 186 190 i += text.length;
} else { 187 191 } else {
i += node.data.length; 188 192 i += node.data.length;
} 189 193 }
}); 190 194 });
var myCard = { 191 195 var myCard = {
'text': $('#new-card-input').text().trim(), 192 196 'text': $('#new-card-input').text().trim(),
'mask': blanks, 193 197 'mask': blanks,
section: sectionId 194 198 section: sectionId
}; 195 199 };
if (myCard.text == '') { 196 200 if (myCard.text == '') {
console.log('blank flashcard not pushed:' + myCard.text); 197 201 console.log('blank flashcard not pushed:' + myCard.text);
return resetModal(); 198 202 return resetModal();
} 199 203 }
$http.post('/api/flashcards/', myCard). 200 204 $http.post('/api/flashcards/', myCard).
success(function(data) { 201 205 success(function(data) {
console.log('flashcard pushed: ' + myCard.text); 202 206 console.log('flashcard pushed: ' + myCard.text);
if (!UserService.hasVerifiedEmail()) { 203 207 if (!UserService.hasVerifiedEmail()) {
Materialize.toast("<p>Thanks for contributing! However, others won't see your card until you verify your email address<p>", 4000); 204 208 Materialize.toast("<p>Thanks for contributing! However, others won't see your card until you verify your email address<p>", 4000);
} 205 209 }
206 210
}). 207 211 }).
error(function(error) { 208 212 error(function(error) {
console.log('something went wrong pushing a card!'); 209 213 console.log('something went wrong pushing a card!');
}); 210 214 });
return resetModal(); 211 215 return resetModal();
}; 212 216 };
213 217
/* Key bindings for the whole feed window. Hotkey it up! */ 214 218 /* Key bindings for the whole feed window. Hotkey it up! */
var listenForC = true; 215 219 var listenForC = true;
216 220
// Need to pass these options into openmodal and leanmodal, 217 221 // Need to pass these options into openmodal and leanmodal,
// otherwise the ready handler doesn't get called 218 222 // otherwise the ready handler doesn't get called
219 223
modal_options = { 220 224 modal_options = {
dismissible: true, // Modal can be dismissed by clicking outside of the modal 221 225 dismissible: true, // Modal can be dismissed by clicking outside of the modal
opacity: 0, // Opacity of modal background 222 226 opacity: 0, // Opacity of modal background
in_duration: 300, // Transition in duration 223 227 in_duration: 300, // Transition in duration
out_duration: 200, // Transition out duration 224 228 out_duration: 200, // Transition out duration
ready: function() { 225 229 ready: function() {
listenForC = false; 226 230 listenForC = false;
console.log('modal OPENING'); 227 231 console.log('modal OPENING');
$('#new-card-input').focus(); 228 232 $('#new-card-input').focus();
}, 229 233 },
complete: function() { 230 234 complete: function() {
listenForC = true; 231 235 listenForC = true;
console.log('modal done, closing'); 232 236 console.log('modal done, closing');
$('#new-card-input').blur(); 233 237 $('#new-card-input').blur();
} 234 238 }
}; 235 239 };
236 240
$(document).keydown(function(e) { 237 241 $(document).keydown(function(e) {
var keyed = e.which; 238 242 var keyed = e.which;
if (keyed == 67 && listenForC) { // "c" for compose 239 243 if (keyed == 67 && listenForC) { // "c" for compose
$('#newCard').openModal(modal_options); 240 244 $('#newCard').openModal(modal_options);
e.preventDefault(); 241 245 e.preventDefault();
listenForC = false; 242 246 listenForC = false;
return false; 243 247 return false;
} else if (keyed == 27) { // clear on ESC 244 248 } else if (keyed == 27) { // clear on ESC
listenForC = true; 245 249 listenForC = true;
document.getElementById('new-card-input').value = ''; 246 250 document.getElementById('new-card-input').value = '';
} 247 251 }
}); 248 252 });
$(document).ready(function() { 249 253 $(document).ready(function() {
$('.tooltipped').tooltip({delay: 50}); 250 254 $('.tooltipped').tooltip({delay: 50});
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered 251 255 // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal(modal_options); 252 256 $('.modal-trigger').leanModal(modal_options);
$('#new-card-input').on('keydown', function(e) { 253 257 $('#new-card-input').on('keydown', function(e) {
if (e.which == 13) { 254 258 if (e.which == 13) {
e.preventDefault(); 255 259 e.preventDefault();
$scope.pushCard(); 256 260 $scope.pushCard();
listenForC = true; 257 261 listenForC = true;
return false; 258 262 return false;
} 259 263 }
}); 260 264 });
$('button#blank-selected').click(function() { 261 265 $('button#blank-selected').click(function() {