FeedController.js 10.5 KB
angular.module('flashy.FeedController', ['ui.router', 'ngAnimate']).
controller('FeedController', function($scope, $rootScope, $stateParams, $state, $http, $window, $timeout, UserService) {
console.log('Hello from feed');
sectionId = parseInt($stateParams.sectionId);
if (!UserService.isInSection(sectionId)) {
console.log('user is not enrolled in ' + sectionId);
return $state.go('addclass');
}
$rootScope.currentSection = $rootScope.SectionResource.get({sectionId: sectionId});
$rootScope.debug_flashcard = false;
$scope.cards = false;
$scope.cardCols = []; // organized data
$scope.numCols = 0;
$scope.cardTable = {}; // look up table of cards, {'colNum':col, 'obj':card}
function calculate_cols() {
var avail = $window.innerWidth - 17;
return Math.max(1, Math.floor(avail / 250));
}
$scope.refreshColumnWidth = function() {
console.log('refreshing column width');
avail = $window.innerWidth - 17;
width = Math.floor(avail / Math.floor(avail / 250));
$('.cardColumn').css({
width: width + 'px',
'font-size': 100 * width / 250 + '%'
});
$('.cardColumn .card.flashy').css({
width: width - 12 + 'px',
height: (width * 3 / 5) + 'px'
});
};
$scope.refreshLayout = function() {
// check if we actually need to refresh the whole layout
if (calculate_cols() == $scope.numCols) return $scope.refreshColumnWidth();
$scope.numCols = calculate_cols();
console.log('refreshing layout for ' + $scope.numCols + ' columns');
$scope.cardCols = [];
var cols = [];
for (i = 0; i < $scope.numCols; i++) cols.push([]);
$scope.cards.forEach(function(card, i) {
cols[i % $scope.numCols].push(card);
$scope.cardTable[card.id] = {'colNum': (i % $scope.numCols), 'obj': card};
});
// wait until the next digest cycle to update cardCols
$timeout(function() {
$scope.cardCols = cols;
$timeout($scope.refreshColumnWidth);
});
};
angular.element($window).bind('resize', $scope.refreshLayout);
$scope.refreshCards = function() {
$http.get('/api/sections/' + sectionId + '/feed/').
success(function(data) {
console.log(data);
$scope.cards = data;
$scope.refreshLayout();
console.log('success in refresh cards...');
}).
error(function(err) {
console.log('refresh fail');
console.log(err);
});
};
$scope.add = function(card) {
var colNum = 0;
var lowestCol = $scope.cardCols[0];
var lowestColNum = 0;
while (colNum < $scope.numCols) {
if ($scope.cardCols[colNum].length == 0) {
lowestCol = $scope.cardCols[colNum];
break;
} else if ($scope.cardCols[colNum].length < lowestCol.length) {
lowestCol = $scope.cardCols[colNum];
lowestColNum = colNum;
lowestColLen = $scope.cardCols[colNum].length;
}
colNum++;
}
console.log(card);
$scope.cards.push(data);
$timeout(function() {
lowestCol.unshift(card);
$scope.cardTable[card.id] = {'colNum': lowestColNum, 'obj': card};
$timeout($scope.refreshColumnWidth);
});
};
$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;
}
});
};
$scope.hide = function(card) {
console.log('hiding card');
var found = -1;
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;
}
console.log('Error finding card to hide:');
console.log(card);
return -1;
};
$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;
for (; i < column.length; i++)
if (column[i].score <= new_score) break;
card.score = new_score;
if ($scope.$$phase) { // most of the time it is "$digest"
column.splice(i, 0, column.splice(found, 1)[0]);
} else {
$scope.$apply(column.splice(i, 0, column.splice(found, 1)[0]));
}
};
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');
ws.onopen = function() {
console.log('websocket connected');
};
ws.onmessage = function(e) {
data = JSON.parse(e.data);
console.log('got websocket message ' + e.data);
console.log(data);
if (data.event_type == 'new_card') {
$scope.add(data.flashcard);
} else if (data.event_type == 'score_change') {
$scope.update(data.flashcard_id, data.new_score);
}
};
ws.onerror = function(e) {
console.error(e);
};
ws.onclose = function(e) {
console.log('connection closed');
};
var resetModal = function() {
$('#new-card-input').html('');
$('#newCard').closeModal(modal_options);
};
$scope.pushCard = function() {
var i = 0;
var blanks = [];
$('#new-card-input')[0].childNodes.forEach(function(node) {
if (typeof node.data == 'undefined') {
console.log('undefined node');
return resetModal();
}
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;
}
});
var myCard = {
'text': $('#new-card-input').text().trim(),
'mask': blanks,
section: sectionId
};
if (myCard.text == '') {
console.log('blank flashcard not pushed:' + myCard.text);
return resetModal();
}
$http.post('/api/flashcards/', myCard).
success(function(data) {
console.log('flashcard pushed: ' + myCard.text);
if (!UserService.hasVerifiedEmail()) {
Materialize.toast("<p>Thanks for contributing! However, others won't see your card until you verify your email address<p>", 4000);
}
}).
error(function(error) {
console.log('something went wrong pushing a card!');
});
return resetModal();
};
/* Key bindings for the whole feed window. Hotkey it up! */
var listenForC = true;
// 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
ready: function() {
listenForC = false;
console.log('modal OPENING');
$('#new-card-input').focus();
},
complete: function() {
listenForC = true;
console.log('modal done, closing');
$('#new-card-input').blur();
}
};
$(document).keydown(function(e) {
var keyed = e.which;
if (keyed == 67 && listenForC) { // "c" for compose
$('#newCard').openModal(modal_options);
e.preventDefault();
listenForC = false;
return false;
} else if (keyed == 27) { // clear on ESC
listenForC = true;
document.getElementById('new-card-input').value = '';
}
});
$(document).ready(function() {
$('.tooltipped').tooltip({delay: 50});
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal(modal_options);
$('#new-card-input').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
$scope.pushCard();
listenForC = true;
return false;
}
});
$('button#blank-selected').click(function() {
console.log(window.getSelection());
document.execCommand('bold');
});
});
$scope.refreshCards();
$scope.$on('$destroy', function() {
ws.close();
$rootScope.currentSection = {};
$(document).off('keydown');
});
$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;
});