Commit ae8bc20b by Brian Jacobel

Run eslint autofixer on /lms

parent a63da43a
;(function (define) {
(function(define) {
'use strict';
define(['jquery', 'underscore', 'support/js/views/certificates'],
function ($, _, CertificatesView) {
return function (options) {
function($, _, CertificatesView) {
return function(options) {
options = _.extend(options, {
el: $('.certificates-content')
});
......
;(function (define) {
(function(define) {
'use strict';
define(['backbone', 'support/js/models/certificate'],
function(Backbone, CertModel) {
......@@ -26,5 +26,5 @@
return url;
}
});
});
});
}).call(this, define || RequireJS.define);
;(function (define) {
(function(define) {
'use strict';
define(['backbone', 'support/js/models/enrollment'],
function(Backbone, EnrollmentModel) {
......@@ -14,5 +14,5 @@
return this.baseUrl + this.user;
}
});
});
});
}).call(this, define || RequireJS.define);
;(function (define) {
(function(define) {
'use strict';
define([
'underscore',
'support/js/views/enrollment'
], function (_, EnrollmentView) {
return function (options) {
], function(_, EnrollmentView) {
return function(options) {
options = _.extend({el: '.enrollment-content'}, options);
return new EnrollmentView(options).render();
};
......
(function (define) {
(function(define) {
'use strict';
define(['backbone'], function (Backbone) {
define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
defaults: {
username: null,
......
(function (define) {
(function(define) {
'use strict';
define(['backbone', 'underscore'], function (Backbone, _) {
define(['backbone', 'underscore'], function(Backbone, _) {
return Backbone.Model.extend({
updateEnrollment: function (new_mode, reason) {
updateEnrollment: function(new_mode, reason) {
return $.ajax({
url: this.url(),
type: 'POST',
......@@ -13,7 +13,7 @@
old_mode: this.get('mode'),
reason: reason
}),
success: _.bind(function (response) {
success: _.bind(function(response) {
this.set('manual_enrollment', response);
this.set('mode', new_mode);
}, this)
......
define([
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'support/js/spec_helpers/enrollment_helpers',
'support/js/collections/enrollment',
], function (AjaxHelpers, EnrollmentHelpers, EnrollmentCollection) {
'support/js/collections/enrollment'
], function(AjaxHelpers, EnrollmentHelpers, EnrollmentCollection) {
'use strict';
describe('EnrollmentCollection', function () {
describe('EnrollmentCollection', function() {
var enrollmentCollection;
beforeEach(function () {
beforeEach(function() {
enrollmentCollection = new EnrollmentCollection([EnrollmentHelpers.mockEnrollmentData], {
user: 'test-user',
baseUrl: '/support/enrollment/'
});
});
it('sets its URL based on the user', function () {
it('sets its URL based on the user', function() {
expect(enrollmentCollection.url()).toEqual('/support/enrollment/test-user');
});
});
......
......@@ -2,20 +2,20 @@ define([
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'support/js/spec_helpers/enrollment_helpers',
'support/js/models/enrollment'
], function (AjaxHelpers, EnrollmentHelpers, EnrollmentModel) {
], function(AjaxHelpers, EnrollmentHelpers, EnrollmentModel) {
'use strict';
describe('EnrollmentModel', function () {
describe('EnrollmentModel', function() {
var enrollment;
beforeEach(function () {
beforeEach(function() {
enrollment = new EnrollmentModel(EnrollmentHelpers.mockEnrollmentData);
enrollment.url = function () {
enrollment.url = function() {
return '/support/enrollment/test-user';
};
});
it('can save an enrollment to the server and updates itself on success', function () {
it('can save an enrollment to the server and updates itself on success', function() {
var requests = AjaxHelpers.requests(this),
manual_enrollment = {
'enrolled_by': 'staff@edx.org',
......@@ -33,7 +33,7 @@ define([
expect(enrollment.get('manual_enrollment')).toEqual(manual_enrollment);
});
it('does not update itself on a server error', function () {
it('does not update itself on a server error', function() {
var requests = AjaxHelpers.requests(this);
enrollment.updateEnrollment('verified', 'Financial Assistance');
AjaxHelpers.respondWithError(requests, 500);
......
......@@ -6,91 +6,90 @@ define([
'use strict';
describe('CertificatesView', function() {
var view = null,
REGENERATE_SEARCH_RESULTS = [
{
'username': 'student',
'status': 'notpassing',
'created': '2015-08-05T17:32:25+00:00',
'grade': '0.0',
'type': 'honor',
'course_key': 'course-v1:edX+DemoX+Demo_Course',
'download_url': null,
'modified': '2015-08-06T19:47:07+00:00',
'regenerate': true
},
{
'username': 'student',
'status': 'downloadable',
'created': '2015-08-05T17:53:33+00:00',
'grade': '1.0',
'type': 'verified',
'course_key': 'edx/test/2015',
'download_url': 'http://www.example.com/certificate.pdf',
'modified': '2015-08-06T19:47:05+00:00',
'regenerate': true
}
],
GENERATE_SEARCH_RESULTS = [
{
'username': 'student',
'status': '',
'created': '',
'grade': '',
'type': '',
'course_key': 'edx/test1/2016',
'download_url': null,
'modified': '',
'regenerate': false
}
],
getSearchResults = function() {
var results = [];
$('.certificates-results tr').each(function(rowIndex, rowValue) {
var columns = [];
$(rowValue).children('td').each(function(colIndex, colValue) {
columns[colIndex] = $(colValue).html();
});
if (columns.length > 0) {
results.push(columns);
REGENERATE_SEARCH_RESULTS = [
{
'username': 'student',
'status': 'notpassing',
'created': '2015-08-05T17:32:25+00:00',
'grade': '0.0',
'type': 'honor',
'course_key': 'course-v1:edX+DemoX+Demo_Course',
'download_url': null,
'modified': '2015-08-06T19:47:07+00:00',
'regenerate': true
},
{
'username': 'student',
'status': 'downloadable',
'created': '2015-08-05T17:53:33+00:00',
'grade': '1.0',
'type': 'verified',
'course_key': 'edx/test/2015',
'download_url': 'http://www.example.com/certificate.pdf',
'modified': '2015-08-06T19:47:05+00:00',
'regenerate': true
}
});
],
GENERATE_SEARCH_RESULTS = [
{
'username': 'student',
'status': '',
'created': '',
'grade': '',
'type': '',
'course_key': 'edx/test1/2016',
'download_url': null,
'modified': '',
'regenerate': false
}
],
getSearchResults = function() {
var results = [];
return results;
},
$('.certificates-results tr').each(function(rowIndex, rowValue) {
var columns = [];
$(rowValue).children('td').each(function(colIndex, colValue) {
columns[colIndex] = $(colValue).html();
});
if (columns.length > 0) {
results.push(columns);
}
});
searchFor = function(user_filter, course_filter, requests, response) {
return results;
},
searchFor = function(user_filter, course_filter, requests, response) {
// Enter the search term and submit
var url = '/certificates/search?user=' + user_filter;
view.setUserFilter(user_filter);
if (course_filter) {
view.setCourseFilter(course_filter);
url += '&course_id=' + course_filter;
}
view.triggerSearch();
var url = '/certificates/search?user=' + user_filter;
view.setUserFilter(user_filter);
if (course_filter) {
view.setCourseFilter(course_filter);
url += '&course_id=' + course_filter;
}
view.triggerSearch();
// Simulate a response from the server
AjaxHelpers.expectJsonRequest(requests, 'GET', url);
AjaxHelpers.respondWithJson(requests, response);
},
AjaxHelpers.expectJsonRequest(requests, 'GET', url);
AjaxHelpers.respondWithJson(requests, response);
},
regenerateCerts = function(username, courseKey) {
var sel = '.btn-cert-regenerate[data-course-key="' + courseKey + '"]';
$(sel).click();
},
regenerateCerts = function(username, courseKey) {
var sel = '.btn-cert-regenerate[data-course-key="' + courseKey + '"]';
$(sel).click();
},
generateCerts = function(username, courseKey) {
var sel = '.btn-cert-generate[data-course-key="' + courseKey + '"]';
$(sel).click();
};
generateCerts = function(username, courseKey) {
var sel = '.btn-cert-generate[data-course-key="' + courseKey + '"]';
$(sel).click();
};
beforeEach(function () {
beforeEach(function() {
spyOn(window.history, 'pushState');
setFixtures('<div class="certificates-content"></div>');
view = new CertificatesView({
......@@ -142,7 +141,6 @@ define([
expect(results[0][3]).toContain('Not available');
expect(results[0][4]).toEqual(GENERATE_SEARCH_RESULTS[0].grade);
expect(results[0][5]).toEqual(GENERATE_SEARCH_RESULTS[0].modified);
});
it('searches for certificates and displays a message when there are no results', function() {
......@@ -201,7 +199,7 @@ define([
AjaxHelpers.respondWithJson(requests, '');
});
it('generate a certificate for a student', function() {
it('generate a certificate for a student', function() {
var requests = AjaxHelpers.requests(this);
// Trigger a search
......@@ -223,6 +221,5 @@ define([
// Respond with success
AjaxHelpers.respondWithJson(requests, '');
});
});
});
......@@ -4,16 +4,15 @@ define([
'support/js/spec_helpers/enrollment_helpers',
'support/js/models/enrollment',
'support/js/views/enrollment_modal'
], function (_, AjaxHelpers, EnrollmentHelpers, EnrollmentModel, EnrollmentModal) {
], function(_, AjaxHelpers, EnrollmentHelpers, EnrollmentModel, EnrollmentModal) {
'use strict';
describe('EnrollmentModal', function () {
describe('EnrollmentModal', function() {
var modal;
beforeEach(function () {
beforeEach(function() {
var enrollment = new EnrollmentModel(EnrollmentHelpers.mockEnrollmentData);
enrollment.url = function () {
enrollment.url = function() {
return '/support/enrollment/test-user';
};
setFixtures('<div class="enrollment-modal-wrapper is-hidden"></div>');
......@@ -23,53 +22,53 @@ define([
modes: ['verified', 'audit'],
reasons: _.reduce(
['Financial Assistance', 'Stampeding Buffalo', 'Angry Customer'],
function (acc, x) { acc[x] = x; return acc; },
function(acc, x) { acc[x] = x; return acc; },
{}
)
}).render();
});
it('can render itself', function () {
it('can render itself', function() {
expect($('.enrollment-modal h1').text()).toContain(
'Change enrollment for ' + EnrollmentHelpers.TEST_COURSE
);
expect($('.enrollment-change-field p').first().text()).toContain('Current enrollment mode: audit');
_.each(['verified', 'audit'], function (mode) {
_.each(['verified', 'audit'], function(mode) {
expect($('.enrollment-new-mode').html()).toContain('<option value="' + mode + '">');
});
_.each(['', 'Financial Assistance', 'Stampeding Buffalo', 'Angry Customer'], function (reason) {
_.each(['', 'Financial Assistance', 'Stampeding Buffalo', 'Angry Customer'], function(reason) {
expect($('.enrollment-reason').html()).toContain('<option value="' + reason + '">');
});
});
it('is hidden by default', function () {
it('is hidden by default', function() {
expect($('.enrollment-modal-wrapper')).toHaveClass('is-hidden');
});
it('can show and hide itself', function () {
it('can show and hide itself', function() {
modal.show();
expect($('.enrollment-modal-wrapper')).not.toHaveClass('is-hidden');
modal.hide();
expect($('.enrollment-modal-wrapper')).toHaveClass('is-hidden');
});
it('shows errors on submit if a reason is not given', function () {
it('shows errors on submit if a reason is not given', function() {
expect($('.enrollment-change-errors').css('display')).toEqual('none');
$('.enrollment-change-submit').click();
expect($('.enrollment-change-errors').css('display')).not.toEqual('none');
expect($('.enrollment-change-errors').text()).toContain('Please specify a reason.');
});
it('can does not error if a free-form reason is given', function () {
it('can does not error if a free-form reason is given', function() {
AjaxHelpers.requests(this);
$('.enrollment-reason-other').val('For Fun');
$('.enrollment-change-submit').click();
expect($('.enrollment-change-errors').css('display')).toEqual('none');
});
it('can submit an enrollment change request and hides itself on success', function () {
it('can submit an enrollment change request and hides itself on success', function() {
var requests = AjaxHelpers.requests(this);
$('.enrollment-new-mode').val('verified');
$('.enrollment-reason').val('Financial Assistance');
......@@ -87,7 +86,7 @@ define([
expect($('.enrollment-change-errors').css('display')).toEqual('none');
});
it('shows a message on a server error', function () {
it('shows a message on a server error', function() {
var requests = AjaxHelpers.requests(this);
$('.enrollment-new-mode').val('verified');
$('.enrollment-reason').val('Financial Assistance');
......@@ -97,7 +96,7 @@ define([
expect($('.enrollment-change-errors').text()).toContain('Something went wrong');
});
it('hides itself on cancel', function () {
it('hides itself on cancel', function() {
var requests = AjaxHelpers.requests(this);
modal.show();
$('.enrollment-change-cancel').click();
......
......@@ -3,11 +3,11 @@ define([
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'support/js/spec_helpers/enrollment_helpers',
'support/js/views/enrollment'
], function (_, AjaxHelpers, EnrollmentHelpers, EnrollmentView) {
], function(_, AjaxHelpers, EnrollmentHelpers, EnrollmentView) {
'use strict';
var enrollmentView,
createEnrollmentView = function (options) {
createEnrollmentView = function(options) {
if (_.isUndefined(options)) {
options = {};
}
......@@ -15,22 +15,22 @@ define([
el: '.enrollment-content',
user: 'test-user',
enrollmentsUrl: '/support/enrollment/',
enrollmentSupportUrl: '/support/enrollment/',
enrollmentSupportUrl: '/support/enrollment/'
}, options));
};
beforeEach(function () {
beforeEach(function() {
setFixtures('<div class="enrollment-content"></div>');
});
describe('EnrollmentView', function () {
it('can render itself without an initial user', function () {
describe('EnrollmentView', function() {
it('can render itself without an initial user', function() {
enrollmentView = createEnrollmentView({user: ''}).render();
expect($('.enrollment-search input').val()).toBe('');
expect($('.enrollment-results').length).toBe(0);
});
it('renders itself when an initial user is provided', function () {
it('renders itself when an initial user is provided', function() {
var requests = AjaxHelpers.requests(this);
enrollmentView = createEnrollmentView().render();
AjaxHelpers.expectRequest(requests, 'GET', '/support/enrollment/test-user', null);
......@@ -43,7 +43,7 @@ define([
});
});
it('re-renders itself when its collection changes', function () {
it('re-renders itself when its collection changes', function() {
var requests = AjaxHelpers.requests(this);
enrollmentView = createEnrollmentView().render();
spyOn(enrollmentView, 'render').and.callThrough();
......@@ -51,7 +51,7 @@ define([
expect(enrollmentView.render).toHaveBeenCalled();
});
it('shows a modal dialog to change enrollments', function () {
it('shows a modal dialog to change enrollments', function() {
var requests = AjaxHelpers.requests(this);
enrollmentView = createEnrollmentView().render();
AjaxHelpers.respondWithJson(requests, [EnrollmentHelpers.mockEnrollmentData]);
......
define([], function () {
define([], function() {
'use strict';
var testCourse = "course-v1:TestX+T101+2015";
var testCourse = 'course-v1:TestX+T101+2015';
return {
TEST_COURSE: testCourse,
mockEnrollmentData: {
created: "2015-12-07T18:17:46.210940Z",
mode: "audit",
created: '2015-12-07T18:17:46.210940Z',
mode: 'audit',
is_active: true,
user: "test-user",
course_end: "2017-01-01T00:00:00Z",
course_start: "2015-01-01T00:00:00Z",
user: 'test-user',
course_end: '2017-01-01T00:00:00Z',
course_start: '2015-01-01T00:00:00Z',
course_modes: [
{
slug: "audit",
name: "Audit",
slug: 'audit',
name: 'Audit',
min_price: 0,
suggested_prices: "",
currency: "usd",
suggested_prices: '',
currency: 'usd',
expiration_datetime: null,
description: null,
sku: "6ED7EDC"
sku: '6ED7EDC'
},
{
slug: "verified",
name: "Verified Certificate",
slug: 'verified',
name: 'Verified Certificate',
min_price: 5,
suggested_prices: "",
currency: "usd",
suggested_prices: '',
currency: 'usd',
expiration_datetime: null,
description: null,
sku: "25A5354"
sku: '25A5354'
}
],
enrollment_start: null,
......
;(function (define) {
(function(define) {
'use strict';
define([
......@@ -8,7 +8,7 @@
'support/js/collections/certificate',
'text!support/templates/certificates.underscore',
'text!support/templates/certificates_results.underscore'
], function (Backbone, _, gettext, CertCollection, certificatesTpl, resultsTpl) {
], function(Backbone, _, gettext, CertCollection, certificatesTpl, resultsTpl) {
return Backbone.View.extend({
events: {
'submit .certificates-form': 'search',
......@@ -53,11 +53,10 @@
},
search: function(event) {
// Fetch the certificate collection for the given user
var url = '/support/certificates?user=' + this.getUserFilter();
//course id is optional.
// course id is optional.
if (this.getCourseFilter()) {
url += '&course_id=' + this.getCourseFilter();
}
......@@ -171,13 +170,13 @@
},
setResults: function(html) {
$(".certificates-results", this.$el).html(html);
$('.certificates-results', this.$el).html(html);
},
disableButtons: function() {
$('.btn-disable-on-submit')
.addClass("is-disabled")
.attr("disabled", true);
.addClass('is-disabled')
.attr('disabled', true);
},
enableButtons: function() {
......
;(function (define) {
(function(define) {
'use strict';
define([
......@@ -8,7 +8,7 @@
'support/js/views/enrollment_modal',
'support/js/collections/enrollment',
'text!support/templates/enrollment.underscore'
], function (Backbone, _, moment, EnrollmentModal, EnrollmentCollection, enrollmentTemplate) {
], function(Backbone, _, moment, EnrollmentModal, EnrollmentCollection, enrollmentTemplate) {
return Backbone.View.extend({
ENROLLMENT_CHANGE_REASONS: {
......@@ -22,7 +22,7 @@
'click .change-enrollment-btn': 'changeEnrollment'
},
initialize: function (options) {
initialize: function(options) {
var user = options.user;
this.initialUser = user;
this.enrollmentSupportUrl = options.enrollmentSupportUrl;
......@@ -33,12 +33,12 @@
this.enrollments.on('change', _.bind(this.render, this));
},
render: function () {
render: function() {
var user = this.enrollments.user;
this.$el.html(_.template(enrollmentTemplate)({
user: user,
enrollments: this.enrollments,
formatDate: function (date) {
formatDate: function(date) {
if (!date) {
return 'N/A';
}
......@@ -56,7 +56,7 @@
* Check if the URL has provided an initial search, and
* perform that search if so.
*/
checkInitialSearch: function () {
checkInitialSearch: function() {
if (this.initialUser) {
delete this.initialUser;
this.$('.enrollment-form').submit();
......@@ -66,18 +66,18 @@
/*
* Return the user's search string.
*/
getSearchString: function () {
getSearchString: function() {
return this.$('#enrollment-query-input').val();
},
/*
* Perform the search. Renders the view on success.
*/
search: function (event) {
search: function(event) {
event.preventDefault();
this.enrollments.user = this.getSearchString();
this.enrollments.fetch({
success: _.bind(function () {
success: _.bind(function() {
this.render();
}, this)
});
......@@ -87,7 +87,7 @@
* Show a modal view allowing the user to change a
* learner's enrollment.
*/
changeEnrollment: function (event) {
changeEnrollment: function(event) {
var button = $(event.currentTarget),
course_id = button.data('course_id'),
modes = button.data('modes').split(','),
......
;(function (define) {
(function(define) {
'use strict';
define([
......@@ -6,44 +6,44 @@
'underscore',
'gettext',
'text!support/templates/enrollment-modal.underscore'
], function (Backbone, _, gettext, modalTemplate) {
], function(Backbone, _, gettext, modalTemplate) {
var EnrollmentModal = Backbone.View.extend({
events: {
'click .enrollment-change-submit': 'submitEnrollmentChange',
'click .enrollment-change-cancel': 'cancel'
},
initialize: function (options) {
initialize: function(options) {
this.enrollment = options.enrollment;
this.modes = options.modes;
this.reasons = options.reasons;
this.template = modalTemplate;
},
render: function () {
render: function() {
this.$el.html(_.template(this.template)({
enrollment: this.enrollment,
modes: this.modes,
reasons: this.reasons,
reasons: this.reasons
}));
return this;
},
show: function () {
show: function() {
this.$el.removeClass('is-hidden').addClass('is-shown');
this.render();
},
hide: function () {
hide: function() {
this.$el.removeClass('is-shown').addClass('is-hidden');
this.render();
},
showErrors: function (errorMessage) {
showErrors: function(errorMessage) {
this.$('.enrollment-change-errors').text(errorMessage).css('display', '');
},
submitEnrollmentChange: function (event) {
submitEnrollmentChange: function(event) {
var new_mode = this.$('.enrollment-new-mode').val(),
reason = this.$('.enrollment-reason').val() || this.$('.enrollment-reason-other').val();
event.preventDefault();
......@@ -53,11 +53,11 @@
else {
this.enrollment.updateEnrollment(new_mode, reason).then(
// Success callback
_.bind(function () {
_.bind(function() {
this.hide();
}, this),
// Error callback
_.bind(function () {
_.bind(function() {
this.showErrors(gettext(
'Something went wrong changing this enrollment. Please try again.'
));
......@@ -66,7 +66,7 @@
}
},
cancel: function (event) {
cancel: function(event) {
event.preventDefault();
this.hide();
}
......
;(function (define) {
(function(define) {
'use strict';
define(['edx-ui-toolkit/js/pagination/paging-collection'],
function(PagingCollection) {
var BaseCollection = PagingCollection.extend({
constructor: function (models, options) {
constructor: function(models, options) {
this.options = options;
this.url = options.url;
if (options.perPage) {
......@@ -17,8 +17,8 @@
this.queryParams = _.extend({}, BaseCollection.prototype.queryParams, this.queryParams);
PagingCollection.prototype.constructor.call(this, models, options);
},
parse: function (response, options) {
parse: function(response, options) {
if (!response) {
response = {};
}
......@@ -37,11 +37,11 @@
// TODO: These changes has been added to backbone.paginator
// remove when backbone.paginator gets a new release
sync: function (method, model, options) {
sync: function(method, model, options) {
// do not send total pages and total records in request
if (method === 'read') {
var params = _.values(_.pick(this.queryParams, ['totalPages', 'totalRecords']));
_.each(params, function (param) {
_.each(params, function(param) {
delete options.data[param];
});
}
......
;(function (define) {
(function(define) {
'use strict';
define(['teams/js/collections/team'], function (TeamCollection) {
define(['teams/js/collections/team'], function(TeamCollection) {
var MyTeamsCollection = TeamCollection.extend({
queryParams: {
username: function () {
username: function() {
return this.options.username;
},
text_search: function () {
text_search: function() {
return this.searchString || '';
}
},
constructor: function (teams, options) {
constructor: function(teams, options) {
TeamCollection.prototype.constructor.call(this, teams, options);
delete this.queryParams.topic_id;
}
......
;(function (define) {
(function(define) {
'use strict';
define(['teams/js/collections/base', 'teams/js/models/team', 'gettext'],
function(BaseCollection, TeamModel, gettext) {
var TeamCollection = BaseCollection.extend({
model: TeamModel,
state: {
sortKey: 'last_activity_at',
order: null
},
queryParams: {
topic_id: function () {
topic_id: function() {
return this.options.topic_id;
},
expand: 'user',
course_id: function () {
course_id: function() {
return this.options.course_id;
},
order_by: function () {
order_by: function() {
return this.getSearchString() ? '' : this.state.sortKey;
},
text_search: function () {
text_search: function() {
return this.getSearchString() || '';
}
},
......@@ -36,10 +36,10 @@
this.registerSortableField('open_slots', gettext('open slots'));
},
setFilterField: function (fieldName, value) {
setFilterField: function(fieldName, value) {
BaseCollection.prototype.setFilterField.call(this, fieldName, value);
this.queryParams[fieldName] = function () {
this.queryParams[fieldName] = function() {
return value;
};
}
......
;(function (define) {
(function(define) {
'use strict';
define(['underscore', 'gettext', 'teams/js/collections/base', 'teams/js/models/topic'],
function(_, gettext, BaseCollection, TopicModel) {
......@@ -10,8 +10,8 @@
},
queryParams: {
course_id: function () { return this.course_id; },
text_search: function () { return this.searchString || ''; }
course_id: function() { return this.course_id; },
text_search: function() { return this.searchString || ''; }
},
constructor: function(topics, options) {
......
/**
* Model for a team.
*/
(function (define) {
(function(define) {
'use strict';
define(['backbone'], function (Backbone) {
define(['backbone'], function(Backbone) {
var Team = Backbone.Model.extend({
defaults: {
id: null,
......
/**
* Model for a team membership.
*/
(function (define) {
(function(define) {
'use strict';
define(['backbone', 'teams/js/models/team'], function (Backbone, TeamModel) {
define(['backbone', 'teams/js/models/team'], function(Backbone, TeamModel) {
var TeamMembership = Backbone.Model.extend({
defaults: {
date_joined: '',
......@@ -12,7 +12,7 @@
user: null
},
parse: function (response) {
parse: function(response) {
response.team = new TeamModel(response.team);
return response;
}
......
/**
* Model for a topic.
*/
(function (define) {
(function(define) {
'use strict';
define(['backbone'], function (Backbone) {
define(['backbone'], function(Backbone) {
var Topic = Backbone.Model.extend({
defaults: {
name: '',
......
define(['backbone', 'URI', 'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'teams/js/spec_helpers/team_spec_helpers'],
function (Backbone, URI, _, AjaxHelpers, TeamSpecHelpers) {
function(Backbone, URI, _, AjaxHelpers, TeamSpecHelpers) {
'use strict';
describe('TopicCollection', function () {
describe('TopicCollection', function() {
var topicCollection;
beforeEach(function () {
beforeEach(function() {
topicCollection = TeamSpecHelpers.createMockTopicCollection();
});
var testRequestParam = function (self, param, value) {
var testRequestParam = function(self, param, value) {
var requests = AjaxHelpers.requests(self),
request,
url,
......@@ -20,25 +20,25 @@ define(['backbone', 'URI', 'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/a
expect(params[param]).toBe(value);
};
it('sets its page size based on initial page size', function () {
it('sets its page size based on initial page size', function() {
expect(topicCollection.getPageSize()).toBe(5);
expect(topicCollection.getTotalPages()).toBe(2);
});
it('sorts by name', function () {
it('sorts by name', function() {
testRequestParam(this, 'order_by', 'name');
});
it('passes a course_id to the server', function () {
it('passes a course_id to the server', function() {
testRequestParam(this, 'course_id', TeamSpecHelpers.testCourseID);
});
it('URL encodes its course_id ', function () {
it('URL encodes its course_id ', function() {
topicCollection.course_id = 'my+course+id';
testRequestParam(this, 'course_id', 'my+course+id');
});
it('sets itself to stale on receiving a teams create or delete event', function () {
it('sets itself to stale on receiving a teams create or delete event', function() {
expect(topicCollection.isStale).toBe(false);
TeamSpecHelpers.triggerTeamEvent('create');
expect(topicCollection.isStale).toBe(true);
......
......@@ -3,7 +3,7 @@ define(['jquery', 'backbone', 'teams/js/teams_tab_factory', 'teams/js/views/team
function($, Backbone, TeamsTabFactory, TeamsTabView, PageHelpers, TeamSpecHelpers) {
'use strict';
describe("Teams Tab Factory", function() {
describe('Teams Tab Factory', function() {
var initializeTeamsTabFactory = function() {
TeamsTabFactory(TeamSpecHelpers.createMockContext());
};
......
......@@ -7,7 +7,7 @@ define([
'teams/js/models/team',
'teams/js/views/team_utils',
'teams/js/spec_helpers/team_spec_helpers'
], function ($, _, Backbone, AjaxHelpers, TeamEditMembershipView, TeamModel, TeamUtils, TeamSpecHelpers) {
], function($, _, Backbone, AjaxHelpers, TeamEditMembershipView, TeamModel, TeamUtils, TeamSpecHelpers) {
'use strict';
describe('CreateEditTeam', function() {
......@@ -19,13 +19,13 @@ define([
'profile_image': {
'has_image': true,
'image_url_medium': '/frodo-image-url'
},
}
},
last_activity_at: "2015-08-21T18:53:01.145Z",
date_joined: "2014-01-01T18:53:01.145Z"
last_activity_at: '2015-08-21T18:53:01.145Z',
date_joined: '2014-01-01T18:53:01.145Z'
}
],
deleteTeamMemember = function (view, confirm) {
deleteTeamMemember = function(view, confirm) {
view.$('.action-remove-member').click();
// Confirm delete dialog
if (confirm) {
......@@ -35,18 +35,18 @@ define([
$('.action-secondary').click();
}
},
verifyTeamMembersView = function (view) {
verifyTeamMembersView = function(view) {
expect(view.$('.team-member').length).toEqual(1);
expect(view.$('.member-profile').attr('href')).toEqual('/u/frodo');
expect(view.$('img.image-url').attr('src')).toEqual('/frodo-image-url');
expect(view.$('.member-info-container .primary').text()).toBe('frodo');
expect(view.$el.find('#last-active abbr').attr('title')).toEqual("2015-08-21T18:53:01.145Z");
expect(view.$el.find('#date-joined abbr').attr('title')).toEqual("2014-01-01T18:53:01.145Z");
expect(view.$el.find('#last-active abbr').attr('title')).toEqual('2015-08-21T18:53:01.145Z');
expect(view.$el.find('#date-joined abbr').attr('title')).toEqual('2014-01-01T18:53:01.145Z');
},
verifyNoMembersView = function (view){
verifyNoMembersView = function(view) {
expect(view.$el.text().trim()).toBe('This team does not have any members.');
},
createTeamModelData = function (membership) {
createTeamModelData = function(membership) {
return {
id: editTeamID,
name: 'Avengers',
......@@ -57,10 +57,10 @@ define([
url: '/api/team/v0/teams/' + editTeamID
};
},
createEditTeamMembersView = function (membership) {
createEditTeamMembersView = function(membership) {
var teamModel = new TeamModel(
createTeamModelData(membership),
{ parse: true }
{parse: true}
);
return new TeamEditMembershipView({
......@@ -71,18 +71,18 @@ define([
}).render();
};
beforeEach(function () {
beforeEach(function() {
setFixtures('<div id="page-prompt"></div><div class="teams-content"></div>');
spyOn(Backbone.history, 'navigate');
spyOn(TeamUtils, 'showMessage');
});
it('can render a message when there are no members', function () {
it('can render a message when there are no members', function() {
var view = createEditTeamMembersView([]);
verifyNoMembersView(view);
});
it('can delete a team member and update the view', function () {
it('can delete a team member and update the view', function() {
var requests = AjaxHelpers.requests(this),
view = createEditTeamMembersView(DEFAULT_MEMBERSHIP);
......@@ -91,8 +91,8 @@ define([
deleteTeamMemember(view, true);
AjaxHelpers.expectJsonRequest(
requests,
'DELETE',
requests,
'DELETE',
'/api/team/v0/team_membership/av,frodo?admin=true'
);
AjaxHelpers.respondWithNoContent(requests);
......@@ -108,7 +108,7 @@ define([
verifyNoMembersView(view);
});
it('can show an error message if removing the user fails', function () {
it('can show an error message if removing the user fails', function() {
var requests = AjaxHelpers.requests(this),
view = createEditTeamMembersView(DEFAULT_MEMBERSHIP);
......@@ -117,9 +117,9 @@ define([
deleteTeamMemember(view, true);
AjaxHelpers.expectJsonRequest(
requests,
'DELETE',
'/api/team/v0/team_membership/av,frodo?admin=true'
requests,
'DELETE',
'/api/team/v0/team_membership/av,frodo?admin=true'
);
AjaxHelpers.respondWithError(requests);
expect(TeamUtils.showMessage).toHaveBeenCalledWith(
......@@ -130,7 +130,7 @@ define([
verifyTeamMembersView(view);
});
it('can cancel team membership deletion', function () {
it('can cancel team membership deletion', function() {
var requests = AjaxHelpers.requests(this);
var view = createEditTeamMembersView(DEFAULT_MEMBERSHIP);
......
......@@ -7,7 +7,7 @@ define([
'teams/js/views/edit_team',
'teams/js/models/team',
'teams/js/spec_helpers/team_spec_helpers'
], function ($, _, Backbone, AjaxHelpers, PageHelpers, TeamEditView, TeamModel, TeamSpecHelpers) {
], function($, _, Backbone, AjaxHelpers, PageHelpers, TeamEditView, TeamModel, TeamSpecHelpers) {
'use strict';
describe('CreateEditTeam', function() {
......@@ -30,8 +30,8 @@ define([
country: 'US',
language: 'en'
},
verifyValidation = function (requests, teamEditView, fieldsData) {
_.each(fieldsData, function (fieldData) {
verifyValidation = function(requests, teamEditView, fieldsData) {
_.each(fieldsData, function(fieldData) {
teamEditView.$(fieldData[0]).val(fieldData[1]);
});
......@@ -47,7 +47,7 @@ define([
'Check the highlighted fields below and try again.'
);
_.each(fieldsData, function (fieldData) {
_.each(fieldsData, function(fieldData) {
if (fieldData[2] === 'error') {
expect(teamEditView.$(fieldData[0].split(' ')[0] + '.error').length).toBe(1);
} else if (fieldData[2] === 'success') {
......@@ -56,12 +56,11 @@ define([
});
AjaxHelpers.expectNoRequests(requests);
},
editTeamID = 'av',
teamAction;
var createEditTeamView = function () {
var createEditTeamView = function() {
var testTeam = {};
if (teamAction === 'edit') {
testTeam = new TeamModel(
......@@ -90,7 +89,7 @@ define([
}).render();
};
beforeEach(function () {
beforeEach(function() {
setFixtures('<div class="teams-content"></div>');
PageHelpers.preventBackboneChangingUrl();
spyOn(Backbone.history, 'navigate');
......@@ -106,7 +105,7 @@ define([
],
teamEditView = createEditTeamView();
_.each(fieldClasses, function (fieldClass) {
_.each(fieldClasses, function(fieldClass) {
expect(teamEditView.$el.find(fieldClass).length).toBe(1);
});
......@@ -122,7 +121,7 @@ define([
};
var requestMethod = function() {
return teamAction === 'create' ? 'POST' : 'PATCH';
return teamAction === 'create' ? 'POST' : 'PATCH';
};
var assertTeamCreateUpdateInfo = function(that, teamsData, teamsUrl, expectedUrl) {
......@@ -220,54 +219,52 @@ define([
expect(Backbone.history.navigate.calls.mostRecent().args[0]).toBe(expectedUrl);
};
describe('NewTeam', function () {
describe('NewTeam', function() {
beforeEach(function() {
teamAction = 'create';
});
it('can render itself correctly', function () {
it('can render itself correctly', function() {
assertFormRendersCorrectly();
});
it('can create a team', function () {
it('can create a team', function() {
assertTeamCreateUpdateInfo(
this, createTeamData, teamsUrl, 'teams/' + TeamSpecHelpers.testTopicID + '/123'
);
});
it('shows validation error message when field is empty', function () {
it('shows validation error message when field is empty', function() {
assertValidationMessagesWhenFieldsEmpty(this);
});
it('shows validation error message when field value length exceeded the limit', function () {
it('shows validation error message when field value length exceeded the limit', function() {
assertValidationMessagesWhenInvalidData(this);
});
it('shows an error message for HTTP 500', function () {
it('shows an error message for HTTP 500', function() {
assertShowMessageOnError(this, createTeamData, teamsUrl, 500);
});
it('shows correct error message when server returns an error', function () {
it('shows correct error message when server returns an error', function() {
assertShowMessageOnError(this, createTeamData, teamsUrl, 400);
});
it('changes route on cancel click', function () {
it('changes route on cancel click', function() {
assertRedirectsToCorrectUrlOnCancel('topics/' + TeamSpecHelpers.testTopicID);
});
});
describe('EditTeam', function () {
describe('EditTeam', function() {
beforeEach(function() {
teamAction = 'edit';
});
it('can render itself correctly', function () {
it('can render itself correctly', function() {
assertFormRendersCorrectly();
});
it('can edit a team', function () {
it('can edit a team', function() {
var copyTeamsData = _.clone(editTeamData);
copyTeamsData.country = 'CA';
copyTeamsData.language = 'fr';
......@@ -278,23 +275,23 @@ define([
);
});
it('shows validation error message when field is empty', function () {
it('shows validation error message when field is empty', function() {
assertValidationMessagesWhenFieldsEmpty(this);
});
it('shows validation error message when field value length exceeded the limit', function () {
it('shows validation error message when field value length exceeded the limit', function() {
assertValidationMessagesWhenInvalidData(this);
});
it('shows an error message for HTTP 500', function () {
it('shows an error message for HTTP 500', function() {
assertShowMessageOnError(this, editTeamData, teamsUrl + editTeamID + '?expand=user', 500);
});
it('shows correct error message when server returns an error', function () {
it('shows correct error message when server returns an error', function() {
assertShowMessageOnError(this, editTeamData, teamsUrl + editTeamID + '?expand=user', 400);
});
it('changes route on cancel click', function () {
it('changes route on cancel click', function() {
assertRedirectsToCorrectUrlOnCancel('teams/' + TeamSpecHelpers.testTopicID + '/' + editTeamID);
});
});
......
......@@ -8,18 +8,18 @@ define([
'teams/js/spec_helpers/team_spec_helpers',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers',
'common/js/spec_helpers/page_helpers'
], function ($, Backbone, _, Team, InstructorToolsView, TeamUtils, TeamSpecHelpers, AjaxHelpers, PageHelpers) {
], function($, Backbone, _, Team, InstructorToolsView, TeamUtils, TeamSpecHelpers, AjaxHelpers, PageHelpers) {
'use strict';
describe('Instructor Tools', function () {
describe('Instructor Tools', function() {
var view,
createInstructorTools = function () {
createInstructorTools = function() {
return new InstructorToolsView({
team: new Team(TeamSpecHelpers.createMockTeamData(1, 1)[0]),
teamEvents: TeamSpecHelpers.teamEvents
});
},
deleteTeam = function (view, confirm) {
deleteTeam = function(view, confirm) {
view.$('.action-delete').click();
// Confirm delete dialog
if (confirm) {
......@@ -29,14 +29,14 @@ define([
$('.action-secondary').click();
}
},
expectSuccessMessage = function (team) {
expectSuccessMessage = function(team) {
expect(TeamUtils.showMessage).toHaveBeenCalledWith(
'Team "' + team.get('name') + '" successfully deleted.',
'success'
);
};
beforeEach(function () {
beforeEach(function() {
setFixtures('<div id="page-prompt"></div>');
PageHelpers.preventBackboneChangingUrl();
spyOn(Backbone.history, 'navigate');
......@@ -45,13 +45,13 @@ define([
spyOn(view.teamEvents, 'trigger');
});
it('can render itself', function () {
it('can render itself', function() {
expect(_.strip(view.$('.action-delete').text())).toEqual('Delete Team');
expect(_.strip(view.$('.action-edit-members').text())).toEqual('Edit Membership');
expect(view.$el.text()).toContain('Instructor tools');
});
it('can delete a team and shows a success message', function () {
it('can delete a team and shows a success message', function() {
var requests = AjaxHelpers.requests(this);
deleteTeam(view, true);
AjaxHelpers.expectJsonRequest(requests, 'DELETE', view.team.url, null);
......@@ -69,24 +69,24 @@ define([
expectSuccessMessage(view.team);
});
it('can cancel team deletion', function () {
it('can cancel team deletion', function() {
var requests = AjaxHelpers.requests(this);
deleteTeam(view, false);
AjaxHelpers.expectNoRequests(requests);
expect(Backbone.history.navigate).not.toHaveBeenCalled();
});
it('shows a success message after receiving a 404', function () {
it('shows a success message after receiving a 404', function() {
var requests = AjaxHelpers.requests(this);
deleteTeam(view, true);
AjaxHelpers.respondWithError(requests, 404);
expectSuccessMessage(view.team);
});
it('can trigger the edit membership view', function () {
});
it('can trigger the edit membership view', function() {
view.$('.action-edit-members').click();
expect(Backbone.history.navigate).toHaveBeenCalledWith(
'teams/' + view.team.get('topic_id') + "/" + view.team.id + "/edit-team/manage-members",
'teams/' + view.team.get('topic_id') + '/' + view.team.id + '/edit-team/manage-members',
{trigger: true}
);
});
......
......@@ -4,10 +4,10 @@ define([
'teams/js/views/my_teams',
'teams/js/spec_helpers/team_spec_helpers',
'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
], function (Backbone, MyTeamsCollection, MyTeamsView, TeamSpecHelpers, AjaxHelpers) {
], function(Backbone, MyTeamsCollection, MyTeamsView, TeamSpecHelpers, AjaxHelpers) {
'use strict';
describe('My Teams View', function () {
beforeEach(function () {
describe('My Teams View', function() {
beforeEach(function() {
setFixtures('<div class="teams-container"></div>');
});
......@@ -20,7 +20,7 @@ define([
}).render();
};
it('can render itself', function () {
it('can render itself', function() {
var teamsData = TeamSpecHelpers.createMockTeamData(1, 5),
teams = TeamSpecHelpers.createMockTeams({results: teamsData}),
myTeamsView = createMyTeamsView(teams);
......@@ -31,7 +31,7 @@ define([
expect(myTeamsView.$('.teams-paging-footer').text().trim()).toBe('');
});
it('shows a message when the user is not a member of any teams', function () {
it('shows a message when the user is not a member of any teams', function() {
var teams = TeamSpecHelpers.createMockTeams({results: []}),
myTeamsView = createMyTeamsView(teams);
TeamSpecHelpers.verifyCards(myTeamsView, []);
......@@ -49,17 +49,17 @@ define([
myTeamsView = createMyTeamsView(teams);
TeamSpecHelpers.verifyCards(myTeamsView, []);
expect(myTeamsView.$el.text().trim()).toBe('You are not currently a member of any team.');
TeamSpecHelpers.teamEvents.trigger('teams:update', { action: 'create' });
TeamSpecHelpers.teamEvents.trigger('teams:update', {action: 'create'});
myTeamsView.render();
AjaxHelpers.expectRequestURL(
requests,
TeamSpecHelpers.testContext.myTeamsUrl,
{
expand : 'user',
username : TeamSpecHelpers.testContext.userInfo.username,
course_id : TeamSpecHelpers.testContext.courseID,
page : '1',
page_size : '5',
expand: 'user',
username: TeamSpecHelpers.testContext.userInfo.username,
course_id: TeamSpecHelpers.testContext.courseID,
page: '1',
page_size: '5',
text_search: '',
order_by: 'last_activity_at'
}
......
......@@ -3,12 +3,12 @@ define(['jquery',
'moment-with-locales',
'teams/js/views/team_card',
'teams/js/models/team'],
function ($, _, moment, TeamCardView, Team) {
function($, _, moment, TeamCardView, Team) {
'use strict';
describe('TeamCardView', function () {
describe('TeamCardView', function() {
var createTeamCardView, view;
createTeamCardView = function () {
createTeamCardView = function() {
var model = new Team({
id: 'test-team',
name: 'Test Team',
......@@ -16,7 +16,7 @@ define(['jquery',
course_id: 'test/course/id',
topic_id: 'test-topic',
description: 'A team for testing',
last_activity_at: "2015-08-21T18:53:01.145Z",
last_activity_at: '2015-08-21T18:53:01.145Z',
country: 'us',
language: 'en',
membership: []
......@@ -35,13 +35,13 @@ define(['jquery',
});
};
beforeEach(function () {
beforeEach(function() {
moment.locale('en');
view = createTeamCardView();
view.render();
});
it('can render itself', function () {
it('can render itself', function() {
expect(view.$el).toHaveClass('list-card');
expect(view.$el.find('.card-title').text()).toContain('Test Team');
expect(view.$el.find('.card-description').text()).toContain('A team for testing');
......@@ -52,11 +52,11 @@ define(['jquery',
expect(view.$el.find('.team-language').text()).toContain('English');
});
it('navigates to the associated team page when its action button is clicked', function () {
it('navigates to the associated team page when its action button is clicked', function() {
expect(view.$('.action').attr('href')).toEqual('#teams/test-topic/test-team');
});
describe('Profile Image Thumbnails', function () {
describe('Profile Image Thumbnails', function() {
/**
* Takes an array of objects representing team
* members, each having the keys 'username',
......@@ -66,9 +66,9 @@ define(['jquery',
*/
var setMemberships, expectThumbnailsOrder;
setMemberships = function (memberships) {
setMemberships = function(memberships) {
view.model.set({
membership: _.map(memberships, function (m) {
membership: _.map(memberships, function(m) {
return {
user: {username: m.username, profile_image: {image_url_small: m.image_url}},
last_activity_at: m.last_activity
......@@ -85,58 +85,58 @@ define(['jquery',
* rendered on the team card match, in order, the
* members of the provided list.
*/
expectThumbnailsOrder = function (members) {
expectThumbnailsOrder = function(members) {
var thumbnails = view.$('.item-member-thumb img');
expect(thumbnails.length).toBe(members.length);
thumbnails.each(function (index, imgEl) {
thumbnails.each(function(index, imgEl) {
expect(thumbnails.eq(index).attr('alt')).toBe(members[index].username);
expect(thumbnails.eq(index).attr('src')).toBe(members[index].image_url);
});
};
it('displays no thumbnails for an empty team', function () {
it('displays no thumbnails for an empty team', function() {
view.model.set({membership: []});
view.render();
expect(view.$('.item-member-thumb').length).toBe(0);
});
it('displays thumbnails for a nonempty team', function () {
it('displays thumbnails for a nonempty team', function() {
var users = [
{
username: 'user_1', image_url: 'user_1_image',
last_activity: new Date("2010/1/1").toString()
last_activity: new Date('2010/1/1').toString()
}, {
username: 'user_2', image_url: 'user_2_image',
last_activity: new Date("2011/1/1").toString()
last_activity: new Date('2011/1/1').toString()
}
];
setMemberships(users);
expectThumbnailsOrder([
{username: 'user_2', image_url: 'user_2_image'},
{username: 'user_1', image_url: 'user_1_image'},
{username: 'user_1', image_url: 'user_1_image'}
]);
});
it('displays thumbnails and an ellipsis for a team with greater than 5 members', function () {
it('displays thumbnails and an ellipsis for a team with greater than 5 members', function() {
var users = [
{
username: 'user_1', image_url: 'user_1_image',
last_activity: new Date("2001/1/1").toString()
last_activity: new Date('2001/1/1').toString()
}, {
username: 'user_2', image_url: 'user_2_image',
last_activity: new Date("2006/1/1").toString()
last_activity: new Date('2006/1/1').toString()
}, {
username: 'user_3', image_url: 'user_3_image',
last_activity: new Date("2003/1/1").toString()
last_activity: new Date('2003/1/1').toString()
}, {
username: 'user_4', image_url: 'user_4_image',
last_activity: new Date("2002/1/1").toString()
last_activity: new Date('2002/1/1').toString()
}, {
username: 'user_5', image_url: 'user_5_image',
last_activity: new Date("2005/1/1").toString()
last_activity: new Date('2005/1/1').toString()
}, {
username: 'user_6', image_url: 'user_6_image',
last_activity: new Date("2004/1/1").toString()
last_activity: new Date('2004/1/1').toString()
}
];
setMemberships(users);
......
......@@ -2,7 +2,7 @@ define([
'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'teams/js/views/team_discussion',
'teams/js/spec_helpers/team_spec_helpers',
'xmodule_js/common_static/common/js/spec_helpers/discussion_spec_helper'
], function (_, AjaxHelpers, TeamDiscussionView, TeamSpecHelpers, DiscussionSpecHelper) {
], function(_, AjaxHelpers, TeamDiscussionView, TeamSpecHelpers, DiscussionSpecHelper) {
'use strict';
xdescribe('TeamDiscussionView', function() {
var discussionView, createDiscussionView, createPost, expandReplies, postReply;
......@@ -38,9 +38,9 @@ define([
};
createPost = function(requests, view, title, body, threadID) {
title = title || "Test title";
body = body || "Test body";
threadID = threadID || "999";
title = title || 'Test title';
body = body || 'Test body';
threadID = threadID || '999';
view.$('.new-post-button').click();
view.$('.js-post-title').val(title);
view.$('.js-post-body textarea').val(body);
......@@ -83,7 +83,7 @@ define([
{
courseID: TeamSpecHelpers.testCourseID,
discussionID: TeamSpecHelpers.testTeamDiscussionID,
threadID: threadID || "999"
threadID: threadID || '999'
},
true
)
......@@ -104,7 +104,7 @@ define([
'/courses/%(courseID)s/discussion/threads/%(threadID)s/reply?ajax=1',
{
courseID: TeamSpecHelpers.testCourseID,
threadID: threadID || "999"
threadID: threadID || '999'
},
true
),
......@@ -115,7 +115,7 @@ define([
body: reply,
comments_count: 1
}),
"annotated_content_info": TeamSpecHelpers.createAnnotatedContentInfo()
'annotated_content_info': TeamSpecHelpers.createAnnotatedContentInfo()
});
};
......@@ -143,8 +143,8 @@ define([
it('can post a reply', function() {
var requests = AjaxHelpers.requests(this),
view = createDiscussionView(requests),
testReply = "Test reply",
testThreadID = "1";
testReply = 'Test reply',
testThreadID = '1';
expandReplies(requests, view, testThreadID);
postReply(requests, view, testReply, testThreadID);
expect(view.$('.discussion-response .response-body').text().trim()).toBe(testReply);
......@@ -153,7 +153,7 @@ define([
it('can post a reply to a new post', function() {
var requests = AjaxHelpers.requests(this),
view = createDiscussionView(requests, []),
testReply = "Test reply";
testReply = 'Test reply';
createPost(requests, view);
expandReplies(requests, view);
postReply(requests, view, testReply);
......@@ -166,7 +166,7 @@ define([
postTopicButton, updatedThreadElement,
updatedTitle = 'Updated title',
updatedBody = 'Updated body',
testThreadID = "1";
testThreadID = '1';
expandReplies(requests, view, testThreadID);
view.$('.action-more .icon').first().click();
view.$('.action-edit').first().click();
......@@ -189,7 +189,7 @@ define([
);
AjaxHelpers.respondWithJson(requests, {
content: TeamSpecHelpers.createMockPostResponse({
id: "999", title: updatedTitle, body: updatedBody
id: '999', title: updatedTitle, body: updatedBody
}),
annotated_content_info: TeamSpecHelpers.createAnnotatedContentInfo()
});
......
define([
'backbone', 'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'teams/js/models/team',
'teams/js/views/team_profile_header_actions', 'teams/js/spec_helpers/team_spec_helpers'
], function (Backbone, _, AjaxHelpers, TeamModel, TeamProfileHeaderActionsView, TeamSpecHelpers) {
], function(Backbone, _, AjaxHelpers, TeamModel, TeamProfileHeaderActionsView, TeamSpecHelpers) {
'use strict';
describe('TeamProfileHeaderActionsView', function () {
describe('TeamProfileHeaderActionsView', function() {
var createTeamsUrl,
createTeamModelData,
createMembershipData,
......@@ -12,12 +12,12 @@ define([
verifyErrorMessage,
ACCOUNTS_API_URL = '/api/user/v1/accounts/';
createTeamsUrl = function (teamId) {
createTeamsUrl = function(teamId) {
return TeamSpecHelpers.testContext.teamsUrl + teamId + '?expand=user';
};
createTeamModelData = function (teamId, teamName, membership) {
return {
createTeamModelData = function(teamId, teamName, membership) {
return {
id: teamId,
name: teamName,
membership: membership,
......@@ -26,7 +26,7 @@ define([
};
createHeaderActionsView = function(requests, maxTeamSize, currentUsername, teamModelData, showEditButton) {
var model = new TeamModel(teamModelData, { parse: true }),
var model = new TeamModel(teamModelData, {parse: true}),
context = TeamSpecHelpers.createMockContext({
maxTeamSize: maxTeamSize,
userInfo: TeamSpecHelpers.createMockUserInfo({
......@@ -46,37 +46,36 @@ define([
).render();
};
createMembershipData = function (username) {
createMembershipData = function(username) {
return [
{
"user": {
"username": username,
"url": ACCOUNTS_API_URL + username
'user': {
'username': username,
'url': ACCOUNTS_API_URL + username
}
}
];
};
describe('JoinButton', function () {
beforeEach(function () {
describe('JoinButton', function() {
beforeEach(function() {
setFixtures(
'<div class="teams-content"><div class="msg-content"><div class="copy"></div></div><div class="header-action-view"></div></div>'
);
});
verifyErrorMessage = function (requests, errorMessage, expectedMessage, joinTeam) {
verifyErrorMessage = function(requests, errorMessage, expectedMessage, joinTeam) {
var view = createHeaderActionsView(requests, 1, 'ma', createTeamModelData('teamA', 'teamAlpha', []));
if (joinTeam) {
// if we want the error to return when user try to join team, respond with no membership
AjaxHelpers.respondWithJson(requests, {"count": 0});
AjaxHelpers.respondWithJson(requests, {'count': 0});
view.$('.action.action-primary').click();
}
AjaxHelpers.respondWithTextError(requests, 400, errorMessage);
expect($('.msg-content .copy').text().trim()).toBe(expectedMessage);
};
it('can render itself', function () {
it('can render itself', function() {
var requests = AjaxHelpers.requests(this);
var teamModelData = createTeamModelData('teamA', 'teamAlpha', createMembershipData('ma'));
var view = createHeaderActionsView(requests, 1, 'ma', teamModelData);
......@@ -84,7 +83,7 @@ define([
expect(view.$('.join-team').length).toEqual(1);
});
it('can join team successfully', function () {
it('can join team successfully', function() {
var requests = AjaxHelpers.requests(this);
var currentUsername = 'ma1';
var teamId = 'teamA';
......@@ -103,7 +102,7 @@ define([
);
// current user is not a member of any team so we should see the Join Team button
AjaxHelpers.respondWithJson(requests, {"count": 0});
AjaxHelpers.respondWithJson(requests, {'count': 0});
expect(view.$('.action.action-primary').length).toEqual(1);
// a post request will be sent to add current user to current team
......@@ -132,7 +131,7 @@ define([
expect(view.$('.join-team-message').length).toEqual(0);
});
it('shows already member message', function () {
it('shows already member message', function() {
var requests = AjaxHelpers.requests(this);
var currentUsername = 'ma1';
var view = createHeaderActionsView(requests, 1, currentUsername, createTeamModelData('teamA', 'teamAlpha', []));
......@@ -148,12 +147,12 @@ define([
);
// current user is a member of another team so we should see the correct message
AjaxHelpers.respondWithJson(requests, {"count": 1});
AjaxHelpers.respondWithJson(requests, {'count': 1});
expect(view.$('.action.action-primary').length).toEqual(0);
expect(view.$('.join-team-message').text().trim()).toBe(view.alreadyMemberMessage);
});
it('shows team full message', function () {
it('shows team full message', function() {
var requests = AjaxHelpers.requests(this);
var view = createHeaderActionsView(
requests,
......@@ -171,7 +170,7 @@ define([
AjaxHelpers.expectNoRequests(requests);
});
it('shows correct error message if user fails to join team', function () {
it('shows correct error message if user fails to join team', function() {
var requests = AjaxHelpers.requests(this);
// verify user_message
......@@ -199,7 +198,7 @@ define([
);
});
it('shows correct error message if initializing the view fails', function () {
it('shows correct error message if initializing the view fails', function() {
var requests = AjaxHelpers.requests(this);
// verify user_message
......@@ -231,17 +230,17 @@ define([
expect(view.$('.action-edit-team').length).toEqual(showEditButton ? 1 : 0);
};
it('renders when option showEditButton is true', function () {
it('renders when option showEditButton is true', function() {
var requests = AjaxHelpers.requests(this);
createAndAssertView(requests, true);
});
it('does not render when option showEditButton is false', function () {
it('does not render when option showEditButton is false', function() {
var requests = AjaxHelpers.requests(this);
createAndAssertView(requests, false);
});
it("can navigate to correct url", function () {
it('can navigate to correct url', function() {
var requests = AjaxHelpers.requests(this);
spyOn(Backbone.history, 'navigate');
createAndAssertView(requests, true);
......
......@@ -2,9 +2,9 @@ define([
'underscore', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'teams/js/models/team',
'teams/js/views/team_profile', 'teams/js/spec_helpers/team_spec_helpers',
'xmodule_js/common_static/common/js/spec_helpers/discussion_spec_helper'
], function (_, AjaxHelpers, TeamModel, TeamProfileView, TeamSpecHelpers, DiscussionSpecHelper) {
], function(_, AjaxHelpers, TeamModel, TeamProfileView, TeamSpecHelpers, DiscussionSpecHelper) {
'use strict';
describe('TeamProfileView', function () {
describe('TeamProfileView', function() {
var profileView, createTeamProfileView, createTeamModelData, clickLeaveTeam,
teamModel,
leaveTeamLinkSelector = '.leave-team-link',
......@@ -20,17 +20,17 @@ define([
}
];
beforeEach(function () {
beforeEach(function() {
setFixtures('<div id="page-prompt"></div>' +
'<div class="teams-content"><div class="msg-content"><div class="copy"></div></div></div>' +
'<div class="profile-view"></div>');
DiscussionSpecHelper.setUnderscoreFixtures();
});
createTeamModelData = function (options) {
createTeamModelData = function(options) {
return {
id: "test-team",
name: "Test Team",
id: 'test-team',
name: 'Test Team',
discussion_topic_id: TeamSpecHelpers.testTeamDiscussionID,
country: options.country || '',
language: options.language || '',
......@@ -40,7 +40,7 @@ define([
};
createTeamProfileView = function(requests, options) {
teamModel = new TeamModel(createTeamModelData(options), { parse: true });
teamModel = new TeamModel(createTeamModelData(options), {parse: true});
profileView = new TeamProfileView({
el: $('.profile-view'),
teamEvents: TeamSpecHelpers.teamEvents,
......@@ -95,13 +95,13 @@ define([
};
describe('DiscussionsView', function() {
it('can render itself', function () {
it('can render itself', function() {
var requests = AjaxHelpers.requests(this),
view = createTeamProfileView(requests, {});
expect(view.$('.discussion-thread').length).toEqual(3);
});
it('shows New Post button when user joins a team', function () {
it('shows New Post button when user joins a team', function() {
var requests = AjaxHelpers.requests(this),
view = createTeamProfileView(requests, {});
......@@ -111,7 +111,7 @@ define([
expect(view.$('.new-post-btn').length).toEqual(1);
});
it('hides New Post button when user left a team', function () {
it('hides New Post button when user left a team', function() {
var requests = AjaxHelpers.requests(this),
view = createTeamProfileView(requests, {membership: DEFAULT_MEMBERSHIP});
......@@ -122,7 +122,6 @@ define([
});
describe('TeamDetailsView', function() {
var assertTeamDetails = function(view, members, memberOfTeam) {
expect(view.$('.team-detail-header').text()).toBe('Team Details');
expect(view.$('.team-country').text()).toContain('United States');
......@@ -133,7 +132,6 @@ define([
};
describe('Non-Member', function() {
it('can render itself', function() {
var requests = AjaxHelpers.requests(this);
var view = createTeamProfileView(requests, {
......@@ -156,7 +154,6 @@ define([
});
describe('Member', function() {
it('can render itself', function() {
var requests = AjaxHelpers.requests(this);
var view = createTeamProfileView(requests, {
......@@ -172,7 +169,7 @@ define([
// assert user profile page url.
expect(view.$('.member-profile').attr('href')).toBe('/u/' + TeamSpecHelpers.testUser);
//Verify that the leave team link is present
// Verify that the leave team link is present
expect(view.$(leaveTeamLinkSelector).text()).toContain('Leave Team');
});
......@@ -198,10 +195,10 @@ define([
assertTeamDetails(view, 1, true);
});
it('shows correct error messages', function () {
it('shows correct error messages', function() {
var requests = AjaxHelpers.requests(this);
var verifyErrorMessage = function (requests, errorMessage, expectedMessage) {
var verifyErrorMessage = function(requests, errorMessage, expectedMessage) {
var view = createTeamProfileView(
requests, {country: 'US', language: 'en', membership: DEFAULT_MEMBERSHIP}
);
......
......@@ -3,10 +3,10 @@ define([
'teams/js/collections/team',
'teams/js/views/teams',
'teams/js/spec_helpers/team_spec_helpers'
], function (Backbone, TeamCollection, TeamsView, TeamSpecHelpers) {
], function(Backbone, TeamCollection, TeamsView, TeamSpecHelpers) {
'use strict';
describe('Teams View', function () {
beforeEach(function () {
describe('Teams View', function() {
beforeEach(function() {
setFixtures('<div class="teams-container"></div>');
});
......@@ -19,7 +19,7 @@ define([
}).render();
};
it('can render itself', function () {
it('can render itself', function() {
var testTeamData = TeamSpecHelpers.createMockTeamData(1, 5),
teamsView = createTeamsView({
teams: TeamSpecHelpers.createMockTeams({
......
......@@ -57,9 +57,9 @@ define([
});
afterEach(function() {
Backbone.history.stop();
$(document).off('ajaxError', TeamsTabView.prototype.errorHandler);
}
Backbone.history.stop();
$(document).off('ajaxError', TeamsTabView.prototype.errorHandler);
}
);
describe('Navigation', function() {
......@@ -71,7 +71,7 @@ define([
expect(teamsTabView.$('.breadcrumbs').length).toBe(0);
});
it('does not interfere with anchor links to #main', function () {
it('does not interfere with anchor links to #main', function() {
var teamsTabView = createTeamsTabView(this);
teamsTabView.router.navigate('#main', {trigger: true});
expect(teamsTabView.$('.wrapper-msg')).toHaveClass('is-hidden');
......@@ -193,8 +193,8 @@ define([
describe('Discussion privileges', function() {
it('allows privileged access to any team', function() {
var teamsTabView = createTeamsTabView(this, {
userInfo: TeamSpecHelpers.createMockUserInfo({privileged: true})
});
userInfo: TeamSpecHelpers.createMockUserInfo({privileged: true})
});
// Note: using `undefined` here to ensure that we
// don't even look at the team when the user is
// privileged
......@@ -203,11 +203,11 @@ define([
it('allows access to a team which an unprivileged user is a member of', function() {
var teamsTabView = createTeamsTabView(this, {
userInfo: TeamSpecHelpers.createMockUserInfo({
username: TeamSpecHelpers.testUser,
privileged: false
})
});
userInfo: TeamSpecHelpers.createMockUserInfo({
username: TeamSpecHelpers.testUser,
privileged: false
})
});
expect(teamsTabView.readOnlyDiscussion({
attributes: {
membership: [{
......@@ -221,8 +221,8 @@ define([
it('does not allow access if the user is neither privileged nor a team member', function() {
var teamsTabView = createTeamsTabView(this, {
userInfo: TeamSpecHelpers.createMockUserInfo({privileged: false, staff: true})
});
userInfo: TeamSpecHelpers.createMockUserInfo({privileged: false, staff: true})
});
expect(teamsTabView.readOnlyDiscussion({
attributes: {membership: []}
})).toBe(true);
......@@ -267,7 +267,7 @@ define([
// Clear the search and submit it again
teamsTabView.$('.search-field').val('');
teamsTabView.$('.action-search').click();
verifyTeamsRequest({
order_by: 'last_activity_at'
});
......
......@@ -2,9 +2,8 @@ define(['jquery',
'underscore',
'teams/js/views/topic_card',
'teams/js/models/topic'],
function ($, _, TopicCardView, Topic) {
describe('Topic card view', function () {
function($, _, TopicCardView, Topic) {
describe('Topic card view', function() {
var createTopicCardView = function() {
return new TopicCardView({
model: new Topic({
......@@ -16,11 +15,11 @@ define(['jquery',
});
};
beforeEach(function () {
beforeEach(function() {
spyOn(TopicCardView.prototype, 'action');
});
it('can render itself', function () {
it('can render itself', function() {
var view = createTopicCardView();
expect(view.$el).toHaveClass('square-card');
expect(view.$el.find('.card-title').text()).toContain('Renewable Energy');
......@@ -29,7 +28,7 @@ define(['jquery',
expect(view.$el.find('.action .sr').text()).toContain('View Teams in the Renewable Energy Topic');
});
it('navigates when action button is clicked', function () {
it('navigates when action button is clicked', function() {
var view = createTopicCardView();
view.$el.find('.action').trigger('click');
// TODO test actual navigation once implemented
......
......@@ -4,9 +4,9 @@ define([
'teams/js/views/topic_teams',
'teams/js/spec_helpers/team_spec_helpers',
'common/js/spec_helpers/page_helpers'
], function (Backbone, _, TopicTeamsView, TeamSpecHelpers, PageHelpers) {
], function(Backbone, _, TopicTeamsView, TeamSpecHelpers, PageHelpers) {
'use strict';
describe('Topic Teams View', function () {
describe('Topic Teams View', function() {
var createTopicTeamsView = function(options) {
options = options || {};
var myTeamsCollection = options.myTeamsCollection || TeamSpecHelpers.createMockTeams({results: []});
......@@ -38,12 +38,12 @@ define([
}
};
beforeEach(function () {
beforeEach(function() {
setFixtures('<div class="teams-container"></div>');
PageHelpers.preventBackboneChangingUrl();
});
it('can render itself', function () {
it('can render itself', function() {
var testTeamData = TeamSpecHelpers.createMockTeamData(1, 5),
teamsView = createTopicTeamsView({
teams: TeamSpecHelpers.createMockTeams({
......@@ -61,21 +61,21 @@ define([
verifyActions(teamsView);
});
it('can browse all teams', function () {
it('can browse all teams', function() {
var teamsView = createTopicTeamsView();
spyOn(Backbone.history, 'navigate');
teamsView.$('.browse-teams').click();
expect(Backbone.history.navigate.calls.mostRecent().args[0]).toBe('browse');
});
it('gives the search field focus when clicking on the search teams link', function () {
it('gives the search field focus when clicking on the search teams link', function() {
var teamsView = createTopicTeamsView();
spyOn($.fn, 'focus').and.callThrough();
teamsView.$('.search-teams').click();
expect(teamsView.$('.search-field').first().focus).toHaveBeenCalled();
});
it('can show the create team modal', function () {
it('can show the create team modal', function() {
var teamsView = createTopicTeamsView();
spyOn(Backbone.history, 'navigate');
teamsView.$('a.create-team').click();
......@@ -84,18 +84,18 @@ define([
);
});
it('does not show actions for a user already in a team', function () {
it('does not show actions for a user already in a team', function() {
var teamsView = createTopicTeamsView({myTeamsCollection: TeamSpecHelpers.createMockTeams()});
verifyActions(teamsView, {showActions: false});
});
it('shows actions for a privileged user already in a team', function () {
var teamsView = createTopicTeamsView({ privileged: true });
it('shows actions for a privileged user already in a team', function() {
var teamsView = createTopicTeamsView({privileged: true});
verifyActions(teamsView);
});
it('shows actions for a staff user already in a team', function () {
var teamsView = createTopicTeamsView({ privileged: false, staff: true });
it('shows actions for a staff user already in a team', function() {
var teamsView = createTopicTeamsView({privileged: false, staff: true});
verifyActions(teamsView);
});
......
define([
'backbone', 'underscore', 'teams/js/collections/topic', 'teams/js/views/topics',
'teams/js/spec_helpers/team_spec_helpers', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'
], function (Backbone, _, TopicCollection, TopicsView, TeamSpecHelpers, AjaxHelpers) {
], function(Backbone, _, TopicCollection, TopicsView, TeamSpecHelpers, AjaxHelpers) {
'use strict';
describe('TopicsView', function () {
describe('TopicsView', function() {
var initialTopics, topicCollection, createTopicsView, triggerUpdateEvent;
createTopicsView = function() {
......@@ -16,25 +16,25 @@ define([
};
triggerUpdateEvent = function(topicsView, sendJoinAfter) {
topicsView.collection.teamEvents.trigger('teams:update', { action: 'create' });
topicsView.collection.teamEvents.trigger('teams:update', {action: 'create'});
if (sendJoinAfter) {
topicsView.collection.teamEvents.trigger('teams:update', { action: 'join' });
topicsView.collection.teamEvents.trigger('teams:update', {action: 'join'});
}
topicsView.render();
};
beforeEach(function () {
beforeEach(function() {
setFixtures('<div class="topics-container"></div>');
initialTopics = TeamSpecHelpers.createMockTopicData(1, 5);
topicCollection = TeamSpecHelpers.createMockTopicCollection(initialTopics);
});
it('can render the first of many pages', function () {
it('can render the first of many pages', function() {
var topicsView = createTopicsView(),
footerEl = topicsView.$('.topics-paging-footer'),
topicCards = topicsView.$('.topic-card');
expect(topicsView.$('.topics-paging-header').text()).toMatch('Showing 1-5 out of 6 total');
_.each(initialTopics, function (topic, index) {
_.each(initialTopics, function(topic, index) {
var currentCard = topicCards.eq(index);
expect(currentCard.text()).toMatch(topic.name);
expect(currentCard.text()).toMatch(topic.description);
......
......@@ -4,14 +4,14 @@ define([
'teams/js/collections/team',
'teams/js/collections/topic',
'teams/js/models/topic'
], function (Backbone, _, TeamCollection, TopicCollection, TopicModel) {
], function(Backbone, _, TeamCollection, TopicCollection, TopicModel) {
'use strict';
var createMockPostResponse, createMockDiscussionResponse, createAnnotatedContentInfo, createMockThreadResponse,
createMockTopicData, createMockTopicCollection, createMockTopic,
testCourseID = 'course/1',
testUser = 'testUser',
testTopicID = 'test-topic-1',
testTeamDiscussionID = "12345",
testTeamDiscussionID = '12345',
teamEvents = _.clone(Backbone.Events),
testCountries = [
['', ''],
......@@ -26,14 +26,14 @@ define([
['fr', 'French']
];
var createMockTeamData = function (startIndex, stopIndex) {
return _.map(_.range(startIndex, stopIndex + 1), function (i) {
var id = "id" + i;
var createMockTeamData = function(startIndex, stopIndex) {
return _.map(_.range(startIndex, stopIndex + 1), function(i) {
var id = 'id' + i;
return {
name: "team " + i,
name: 'team ' + i,
id: id,
language: testLanguages[i%4][0],
country: testCountries[i%4][0],
language: testLanguages[i % 4][0],
country: testCountries[i % 4][0],
membership: [],
last_activity_at: '',
topic_id: 'topic_id' + i,
......@@ -56,7 +56,7 @@ define([
};
var createMockTeams = function(responseOptions, options, collectionType) {
if(_.isUndefined(collectionType)) {
if (_.isUndefined(collectionType)) {
collectionType = TeamCollection;
}
return new collectionType(
......@@ -72,7 +72,7 @@ define([
var createMockTeamMembershipsData = function(startIndex, stopIndex) {
var teams = createMockTeamData(startIndex, stopIndex);
return _.map(_.range(startIndex, stopIndex + 1), function (i) {
return _.map(_.range(startIndex, stopIndex + 1), function(i) {
return {
user: {
username: testUser,
......@@ -81,7 +81,7 @@ define([
image_url_small: 'test_profile_image'
}
},
team: teams[i-1]
team: teams[i - 1]
};
});
};
......@@ -100,7 +100,7 @@ define([
var verifyCards = function(view, teams) {
var teamCards = view.$('.team-card');
_.each(teams, function (team, index) {
_.each(teams, function(team, index) {
var currentCard = teamCards.eq(index);
expect(currentCard.text()).toMatch(team.name);
expect(currentCard.text()).toMatch(_.object(testLanguages)[team.language]);
......@@ -108,7 +108,7 @@ define([
});
};
var triggerTeamEvent = function (action) {
var triggerTeamEvent = function(action) {
teamEvents.trigger('teams:update', {action: action});
};
......@@ -119,20 +119,20 @@ define([
course_id: testCourseID,
commentable_id: testTeamDiscussionID,
type: 'thread',
body: "",
body: '',
anonymous_to_peers: false,
unread_comments_count: 0,
updated_at: '2015-07-29T18:44:56Z',
group_name: 'Default Group',
pinned: false,
votes: {count: 0, down_count: 0, point: 0, up_count: 0},
user_id: "9",
user_id: '9',
abuse_flaggers: [],
closed: false,
at_position_list: [],
read: false,
anonymous: false,
created_at: "2015-07-29T18:44:56Z",
created_at: '2015-07-29T18:44:56Z',
thread_type: 'discussion',
comments_count: 0,
group_id: 1,
......@@ -145,36 +145,36 @@ define([
createMockDiscussionResponse = function(threads) {
if (_.isUndefined(threads)) {
threads = [
createMockPostResponse({ id: "1", title: "First Post"}),
createMockPostResponse({ id: "2", title: "Second Post"}),
createMockPostResponse({ id: "3", title: "Third Post"})
createMockPostResponse({id: '1', title: 'First Post'}),
createMockPostResponse({id: '2', title: 'Second Post'}),
createMockPostResponse({id: '3', title: 'Third Post'})
];
}
return {
"num_pages": 1,
"page": 1,
"discussion_data": threads,
"user_info": {
"username": testUser,
"follower_ids": [],
"default_sort_key": "date",
"downvoted_ids": [],
"subscribed_thread_ids": [],
"upvoted_ids": [],
"external_id": "9",
"id": "9",
"subscribed_user_ids": [],
"subscribed_commentable_ids": []
'num_pages': 1,
'page': 1,
'discussion_data': threads,
'user_info': {
'username': testUser,
'follower_ids': [],
'default_sort_key': 'date',
'downvoted_ids': [],
'subscribed_thread_ids': [],
'upvoted_ids': [],
'external_id': '9',
'id': '9',
'subscribed_user_ids': [],
'subscribed_commentable_ids': []
},
"annotated_content_info": {
'annotated_content_info': {
},
"roles": {"Moderator": [], "Administrator": [], "Community TA": []},
"course_settings": {
"is_cohorted": false,
"allow_anonymous_to_peers": false,
"allow_anonymous": true,
"category_map": {"subcategories": {}, "children": [], "entries": {}},
"cohorts": []
'roles': {'Moderator': [], 'Administrator': [], 'Community TA': []},
'course_settings': {
'is_cohorted': false,
'allow_anonymous_to_peers': false,
'allow_anonymous': true,
'category_map': {'subcategories': {}, 'children': [], 'entries': {}},
'cohorts': []
}
};
};
......@@ -203,36 +203,36 @@ define([
comments_count: 0,
anonymous_to_peers: false,
unread_comments_count: 0,
updated_at: "2015-08-04T21:44:28Z",
updated_at: '2015-08-04T21:44:28Z',
resp_skip: 0,
id: "55c1323c56c02ce921000001",
id: '55c1323c56c02ce921000001',
pinned: false,
votes: {"count": 0, "down_count": 0, "point": 0, "up_count": 0},
votes: {'count': 0, 'down_count': 0, 'point': 0, 'up_count': 0},
resp_limit: 25,
abuse_flaggers: [],
closed: false,
resp_total: 1,
at_position_list: [],
type: "thread",
type: 'thread',
read: true,
anonymous: false,
user_id: "5",
created_at: "2015-08-04T21:44:28Z",
thread_type: "discussion",
context: "standalone",
user_id: '5',
created_at: '2015-08-04T21:44:28Z',
thread_type: 'discussion',
context: 'standalone',
endorsed: false
},
options
);
};
createMockTopicData = function (startIndex, stopIndex) {
return _.map(_.range(startIndex, stopIndex + 1), function (i) {
createMockTopicData = function(startIndex, stopIndex) {
return _.map(_.range(startIndex, stopIndex + 1), function(i) {
return {
"description": "Test description " + i,
"name": "Test Topic " + i,
"id": "test-topic-" + i,
"team_count": 0
'description': 'Test description ' + i,
'name': 'Test Topic ' + i,
'id': 'test-topic-' + i,
'team_count': 0
};
});
};
......@@ -273,7 +273,7 @@ define([
return _.extend({}, testContext, options);
};
createMockTopicCollection = function (topicData) {
createMockTopicCollection = function(topicData) {
topicData = topicData !== undefined ? topicData : createMockTopicData(1, 5);
return new TopicCollection(
......
;(function (define) {
(function(define) {
'use strict';
define(['jquery', 'teams/js/views/teams_tab'],
function ($, TeamsTabView) {
return function (options) {
function($, TeamsTabView) {
return function(options) {
var teamsTab = new TeamsTabView({
el: $('.teams-content'),
context: options,
viewLabel: gettext("Teams")
viewLabel: gettext('Teams')
});
teamsTab.start();
};
......
......@@ -2,14 +2,14 @@
* Utility methods for emitting teams events. See the event spec:
* https://openedx.atlassian.net/wiki/display/AN/Teams+Feature+Event+Design
*/
;(function (define) {
(function(define) {
'use strict';
define([
'logger'
], function (Logger) {
], function(Logger) {
var TeamAnalytics = {
emitPageViewed: function (page_name, topic_id, team_id) {
emitPageViewed: function(page_name, topic_id, team_id) {
Logger.log('edx.team.page_viewed', {
page_name: page_name,
topic_id: topic_id,
......
;(function (define) {
(function(define) {
'use strict';
define(['backbone',
......@@ -8,7 +8,7 @@
'teams/js/models/team',
'common/js/components/utils/view_utils',
'text!teams/templates/edit-team.underscore'],
function (Backbone, _, gettext, FieldViews, TeamModel, ViewUtils, editTeamTemplate) {
function(Backbone, _, gettext, FieldViews, TeamModel, ViewUtils, editTeamTemplate) {
return Backbone.View.extend({
maxTeamNameLength: 255,
......@@ -30,12 +30,12 @@
if (this.action === 'create') {
this.teamModel = new TeamModel({});
this.teamModel.url = this.context.teamsUrl;
this.primaryButtonTitle = gettext("Create");
} else if(this.action === 'edit' ) {
this.primaryButtonTitle = gettext('Create');
} else if (this.action === 'edit') {
this.teamModel = options.model;
this.teamModel.url = this.context.teamsDetailUrl.replace('team_id', options.model.get('id')) +
'?expand=user';
this.primaryButtonTitle = gettext("Update");
this.primaryButtonTitle = gettext('Update');
}
this.teamNameField = new FieldViews.TextFieldView({
......@@ -78,7 +78,7 @@
},
render: function() {
this.$el.html(_.template(editTeamTemplate) ({
this.$el.html(_.template(editTeamTemplate)({
primaryButtonTitle: this.primaryButtonTitle,
action: this.action,
totalMembers: _.isUndefined(this.teamModel) ? 0 : this.teamModel.get('membership').length
......@@ -99,7 +99,7 @@
}
},
createOrUpdateTeam: function (event) {
createOrUpdateTeam: function(event) {
event.preventDefault();
var view = this,
teamLanguage = this.teamLanguageField.fieldValue(),
......@@ -117,7 +117,7 @@
if (this.action === 'create') {
data.course_id = this.context.courseID;
data.topic_id = this.topic.id;
} else if (this.action === 'edit' ) {
} else if (this.action === 'edit') {
saveOptions.patch = true;
saveOptions.contentType = 'application/merge-patch+json';
}
......@@ -140,15 +140,15 @@
})
.fail(function(data) {
var response = JSON.parse(data.responseText);
var message = gettext("An error occurred. Please try again.");
if ('user_message' in response){
var message = gettext('An error occurred. Please try again.');
if ('user_message' in response) {
message = response.user_message;
}
view.showMessage(message, message);
});
},
validateTeamData: function (data) {
validateTeamData: function(data) {
var status = true,
message = gettext('Check the highlighted fields below and try again.');
var srMessages = [];
......@@ -156,7 +156,7 @@
this.teamNameField.unhighlightField();
this.teamDescriptionField.unhighlightField();
if (_.isEmpty(data.name.trim()) ) {
if (_.isEmpty(data.name.trim())) {
status = false;
this.teamNameField.highlightFieldOnError();
srMessages.push(
......@@ -170,7 +170,7 @@
);
}
if (_.isEmpty(data.description.trim()) ) {
if (_.isEmpty(data.description.trim())) {
status = false;
this.teamDescriptionField.highlightFieldOnError();
srMessages.push(
......@@ -191,7 +191,7 @@
};
},
showMessage: function (message, screenReaderMessage) {
showMessage: function(message, screenReaderMessage) {
this.$('.wrapper-msg').removeClass('is-hidden');
this.$('.msg-content .copy p').text(message);
this.$('.wrapper-msg').focus();
......@@ -201,12 +201,12 @@
}
},
cancelAndGoBack: function (event) {
cancelAndGoBack: function(event) {
event.preventDefault();
var url;
if (this.action === 'create') {
url = 'topics/' + this.topic.id;
} else if (this.action === 'edit' ) {
} else if (this.action === 'edit') {
url = 'teams/' + this.topic.id + '/' + this.teamModel.get('id');
}
Backbone.history.navigate(url, {trigger: true});
......
;(function (define) {
(function(define) {
'use strict';
define(['backbone',
......@@ -11,11 +11,11 @@
'text!teams/templates/edit-team-member.underscore',
'text!teams/templates/date.underscore'
],
function (Backbone, $, _, gettext, TeamModel, TeamUtils, ViewUtils, editTeamMemberTemplate, dateTemplate) {
function(Backbone, $, _, gettext, TeamModel, TeamUtils, ViewUtils, editTeamMemberTemplate, dateTemplate) {
return Backbone.View.extend({
dateTemplate: _.template(dateTemplate),
teamMemberTemplate: _.template(editTeamMemberTemplate),
errorMessage: gettext("An error occurred while removing the member from the team. Try again."),
errorMessage: gettext('An error occurred while removing the member from the team. Try again.'),
events: {
'click .action-remove-member': 'removeMember'
......@@ -28,7 +28,7 @@
// as the actual user to be removed from the team will be added on before calling DELETE.
this.teamMembershipDetailUrl = options.context.teamMembershipDetailUrl.substring(
0, this.options.context.teamMembershipDetailUrl.lastIndexOf('team_id')
) + this.model.get('id') + ",";
) + this.model.get('id') + ',';
this.teamEvents = options.teamEvents;
},
......@@ -50,14 +50,14 @@
_.each(this.model.get('membership'), function(membership) {
dateJoined = interpolate(
// Translators: 'date' is a placeholder for a fuzzy, relative timestamp (see: https://github.com/rmm5t/jquery-timeago)
gettext("Joined %(date)s"),
gettext('Joined %(date)s'),
{date: self.dateTemplate({date: membership.date_joined})},
true
);
lastActivity = interpolate(
// Translators: 'date' is a placeholder for a fuzzy, relative timestamp (see: https://github.com/rmm5t/jquery-timeago)
gettext("Last Activity %(date)s"),
gettext('Last Activity %(date)s'),
{date: self.dateTemplate({date: membership.last_activity_at})},
true
);
......@@ -74,7 +74,7 @@
this.$('abbr').timeago();
},
removeMember: function (event) {
removeMember: function(event) {
var self = this, username = $(event.currentTarget).data('username');
event.preventDefault();
......@@ -82,17 +82,17 @@
gettext('Remove this team member?'),
gettext('This learner will be removed from the team, allowing another learner to take the available spot.'),
gettext('Remove'),
function () {
function() {
$.ajax({
type: 'DELETE',
url: self.teamMembershipDetailUrl.concat(username, '?admin=true')
}).done(function () {
}).done(function() {
self.teamEvents.trigger('teams:update', {
action: 'leave',
team: self.model
});
self.model.fetch().done(function() { self.render(); });
}).fail(function (data) {
}).fail(function(data) {
TeamUtils.parseAndShowMessage(data, self.errorMessage);
});
}
......
;(function (define) {
(function(define) {
'use strict';
define(['backbone',
......@@ -8,7 +8,7 @@
'teams/js/views/team_utils',
'common/js/components/utils/view_utils',
'text!teams/templates/instructor-tools.underscore'],
function (Backbone, _, gettext, StringUtils, TeamUtils, ViewUtils, instructorToolbarTemplate) {
function(Backbone, _, gettext, StringUtils, TeamUtils, ViewUtils, instructorToolbarTemplate) {
return Backbone.View.extend({
events: {
......@@ -27,7 +27,7 @@
return this;
},
deleteTeam: function (event) {
deleteTeam: function(event) {
event.preventDefault();
ViewUtils.confirmThenRunOperation(
gettext('Delete this team?'),
......@@ -37,17 +37,17 @@
);
},
editMembership: function (event) {
editMembership: function(event) {
event.preventDefault();
Backbone.history.navigate(
'teams/' + this.team.get('topic_id') + '/' + this.team.id +'/edit-team/manage-members',
'teams/' + this.team.get('topic_id') + '/' + this.team.id + '/edit-team/manage-members',
{trigger: true}
);
},
handleDelete: function () {
handleDelete: function() {
var self = this,
postDelete = function () {
postDelete = function() {
self.teamEvents.trigger('teams:update', {
action: 'delete',
team: self.team
......@@ -62,7 +62,7 @@
'success'
);
};
this.team.destroy().then(postDelete).fail(function (response) {
this.team.destroy().then(postDelete).fail(function(response) {
// In the 404 case, this team has already been
// deleted by someone else. Since the team was
// successfully deleted anyway, just show a
......
;(function (define) {
(function(define) {
'use strict';
define(['backbone', 'gettext', 'teams/js/views/teams'],
function (Backbone, gettext, TeamsView) {
function(Backbone, gettext, TeamsView) {
var MyTeamsView = TeamsView.extend({
render: function() {
var view = this;
......
(function (define) {
(function(define) {
'use strict';
define([
'jquery',
......@@ -11,7 +11,7 @@
'text!teams/templates/team-membership-details.underscore',
'text!teams/templates/team-country-language.underscore',
'text!teams/templates/date.underscore'
], function (
], function(
$,
Backbone,
_,
......@@ -30,15 +30,15 @@
className: 'team-members',
template: _.template(teamMembershipDetailsTemplate),
initialize: function (options) {
initialize: function(options) {
this.maxTeamSize = options.maxTeamSize;
this.memberships = options.memberships;
},
render: function () {
var allMemberships = _(this.memberships).sortBy(function (member) {
return new Date(member.last_activity_at);
}).reverse(),
render: function() {
var allMemberships = _(this.memberships).sortBy(function(member) {
return new Date(member.last_activity_at);
}).reverse(),
displayableMemberships = allMemberships.slice(0, 5),
maxMemberCount = this.maxTeamSize;
this.$el.html(this.template({
......@@ -55,7 +55,7 @@
TeamCountryLanguageView = Backbone.View.extend({
template: _.template(teamCountryLanguageTemplate),
initialize: function (options) {
initialize: function(options) {
this.countries = options.countries;
this.languages = options.languages;
},
......@@ -74,18 +74,18 @@
className: 'team-activity',
template: _.template(dateTemplate),
initialize: function (options) {
initialize: function(options) {
this.date = options.date;
},
render: function () {
render: function() {
var lastActivity = moment(this.date),
currentLanguage = $('html').attr('lang');
lastActivity.locale(currentLanguage);
this.$el.html(
interpolate(
// Translators: 'date' is a placeholder for a fuzzy, relative timestamp (see: http://momentjs.com/)
gettext("Last activity %(date)s"),
gettext('Last activity %(date)s'),
{date: this.template({date: lastActivity.format('MMMM Do YYYY, h:mm:ss a')})},
true
)
......@@ -95,7 +95,7 @@
});
TeamCardView = CardView.extend({
initialize: function () {
initialize: function() {
CardView.prototype.initialize.apply(this, arguments);
// TODO: show last activity detail view
this.detailViews = [
......@@ -107,16 +107,16 @@
}),
new TeamActivityView({date: this.model.get('last_activity_at')})
];
this.model.on('change:membership', function () {
this.model.on('change:membership', function() {
this.detailViews[0].memberships = this.model.get('membership');
}, this);
},
configuration: 'list_card',
cardClass: 'team-card',
title: function () { return this.model.get('name'); },
description: function () { return this.model.get('description'); },
details: function () { return this.detailViews; },
title: function() { return this.model.get('name'); },
description: function() { return this.model.get('description'); },
details: function() { return this.detailViews; },
actionClass: 'action-view',
actionContent: function() {
return interpolate(
......@@ -125,7 +125,7 @@
true
);
},
actionUrl: function () {
actionUrl: function() {
return '#teams/' + this.model.get('topic_id') + '/' + this.model.get('id');
}
});
......
/**
* View that shows the discussion for a team.
*/
;(function (define) {
(function(define) {
'use strict';
define(['backbone', 'underscore', 'gettext', 'DiscussionModuleView'],
function (Backbone, _, gettext, DiscussionModuleView) {
function(Backbone, _, gettext, DiscussionModuleView) {
var TeamDiscussionView = Backbone.View.extend({
initialize: function () {
window.$$course_id = this.$el.data("course-id");
initialize: function() {
window.$$course_id = this.$el.data('course-id');
},
render: function () {
render: function() {
var discussionModuleView = new DiscussionModuleView({
el: this.$el,
context: 'standalone'
......
/**
* View for an individual team.
*/
;(function (define) {
(function(define) {
'use strict';
define([
'backbone',
'underscore',
'gettext',
'edx-ui-toolkit/js/utils/html-utils',
'teams/js/views/team_discussion',
'common/js/components/utils/view_utils',
'teams/js/views/team_utils',
'text!teams/templates/team-profile.underscore',
'text!teams/templates/team-member.underscore'
],
function (Backbone, _, gettext, HtmlUtils, TeamDiscussionView, ViewUtils, TeamUtils,
'backbone',
'underscore',
'gettext',
'edx-ui-toolkit/js/utils/html-utils',
'teams/js/views/team_discussion',
'common/js/components/utils/view_utils',
'teams/js/views/team_utils',
'text!teams/templates/team-profile.underscore',
'text!teams/templates/team-member.underscore'
],
function(Backbone, _, gettext, HtmlUtils, TeamDiscussionView, ViewUtils, TeamUtils,
teamTemplate, teamMemberTemplate) {
var TeamProfileView = Backbone.View.extend({
errorMessage: gettext("An error occurred. Try again."),
errorMessage: gettext('An error occurred. Try again.'),
events: {
'click .leave-team-link': 'leaveTeam'
},
initialize: function (options) {
initialize: function(options) {
this.teamEvents = options.teamEvents;
this.context = options.context;
this.setFocusToHeaderFunc = options.setFocusToHeaderFunc;
......@@ -32,10 +32,10 @@
this.countries = TeamUtils.selectorOptionsArrayToHashWithBlank(this.context.countries);
this.languages = TeamUtils.selectorOptionsArrayToHashWithBlank(this.context.languages);
this.listenTo(this.model, "change", this.render);
this.listenTo(this.model, 'change', this.render);
},
render: function () {
render: function() {
var memberships = this.model.get('membership'),
discussionTopicID = this.model.get('discussion_topic_id'),
isMember = TeamUtils.isUserMemberOfTeam(memberships, this.context.userInfo.username);
......@@ -84,18 +84,18 @@
$(event.currentTarget).select();
},
leaveTeam: function (event) {
leaveTeam: function(event) {
event.preventDefault();
var view = this;
ViewUtils.confirmThenRunOperation(
gettext("Leave this team?"),
gettext('Leave this team?'),
gettext("If you leave, you can no longer post in this team's discussions. Your place will be available to another learner."),
gettext("Confirm"),
gettext('Confirm'),
function() {
$.ajax({
type: 'DELETE',
url: view.context.teamMembershipDetailUrl.replace('team_id', view.model.get('id'))
}).done(function (data) {
}).done(function(data) {
view.model.fetch()
.done(function() {
view.teamEvents.trigger('teams:update', {
......@@ -103,7 +103,7 @@
team: view.model
});
});
}).fail(function (data) {
}).fail(function(data) {
TeamUtils.parseAndShowMessage(data, view.errorMessage);
});
}
......
;(function (define) {
(function(define) {
'use strict';
define(['backbone',
......@@ -7,16 +7,16 @@
'gettext',
'teams/js/views/team_utils',
'text!teams/templates/team-profile-header-actions.underscore'],
function (Backbone, $, _, gettext, TeamUtils, teamProfileHeaderActionsTemplate) {
function(Backbone, $, _, gettext, TeamUtils, teamProfileHeaderActionsTemplate) {
return Backbone.View.extend({
errorMessage: gettext("An error occurred. Try again."),
alreadyMemberMessage: gettext("You already belong to another team."),
teamFullMessage: gettext("This team is full."),
errorMessage: gettext('An error occurred. Try again.'),
alreadyMemberMessage: gettext('You already belong to another team.'),
teamFullMessage: gettext('This team is full.'),
events: {
"click .action-primary": "joinTeam",
"click .action-edit-team": "editTeam"
'click .action-primary': 'joinTeam',
'click .action-edit-team': 'editTeam'
},
initialize: function(options) {
......@@ -25,7 +25,7 @@
this.context = options.context;
this.showEditButton = options.showEditButton;
this.topic = options.topic;
this.listenTo(this.model, "change", this.render);
this.listenTo(this.model, 'change', this.render);
},
render: function() {
......@@ -34,7 +34,7 @@
message,
showJoinButton,
teamHasSpace;
this.getUserTeamInfo(username, this.context.maxTeamSize).done(function (info) {
this.getUserTeamInfo(username, this.context.maxTeamSize).done(function(info) {
teamHasSpace = info.teamHasSpace;
// if user is the member of current team then we wouldn't show anything
......@@ -57,7 +57,7 @@
return view;
},
joinTeam: function (event) {
joinTeam: function(event) {
var view = this;
event.preventDefault();
......@@ -65,7 +65,7 @@
type: 'POST',
url: view.context.teamMembershipsUrl,
data: {'username': view.context.userInfo.username, 'team_id': view.model.get('id')}
}).done(function (data) {
}).done(function(data) {
view.model.fetch()
.done(function() {
view.teamEvents.trigger('teams:update', {
......@@ -73,12 +73,12 @@
team: view.model
});
});
}).fail(function (data) {
}).fail(function(data) {
TeamUtils.parseAndShowMessage(data, view.errorMessage);
});
},
getUserTeamInfo: function (username, maxTeamSize) {
getUserTeamInfo: function(username, maxTeamSize) {
var deferred = $.Deferred();
var info = {
alreadyMember: false,
......@@ -100,12 +100,12 @@
type: 'GET',
url: view.context.teamMembershipsUrl,
data: {'username': username, 'course_id': view.context.courseID}
}).done(function (data) {
}).done(function(data) {
info.alreadyMember = (data.count > 0);
info.memberOfCurrentTeam = false;
info.teamHasSpace = teamHasSpace;
deferred.resolve(info);
}).fail(function (data) {
}).fail(function(data) {
TeamUtils.parseAndShowMessage(data, view.errorMessage);
deferred.reject();
});
......@@ -117,10 +117,10 @@
return deferred.promise();
},
editTeam: function (event) {
editTeam: function(event) {
event.preventDefault();
Backbone.history.navigate(
'teams/' + this.topic.id + '/' + this.model.get('id') +'/edit-team',
'teams/' + this.topic.id + '/' + this.model.get('id') + '/edit-team',
{trigger: true}
);
}
......
/* Team utility methods*/
;(function (define) {
(function(define) {
'use strict';
define(["jquery", "underscore"
], function ($, _) {
define(['jquery', 'underscore'
], function($, _) {
return {
/**
......@@ -13,13 +13,13 @@
* @example selectorOptionsArrayToHashWithBlank([["a", "alpha"],["b","beta"]])
* // returns {"a":"alpha", "b":"beta", "":""}
*/
selectorOptionsArrayToHashWithBlank: function (options) {
selectorOptionsArrayToHashWithBlank: function(options) {
var map = _.object(options);
map[""] = "";
map[''] = '';
return map;
},
teamCapacityText: function (memberCount, maxMemberCount) {
teamCapacityText: function(memberCount, maxMemberCount) {
return interpolate(
// Translators: The following message displays the number of members on a team.
ngettext(
......@@ -40,11 +40,11 @@
);
},
hideMessage: function () {
hideMessage: function() {
$('#teams-message').addClass('.is-hidden');
},
showMessage: function (message, type) {
showMessage: function(message, type) {
var messageElement = $('#teams-message');
if (_.isUndefined(type)) {
type = 'warning';
......@@ -57,17 +57,16 @@
/**
* Parse `data` and show user message. If parsing fails than show `genericErrorMessage`
*/
parseAndShowMessage: function (data, genericErrorMessage, type) {
parseAndShowMessage: function(data, genericErrorMessage, type) {
try {
var errors = JSON.parse(data.responseText);
this.showMessage(
var errors = JSON.parse(data.responseText);
this.showMessage(
_.isUndefined(errors.user_message) ? genericErrorMessage : errors.user_message, type
);
} catch (error) {
this.showMessage(genericErrorMessage, type);
this.showMessage(genericErrorMessage, type);
}
}
};
});
}).call(this, define || RequireJS.define);
;(function (define) {
(function(define) {
'use strict';
define([
'backbone',
......@@ -6,7 +6,7 @@
'teams/js/views/team_card',
'common/js/components/views/paginated_view',
'teams/js/views/team_utils'
], function (Backbone, gettext, TeamCardView, PaginatedView, TeamUtils) {
], function(Backbone, gettext, TeamCardView, PaginatedView, TeamUtils) {
var TeamsView = PaginatedView.extend({
type: 'teams',
......@@ -17,7 +17,7 @@
paginationLabel: gettext('Teams Pagination'),
initialize: function (options) {
initialize: function(options) {
this.context = options.context;
this.itemViewClass = TeamCardView.extend({
router: options.router,
......
/**
* A custom TabbedView for Teams.
*/
;(function (define) {
(function(define) {
'use strict';
define([
'common/js/components/views/tabbed_view',
'teams/js/utils/team_analytics'
], function (TabbedView, TeamAnalytics) {
], function(TabbedView, TeamAnalytics) {
var TeamsTabbedView = TabbedView.extend({
/**
* Overrides TabbedView.prototype.setActiveTab in order to
* log page viewed events.
*/
setActiveTab: function (index) {
setActiveTab: function(index) {
TabbedView.prototype.setActiveTab.call(this, index);
TeamAnalytics.emitPageViewed(this.getTabMeta(index).tab.url, null, null);
}
......
/**
* View for a topic card. Displays a Topic.
*/
;(function (define) {
(function(define) {
'use strict';
define(['backbone', 'underscore', 'gettext', 'js/components/card/views/card'],
function (Backbone, _, gettext, CardView) {
function(Backbone, _, gettext, CardView) {
var TeamCountDetailView = Backbone.View.extend({
tagName: 'p',
className: 'team-count',
initialize: function () {
initialize: function() {
this.render();
},
render: function () {
render: function() {
var team_count = this.model.get('team_count');
this.$el.html(_.escape(interpolate(
ngettext('%(team_count)s Team', '%(team_count)s Teams', team_count),
......@@ -25,26 +25,26 @@
});
var TopicCardView = CardView.extend({
initialize: function () {
this.detailViews = [new TeamCountDetailView({ model: this.model })];
initialize: function() {
this.detailViews = [new TeamCountDetailView({model: this.model})];
CardView.prototype.initialize.apply(this, arguments);
},
actionUrl: function () {
actionUrl: function() {
return '#topics/' + this.model.get('id');
},
configuration: 'square_card',
cardClass: 'topic-card',
pennant: gettext('Topic'),
title: function () { return this.model.get('name'); },
description: function () { return this.model.get('description'); },
details: function () { return this.detailViews; },
title: function() { return this.model.get('name'); },
description: function() { return this.model.get('description'); },
details: function() { return this.detailViews; },
actionClass: 'action-view',
actionContent: function () {
actionContent: function() {
var screenReaderText = _.escape(interpolate(
gettext('View Teams in the %(topic_name)s Topic'),
{ topic_name: this.model.get('name') }, true
{topic_name: this.model.get('name')}, true
));
return '<span class="sr">' + screenReaderText + '</span><span class="icon fa fa-arrow-right" aria-hidden="true"></span>'; // eslint-disable-line max-len
}
......
;(function (define) {
(function(define) {
'use strict';
define([
'backbone',
......@@ -6,36 +6,36 @@
'teams/js/views/teams',
'common/js/components/views/paging_header',
'text!teams/templates/team-actions.underscore'
], function (Backbone, gettext, TeamsView, PagingHeader, teamActionsTemplate) {
var TopicTeamsView = TeamsView.extend({
events: {
'click a.browse-teams': 'browseTeams',
'click a.search-teams': 'searchTeams',
'click a.create-team': 'showCreateTeamForm'
},
], function(Backbone, gettext, TeamsView, PagingHeader, teamActionsTemplate) {
var TopicTeamsView = TeamsView.extend({
events: {
'click a.browse-teams': 'browseTeams',
'click a.search-teams': 'searchTeams',
'click a.create-team': 'showCreateTeamForm'
},
initialize: function(options) {
this.options = _.extend({}, options);
this.showSortControls = options.showSortControls;
this.context = options.context;
this.myTeamsCollection = options.myTeamsCollection;
TeamsView.prototype.initialize.call(this, options);
},
initialize: function(options) {
this.options = _.extend({}, options);
this.showSortControls = options.showSortControls;
this.context = options.context;
this.myTeamsCollection = options.myTeamsCollection;
TeamsView.prototype.initialize.call(this, options);
},
canUserCreateTeam: function () {
canUserCreateTeam: function() {
// Note: non-staff and non-privileged users are automatically added to any team
// that they create. This means that if multiple team membership is
// disabled that they cannot create a new team when they already
// belong to one.
return this.context.staff || this.context.privileged || this.myTeamsCollection.length === 0;
},
return this.context.staff || this.context.privileged || this.myTeamsCollection.length === 0;
},
render: function() {
var self = this;
this.collection.refresh().done(function() {
TeamsView.prototype.render.call(self);
if (self.canUserCreateTeam()) {
var message = interpolate_text(
render: function() {
var self = this;
this.collection.refresh().done(function() {
TeamsView.prototype.render.call(self);
if (self.canUserCreateTeam()) {
var message = interpolate_text(
// Translators: this string is shown at the bottom of the teams page
// to find a team to join or else to create a new one. There are three
// links that need to be included in the message:
......@@ -45,51 +45,51 @@
// Be careful to start each link with the appropriate start indicator
// (e.g. {browse_span_start} for #1) and finish it with {span_end}.
_.escape(gettext("{browse_span_start}Browse teams in other topics{span_end} or {search_span_start}search teams{span_end} in this topic. If you still can't find a team to join, {create_span_start}create a new team in this topic{span_end}.")),
{
'browse_span_start': '<a class="browse-teams" href="">',
'search_span_start': '<a class="search-teams" href="">',
'create_span_start': '<a class="create-team" href="">',
'span_end': '</a>'
}
{
'browse_span_start': '<a class="browse-teams" href="">',
'search_span_start': '<a class="search-teams" href="">',
'create_span_start': '<a class="create-team" href="">',
'span_end': '</a>'
}
);
self.$el.append(_.template(teamActionsTemplate)({message: message}));
}
});
return this;
},
self.$el.append(_.template(teamActionsTemplate)({message: message}));
}
});
return this;
},
browseTeams: function (event) {
event.preventDefault();
Backbone.history.navigate('browse', {trigger: true});
},
browseTeams: function(event) {
event.preventDefault();
Backbone.history.navigate('browse', {trigger: true});
},
searchTeams: function (event) {
var searchField = $('.page-header-search .search-field');
event.preventDefault();
searchField.focus();
searchField.select();
$('html, body').animate({
scrollTop: 0
}, 500);
},
searchTeams: function(event) {
var searchField = $('.page-header-search .search-field');
event.preventDefault();
searchField.focus();
searchField.select();
$('html, body').animate({
scrollTop: 0
}, 500);
},
showCreateTeamForm: function (event) {
event.preventDefault();
Backbone.history.navigate(
showCreateTeamForm: function(event) {
event.preventDefault();
Backbone.history.navigate(
'topics/' + this.model.id + '/create-team',
{trigger: true}
);
},
},
createHeaderView: function () {
return new PagingHeader({
collection: this.options.collection,
srInfo: this.srInfo,
showSortControls: this.showSortControls
});
}
});
return TopicTeamsView;
createHeaderView: function() {
return new PagingHeader({
collection: this.options.collection,
srInfo: this.srInfo,
showSortControls: this.showSortControls
});
}
});
return TopicTeamsView;
});
}).call(this, define || RequireJS.define);
;(function (define) {
(function(define) {
'use strict';
define([
'gettext',
......@@ -6,7 +6,7 @@
'teams/js/views/team_utils',
'common/js/components/views/paging_header',
'common/js/components/views/paginated_view'
], function (gettext, TopicCardView, TeamUtils, PagingHeader, PaginatedView) {
], function(gettext, TopicCardView, TeamUtils, PagingHeader, PaginatedView) {
var TopicsView = PaginatedView.extend({
type: 'topics',
......@@ -15,7 +15,7 @@
text: gettext('All topics')
},
initialize: function (options) {
initialize: function(options) {
this.options = _.extend({}, options);
this.itemViewClass = TopicCardView.extend({
router: options.router,
......@@ -24,7 +24,7 @@
PaginatedView.prototype.initialize.call(this);
},
createHeaderView: function () {
createHeaderView: function() {
return new PagingHeader({
collection: this.options.collection,
srInfo: this.srInfo,
......
(function () {
(function() {
var output, Converter;
if (typeof exports === "object" && typeof require === "function") { // we're in a CommonJS (e.g. Node.js) module
if (typeof exports === 'object' && typeof require === 'function') { // we're in a CommonJS (e.g. Node.js) module
output = exports;
Converter = require("./Markdown.Converter").Converter;
Converter = require('./Markdown.Converter').Converter;
} else {
output = window.Markdown;
Converter = output.Converter;
}
output.getSanitizingConverter = function () {
output.getSanitizingConverter = function() {
var converter = new Converter();
converter.hooks.chain("postConversion", sanitizeHtml);
converter.hooks.chain("postConversion", balanceTags);
converter.hooks.chain('postConversion', sanitizeHtml);
converter.hooks.chain('postConversion', balanceTags);
return converter;
}
};
function sanitizeHtml(html) {
return html.replace(/<[^>]*>?/gi, sanitizeTag);
......@@ -31,21 +31,20 @@
if (tag.match(basic_tag_whitelist) || tag.match(a_white) || tag.match(img_white))
return tag;
else
return "";
return '';
}
/// <summary>
/// attempt to balance HTML tags in the html string
/// by removing any unmatched opening or closing tags
/// IMPORTANT: we *assume* HTML has *already* been
/// sanitized and is safe/sane before balancing!
///
/// adapted from CODESNIPPET: A8591DBA-D1D3-11DE-947C-BA5556D89593
/// </summary>
// / <summary>
// / attempt to balance HTML tags in the html string
// / by removing any unmatched opening or closing tags
// / IMPORTANT: we *assume* HTML has *already* been
// / sanitized and is safe/sane before balancing!
// /
// / adapted from CODESNIPPET: A8591DBA-D1D3-11DE-947C-BA5556D89593
// / </summary>
function balanceTags(html) {
if (html == "")
return "";
if (html == '')
return '';
var re = /<\/?\w+[^>]*(\s|$|>)/g;
// convert everything to lower case; this makes
......@@ -58,7 +57,7 @@
return html;
var tagname, tag;
var ignoredtags = "<p><img><br><li><hr>";
var ignoredtags = '<p><img><br><li><hr>';
var match;
var tagpaired = [];
var tagremove = [];
......@@ -66,10 +65,10 @@
// loop through matched tags in forward order
for (var ctag = 0; ctag < tagcount; ctag++) {
tagname = tags[ctag].replace(/<\/?(\w+).*/, "$1");
tagname = tags[ctag].replace(/<\/?(\w+).*/, '$1');
// skip any already paired tags
// and skip tags in our ignore list; assume they're self-closed
if (tagpaired[ctag] || ignoredtags.search("<" + tagname + ">") > -1)
if (tagpaired[ctag] || ignoredtags.search('<' + tagname + '>') > -1)
continue;
tag = tags[ctag];
......@@ -79,7 +78,7 @@
// this is an opening tag
// search forwards (next tags), look for closing tags
for (var ntag = ctag + 1; ntag < tagcount; ntag++) {
if (!tagpaired[ntag] && tags[ntag] == "</" + tagname + ">") {
if (!tagpaired[ntag] && tags[ntag] == '</' + tagname + '>') {
match = ntag;
break;
}
......@@ -98,8 +97,8 @@
// delete all orphaned tags from the string
var ctag = 0;
html = html.replace(re, function (match) {
var res = tagremove[ctag] ? "" : match;
html = html.replace(re, function(match) {
var res = tagremove[ctag] ? '' : match;
ctag++;
return res;
});
......
$(document).ajaxError(function (event, jXHR) {
$(document).ajaxError(function(event, jXHR) {
if (jXHR.status === 403 && jXHR.responseText === 'Unauthenticated') {
var message = gettext(
'You have been logged out of your edX account. '+
'Click Okay to log in again now. '+
'Click Cancel to stay on this page '+
'You have been logged out of your edX account. ' +
'Click Okay to log in again now. ' +
'Click Cancel to stay on this page ' +
'(you must log in again to save your work).'
);
if (window.confirm(message)) {
var currentLocation = window.location.pathname;
window.location.href = '/login?next=' + encodeURIComponent(currentLocation);
};
}
}
});
;(function (define) {
(function(define) {
'use strict';
define(['js/api_admin/views/catalog_preview'], function (CatalogPreviewView) {
return function (options) {
define(['js/api_admin/views/catalog_preview'], function(CatalogPreviewView) {
return function(options) {
var view = new CatalogPreviewView({
el: '.catalog-body',
previewUrl: options.previewUrl,
catalogApiUrl: options.catalogApiUrl,
catalogApiUrl: options.catalogApiUrl
});
return view.render();
};
......
;(function(define) {
(function(define) {
'use strict';
define([
......@@ -7,21 +7,21 @@
'gettext',
'text!../../../templates/api_admin/catalog-results.underscore',
'text!../../../templates/api_admin/catalog-error.underscore'
], function (Backbone, _, gettext, catalogResultsTpl, catalogErrorTpl) {
], function(Backbone, _, gettext, catalogResultsTpl, catalogErrorTpl) {
return Backbone.View.extend({
events: {
'click .preview-query': 'previewQuery'
},
initialize: function (options) {
initialize: function(options) {
this.previewUrl = options.previewUrl;
this.catalogApiUrl = options.catalogApiUrl;
},
render: function () {
render: function() {
this.$('#id_query').after(
'<button class="preview-query">'+ gettext('Preview this query') + '</button>'
'<button class="preview-query">' + gettext('Preview this query') + '</button>'
);
return this;
},
......@@ -29,8 +29,8 @@
/*
* Return the user's query, URL-encoded.
*/
getQuery: function () {
return encodeURIComponent(this.$("#id_query").val());
getQuery: function() {
return encodeURIComponent(this.$('#id_query').val());
},
/*
......@@ -38,12 +38,12 @@
* with the user's query. On success, displays the
* results, and on failure, displays an error message.
*/
previewQuery: function (event) {
previewQuery: function(event) {
event.preventDefault();
$.ajax(this.previewUrl + '?q=' + this.getQuery(), {
method: 'GET',
success: _.bind(this.renderCourses, this),
error: _.bind(function () {
error: _.bind(function() {
this.$('.preview-results').html(_.template(catalogErrorTpl)({}));
}, this)
});
......@@ -53,12 +53,12 @@
* Render a list of courses with data returned by the
* courses API.
*/
renderCourses: function (data) {
renderCourses: function(data) {
this.$('.preview-results').html(_.template(catalogResultsTpl)({
'courses': data.results,
'catalogApiUrl': this.catalogApiUrl,
'catalogApiUrl': this.catalogApiUrl
}));
},
}
});
});
}).call(this, define || RequireJS.define);
;(function (define) {
(function(define) {
'use strict';
define([
'backbone',
'edx-ui-toolkit/js/pagination/paging-collection',
'js/bookmarks/models/bookmark'
], function (Backbone, PagingCollection, BookmarkModel) {
return PagingCollection.extend({
model: BookmarkModel,
], function(Backbone, PagingCollection, BookmarkModel) {
return PagingCollection.extend({
model: BookmarkModel,
queryParams: {
course_id: function () { return this.options.course_id; },
fields : function () { return 'display_name,path'; }
},
queryParams: {
course_id: function() { return this.options.course_id; },
fields: function() { return 'display_name,path'; }
},
url: function() {
return this.url;
},
url: function() {
return this.url;
},
constructor: function (models, options) {
this.options = options;
this.url = options.url;
PagingCollection.prototype.constructor.call(this, models, options);
}
});
constructor: function(models, options) {
this.options = options;
this.url = options.url;
PagingCollection.prototype.constructor.call(this, models, options);
}
});
});
})(define || RequireJS.define);
;(function (define) {
(function(define) {
'use strict';
define(['backbone'], function (Backbone) {
define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
idAttribute: 'id',
defaults: {
......@@ -12,10 +11,9 @@
created: ''
},
blockUrl: function () {
blockUrl: function() {
return '/courses/' + this.get('course_id') + '/jump_to/' + this.get('usage_id');
}
});
});
})(define || RequireJS.define);
;(function (define, undefined) {
(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'js/views/message_banner'],
function (gettext, $, _, Backbone, MessageBannerView) {
function(gettext, $, _, Backbone, MessageBannerView) {
return Backbone.View.extend({
errorMessage: gettext('An error has occurred. Please try again.'),
return Backbone.View.extend({
errorMessage: gettext('An error has occurred. Please try again.'),
srAddBookmarkText: gettext('Click to add'),
srRemoveBookmarkText: gettext('Click to remove'),
srAddBookmarkText: gettext('Click to add'),
srRemoveBookmarkText: gettext('Click to remove'),
events: {
'click': 'toggleBookmark'
},
events: {
'click': 'toggleBookmark'
},
showBannerInterval: 5000, // time in ms
showBannerInterval: 5000, // time in ms
initialize: function(options) {
this.apiUrl = options.apiUrl;
this.bookmarkId = options.bookmarkId;
this.bookmarked = options.bookmarked;
this.usageId = options.usageId;
this.setBookmarkState(this.bookmarked);
},
initialize: function (options) {
this.apiUrl = options.apiUrl;
this.bookmarkId = options.bookmarkId;
this.bookmarked = options.bookmarked;
this.usageId = options.usageId;
this.setBookmarkState(this.bookmarked);
},
toggleBookmark: function(event) {
event.preventDefault();
toggleBookmark: function(event) {
event.preventDefault();
this.$el.prop('disabled', true);
this.$el.prop('disabled', true);
if (this.$el.hasClass('bookmarked')) {
this.removeBookmark();
} else {
this.addBookmark();
}
},
if (this.$el.hasClass('bookmarked')) {
this.removeBookmark();
} else {
this.addBookmark();
}
},
addBookmark: function() {
var view = this;
$.ajax({
data: {usage_id: view.usageId},
type: "POST",
url: view.apiUrl,
dataType: 'json',
success: function () {
view.$el.trigger('bookmark:add');
view.setBookmarkState(true);
},
error: function (jqXHR) {
try {
var response = jqXHR.responseText ? JSON.parse(jqXHR.responseText) : '';
var userMessage = response ? response.user_message : '';
view.showError(userMessage);
}
catch(err) {
addBookmark: function() {
var view = this;
$.ajax({
data: {usage_id: view.usageId},
type: 'POST',
url: view.apiUrl,
dataType: 'json',
success: function() {
view.$el.trigger('bookmark:add');
view.setBookmarkState(true);
},
error: function(jqXHR) {
try {
var response = jqXHR.responseText ? JSON.parse(jqXHR.responseText) : '';
var userMessage = response ? response.user_message : '';
view.showError(userMessage);
}
catch (err) {
view.showError();
}
},
complete: function () {
view.$el.prop('disabled', false);
}
});
},
},
complete: function() {
view.$el.prop('disabled', false);
}
});
},
removeBookmark: function() {
var view = this;
var deleteUrl = view.apiUrl + view.bookmarkId + '/';
removeBookmark: function() {
var view = this;
var deleteUrl = view.apiUrl + view.bookmarkId + '/';
$.ajax({
type: "DELETE",
url: deleteUrl,
success: function () {
view.$el.trigger('bookmark:remove');
view.setBookmarkState(false);
},
error: function() {
view.showError();
},
complete: function() {
view.$el.prop('disabled', false);
}
});
},
$.ajax({
type: 'DELETE',
url: deleteUrl,
success: function() {
view.$el.trigger('bookmark:remove');
view.setBookmarkState(false);
},
error: function() {
view.showError();
},
complete: function() {
view.$el.prop('disabled', false);
}
});
},
setBookmarkState: function(bookmarked) {
if (bookmarked) {
this.$el.addClass('bookmarked');
this.$el.attr('aria-pressed', 'true');
this.$el.find('.bookmark-sr').text(this.srRemoveBookmarkText);
} else {
this.$el.removeClass('bookmarked');
this.$el.attr('aria-pressed', 'false');
this.$el.find('.bookmark-sr').text(this.srAddBookmarkText);
}
},
setBookmarkState: function(bookmarked) {
if (bookmarked) {
this.$el.addClass('bookmarked');
this.$el.attr('aria-pressed', 'true');
this.$el.find('.bookmark-sr').text(this.srRemoveBookmarkText);
} else {
this.$el.removeClass('bookmarked');
this.$el.attr('aria-pressed', 'false');
this.$el.find('.bookmark-sr').text(this.srAddBookmarkText);
}
},
showError: function (errorText) {
var errorMsg = errorText || this.errorMessage;
showError: function(errorText) {
var errorMsg = errorText || this.errorMessage;
if (!this.messageView) {
this.messageView = new MessageBannerView({
el: $('.message-banner'),
type: 'error'
});
}
this.messageView.showMessage(errorMsg);
if (!this.messageView) {
this.messageView = new MessageBannerView({
el: $('.message-banner'),
type: 'error'
});
}
this.messageView.showMessage(errorMsg);
// Hide message automatically after some interval
setTimeout(_.bind(function () {
this.messageView.hideMessage();
}, this), this.showBannerInterval);
}
setTimeout(_.bind(function() {
this.messageView.hideMessage();
}, this), this.showBannerInterval);
}
});
});
});
}).call(this, define || RequireJS.define);
;(function (define, undefined) {
(function(define, undefined) {
'use strict';
define(['gettext', 'jquery', 'underscore', 'backbone', 'js/bookmarks/views/bookmarks_list',
'js/bookmarks/collections/bookmarks', 'js/views/message_banner'],
function (gettext, $, _, Backbone, BookmarksListView, BookmarksCollection, MessageBannerView) {
function(gettext, $, _, Backbone, BookmarksListView, BookmarksCollection, MessageBannerView) {
return Backbone.View.extend({
return Backbone.View.extend({
el: '.courseware-bookmarks-button',
el: '.courseware-bookmarks-button',
loadingMessageElement: '#loading-message',
errorMessageElement: '#error-message',
loadingMessageElement: '#loading-message',
errorMessageElement: '#error-message',
events: {
'click .bookmarks-list-button': 'toggleBookmarksListView'
},
events: {
'click .bookmarks-list-button': 'toggleBookmarksListView'
},
initialize: function () {
var bookmarksCollection = new BookmarksCollection([],
{
course_id: $('.courseware-results').data('courseId'),
url: $('.courseware-bookmarks-button').data('bookmarksApiUrl')
}
initialize: function() {
var bookmarksCollection = new BookmarksCollection([],
{
course_id: $('.courseware-results').data('courseId'),
url: $('.courseware-bookmarks-button').data('bookmarksApiUrl')
}
);
this.bookmarksListView = new BookmarksListView(
{
collection: bookmarksCollection,
loadingMessageView: new MessageBannerView({el: $(this.loadingMessageElement)}),
errorMessageView: new MessageBannerView({el: $(this.errorMessageElement)})
}
this.bookmarksListView = new BookmarksListView(
{
collection: bookmarksCollection,
loadingMessageView: new MessageBannerView({el: $(this.loadingMessageElement)}),
errorMessageView: new MessageBannerView({el: $(this.errorMessageElement)})
}
);
},
},
toggleBookmarksListView: function () {
if (this.bookmarksListView.areBookmarksVisible()) {
this.bookmarksListView.hideBookmarks();
this.$('.bookmarks-list-button').attr('aria-pressed', 'false');
this.$('.bookmarks-list-button').removeClass('is-active').addClass('is-inactive');
} else {
this.bookmarksListView.showBookmarks();
this.$('.bookmarks-list-button').attr('aria-pressed', 'true');
this.$('.bookmarks-list-button').removeClass('is-inactive').addClass('is-active');
toggleBookmarksListView: function() {
if (this.bookmarksListView.areBookmarksVisible()) {
this.bookmarksListView.hideBookmarks();
this.$('.bookmarks-list-button').attr('aria-pressed', 'false');
this.$('.bookmarks-list-button').removeClass('is-active').addClass('is-inactive');
} else {
this.bookmarksListView.showBookmarks();
this.$('.bookmarks-list-button').attr('aria-pressed', 'true');
this.$('.bookmarks-list-button').removeClass('is-inactive').addClass('is-active');
}
}
}
});
});
});
}).call(this, define || RequireJS.define);
$(function () {
$(function() {
'use strict';
$('.action-share-mozillaopenbadges').click(function (event) {
$('.action-share-mozillaopenbadges').click(function(event) {
$('.badges-overlay').fadeIn();
event.preventDefault();
});
$('.badges-modal .close').click(function () {
$('.badges-modal .close').click(function() {
$('.badges-overlay').fadeOut();
});
});
\ No newline at end of file
});
// Backbone.js Application Collection: CertificateInvalidationCollection
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define) {
(function(define) {
'use strict';
define(
......@@ -17,4 +17,4 @@
});
}
);
}).call(this, define || RequireJS.define);
\ No newline at end of file
}).call(this, define || RequireJS.define);
// Backbone.js Application Collection: CertificateWhiteList
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define){
(function(define) {
'use strict';
define([
'backbone',
'gettext',
'js/certificates/models/certificate_exception'
],
'backbone',
'gettext',
'js/certificates/models/certificate_exception'
],
function(Backbone, gettext, CertificateExceptionModel){
var CertificateWhiteList = Backbone.Collection.extend({
function(Backbone, gettext, CertificateExceptionModel) {
var CertificateWhiteList = Backbone.Collection.extend({
model: CertificateExceptionModel,
initialize: function(attrs, options){
initialize: function(attrs, options) {
this.url = options.url;
this.generate_certificates_url = options.generate_certificates_url;
},
getModel: function(attrs){
getModel: function(attrs) {
var model = this.findWhere({user_name: attrs.user_name});
if(attrs.user_name && model){
if (attrs.user_name && model) {
return model;
}
model = this.findWhere({user_email: attrs.user_email});
if(attrs.user_email && model){
if (attrs.user_email && model) {
return model;
}
return undefined;
},
sync: function(options, appended_url){
sync: function(options, appended_url) {
var filtered = [];
if(appended_url === 'new'){
filtered = this.filter(function(model){
if (appended_url === 'new') {
filtered = this.filter(function(model) {
return model.get('new');
});
}
......@@ -48,8 +47,8 @@
);
},
update: function(data){
_.each(data, function(item){
update: function(data) {
_.each(data, function(item) {
var certificate_exception_model =
this.getModel({user_name: item.user_name, user_email: item.user_email});
certificate_exception_model.set(item);
......@@ -60,4 +59,4 @@
return CertificateWhiteList;
}
);
}).call(this, define || RequireJS.define);
\ No newline at end of file
}).call(this, define || RequireJS.define);
// Backbone.js Page Object Factory: Certificate Invalidation Factory
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define) {
(function(define) {
'use strict';
define(
[
......@@ -9,7 +9,6 @@
'js/certificates/collections/certificate_invalidation_collection'
],
function(CertificateInvalidationView, CertificateInvalidationCollection) {
return function(certificate_invalidation_collection_json, certificate_invalidation_url) {
var certificate_invalidation_collection = new CertificateInvalidationCollection(
JSON.parse(certificate_invalidation_collection_json), {
......@@ -25,7 +24,6 @@
certificate_invalidation_view.render();
};
}
);
}).call(this, define || RequireJS.define);
\ No newline at end of file
}).call(this, define || RequireJS.define);
// Backbone.js Page Object Factory: Certificates
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define){
(function(define) {
'use strict';
define([
'jquery',
'js/certificates/views/certificate_whitelist',
'js/certificates/models/certificate_exception',
'js/certificates/views/certificate_whitelist_editor',
'js/certificates/collections/certificate_whitelist',
'js/certificates/views/certificate_bulk_whitelist'
],
function($, CertificateWhiteListListView, CertificateExceptionModel, CertificateWhiteListEditorView ,
CertificateWhiteListCollection, CertificateBulkWhiteList){
'jquery',
'js/certificates/views/certificate_whitelist',
'js/certificates/models/certificate_exception',
'js/certificates/views/certificate_whitelist_editor',
'js/certificates/collections/certificate_whitelist',
'js/certificates/views/certificate_bulk_whitelist'
],
function($, CertificateWhiteListListView, CertificateExceptionModel, CertificateWhiteListEditorView,
CertificateWhiteListCollection, CertificateBulkWhiteList) {
return function(certificate_white_list_json, generate_certificate_exceptions_url,
certificate_exception_view_url, generate_bulk_certificate_exceptions_url,
active_certificate){
active_certificate) {
var certificateWhiteList = new CertificateWhiteListCollection(certificate_white_list_json, {
parse: true,
canBeEmpty: true,
......@@ -38,8 +37,7 @@
new CertificateBulkWhiteList({
bulk_exception_url: generate_bulk_certificate_exceptions_url
}).render();
};
}
);
}).call(this, define || RequireJS.define);
\ No newline at end of file
}).call(this, define || RequireJS.define);
// Backbone.js Application Model: CertificateWhitelist
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define){
(function(define) {
'use strict';
define([
'underscore',
'underscore.string',
'backbone',
'gettext'
],
function(_, str, Backbone, gettext){
'underscore',
'underscore.string',
'backbone',
'gettext'
],
function(_, str, Backbone, gettext) {
return Backbone.Model.extend({
idAttribute: 'id',
......@@ -24,17 +23,16 @@
certificate_generated: '',
notes: ''
},
initialize: function (attributes, options) {
initialize: function(attributes, options) {
this.url = options.url;
},
validate: function(attrs){
validate: function(attrs) {
if (!str.trim(attrs.user_name) && !str.trim(attrs.user_email)) {
return gettext('Student username/email field is required and can not be empty. ' +
'Kindly fill in username/email and then press "Add to Exception List" button.');
}
}
});
}
);
}).call(this, define || RequireJS.define);
\ No newline at end of file
}).call(this, define || RequireJS.define);
// Backbone.js Application Model: CertificateInvalidation
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define) {
(function(define) {
'use strict';
define(
['underscore', 'underscore.string', 'gettext', 'backbone'],
function(_, str, gettext, Backbone) {
return Backbone.Model.extend({
idAttribute: 'id',
......@@ -19,7 +18,7 @@
notes: ''
},
initialize: function (attributes, options) {
initialize: function(attributes, options) {
this.url = options.url;
},
......@@ -33,4 +32,4 @@
});
}
);
}).call(this, define || RequireJS.define);
\ No newline at end of file
}).call(this, define || RequireJS.define);
// Backbone Application View: CertificateBulkWhitelist View
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define){
(function(define) {
'use strict';
define([
'jquery',
'underscore',
'gettext',
'backbone'
],
'jquery',
'underscore',
'gettext',
'backbone'
],
function($, _, gettext, Backbone){
function($, _, gettext, Backbone) {
var DOM_SELECTORS = {
bulk_exception: ".bulk-white-list-exception",
upload_csv_button: ".upload-csv-button",
browse_file: ".browse-file",
bulk_white_list_exception_form: "form#bulk-white-list-exception-form"
bulk_exception: '.bulk-white-list-exception',
upload_csv_button: '.upload-csv-button',
browse_file: '.browse-file',
bulk_white_list_exception_form: 'form#bulk-white-list-exception-form'
};
var MESSAGE_GROUP = {
......@@ -36,19 +36,19 @@
'click .arrow': 'toggleMessageDetails'
},
initialize: function(options){
initialize: function(options) {
// Re-render the view when an item is added to the collection
this.bulk_exception_url = options.bulk_exception_url;
},
render: function(){
render: function() {
var template = this.loadTemplate('certificate-bulk-white-list');
this.$el.html(template());
},
loadTemplate: function(name) {
var templateSelector = "#" + name + "-tpl",
templateText = $(templateSelector).text();
var templateSelector = '#' + name + '-tpl',
templateText = $(templateSelector).text();
return _.template(templateText);
},
......@@ -57,7 +57,7 @@
var self = this;
form.unbind('submit').submit(function(e) {
var data = new FormData(e.currentTarget);
$.ajax({
$.ajax({
dataType: 'json',
type: 'POST',
url: self.bulk_exception_url,
......@@ -67,13 +67,13 @@
success: function(data_from_server) {
self.display_response(data_from_server);
}
});
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
},
display_response: function(data_from_server) {
$(".bulk-exception-results").removeClass('hidden').empty();
$('.bulk-exception-results').removeClass('hidden').empty();
// Display general error messages
if (data_from_server.general_errors.length) {
......@@ -138,54 +138,54 @@
$('<div/>', {
class: 'message ' + group
}).appendTo('.bulk-exception-results').prepend(
"<button type='button' id= '" + group + "' class='arrow'> + </button>" + heading
"<button type='button' id= '" + group + "' class='arrow'> + </button>" + heading
).append($('<ul/>', {
class: group
}));
class: group
}));
for(var i = 0; i < display_data.length; i++){
for (var i = 0; i < display_data.length; i++) {
$('<li/>', {
text: display_data[i]
}).appendTo('div.message > .' + group);
}
$("div.message > ." + group).hide();
$('div.message > .' + group).hide();
}
function get_text(qty, group) {
// inner function to display appropriate heading text
var text;
switch(group) {
case MESSAGE_GROUP.successfully_added:
text = qty > 1 ? gettext(qty + ' learners are successfully added to exception list'):
switch (group) {
case MESSAGE_GROUP.successfully_added:
text = qty > 1 ? gettext(qty + ' learners are successfully added to exception list') :
gettext(qty + ' learner is successfully added to the exception list');
break;
break;
case MESSAGE_GROUP.data_format_error:
text = qty > 1 ? gettext(qty + ' records are not in correct format and not added to' +
' the exception list'):
case MESSAGE_GROUP.data_format_error:
text = qty > 1 ? gettext(qty + ' records are not in correct format and not added to' +
' the exception list') :
gettext(qty + ' record is not in correct format and not added to the exception' +
' list');
break;
break;
case MESSAGE_GROUP.user_not_exist:
text = qty > 1 ? gettext(qty + ' learners do not exist in LMS and not added to the' +
' exception list'):
case MESSAGE_GROUP.user_not_exist:
text = qty > 1 ? gettext(qty + ' learners do not exist in LMS and not added to the' +
' exception list') :
gettext(qty + ' learner does not exist in LMS and not added to the exception list');
break;
break;
case MESSAGE_GROUP.user_already_white_listed:
text = qty > 1 ? gettext(qty + ' learners are already white listed and not added to' +
' the exception list'):
case MESSAGE_GROUP.user_already_white_listed:
text = qty > 1 ? gettext(qty + ' learners are already white listed and not added to' +
' the exception list') :
gettext(qty + ' learner is already white listed and not added to the exception ' +
'list');
break;
break;
case MESSAGE_GROUP.user_not_enrolled:
text = qty > 1 ? gettext(qty + ' learners are not enrolled in course and not added to' +
' the exception list'):
case MESSAGE_GROUP.user_not_enrolled:
text = qty > 1 ? gettext(qty + ' learners are not enrolled in course and not added to' +
' the exception list') :
gettext(qty + ' learner is not enrolled in course and not added to the exception' +
' list');
break;
break;
}
return text;
}
......@@ -194,11 +194,11 @@
toggleMessageDetails: function(event) {
if (event && event.preventDefault) { event.preventDefault(); }
var group = event.target.id;
$("div.message > ." + group).slideToggle( "fast", function() {
$('div.message > .' + group).slideToggle('fast', function() {
if ($(this).is(':visible')) {
event.target.text = ' -- ';
} else {
event.target.text = ' + ';
event.target.text = ' + ';
}
});
},
......@@ -208,7 +208,7 @@
if (event.currentTarget.files.length === 1) {
this.$el.find(DOM_SELECTORS.upload_csv_button).removeAttr('disabled');
this.$el.find(DOM_SELECTORS.browse_file).val(
event.currentTarget.value.substring(event.currentTarget.value.lastIndexOf("\\") + 1));
event.currentTarget.value.substring(event.currentTarget.value.lastIndexOf('\\') + 1));
}
}
});
......
// Backbone Application View: CertificateInvalidationView
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define) {
(function(define) {
'use strict';
define(
['jquery', 'underscore', 'gettext', 'backbone', 'js/certificates/models/certificate_invalidation'],
function($, _, gettext, Backbone, CertificateInvalidationModel) {
return Backbone.View.extend({
el: "#certificate-invalidation",
messages: "div.message",
el: '#certificate-invalidation',
messages: 'div.message',
events: {
'click #invalidate-certificate': 'invalidateCertificate',
'click .re-validate-certificate': 'reValidateCertificate'
......@@ -25,15 +25,15 @@
},
loadTemplate: function(name) {
var templateSelector = "#" + name + "-tpl",
templateText = $(templateSelector).text();
var templateSelector = '#' + name + '-tpl',
templateText = $(templateSelector).text();
return _.template(templateText);
},
invalidateCertificate: function() {
var user = this.$("#certificate-invalidation-user").val();
var notes = this.$("#certificate-invalidation-notes").val();
var message = "";
var user = this.$('#certificate-invalidation-user').val();
var notes = this.$('#certificate-invalidation-notes').val();
var message = '';
var certificate_invalidation = new CertificateInvalidationModel(
{
......@@ -65,14 +65,13 @@
var response_data = JSON.parse(response.responseText);
self.escapeAndShowMessage(response_data.message);
}
catch(exception) {
catch (exception) {
self.escapeAndShowMessage(
gettext("Server Error, Please refresh the page and try again.")
gettext('Server Error, Please refresh the page and try again.')
);
}
}
});
}
else {
this.escapeAndShowMessage(certificate_invalidation.validationError);
......@@ -96,9 +95,9 @@
var response_data = JSON.parse(response.responseText);
self.escapeAndShowMessage(response_data.message);
}
catch(exception) {
catch (exception) {
self.escapeAndShowMessage(
gettext("Server Error, Please refresh the page and try again.")
gettext('Server Error, Please refresh the page and try again.')
);
}
},
......@@ -119,8 +118,8 @@
},
escapeAndShowMessage: function(message) {
$(this.messages + ">p" ).remove();
this.$(this.messages).removeClass('hidden').append("<p>"+ _.escape(message) + "</p>");
$(this.messages + '>p').remove();
this.$(this.messages).removeClass('hidden').append('<p>' + _.escape(message) + '</p>');
}
});
......
// Backbone Application View: CertificateWhitelist View
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define){
(function(define) {
'use strict';
define([
'jquery',
'underscore',
'gettext',
'backbone'
],
'jquery',
'underscore',
'gettext',
'backbone'
],
function($, _, gettext, Backbone){
function($, _, gettext, Backbone) {
return Backbone.View.extend({
el: "#white-listed-students",
el: '#white-listed-students',
message_div: 'div.white-listed-students > div.message',
generate_exception_certificates_radio:
'input:radio[name=generate-exception-certificates-radio]:checked',
......@@ -23,35 +23,35 @@
'click .delete-exception': 'removeException'
},
initialize: function(options){
initialize: function(options) {
this.certificateWhiteListEditorView = options.certificateWhiteListEditorView;
this.active_certificate = options.active_certificate;
// Re-render the view when an item is added to the collection
this.listenTo(this.collection, 'change add remove', this.render);
},
render: function(){
render: function() {
var template = this.loadTemplate('certificate-white-list');
this.$el.html(template({certificates: this.collection.models}));
if (!this.active_certificate || this.collection.isEmpty()){
this.$("#generate-exception-certificates").attr("disabled", "disabled");
if (!this.active_certificate || this.collection.isEmpty()) {
this.$('#generate-exception-certificates').attr('disabled', 'disabled');
}
else {
this.$("#generate-exception-certificates").removeAttr("disabled");
this.$('#generate-exception-certificates').removeAttr('disabled');
}
},
loadTemplate: function(name) {
var templateSelector = "#" + name + "-tpl",
templateText = $(templateSelector).text();
var templateSelector = '#' + name + '-tpl',
templateText = $(templateSelector).text();
return _.template(templateText);
},
removeException: function(event){
removeException: function(event) {
var certificate = $(event.target).data();
var model = this.collection.findWhere(certificate);
var self = this;
if(model){
if (model) {
model.destroy(
{
success: function() {
......@@ -65,41 +65,41 @@
}
);
}
else{
else {
this.escapeAndShowMessage(
gettext('Could not find Certificate Exception in white list. Please refresh the page and try again') // eslint-disable-line max-len
);
}
},
generateExceptionCertificates: function(){
generateExceptionCertificates: function() {
this.collection.sync(
{success: this.showSuccess(this), error: this.showError(this)},
$(this.generate_exception_certificates_radio).val()
);
},
escapeAndShowMessage: function(message){
$(this.message_div + ">p" ).remove();
$(this.message_div).removeClass('hidden').append("<p>"+ _.escape(message) + "</p>").focus();
$(this.message_div).fadeOut(6000, "linear");
escapeAndShowMessage: function(message) {
$(this.message_div + '>p').remove();
$(this.message_div).removeClass('hidden').append('<p>' + _.escape(message) + '</p>').focus();
$(this.message_div).fadeOut(6000, 'linear');
},
showSuccess: function(caller_object){
return function(xhr){
showSuccess: function(caller_object) {
return function(xhr) {
caller_object.escapeAndShowMessage(xhr.message);
};
},
showError: function(caller_object){
return function(xhr){
try{
showError: function(caller_object) {
return function(xhr) {
try {
var response = JSON.parse(xhr.responseText);
caller_object.escapeAndShowMessage(response.message);
}
catch(exception){
catch (exception) {
caller_object.escapeAndShowMessage(
gettext("Server Error, Please refresh the page and try again.")
gettext('Server Error, Please refresh the page and try again.')
);
}
};
......
// Backbone Application View: CertificateWhiteList Editor View
/*global define, RequireJS */
/* global define, RequireJS */
;(function(define){
(function(define) {
'use strict';
define([
'jquery',
'underscore',
'gettext',
'backbone',
'js/certificates/models/certificate_exception'
],
function($, _, gettext, Backbone, CertificateExceptionModel){
'jquery',
'underscore',
'gettext',
'backbone',
'js/certificates/models/certificate_exception'
],
function($, _, gettext, Backbone, CertificateExceptionModel) {
return Backbone.View.extend({
el: "#certificate-white-list-editor",
el: '#certificate-white-list-editor',
message_div: '.message',
events: {
'click #add-exception': 'addException'
},
render: function(){
render: function() {
var template = this.loadTemplate('certificate-white-list-editor');
this.$el.html(template());
},
loadTemplate: function(name) {
var templateSelector = "#" + name + "-tpl",
templateText = $(templateSelector).text();
var templateSelector = '#' + name + '-tpl',
templateText = $(templateSelector).text();
return _.template(templateText);
},
addException: function(){
var value = this.$("#certificate-exception").val();
var notes = this.$("#notes").val();
var user_email = '', user_name='', model={};
addException: function() {
var value = this.$('#certificate-exception').val();
var notes = this.$('#notes').val();
var user_email = '', user_name = '', model = {};
if(this.isEmailAddress(value)){
if (this.isEmailAddress(value)) {
user_email = value;
model = {user_email: user_email};
}
else{
else {
user_name = value;
model = {user_name: user_name};
}
......@@ -55,15 +55,15 @@
url: this.collection.url
}
);
var message = "";
var message = '';
if(this.collection.findWhere(model)){
message = gettext("<%= user %> already in exception list.");
if (this.collection.findWhere(model)) {
message = gettext('<%= user %> already in exception list.');
this.escapeAndShowMessage(
_.template(message)({user: (user_name || user_email)})
);
}
else if(certificate_exception.isValid()){
else if (certificate_exception.isValid()) {
message = gettext('<%= user %> has been successfully added to the exception list. Click Generate Exception Certificate below to send the certificate.'); // eslint-disable-line max-len
certificate_exception.save(
null,
......@@ -76,9 +76,8 @@
error: this.showError(this)
}
);
}
else{
else {
this.escapeAndShowMessage(certificate_exception.validationError);
}
},
......@@ -88,29 +87,29 @@
return re.test(email);
},
escapeAndShowMessage: function(message){
$(this.message_div + ">p" ).remove();
this.$(this.message_div).removeClass('hidden').append("<p>"+ _.escape(message) + "</p>");
escapeAndShowMessage: function(message) {
$(this.message_div + '>p').remove();
this.$(this.message_div).removeClass('hidden').append('<p>' + _.escape(message) + '</p>');
},
showSuccess: function(caller, add_model, message){
return function(model){
if(add_model){
showSuccess: function(caller, add_model, message) {
return function(model) {
if (add_model) {
caller.collection.add(model);
}
caller.escapeAndShowMessage(message);
};
},
showError: function(caller){
return function(model, response){
try{
showError: function(caller) {
return function(model, response) {
try {
var response_data = JSON.parse(response.responseText);
caller.escapeAndShowMessage(response_data.message);
}
catch(exception){
catch (exception) {
caller.escapeAndShowMessage(
gettext("Server Error, Please refresh the page and try again.")
gettext('Server Error, Please refresh the page and try again.')
);
}
};
......
......@@ -3,13 +3,13 @@
*/
var edx = edx || {};
(function ($, _) {
(function($, _) {
'use strict';
edx.commerce = edx.commerce || {};
edx.commerce.credit = edx.commerce.credit || {};
edx.commerce.credit.createCreditRequest = function (providerId, courseKey, username) {
edx.commerce.credit.createCreditRequest = function(providerId, courseKey, username) {
return $.ajax({
url: '/api/credit/v1/providers/' + providerId + '/request/',
type: 'POST',
......@@ -23,7 +23,7 @@ var edx = edx || {};
'username': username
}),
context: this,
success: function (requestData) {
success: function(requestData) {
var $form = $('<form>', {
'class': 'hidden',
'action': requestData.url,
......@@ -31,7 +31,7 @@ var edx = edx || {};
'accept-method': 'UTF-8'
});
_.each(requestData.parameters, function (value, key) {
_.each(requestData.parameters, function(value, key) {
$('<textarea>').attr({
name: key,
value: value
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment