Commit 88ca25463b53617a8bea0d42500d8d9d835e3589

Authored by Andrew Buss
1 parent 4b3a411749

fixed broken authorizedFor

Showing 5 changed files with 47 additions and 40 deletions Inline Diff

angular.module('flashy', [ 1 1 angular.module('flashy', [
'flashy.LoginController', 2 2 'flashy.LoginController',
'flashy.RootController', 3 3 'flashy.RootController',
'flashy.FeedController', 4 4 'flashy.FeedController',
'flashy.DeckController', 5 5 'flashy.DeckController',
'flashy.ClassAddController', 6 6 'flashy.ClassAddController',
'flashy.ClassDropController', 7 7 'flashy.ClassDropController',
'flashy.RequestResetController', 8 8 'flashy.RequestResetController',
'flashy.StudyController', 9 9 'flashy.StudyController',
'flashy.UserService', 10 10 'flashy.UserService',
'flashy.FlashcardDirective', 11 11 'flashy.FlashcardDirective',
//'flashy.SelectDirective', 12 12 //'flashy.SelectDirective',
// DOESNT WORK RN 13 13 // DOESNT WORK RN
'flashy.ResetPasswordController', 14 14 'flashy.ResetPasswordController',
'flashy.VerifyEmailController', 15 15 'flashy.VerifyEmailController',
'flashy.CardListController', 16 16 'flashy.CardListController',
'flashy.HelpController', 17 17 'flashy.HelpController',
'flashy.SettingsController', 18 18 'flashy.SettingsController',
'ngCookies']). 19 19 'ngCookies']).
config(function($stateProvider, $urlRouterProvider, $resourceProvider, $httpProvider, $locationProvider) { 20 20 config(function($stateProvider, $urlRouterProvider, $resourceProvider, $httpProvider, $locationProvider) {
'use strict'; 21 21 'use strict';
$httpProvider.defaults.withCredentials = true; 22 22 $httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.xsrfCookieName = 'csrftoken'; 23 23 $httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; 24 24 $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$resourceProvider.defaults.stripTrailingSlashes = false; 25 25 $resourceProvider.defaults.stripTrailingSlashes = false;
var arrayMethods = Object.getOwnPropertyNames(Array.prototype); 26 26 var arrayMethods = Object.getOwnPropertyNames(Array.prototype);
arrayMethods.forEach(attachArrayMethodsToNodeList); 27 27 arrayMethods.forEach(attachArrayMethodsToNodeList);
function attachArrayMethodsToNodeList(methodName) { 28 28 function attachArrayMethodsToNodeList(methodName) {
if (methodName !== 'length') { 29 29 if (methodName !== 'length') {
NodeList.prototype[methodName] = Array.prototype[methodName]; 30 30 NodeList.prototype[methodName] = Array.prototype[methodName];
} 31 31 }
} 32 32 }
33 33
$httpProvider.interceptors.push(function($q, $rootScope) { 34 34 $httpProvider.interceptors.push(function($q, $rootScope) {
return { 35 35 return {
'responseError': function(rejection) { // need a better redirect 36 36 'responseError': function(rejection) { // need a better redirect
if (rejection.status >= 500) { 37 37 if (rejection.status >= 500) {
console.log('got error'); 38 38 console.log('got error');
console.log(rejection); 39 39 console.log(rejection);
$rootScope.$broadcast('server_error', rejection); 40 40 $rootScope.$broadcast('server_error', rejection);
} 41 41 }
if (rejection.status == 403) { 42 42 if (rejection.status == 403) {
console.log(rejection); 43 43 console.log(rejection);
if (rejection.data && rejection.data.detail == 'Please verify your email before continuing') { 44 44 if (rejection.data && rejection.data.detail == 'Please verify your email before continuing') {
UserService.showLockedMessage(); 45 45 UserService.showLockedMessage();
UserService.logout(); 46 46 UserService.logout();
} 47 47 }
} 48 48 }
return $q.reject(rejection); 49 49 return $q.reject(rejection);
} 50 50 }
}; 51 51 };
}); 52 52 });
$locationProvider.html5Mode(true); 53 53 $locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/404'); 54 54 $urlRouterProvider.otherwise('/404');
var auth_resolve = { 55 55 var auth_resolve = {
authorize: function($q, $rootScope, $state, $stateParams, UserService) { 56 56 authorize: function($q, $rootScope, $state, $stateParams, UserService) {
57 57
console.log('do we need to authorize a user for', $rootScope.nextState.name); 58 58 console.log('do we need to authorize a user for', $rootScope.nextState.name);
if (UserService.noAuthRequired($rootScope.nextState)) { 59 59 if (UserService.noAuthRequired($rootScope.nextState)) {
console.log('no auth required for', $rootScope.nextState.name); 60 60 console.log('no auth required for', $rootScope.nextState.name);
return UserService.getUserData(); 61 61 return UserService.getUserData();
} 62 62 }
console.log('resolving user before continuing for ' + $state.name); 63 63 console.log('resolving user before continuing for ' + $state.name);
var redirectAsNeeded = function() { 64 64 var redirectAsNeeded = function() {
if (!UserService.isLoggedIn()) { 65 65 if (!UserService.isLoggedIn()) {
console.log(UserService.getUserData()); 66 66 console.log(UserService.getUserData());
console.log('making the user log in'); 67 67 console.log('making the user log in');
$state.go('login'); 68 68 $state.go('login');
} 69 69 }
if (!UserService.authorizedFor($state, $stateParams)) { 70 70 if (!UserService.authorizedFor($rootScope.nextState, $rootScope.nextStateParams)) {
console.log('user not authorized for ' + $state.name); 71 71 console.log('user not authorized for ' + $rootScope.nextState.name);
$state.go('addclass'); 72 72 $state.go('addclass');
} 73 73 }
}; 74 74 };
if (UserService.isResolved()) return redirectAsNeeded(); 75 75 if (UserService.isResolved()) return redirectAsNeeded();
return UserService.getUserData().then(redirectAsNeeded); 76 76 return UserService.getUserData().then(redirectAsNeeded);
} 77 77 }
}; 78 78 };
$stateProvider. 79 79 $stateProvider.
state('login', { 80 80 state('login', {
resolve: auth_resolve, 81 81 resolve: auth_resolve,
url: '/login', 82 82 url: '/login',
templateUrl: 'templates/login.html', 83 83 templateUrl: 'templates/login.html',
controller: 'LoginController' 84 84 controller: 'LoginController'
}). 85 85 }).
state('root', { 86 86 state('root', {
resolve: auth_resolve, 87 87 resolve: auth_resolve,
url: '', 88 88 url: '',
controller: 'RootController' 89 89 controller: 'RootController'
}). 90 90 }).
state('feed', { 91 91 state('feed', {
resolve: auth_resolve, 92 92 resolve: auth_resolve,
url: '/feed/{sectionId}', 93 93 url: '/feed/{sectionId}',
templateUrl: 'templates/feed.html', 94 94 templateUrl: 'templates/feed.html',
controller: 'FeedController' 95 95 controller: 'FeedController'
}). 96 96 }).
state('cardlist', { 97 97 state('cardlist', {
resolve: auth_resolve, 98 98 resolve: auth_resolve,
url: '/cards/{sectionId}', 99 99 url: '/cards/{sectionId}',
templateUrl: 'templates/cardlist.html', 100 100 templateUrl: 'templates/cardlist.html',
controller: 'CardListController' 101 101 controller: 'CardListController'
}). 102 102 }).
state('addclass', { 103 103 state('addclass', {
resolve: auth_resolve, 104 104 resolve: auth_resolve,
url: '/addclass', 105 105 url: '/addclass',
templateUrl: 'templates/addclass.html', 106 106 templateUrl: 'templates/addclass.html',
controller: 'ClassAddController' 107 107 controller: 'ClassAddController'
}). 108 108 }).
state('dropclass', { 109 109 state('dropclass', {
resolve: auth_resolve, 110 110 resolve: auth_resolve,
url: '/settings/dropclass', 111 111 url: '/settings/dropclass',
templateUrl: 'templates/dropclass.html', 112 112 templateUrl: 'templates/dropclass.html',
controller: 'ClassDropController' 113 113 controller: 'ClassDropController'
}). 114 114 }).
state('deck', { 115 115 state('deck', {
resolve: auth_resolve, 116 116 resolve: auth_resolve,
url: '/deck/{sectionId}', 117 117 url: '/deck/{sectionId}',
templateUrl: 'templates/deck.html', 118 118 templateUrl: 'templates/deck.html',
controller: 'DeckController' 119 119 controller: 'DeckController'
}). 120 120 }).
state('study', { 121 121 state('study', {
resolve: auth_resolve, 122 122 resolve: auth_resolve,
url: '/study', 123 123 url: '/study',
templateUrl: 'templates/study.html', 124 124 templateUrl: 'templates/study.html',
controller: 'StudyController' 125 125 controller: 'StudyController'
}). 126 126 }).
state('flashcard', { 127 127 state('flashcard', {
resolve: auth_resolve, 128 128 resolve: auth_resolve,
url: '/flashcard', 129 129 url: '/flashcard',
templateUrl: 'templates/flashcard.html', 130 130 templateUrl: 'templates/flashcard.html',
controller: 'FlashcardController' 131 131 controller: 'FlashcardController'
}). 132 132 }).
state('settings', { 133 133 state('settings', {
resolve: auth_resolve, 134 134 resolve: auth_resolve,
url: '/settings', 135 135 url: '/settings',
templateUrl: 'templates/settings.html', 136 136 templateUrl: 'templates/settings.html',
controller: 'SettingsController' 137 137 controller: 'SettingsController'
}). 138 138 }).
state('requestpasswordreset', { 139 139 state('requestpasswordreset', {
url: '/requestpasswordreset', 140 140 url: '/requestpasswordreset',
templateUrl: 'templates/requestpasswordreset.html', 141 141 templateUrl: 'templates/requestpasswordreset.html',
controller: 'RequestResetController' 142 142 controller: 'RequestResetController'
}). 143 143 }).
state('resetpassword', { 144 144 state('resetpassword', {
url: '/resetpassword/{uid}/{token}', 145 145 url: '/resetpassword/{uid}/{token}',
templateUrl: 'templates/resetpassword.html', 146 146 templateUrl: 'templates/resetpassword.html',
controller: 'ResetPasswordController' 147 147 controller: 'ResetPasswordController'
}). 148 148 }).
state('verifyemail', { 149 149 state('verifyemail', {
url: '/verifyemail/{key}', 150 150 url: '/verifyemail/{key}',
templateUrl: 'templates/verifyemail.html', 151 151 templateUrl: 'templates/verifyemail.html',
controller: 'VerifyEmailController' 152 152 controller: 'VerifyEmailController'
}). 153 153 }).
state('404', { 154 154 state('404', {
url: '/404', 155 155 url: '/404',
template: "<h1>This page doesn't exist!</h1>" 156 156 template: "<h1>This page doesn't exist!</h1>"
}). 157 157 }).
state('help', { 158 158 state('help', {
resolve: auth_resolve, 159 159 resolve: auth_resolve,
url: '/help', 160 160 url: '/help',
templateUrl: 'templates/help.html', 161 161 templateUrl: 'templates/help.html',
controller: 'HelpController' 162 162 controller: 'HelpController'
}); 163 163 });
}). 164 164 }).
run(function($rootScope, $state, $stateParams, $location, UserService) { 165 165 run(function($rootScope, $state, $stateParams, $location, UserService) {
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) { 166 166 $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
console.log('failed to change state: ' + error); 167 167 console.log('failed to change state: ' + error);
$state.go('login'); 168 168 $state.go('login');
}); 169 169 });
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { 170 170 $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
$rootScope.nextState = toState; 171 171 $rootScope.nextState = toState;
172 $rootScope.nextStateParams = toParams;
console.log('changing state to', toState); 172 173 console.log('changing state to', toState);
if (['feed', 'deck', 'cardlist'].indexOf(toState.name) >= 0) { 173 174 if (['feed', 'deck', 'cardlist'].indexOf(toState.name) >= 0) {
localStorage.setItem('last_state', toState.name); 174 175 localStorage.setItem('last_state', toState.name);
localStorage.setItem('last_state_params', JSON.stringify(toParams)); 175 176 localStorage.setItem('last_state_params', JSON.stringify(toParams));
} 176 177 }
}); 177 178 });
}); 178 179 });
scripts/CardGridController.js View file @ 88ca254
angular.module('flashy.CardGridController', ['ui.router', 'ngAnimate', 'ngWebSocket']).controller = 1 1 angular.module('flashy.CardGridController', ['ui.router', 'ngAnimate', 'ngWebSocket']).controller =
function($scope, $rootScope, $state, $http, $window, $timeout, $stateParams, $websocket, UserService) { 2 2 function($scope, $rootScope, $state, $http, $window, $timeout, $stateParams, $websocket, UserService) {
console.log(arguments); 3 3 console.log(arguments);
console.log($stateParams); 4 4 console.log($stateParams);
console.log(UserService); 5 5 console.log(UserService);
$scope.cards = false; 6 6 $scope.cards = false;
$scope.cardCols = []; // organized data 7 7 $scope.cardCols = []; // organized data
$scope.numCols = 0; 8 8 $scope.numCols = 0;
$scope.cardTable = {}; // look up table of cards, {'colNum':col, 'obj':card} 9 9 $scope.cardTable = {}; // look up table of cards, {'colNum':col, 'obj':card}
$scope.sectionId = parseInt($stateParams.sectionId); 10 10 $scope.sectionId = parseInt($stateParams.sectionId);
$scope.section = $rootScope.SectionResource.get({sectionId: $scope.sectionId}); 11 11 $scope.section = $rootScope.SectionResource.get({sectionId: $scope.sectionId});
$rootScope.currentSection = $scope.section; 12 12 $rootScope.currentSection = $scope.section;
console.log('hello from cardgridcontroller'); 13 13 console.log('hello from cardgridcontroller');
14 14
if (!UserService.isInSection($scope.sectionId)) { 15 15 if (!UserService.isInSection($scope.sectionId)) {
console.log('user is not enrolled in ' + $scope.sectionId); 16 16 console.log('user is not enrolled in ' + $scope.sectionId);
return $state.go('addclass'); 17 17 $state.go('addclass');
} 18 18 }
19 19
$scope.refreshColumnWidth = function() { 20 20 $scope.refreshColumnWidth = function() {
console.log('refreshing column width'); 21 21 console.log('refreshing column width');
avail = $window.innerWidth - 17; 22 22 avail = $window.innerWidth - 17;
width = Math.floor(avail / Math.floor(avail / 250)); 23 23 width = Math.floor(avail / Math.floor(avail / 250));
$('.cardColumn').css({ 24 24 $('.cardColumn').css({
width: width + 'px', 25 25 width: width + 'px',
'font-size': 100 * width / 250 + '%' 26 26 'font-size': 100 * width / 250 + '%'
}); 27 27 });
$('.cardColumn .card.flashy').css({ 28 28 $('.cardColumn .card.flashy').css({
width: width - 12 + 'px', 29 29 width: width - 12 + 'px',
height: (width * 3 / 5) + 'px' 30 30 height: (width * 3 / 5) + 'px'
}); 31 31 });
}; 32 32 };
33 33
$scope.refreshLayout = function() { 34 34 $scope.refreshLayout = function() {
numCols = Math.max(1, Math.floor(($window.innerWidth - 17) / 250)); 35 35 numCols = Math.max(1, Math.floor(($window.innerWidth - 17) / 250));
36 36
// check if we actually need to refresh the whole layout 37 37 // check if we actually need to refresh the whole layout
if (numCols == $scope.numCols) return $scope.refreshColumnWidth(); 38 38 if (numCols == $scope.numCols) return $scope.refreshColumnWidth();
$scope.numCols = numCols; 39 39 $scope.numCols = numCols;
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.ws_host = window.location.origin.replace('http', 'ws'); 59 59 $scope.ws_host = window.location.origin.replace('http', 'ws');
$scope.deck_ws = $websocket($scope.ws_host + '/ws/deck/' + $scope.sectionId + '?subscribe-user'); 60 60 $scope.deck_ws = $websocket($scope.ws_host + '/ws/deck/' + $scope.sectionId + '?subscribe-user');
$scope.deck_ws.onOpen(function() { 61 61 $scope.deck_ws.onOpen(function() {
console.log('deck ws open'); 62 62 console.log('deck ws open');
}); 63 63 });
64 64
$scope.deck_ws.onMessage(function(message) { 65 65 $scope.deck_ws.onMessage(function(message) {
console.log('message', message); 66 66 console.log('message', message);
}); 67 67 });
68 68
$scope.add = function(card) { 69 69 $scope.add = function(card) {
var colNum = 0; 70 70 var colNum = 0;
var lowestCol = $scope.cardCols[0]; 71 71 var lowestCol = $scope.cardCols[0];
var lowestColNum = 0; 72 72 var lowestColNum = 0;
while (colNum < $scope.numCols) { 73 73 while (colNum < $scope.numCols) {
if ($scope.cardCols[colNum].length == 0) { 74 74 if ($scope.cardCols[colNum].length == 0) {
lowestCol = $scope.cardCols[colNum]; 75 75 lowestCol = $scope.cardCols[colNum];
break; 76 76 break;
} else if ($scope.cardCols[colNum].length < lowestCol.length) { 77 77 } else if ($scope.cardCols[colNum].length < lowestCol.length) {
lowestCol = $scope.cardCols[colNum]; 78 78 lowestCol = $scope.cardCols[colNum];
lowestColNum = colNum; 79 79 lowestColNum = colNum;
lowestColLen = $scope.cardCols[colNum].length; 80 80 lowestColLen = $scope.cardCols[colNum].length;
} 81 81 }
colNum++; 82 82 colNum++;
} 83 83 }
console.log(card); 84 84 console.log(card);
$scope.cards.push(data); 85 85 $scope.cards.push(data);
lowestCol.unshift(card); 86 86 lowestCol.unshift(card);
$scope.cardTable[card.id] = {'colNum': lowestColNum, 'obj': card}; 87 87 $scope.cardTable[card.id] = {'colNum': lowestColNum, 'obj': card};
$timeout($scope.refreshColumnWidth); 88 88 $timeout($scope.refreshColumnWidth);
}; 89 89 };
90 90
$http.get('/api/sections/' + $scope.sectionId + '/deck/'). 91 91 $http.get('/api/sections/' + $scope.sectionId + '/deck/').
success(function(data) { 92 92 success(function(data) {
$scope.deck_cards = data; 93 93 $scope.deck_cards = data;
console.log("got user's deck"); 94 94 console.log("got user's deck");
console.log(data); 95 95 console.log(data);
scripts/ClassDropController.js View file @ 88ca254
angular.module('flashy.ClassDropController', ['ui.router']). 1 1 angular.module('flashy.ClassDropController', ['ui.router']).
controller('ClassDropController', function($rootScope, $resource, $scope, $state, $http, UserService) { 2 2 controller('ClassDropController', function($rootScope, $resource, $scope, $state, $http, UserService) {
$scope.hi = "hi"; 3 3 $scope.hi = 'hi';
$rootScope.SectionResource = $resource('/api/sections/:sectionId/'); 4 4 $rootScope.SectionResource = $resource('/api/sections/:sectionId/');
$rootScope.currentSection = {}; 5 5 $rootScope.currentSection = {};
$rootScope.UserService = UserService; 6 6 $rootScope.UserService = UserService;
7 7
$scope.dropClass = function(section) { 8 8 $scope.dropClass = function(section) {
$http.post('/api/sections/' + section.id + '/drop/'). 9 9 $http.post('/api/sections/' + section.id + '/drop/').
success(function(data) { 10 10 success(function(data) {
console.log(section.short_name + ' dropped'); 11 11 console.log(section.short_name + ' dropped');
12 12
Materialize.toast('Dropped', 3000, 'rounded'); 13 13 Materialize.toast('Dropped', 3000, 'rounded');
}). 14 14 }).
error(function(err) { 15 15 error(function(err) {
console.log('no drop for you'); 16 16 console.log('no drop for you');
}); 17 17 });
}; 18 18 };
19 19
scripts/FeedController.js View file @ 88ca254
angular.module('flashy.FeedController', ['ui.router', 'ngAnimate', 'ngWebSocket', 'contenteditable']). 1 1 angular.module('flashy.FeedController', ['ui.router', 'ngAnimate', 'ngWebSocket', 'contenteditable']).
2 2
controller('FeedController', function($scope, $rootScope, $state, $http, $window, $timeout, $stateParams, $websocket, UserService) { 3 3 controller('FeedController', function($scope, $rootScope, $state, $http, $window, $timeout, $stateParams, $websocket, UserService) {
angular.module('flashy.CardGridController').controller.apply(this, arguments); 4 4 angular.module('flashy.CardGridController').controller.apply(this, arguments);
console.log('Hello from feed'); 5 5 console.log('Hello from feed');
6 6
$scope.refreshCards = function() { 7 7 $scope.refreshCards = function() {
$http.get('/api/sections/' + $scope.sectionId + '/feed/'). 8 8 $http.get('/api/sections/' + $scope.sectionId + '/feed/').
success(function(data) { 9 9 success(function(data) {
console.log(data); 10 10 console.log(data);
$scope.cards = data; 11 11 $scope.cards = data;
$scope.refreshLayout(); 12 12 $scope.refreshLayout();
console.log('success in refresh cards...'); 13 13 console.log('success in refresh cards...');
}). 14 14 }).
error(function(err) { 15 15 error(function(err) {
console.log('refresh fail'); 16 16 console.log('refresh fail');
console.log(err); 17 17 console.log(err);
}); 18 18 });
}; 19 19 };
20 20
$scope.sortAdd = function(card, array) { 21 21 $scope.sortAdd = function(card, array) {
console.log('sort add'); 22 22 console.log('sort add');
array.forEach(function(ele, i, ary) { 23 23 array.forEach(function(ele, i, ary) {
if (ele.score <= card.score) { 24 24 if (ele.score <= card.score) {
ary.splice(i, 0, card); 25 25 ary.splice(i, 0, card);
return; 26 26 return;
} 27 27 }
}); 28 28 });
}; 29 29 };
30 30
$scope.hide = function(card) { 31 31 $scope.hide = function(card) {
console.log('hiding card'); 32 32 console.log('hiding card');
var found = -1; 33 33 var found = -1;
col = $scope.cardTable[card.id].colNum; 34 34 col = $scope.cardTable[card.id].colNum;
found = $scope.cardCols[col].indexOf(card); 35 35 found = $scope.cardCols[col].indexOf(card);
if (found != -1) { 36 36 if (found != -1) {
$scope.cardCols[col].splice(found, 1); 37 37 $scope.cardCols[col].splice(found, 1);
console.log('card hidden'); 38 38 console.log('card hidden');
return col; 39 39 return col;
} 40 40 }
console.log('Error finding card to hide:'); 41 41 console.log('Error finding card to hide:');
console.log(card); 42 42 console.log(card);
return -1; 43 43 return -1;
}; 44 44 };
45 45
$scope.update = function(id, new_score) { 46 46 $scope.update = function(id, new_score) {
card = $scope.cardTable[id].obj; 47 47 card = $scope.cardTable[id].obj;
if (Math.abs(new_score - card.score) < .0001) { 48 48 if (Math.abs(new_score - card.score) < .0001) {
console.log('score same, no update required'); 49 49 console.log('score same, no update required');
return; 50 50 return;
} 51 51 }
console.log('updating'); 52 52 console.log('updating');
console.log(card); 53 53 console.log(card);
var column = $scope.cardCols[$scope.cardTable[id].colNum]; 54 54 var column = $scope.cardCols[$scope.cardTable[id].colNum];
var found = column.indexOf(card); 55 55 var found = column.indexOf(card);
var i = 0; 56 56 var i = 0;
for (; i < column.length; i++) 57 57 for (; i < column.length; i++)
if (column[i].score <= new_score) break; 58 58 if (column[i].score <= new_score) break;
card.score = new_score; 59 59 card.score = new_score;
if ($scope.$$phase) { // most of the time it is "$digest" 60 60 if ($scope.$$phase) { // most of the time it is "$digest"
column.splice(i, 0, column.splice(found, 1)[0]); 61 61 column.splice(i, 0, column.splice(found, 1)[0]);
} else { 62 62 } else {
$scope.$apply(column.splice(i, 0, column.splice(found, 1)[0])); 63 63 $scope.$apply(column.splice(i, 0, column.splice(found, 1)[0]));
} 64 64 }
}; 65 65 };
66 66
$scope.feed_ws = $websocket($scope.ws_host + '/ws/feed/' + $scope.sectionId + '?subscribe-broadcast'); 67 67 $scope.feed_ws = $websocket($scope.ws_host + '/ws/feed/' + $scope.sectionId + '?subscribe-broadcast');
$scope.feed_ws.onOpen(function() { 68 68 $scope.feed_ws.onOpen(function() {
console.log('deck ws open'); 69 69 console.log('deck ws open');
}); 70 70 });
71 71
$scope.feed_ws.onMessage(function(e) { 72 72 $scope.feed_ws.onMessage(function(e) {
data = JSON.parse(e.data); 73 73 data = JSON.parse(e.data);
console.log('got websocket message ' + e.data); 74 74 console.log('got websocket message ' + e.data);
console.log(data); 75 75 console.log(data);
if (data.event_type == 'new_card') { 76 76 if (data.event_type == 'new_card') {
$scope.add(data.flashcard); 77 77 $scope.add(data.flashcard);
} else if (data.event_type == 'score_change') { 78 78 } else if (data.event_type == 'score_change') {
$scope.update(data.flashcard_id, data.new_score); 79 79 $scope.update(data.flashcard_id, data.new_score);
} 80 80 }
}); 81 81 });
82 82
$scope.pushCard = function() { 83 83 $scope.pushCard = function() {
var i = 0; 84
var blanks = []; 85
$('#new-card-input')[0].childNodes.forEach(function(node) { 86
if (typeof node.data == 'undefined') { 87
console.log('undefined node'); 88
} 89
node = $(node)[0]; 90
if (node.tagName == 'B') { 91
var text = $(node).text(); 92
console.log(text.length, text); 93
var leftspaces = 0, rightspaces = 0; 94
// awful way to find the first non-space character from the left or the right. thanks.js 95
while (text[leftspaces] == ' ' || text[leftspaces] == '\xa0') leftspaces++; 96
while (text[text.length - 1 - rightspaces] == ' ' || text[text.length - 1 - rightspaces] == '\xa0') rightspaces++; 97
if (leftspaces != text.length) blanks.push([i + leftspaces, i + text.length - rightspaces]); 98
i += text.length; 99
} else if (!node.data) { 100
console.log('weird node', node); 101
i += $(node).text().length; 102
} else { 103
i += node.data.length; 104
} 105
}); 106
var myCard = { 107 84 var myCard = {
// we can't trim this string because it'd mess up the blanks. Something to fix. 108 85 // we can't trim this string because it'd mess up the blanks. Something to fix.
'text': $('#new-card-input').text(), 109 86 'text': $('#new-card-input').text(),
'mask': blanks, 110 87 'mask': $scope.newCardBlanks,
section: $scope.section.id 111 88 section: $scope.section.id
}; 112 89 };
if (myCard.text == '') { 113 90 if (myCard.text == '') {
console.log('blank flashcard not pushed:' + myCard.text); 114 91 console.log('blank flashcard not pushed:' + myCard.text);
return closeNewCard(); 115 92 return closeNewCard();
} 116 93 }
$http.post('/api/flashcards/', myCard). 117 94 $http.post('/api/flashcards/', myCard).
success(function(data) { 118 95 success(function(data) {
console.log('flashcard pushed: ' + myCard.text); 119 96 console.log('flashcard pushed: ' + myCard.text);
if (!UserService.hasVerifiedEmail()) { 120 97 if (!UserService.hasVerifiedEmail()) {
Materialize.toast("<p>Thanks for contributing! However, others won't see your card until you verify your email address<p>", 4000); 121 98 Materialize.toast("<p>Thanks for contributing! However, others won't see your card until you verify your email address<p>", 4000);
} 122 99 }
}). 123 100 }).
error(function(error) { 124 101 error(function(error) {
console.log('something went wrong pushing a card!'); 125 102 console.log('something went wrong pushing a card!');
}); 126 103 });
return $scope.closeNewCardModal(); 127 104 return $scope.closeNewCardModal();
}; 128 105 };
129 106
/* Key bindings for the whole feed window. Hotkey it up! */ 130 107 /* Key bindings for the whole feed window. Hotkey it up! */
var listenForC = true; 131 108 var listenForC = true;
132 109
// Need to pass these options into openmodal and leanmodal, 133 110 // Need to pass these options into openmodal and leanmodal,
// otherwise the ready handler doesn't get called 134 111 // otherwise the ready handler doesn't get called
135 112
modal_options = { 136 113 modal_options = {
dismissible: true, // Modal can be dismissed by clicking outside of the modal 137 114 dismissible: true, // Modal can be dismissed by clicking outside of the modal
opacity: 0, // Opacity of modal background 138 115 opacity: 0, // Opacity of modal background
in_duration: 300, // Transition in duration 139 116 in_duration: 300, // Transition in duration
out_duration: 200, // Transition out duration 140 117 out_duration: 200, // Transition out duration
ready: function() { 141 118 ready: function() {
$('#new-card-input').focus(); 142 119 $('#new-card-input').focus();
document.execCommand('selectAll', false, null); 143 120 document.execCommand('selectAll', false, null);
} 144 121 }
}; 145 122 };
146 123
$(document).keydown(function(e) { 147 124 $(document).keydown(function(e) {
var keyed = e.which; 148 125 var keyed = e.which;
if (keyed == 67 && listenForC) { // "c" for compose 149 126 if (keyed == 67 && listenForC) { // "c" for compose
$scope.openNewCardModal(); 150 127 $scope.openNewCardModal();
e.preventDefault(); 151 128 e.preventDefault();
return false; 152 129 return false;
} else if (keyed == 27) { // clear on ESC 153 130 } else if (keyed == 27) { // clear on ESC
$scope.closeNewCardModal(); 154 131 $scope.closeNewCardModal();
} 155 132 }
}); 156 133 });
157 134
$scope.openNewCardModal = function() { 158 135 $scope.openNewCardModal = function() {
$('#newCard').openModal(modal_options); 159 136 $('#newCard').openModal(modal_options);
listenForC = false; 160 137 listenForC = false;
$('#new-card-input').html('Write a flashcard!'); 161 138 $('#new-card-input').html('Write a flashcard!');
162
}; 163 139 };
164 140
$scope.closeNewCardModal = function() { 165 141 $scope.closeNewCardModal = function() {
listenForC = true; 166 142 listenForC = true;
$('#new-card-input').html('').blur(); 167 143 $('#new-card-input').html('').blur();
$('#newCard').closeModal(modal_options); 168 144 $('#newCard').closeModal(modal_options);
}; 169 145 };
170 146
$('.tooltipped').tooltip({delay: 50}); 171 147 $('.tooltipped').tooltip({delay: 50});
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered 172 148 // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal(modal_options); 173 149 $('.modal-trigger').leanModal(modal_options);
$('#new-card-input').on('keydown', function(e) { 174 150 $('#new-card-input').on('keydown', function(e) {
if (e.which == 13) { 175 151 if (e.which == 13) {
e.preventDefault(); 176 152 e.preventDefault();
$scope.pushCard(); 177 153 $scope.pushCard();
listenForC = true; 178 154 listenForC = true;
return false; 179 155 return false;
156 } else {
157
} 180 158 }
}); 181 159 });
$('button#blank-selected').click(function() { 182 160 $('button#blank-selected').click(function() {
console.log(window.getSelection()); 183 161 console.log(window.getSelection());
document.execCommand('bold'); 184 162 document.execCommand('bold');
}); 185 163 });
$scope.refreshCards(); 186 164 $scope.refreshCards();
165 $scope.newCardBlanks = [];
166 $scope.refreshNewCardInput = function() {
167 $scope.newCardText = $('#new-card-input').text();
168 $scope.submit_enabled = $scope.newCardText.length >= 5 && $scope.newCardText.length <= 160;
169 $('#new-card-input')[0].childNodes.forEach(function(node) {
170 if (typeof node.data == 'undefined') {
171 console.log('undefined node');
172 }
173 node = $(node)[0];
174 if (node.tagName == 'B') {
175 var text = $(node).text();
176 console.log(text.length, text);
177 var leftspaces = 0, rightspaces = 0;
178 // awful way to find the first non-space character from the left or the right. thanks.js
179 while (text[leftspaces] == ' ' || text[leftspaces] == '\xa0') leftspaces++;
180 while (text[text.length - 1 - rightspaces] == ' ' || text[text.length - 1 - rightspaces] == '\xa0') rightspaces++;
181 if (leftspaces != text.length) $scope.newCardBlanks.push([i + leftspaces, i + text.length - rightspaces]);
182 i += text.length;
183 } else if (!node.data) {
184 console.log('weird node', node);
185 i += $(node).text().length;
186 } else {
187 i += node.data.length;
templates/feed.html View file @ 88ca254
<div class="row"> 1 1 <div class="row">
<h2 ng-cloak ng-show="cards.length == 0">No cards. Be the first one to add a card!</h2> 2 2 <h2 ng-cloak ng-show="cards.length == 0">No cards. Be the first one to add a card!</h2>
3 3
<div class="progress center-align" style="margin: 70px auto auto;width:50%;" ng-if="cards === false"> 4 4 <div class="progress center-align" style="margin: 70px auto auto;width:50%;" ng-if="cards === false">
<div class="indeterminate"></div> 5 5 <div class="indeterminate"></div>
</div> 6 6 </div>
7 7
<div class="cardColumn" ng-repeat="col in cardCols"> 8 8 <div class="cardColumn" ng-repeat="col in cardCols">
<div class="repeated-card" ng-repeat="card in col"> 9 9 <div class="repeated-card" ng-repeat="card in col">
<flashcard flashcard-obj="card"/> 10 10 <flashcard flashcard-obj="card"/>
</div> 11 11 </div>
</div> 12 12 </div>
</div> 13 13 </div>
14 14
15 15
<!--Lil plus button in corner--> 16 16 <!--Lil plus button in corner-->
<div class="fixed-action-btn" style="bottom: 96px; right: 24px;"> 17 17 <div class="fixed-action-btn" style="bottom: 96px; right: 24px;">
<a data-target="newCard" class="btn-floating btn-large modal-trigger tooltipped" data-position="left" 18 18 <a data-target="newCard" class="btn-floating btn-large modal-trigger tooltipped" data-position="left"
data-delay="50" ng-click="openNewCardModal()" 19 19 data-delay="50" ng-click="openNewCardModal()"
data-tooltip="(C)ompose"> 20 20 data-tooltip="(C)ompose">
<i class="large mdi-content-add"></i> 21 21 <i class="large mdi-content-add"></i>
</a> 22 22 </a>
</div> 23 23 </div>
24 24
<div id="newCard" class="modal bottom-sheet row" style="max-height:none;"> 25 25 <div id="newCard" class="modal bottom-sheet row" style="max-height:none;">
<form id="new-card-form"> 26 26 <form id="new-card-form">
<div class="modal-content col"> 27 27 <div class="modal-content col">
<div class="row" style="margin-bottom:0"> 28 28 <div class="row" style="margin-bottom:0">
<div class="card cyan-text text-darken-2" 29 29 <div class="card cyan-text text-darken-2"
style="width:300px; height:180px; margin-bottom:0; font-size:120%;"> 30 30 style="width:300px; height:180px; margin-bottom:0; font-size:120%;">
<div class="valign-wrapper"> 31 31 <div class="valign-wrapper">
<div id="new-card-input" ng-model="newcardtext" style="outline:0px solid transparent;" 32 32 <div id="new-card-input" ng-model="newCardFormattedText" style="outline:0px solid transparent;"
class="card-content valign center-align" 33 33 class="card-content valign center-align"
contenteditable> 34 34 contenteditable select-non-editable="true" ng-change="refreshNewCardInput()">
35 35
</div> 36 36 </div>
</div> 37 37 </div>
38 38
</div> 39 39 </div>
</div> 40 40 </div>
</div> 41 41 </div>
42 42
<div class="col"> 43 43 <div class="col">
<div class="row"> 44 44 <div class="row">
45 45
</div> 46 46 </div>
<div class="row"> 47 47 <div class="row">
<button class="btn modal-close tooltipped" type="submit" ng-click="pushCard()" data-position="left" 48 48 <button class="btn modal-close tooltipped" type="submit" ng-click="pushCard()"
data-delay="50" ng-class="newcardtext.length >= 5?{}:'disabled'" 49 49 data-position="left"
data-tooltip="Enter">Submit 50 50 data-delay="50" ng-class="submit_enabled?{}:'disabled'"
51 data-tooltip="Enter">Contribute
<i class="mdi-hardware-keyboard-return right"></i> 51 52 <i class="mdi-hardware-keyboard-return right"></i>
</button> 52 53 </button>
</div> 53 54 </div>
<div class="row"> 54 55 <div class="row">
<button id="blank-selected" style="float:left" class="btn tooltipped" data-position="right" data-delay="50" 55 56 <button id="blank-selected" style="float:left" class="btn tooltipped" data-position="right" data-delay="50"
data-tooltip="Ctrl-B">Blank Selected Text 56 57 data-tooltip="Ctrl-B">Blank Selected Text
</button> 57 58 </button>
</div> 58 59 </div>
<div class="row" ng-show="newcardtext"> 59 60 <div class="row" ng-show="newCardText" ng-style="(newCardText.length>160)?{color:'red'}:{}">
{{newcardtext.length}}/160 characters 60 61 {{newCardText.length}}/160 characters
</div> 61 62 </div>
<div class="row" ng-show="newcardtext.length < 5"> 62 63 <div class="row" ng-show="newCardText.length < 5">
Please write a little more! 63 64 Please write a little more!
</div> 64 65 </div>
<div class="row" ng-show="newcardtext.length > 140"> 65 66 <div class="row" ng-show="newCardText.length > 140">
You' 66 67 Good flashcards have a<br>
68 single atomic fact
</div> 67 69 </div>
</div> 68 70 </div>
</form> 69 71 </form>
</div> 70 72 </div>
71 73