diff --git a/.eslintrc.json b/.eslintrc.json index 9cc8eb1a57..7c3b44d431 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -49,7 +49,6 @@ "import/no-dynamic-require": "off", "import/no-unresolved": "off", "max-len": "off", - "newline-per-chained-call": "off", "no-console": "off", "no-lonely-if": "off", "no-param-reassign": "off", @@ -69,11 +68,9 @@ "prefer-arrow-callback": "off", "prefer-destructuring": "off", "prefer-rest-params": "off", - "prefer-template": "off", "radix": "off", "react/jsx-indent-props": ["error", 4], "react/prop-types": "off", - "semi": "off", "vars-on-top": "off" } } diff --git a/cms/static/cms/js/require-config.js b/cms/static/cms/js/require-config.js index db784c45cb..94dc59d8c0 100644 --- a/cms/static/cms/js/require-config.js +++ b/cms/static/cms/js/require-config.js @@ -28,7 +28,7 @@ define(name, [], function() { return globalValue; }); } } else { - console.error('Expected library to be included on page, but not found on window object: ' + name); + console.error(`Expected library to be included on page, but not found on window object: ${name}`); } }; diff --git a/cms/static/cms/js/spec/main.js b/cms/static/cms/js/spec/main.js index 46a20ac517..07abfd1469 100644 --- a/cms/static/cms/js/spec/main.js +++ b/cms/static/cms/js/spec/main.js @@ -286,7 +286,7 @@ i = 0; while (i < testFiles.length) { - testFiles[i] = '/base/' + testFiles[i] + '.js'; + testFiles[i] = `/base/${testFiles[i]}.js`; i++; } diff --git a/cms/static/cms/js/spec/main_squire.js b/cms/static/cms/js/spec/main_squire.js index 8feb056922..6dcc64718a 100644 --- a/cms/static/cms/js/spec/main_squire.js +++ b/cms/static/cms/js/spec/main_squire.js @@ -199,7 +199,7 @@ i = 0; while (i < testFiles.length) { - testFiles[i] = '/base/' + testFiles[i] + '.js'; + testFiles[i] = `/base/${testFiles[i]}.js`; i++; } diff --git a/cms/static/cms/js/spec/main_webpack.js b/cms/static/cms/js/spec/main_webpack.js index 020b4d313f..801fb68b50 100644 --- a/cms/static/cms/js/spec/main_webpack.js +++ b/cms/static/cms/js/spec/main_webpack.js @@ -12,6 +12,7 @@ import _ from 'underscore'; import str from 'underscore.string'; import HtmlUtils from 'edx-ui-toolkit/js/utils/html-utils'; import StringUtils from 'edx-ui-toolkit/js/utils/string-utils'; + window._ = _; window._.str = str; window.edx = window.edx || {}; diff --git a/cms/static/js/certificates/models/certificate.js b/cms/static/js/certificates/models/certificate.js index 8ca59d7b09..769c343d64 100644 --- a/cms/static/js/certificates/models/certificate.js +++ b/cms/static/js/certificates/models/certificate.js @@ -67,7 +67,7 @@ function(_, Backbone, BackboneRelational, BackboneAssociations, gettext, CoffeeS // If no url is defined for the signatories child collection we'll need to create that here as well if (!this.isNew() && !this.get('signatories').url) { - this.get('signatories').url = this.collection.url + '/' + this.get('id') + '/signatories'; + this.get('signatories').url = `${this.collection.url}/${this.get('id')}/signatories`; } }, diff --git a/cms/static/js/certificates/spec/custom_matchers.js b/cms/static/js/certificates/spec/custom_matchers.js index 18062476b8..32e19dec6a 100644 --- a/cms/static/js/certificates/spec/custom_matchers.js +++ b/cms/static/js/certificates/spec/custom_matchers.js @@ -2,8 +2,8 @@ // http://tobyho.com/2012/01/30/write-a-jasmine-matcher/ define(['jquery'], function($) { // eslint-disable-line no-unused-vars - -'use strict'; + + 'use strict'; return function() { jasmine.addMatchers({ diff --git a/cms/static/js/certificates/spec/views/certificate_details_spec.js b/cms/static/js/certificates/spec/views/certificate_details_spec.js index b803bd0cbe..12754bcd3b 100644 --- a/cms/static/js/certificates/spec/views/certificate_details_spec.js +++ b/cms/static/js/certificates/spec/views/certificate_details_spec.js @@ -97,7 +97,7 @@ function(_, Course, CertificatesCollection, CertificateModel, CertificateDetails }, this.newModelOptions); this.collection = new CertificatesCollection([this.model], { - certificateUrl: '/certificates/' + window.course.id + certificateUrl: `/certificates/${window.course.id}` }); this.model.set('id', 0); this.view = new CertificateDetailsView({ @@ -121,7 +121,7 @@ function(_, Course, CertificatesCollection, CertificateModel, CertificateDetails describe('The Certificate Details view', function() { it('should parse a JSON string collection into a Backbone model collection', function() { var course_title = 'Test certificate course title override 2'; - var CERTIFICATE_JSON = '[{"course_title": "' + course_title + '", "signatories":"[]"}]'; + var CERTIFICATE_JSON = `[{"course_title": "${course_title}", "signatories":"[]"}]`; this.collection.parse(CERTIFICATE_JSON); var model = this.collection.at(1); expect(model.get('course_title')).toEqual(course_title); diff --git a/cms/static/js/certificates/spec/views/certificate_editor_spec.js b/cms/static/js/certificates/spec/views/certificate_editor_spec.js index 64ef492c82..12c85c6d5c 100644 --- a/cms/static/js/certificates/spec/views/certificate_editor_spec.js +++ b/cms/static/js/certificates/spec/views/certificate_editor_spec.js @@ -111,7 +111,7 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce }, this.newModelOptions); this.collection = new CertificatesCollection([this.model], { - certificateUrl: '/certificates/' + window.course.id + certificateUrl: `/certificates/${window.course.id}` }); this.model.set('id', 0); this.view = new CertificateEditorView({ @@ -220,8 +220,8 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce // now delete anyone of the signatory, Add signatory should be enabled. var signatory = this.model.get('signatories').at(0); - var text = 'Delete "' + signatory.get('name') + '" from the list of signatories?'; - clickDeleteItem(this, text, SELECTORS.signatoryDeleteButton + ':first'); + var text = `Delete "${signatory.get('name')}" from the list of signatories?`; + clickDeleteItem(this, text, `${SELECTORS.signatoryDeleteButton}:first`); expect(this.view.$(SELECTORS.addSignatoryButton)).not.toHaveClass('disableClick'); } ); @@ -273,8 +273,8 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce var signatory_url = '/certificates/signatory'; signatory.url = signatory_url; spyOn(signatory, 'isNew').and.returnValue(false); - var text = 'Delete "' + signatory.get('name') + '" from the list of signatories?'; - clickDeleteItem(this, text, SELECTORS.signatoryDeleteButton + ':first', signatory_url); + var text = `Delete "${signatory.get('name')}" from the list of signatories?`; + clickDeleteItem(this, text, `${SELECTORS.signatoryDeleteButton}:first`, signatory_url); expect(this.model.get('signatories').length).toEqual(total_signatories - 1); }); @@ -287,8 +287,8 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce var total_signatories = this.model.get('signatories').length; var signatory_url = '/certificates/signatory'; signatory.url = signatory_url; - var text = 'Delete "' + signatory.get('name') + '" from the list of signatories?'; - showConfirmPromptAndClickCancel(this.view, SELECTORS.signatoryDeleteButton + ':first', text); + var text = `Delete "${signatory.get('name')}" from the list of signatories?`; + showConfirmPromptAndClickCancel(this.view, `${SELECTORS.signatoryDeleteButton}:first`, text); expect(this.model.get('signatories').length).toEqual(total_signatories); }); diff --git a/cms/static/js/certificates/spec/views/certificate_preview_spec.js b/cms/static/js/certificates/spec/views/certificate_preview_spec.js index 741c7c5996..16a70b9ab7 100644 --- a/cms/static/js/certificates/spec/views/certificate_preview_spec.js +++ b/cms/static/js/certificates/spec/views/certificate_preview_spec.js @@ -43,7 +43,7 @@ function(_, $, Course, CertificatePreview, TemplateHelpers, ViewHelpers, AjaxHel el: $('.preview-certificate'), course_modes: ['test1', 'test2', 'test3'], certificate_web_view_url: '/users/1/courses/orgX/009/2016?preview=test1', - certificate_activation_handler_url: '/certificates/activation/' + window.course.id, + certificate_activation_handler_url: `/certificates/activation/${window.course.id}`, is_active: true }); appendSetFixtures(this.view.render().el); @@ -64,16 +64,16 @@ function(_, $, Course, CertificatePreview, TemplateHelpers, ViewHelpers, AjaxHel it('course mode selection updating the link successfully', function() { selectDropDownByText(this.view.$(SELECTORS.course_modes), 'test1'); - expect(this.view.$(SELECTORS.preview_certificate).attr('href')). - toEqual('/users/1/courses/orgX/009/2016?preview=test1'); + expect(this.view.$(SELECTORS.preview_certificate).attr('href')) + .toEqual('/users/1/courses/orgX/009/2016?preview=test1'); selectDropDownByText(this.view.$(SELECTORS.course_modes), 'test2'); - expect(this.view.$(SELECTORS.preview_certificate).attr('href')). - toEqual('/users/1/courses/orgX/009/2016?preview=test2'); + expect(this.view.$(SELECTORS.preview_certificate).attr('href')) + .toEqual('/users/1/courses/orgX/009/2016?preview=test2'); selectDropDownByText(this.view.$(SELECTORS.course_modes), 'test3'); - expect(this.view.$(SELECTORS.preview_certificate).attr('href')). - toEqual('/users/1/courses/orgX/009/2016?preview=test3'); + expect(this.view.$(SELECTORS.preview_certificate).attr('href')) + .toEqual('/users/1/courses/orgX/009/2016?preview=test3'); }); it('toggle certificate activation event works fine', function() { @@ -87,7 +87,7 @@ function(_, $, Course, CertificatePreview, TemplateHelpers, ViewHelpers, AjaxHel var requests = AjaxHelpers.requests(this), notificationSpy = ViewHelpers.createNotificationSpy(); this.view.$(SELECTORS.activate_certificate).click(); - AjaxHelpers.expectJsonRequest(requests, 'POST', '/certificates/activation/' + window.course.id, { + AjaxHelpers.expectJsonRequest(requests, 'POST', `/certificates/activation/${window.course.id}`, { is_active: false }); ViewHelpers.verifyNotificationShowing(notificationSpy, /Deactivating/); @@ -98,7 +98,7 @@ function(_, $, Course, CertificatePreview, TemplateHelpers, ViewHelpers, AjaxHel notificationSpy = ViewHelpers.createNotificationSpy(); this.view.is_active = false; this.view.$(SELECTORS.activate_certificate).click(); - AjaxHelpers.expectJsonRequest(requests, 'POST', '/certificates/activation/' + window.course.id, { + AjaxHelpers.expectJsonRequest(requests, 'POST', `/certificates/activation/${window.course.id}`, { is_active: true }); ViewHelpers.verifyNotificationShowing(notificationSpy, /Activating/); diff --git a/cms/static/js/certificates/spec/views/certificates_list_spec.js b/cms/static/js/certificates/spec/views/certificates_list_spec.js index fec1829611..ff07936e99 100644 --- a/cms/static/js/certificates/spec/views/certificates_list_spec.js +++ b/cms/static/js/certificates/spec/views/certificates_list_spec.js @@ -54,7 +54,7 @@ function(_, Course, CertificatesCollection, CertificateModel, CertificateDetails }, {add: true}); this.collection = new CertificatesCollection([], { - certificateUrl: '/certificates/' + window.course.id + certificateUrl: `/certificates/${window.course.id}` }); this.model.set('id', 0); this.view = new CertificatesListView({ diff --git a/cms/static/js/certificates/views/certificate_editor.js b/cms/static/js/certificates/views/certificate_editor.js index e81da1b2b4..6a04fd6f4a 100644 --- a/cms/static/js/certificates/views/certificate_editor.js +++ b/cms/static/js/certificates/views/certificate_editor.js @@ -39,7 +39,7 @@ function($, _, Backbone, gettext, 'collection-edit', 'certificates', 'certificate-edit', - 'certificate-edit-' + index + `certificate-edit-${index}` ].join(' '); }, diff --git a/cms/static/js/certificates/views/certificate_preview.js b/cms/static/js/certificates/views/certificate_preview.js index 741d4d9669..b834ca9a04 100644 --- a/cms/static/js/certificates/views/certificate_preview.js +++ b/cms/static/js/certificates/views/certificate_preview.js @@ -63,7 +63,7 @@ function(_, gettext, BaseView, ViewUtils, NotificationView, certificateWebPrevie courseModeChanged: function(event) { $('.preview-certificate-link').attr('href', function(index, value) { return value.replace(/preview=([^&]+)/, function() { - return 'preview=' + event.target.options[event.target.selectedIndex].text; + return `preview=${event.target.options[event.target.selectedIndex].text}`; }); }); }, diff --git a/cms/static/js/certificates/views/signatory_details.js b/cms/static/js/certificates/views/signatory_details.js index 6caf73dd55..7a41d20417 100644 --- a/cms/static/js/certificates/views/signatory_details.js +++ b/cms/static/js/certificates/views/signatory_details.js @@ -32,7 +32,7 @@ function($, _, str, Backbone, gettext, TemplateUtils, ViewUtils, BaseView, Signa var index = this.model.collection.indexOf(this.model); return [ 'signatory-details', - 'signatory-details-view-' + index + `signatory-details-view-${index}` ].join(' '); }, diff --git a/cms/static/js/certificates/views/signatory_editor.js b/cms/static/js/certificates/views/signatory_editor.js index e0dd135733..57a218fe30 100644 --- a/cms/static/js/certificates/views/signatory_editor.js +++ b/cms/static/js/certificates/views/signatory_editor.js @@ -35,7 +35,7 @@ function($, _, Backbone, gettext, var index = this.getModelIndex(this.model); return [ 'signatory-edit', - 'signatory-edit-view-' + index + `signatory-edit-view-${index}` ].join(' '); }, @@ -194,7 +194,7 @@ function($, _, Backbone, gettext, * @param string modelAttribute - the attribute of the signatory model e.g. name, title. */ toggleValidationErrorMessage: function(modelAttribute) { - var selector = 'div.add-signatory-' + modelAttribute; + var selector = `div.add-signatory-${modelAttribute}`; var errorMessage; if (!this.model.isValid() && _.has(this.model.validationError, modelAttribute)) { // Show the error message if it is not exist before. @@ -206,7 +206,7 @@ function($, _, Backbone, gettext, } else { // Remove the error message. $(selector).removeClass('error'); - $(selector + '>span.message-error').remove(); + $(`${selector}>span.message-error`).remove(); } } diff --git a/cms/static/js/factories/container.js b/cms/static/js/factories/container.js index cfca298851..892eb61960 100644 --- a/cms/static/js/factories/container.js +++ b/cms/static/js/factories/container.js @@ -23,4 +23,4 @@ export default function ContainerFactory(componentTemplates, XBlockInfoJson, act }); }; -export {ContainerFactory} +export {ContainerFactory}; diff --git a/cms/static/js/factories/context_course.js b/cms/static/js/factories/context_course.js index 475e5a6282..24745295ec 100644 --- a/cms/static/js/factories/context_course.js +++ b/cms/static/js/factories/context_course.js @@ -1,3 +1,3 @@ import * as ContextCourse from 'js/models/course'; -export {ContextCourse} +export {ContextCourse}; diff --git a/cms/static/js/factories/edit_tabs.js b/cms/static/js/factories/edit_tabs.js index 51688bf6a1..5ec459e520 100644 --- a/cms/static/js/factories/edit_tabs.js +++ b/cms/static/js/factories/edit_tabs.js @@ -23,4 +23,4 @@ export default function EditTabsFactory(courseLocation, explicitUrl) { }); }; -export {EditTabsFactory} +export {EditTabsFactory}; diff --git a/cms/static/js/factories/library.js b/cms/static/js/factories/library.js index 7f8d458502..0e72bdb4b4 100644 --- a/cms/static/js/factories/library.js +++ b/cms/static/js/factories/library.js @@ -26,4 +26,4 @@ export default function LibraryFactory(componentTemplates, XBlockInfoJson, optio }); }; -export {LibraryFactory} +export {LibraryFactory}; diff --git a/cms/static/js/factories/settings.js b/cms/static/js/factories/settings.js index b170731397..90854f6a92 100644 --- a/cms/static/js/factories/settings.js +++ b/cms/static/js/factories/settings.js @@ -8,7 +8,7 @@ define([ // highlighting labels when fields are focused in $('form :input') .focus(function() { - $('label[for="' + this.id + '"]').addClass('is-focused'); + $(`label[for="${this.id}"]`).addClass('is-focused'); }) .blur(function() { $('label').removeClass('is-focused'); @@ -16,9 +16,9 @@ define([ // Toggle collapsibles when trigger is clicked $('.collapsible .collapsible-trigger').click(function() { - const contentId = this.id.replace('-trigger', '-content') - $(`#${contentId}`).toggleClass('collapsed') - }) + const contentId = this.id.replace('-trigger', '-content'); + $(`#${contentId}`).toggleClass('collapsed'); + }); model = new CourseDetailsModel(); model.urlRoot = detailsUrl; diff --git a/cms/static/js/factories/settings_advanced.js b/cms/static/js/factories/settings_advanced.js index 4ddc2305d6..bdbc3ce92b 100644 --- a/cms/static/js/factories/settings_advanced.js +++ b/cms/static/js/factories/settings_advanced.js @@ -8,7 +8,7 @@ define([ $('form :input') .focus(function() { - $('label[for="' + this.id + '"]').addClass('is-focused'); + $(`label[for="${this.id}"]`).addClass('is-focused'); }) .blur(function() { $('label').removeClass('is-focused'); diff --git a/cms/static/js/factories/settings_graders.js b/cms/static/js/factories/settings_graders.js index dc75029e0f..8a02defbe4 100644 --- a/cms/static/js/factories/settings_graders.js +++ b/cms/static/js/factories/settings_graders.js @@ -8,7 +8,7 @@ define([ $('form :input') .focus(function() { - $('label[for="' + this.id + '"]').addClass('is-focused'); + $(`label[for="${this.id}"]`).addClass('is-focused'); }) .blur(function() { $('label').removeClass('is-focused'); diff --git a/cms/static/js/factories/textbooks.js b/cms/static/js/factories/textbooks.js index 01950f867f..a257b36886 100644 --- a/cms/static/js/factories/textbooks.js +++ b/cms/static/js/factories/textbooks.js @@ -21,4 +21,4 @@ export default function TextbooksFactory(textbooksJson) { }); }; -export {TextbooksFactory} +export {TextbooksFactory}; diff --git a/cms/static/js/factories/xblock_validation.js b/cms/static/js/factories/xblock_validation.js index 0411dc9150..03bee7547c 100644 --- a/cms/static/js/factories/xblock_validation.js +++ b/cms/static/js/factories/xblock_validation.js @@ -18,4 +18,4 @@ export default function XBlockValidationFactory(validationMessages, hasEditingUr } }; -export {XBlockValidationFactory} +export {XBlockValidationFactory}; diff --git a/cms/static/js/features/import/factories/import.js b/cms/static/js/features/import/factories/import.js index 6b81540dbe..39a29ec934 100644 --- a/cms/static/js/features/import/factories/import.js +++ b/cms/static/js/features/import/factories/import.js @@ -17,10 +17,10 @@ define([ $submitBtn = $('.submit-button'), $chooseBtn = $('.view-import .choose-file-button'), defaults = [ - gettext('There was an error during the upload process.') + '\n', - gettext('There was an error while unpacking the file.') + '\n', - gettext('There was an error while verifying the file you submitted.') + '\n', - dbError + '\n' + `${gettext('There was an error during the upload process.')}\n`, + `${gettext('There was an error while unpacking the file.')}\n`, + `${gettext('There was an error while verifying the file you submitted.')}\n`, + `${dbError}\n` ], unloading = false, previousImport = Import.storedImport(), @@ -116,7 +116,7 @@ define([ Import.reset(); onComplete(); - alert(gettext('Your import has failed.') + '\n\n' + errMsg); // eslint-disable-line max-len, no-alert + alert(`${gettext('Your import has failed.')}\n\n${errMsg}`); // eslint-disable-line max-len, no-alert } } }); @@ -130,7 +130,7 @@ define([ progressall: function(e, data) { var percentInt = data.loaded / data.total * 100, - percentVal = parseInt(percentInt, 10) + '%', + percentVal = `${parseInt(percentInt, 10)}%`, doneAt; // Firefox makes ProgressEvent.loaded equal ProgressEvent.total only // after receiving a response from the server (see Mozilla bug 637002), diff --git a/cms/static/js/features/import/views/import.js b/cms/static/js/features/import/views/import.js index e34965a092..42b36b133c 100644 --- a/cms/static/js/features/import/views/import.js +++ b/cms/static/js/features/import/views/import.js @@ -151,7 +151,7 @@ define( $dom.successStage .find('.item-progresspoint-success-date') - .text('(' + date + ' at ' + time + ' UTC)'); + .text(`(${date} at ${time} UTC)`); break; diff --git a/cms/static/js/index.js b/cms/static/js/index.js index b27f0e0c0d..38a496afd9 100644 --- a/cms/static/js/index.js +++ b/cms/static/js/index.js @@ -89,13 +89,13 @@ function(domReady, $, _, CancelOnEscape, CreateCourseUtilsFactory, CreateLibrary var makeCancelHandler = function(addType) { return function(e) { e.preventDefault(); - $('.new-' + addType + '-button').removeClass('is-disabled').attr('aria-disabled', false); - $('.wrapper-create-' + addType).removeClass('is-shown'); + $(`.new-${addType}-button`).removeClass('is-disabled').attr('aria-disabled', false); + $(`.wrapper-create-${addType}`).removeClass('is-shown'); // Clear out existing fields and errors - $('#create-' + addType + '-form input[type=text]').val(''); - $('#' + addType + '_creation_error').html(''); - $('.create-' + addType + ' .wrap-error').removeClass('is-shown'); - $('.new-' + addType + '-save').off('click'); + $(`#create-${addType}-form input[type=text]`).val(''); + $(`#${addType}_creation_error`).html(''); + $(`.create-${addType} .wrap-error`).removeClass('is-shown'); + $(`.new-${addType}-save`).off('click'); }; }; diff --git a/cms/static/js/maintenance/force_publish_course.js b/cms/static/js/maintenance/force_publish_course.js index 642b5bea4f..817efcb083 100644 --- a/cms/static/js/maintenance/force_publish_course.js +++ b/cms/static/js/maintenance/force_publish_course.js @@ -22,7 +22,7 @@ function($, _, gettext, ViewUtils, StringUtils, HtmlUtils) { showError = function(containerElSelector, error) { var errorWrapperElSelector, errorHtml; - errorWrapperElSelector = containerElSelector + ' .wrapper-error'; + errorWrapperElSelector = `${containerElSelector} .wrapper-error`; errorHtml = HtmlUtils.joinHtml( HtmlUtils.HTML('
'), error, diff --git a/cms/static/js/models/assignment_grade.js b/cms/static/js/models/assignment_grade.js index 86db8d3a13..5ab85f2329 100644 --- a/cms/static/js/models/assignment_grade.js +++ b/cms/static/js/models/assignment_grade.js @@ -8,7 +8,7 @@ define(['backbone', 'underscore'], function(Backbone, _) { urlRoot: '/xblock/', url: function() { // add ?fields=graderType to the request url (only needed for fetch, but innocuous for others) - return Backbone.Model.prototype.url.apply(this) + '?' + $.param({fields: 'graderType'}); + return `${Backbone.Model.prototype.url.apply(this)}?${$.param({fields: 'graderType'})}`; } }); return AssignmentGrade; diff --git a/cms/static/js/models/custom_sync_xblock_info.js b/cms/static/js/models/custom_sync_xblock_info.js index 8e9569d5fd..b96d1cbace 100644 --- a/cms/static/js/models/custom_sync_xblock_info.js +++ b/cms/static/js/models/custom_sync_xblock_info.js @@ -2,7 +2,7 @@ define(['js/models/xblock_info'], function(XBlockInfo) { var CustomSyncXBlockInfo = XBlockInfo.extend({ sync: function(method, model, options) { - options.url = (this.urlRoots[method] || this.urlRoot) + '/' + this.get('id'); + options.url = `${this.urlRoots[method] || this.urlRoot}/${this.get('id')}`; return XBlockInfo.prototype.sync.call(this, method, model, options); } }); diff --git a/cms/static/js/models/group.js b/cms/static/js/models/group.js index b61a27f467..335b3a72ba 100644 --- a/cms/static/js/models/group.js +++ b/cms/static/js/models/group.js @@ -15,7 +15,7 @@ define([ }, url: function() { var parentModel = this.collection.parents[0]; - return parentModel.urlRoot + '/' + encodeURIComponent(parentModel.id) + '/' + encodeURIComponent(this.id); + return `${parentModel.urlRoot}/${encodeURIComponent(parentModel.id)}/${encodeURIComponent(this.id)}`; }, reset: function() { diff --git a/cms/static/js/models/license.js b/cms/static/js/models/license.js index e60c174e2a..f9fbb4550a 100644 --- a/cms/static/js/models/license.js +++ b/cms/static/js/models/license.js @@ -31,13 +31,13 @@ define(['backbone', 'underscore'], function(Backbone, _) { if (_.isBoolean(value)) { return value ? key : null; } else { - return key + '=' + value; + return `${key}=${value}`; } }); // filter out nulls optionStrings = _.filter(optionStrings, _.identity); // build license string and return - return type + ': ' + optionStrings.join(' '); + return `${type}: ${optionStrings.join(' ')}`; }, setFromString: function(string, options) { diff --git a/cms/static/js/models/location.js b/cms/static/js/models/location.js index 75b4ecb633..011dbef309 100644 --- a/cms/static/js/models/location.js +++ b/cms/static/js/models/location.js @@ -9,11 +9,11 @@ define(['backbone', 'underscore'], function(Backbone, _) { }, toUrl: function(overrides) { return; - (overrides && overrides.tag ? overrides.tag : this.get('tag')) + '://' - + (overrides && overrides.org ? overrides.org : this.get('org')) + '/' - + (overrides && overrides.course ? overrides.course : this.get('course')) + '/' - + (overrides && overrides.category ? overrides.category : this.get('category')) + '/' - + (overrides && overrides.name ? overrides.name : this.get('name')) + '/'; + `${overrides && overrides.tag ? overrides.tag : this.get('tag')}://${ + overrides && overrides.org ? overrides.org : this.get('org')}/${ + overrides && overrides.course ? overrides.course : this.get('course')}/${ + overrides && overrides.category ? overrides.category : this.get('category')}/${ + overrides && overrides.name ? overrides.name : this.get('name')}/`; }, _tagPattern: /[^:]+/g, _fieldPattern: new RegExp('[^/]+', 'g'), diff --git a/cms/static/js/models/settings/course_details.js b/cms/static/js/models/settings/course_details.js index 302f214fd6..83235601b9 100644 --- a/cms/static/js/models/settings/course_details.js +++ b/cms/static/js/models/settings/course_details.js @@ -153,7 +153,7 @@ function(Backbone, _, gettext, ValidationHelpers, DateUtils, StringUtils) { }, videosourceSample: function() { - if (this.has('intro_video')) { return '//www.youtube.com/embed/' + this.get('intro_video'); } else { return ''; } + if (this.has('intro_video')) { return `//www.youtube.com/embed/${this.get('intro_video')}`; } else { return ''; } }, // Whether or not the course pacing can be toggled. If the course diff --git a/cms/static/js/models/settings/course_grading_policy.js b/cms/static/js/models/settings/course_grading_policy.js index 498815cf13..4ed105c7ee 100644 --- a/cms/static/js/models/settings/course_grading_policy.js +++ b/cms/static/js/models/settings/course_grading_policy.js @@ -10,7 +10,7 @@ define(['backbone', 'js/models/location', 'js/collections/course_grader', 'edx-u grace_period: null, // either null or { hours: n, minutes: m, ...} minimum_grade_credit: null, // either null or percentage assignment_count_info: [], // Object with keys mapping assignment type names to a list of - //assignment display names + // assignment display names }, parse: function(attributes) { if (attributes.graders) { diff --git a/cms/static/js/models/uploads.js b/cms/static/js/models/uploads.js index 6e3879e1f3..e2d26b2ab3 100644 --- a/cms/static/js/models/uploads.js +++ b/cms/static/js/models/uploads.js @@ -42,7 +42,7 @@ define(['backbone', 'underscore', 'gettext'], function(Backbone, _, gettext) { var attrs = this.attributes, getRegExp = function(formats) { // Creates regular expression like: /(?:.+)\.(jpg|png|gif)$/i - return RegExp(('(?:.+)\\.(' + formats.join('|') + ')$'), 'i'); + return RegExp((`(?:.+)\\.(${formats.join('|')})$`), 'i'); }; return (attrs.mimeTypes.length === 0 && attrs.fileFormats.length === 0) @@ -57,7 +57,7 @@ define(['backbone', 'underscore', 'gettext'], function(Backbone, _, gettext) { if (attrs.mimeTypes.concat(attrs.fileFormats).length === 1) { return { fileTypes: this.fileTypes()[0], - fileExtensions: '.' + this.fileTypes()[0].toLowerCase() + fileExtensions: `.${this.fileTypes()[0].toLowerCase()}` }; } var or = gettext('or'); @@ -73,7 +73,7 @@ define(['backbone', 'underscore', 'gettext'], function(Backbone, _, gettext) { fileExtensions: formatTypes( _.map(this.fileTypes(), function(type) { - return '.' + type.toLowerCase(); + return `.${type.toLowerCase()}`; }) ) }; diff --git a/cms/static/js/models/xblock_info.js b/cms/static/js/models/xblock_info.js index ea64061e9d..8447478f96 100644 --- a/cms/static/js/models/xblock_info.js +++ b/cms/static/js/models/xblock_info.js @@ -251,7 +251,7 @@ define( helpers = {}; _.each(categories, function(item) { - helpers['is' + str.titleize(item)] = function() { + helpers[`is${str.titleize(item)}`] = function() { return this.get('category') === item; }; }, this); diff --git a/cms/static/js/sock.js b/cms/static/js/sock.js index 43c41ba254..1512ec51bc 100644 --- a/cms/static/js/sock.js +++ b/cms/static/js/sock.js @@ -4,7 +4,7 @@ import 'jquery.smoothScroll'; 'use strict'; -var toggleSock = function (e) { +var toggleSock = function(e) { e.preventDefault(); var $btnShowSockLabel = $(this).find('.copy-show'); @@ -33,9 +33,9 @@ var toggleSock = function (e) { }); }; -domReady(function () { +domReady(function() { // toggling footer additional support $('.cta-show-sock').bind('click', toggleSock); }); -export {toggleSock} +export {toggleSock}; diff --git a/cms/static/js/spec/utils/handle_iframe_binding_spec.js b/cms/static/js/spec/utils/handle_iframe_binding_spec.js index 9cf632161a..3f652d2c6a 100644 --- a/cms/static/js/spec/utils/handle_iframe_binding_spec.js +++ b/cms/static/js/spec/utils/handle_iframe_binding_spec.js @@ -12,7 +12,7 @@ define( doc.body.innerHTML = iframe_html; var verify_no_modification = function(src) { - iframe_html = ''; + iframe_html = ``; doc.body.innerHTML = iframe_html; IframeBinding.iframeBinding(doc); diff --git a/cms/static/js/spec/video/file_uploader_editor_spec.js b/cms/static/js/spec/video/file_uploader_editor_spec.js index 145b262a3c..552c59cb67 100644 --- a/cms/static/js/spec/video/file_uploader_editor_spec.js +++ b/cms/static/js/spec/video/file_uploader_editor_spec.js @@ -50,7 +50,7 @@ define( return { pass: passed, - message: 'Expected ' + actual + (passed ? '' : ' not') + ' to equal ' + expected + message: `Expected ${actual}${passed ? '' : ' not'} to equal ${expected}` }; } }; @@ -69,7 +69,7 @@ define( return { pass: passed, - message: 'Expected ' + actual + (passed ? '' : ' not') + ' to equal ' + expected + message: `Expected ${actual}${passed ? '' : ' not'} to equal ${expected}` }; } }; diff --git a/cms/static/js/spec/video/transcripts/editor_spec.js b/cms/static/js/spec/video/transcripts/editor_spec.js index def29d5040..050bdbd240 100644 --- a/cms/static/js/spec/video/transcripts/editor_spec.js +++ b/cms/static/js/spec/video/transcripts/editor_spec.js @@ -181,7 +181,7 @@ define( }); $.each(metadataDict, function(index, val) { - it('toModels with argument as ' + index, function() { + it(`toModels with argument as ${index}`, function() { expect(transcripts.toModels(val)).toEqual(models); }); }); diff --git a/cms/static/js/spec/video/transcripts/file_uploader_spec.js b/cms/static/js/spec/video/transcripts/file_uploader_spec.js index 03de571d11..4373b478f7 100644 --- a/cms/static/js/spec/video/transcripts/file_uploader_spec.js +++ b/cms/static/js/spec/video/transcripts/file_uploader_spec.js @@ -81,7 +81,7 @@ define( var elList = ['$form', '$input', '$progress'], validFileExtensions = ['srt', 'sjson'], result = $.map(validFileExtensions, function(item, index) { - return '.' + item; + return `.${item}`; }).join(', '); view.validFileExtensions = validFileExtensions; @@ -169,7 +169,7 @@ define( }; $.each(data, function(fileType, fileInfo) { - it(fileType + ' file type', function() { + it(`${fileType} file type`, function() { var result = view.checkExtValidity(fileInfo); expect(result).toBe(fileInfo.isValid); @@ -190,8 +190,8 @@ define( spyOn($.fn, 'width').and.callThrough(); view.xhrProgressHandler(null, null, null, percent); - expect(view.$progress.width).toHaveBeenCalledWith(percent + '%'); - expect(view.$progress.html()).toBe(percent + '%'); + expect(view.$progress.width).toHaveBeenCalledWith(`${percent}%`); + expect(view.$progress.html()).toBe(`${percent}%`); }); describe('xhrCompleteHandler', function() { diff --git a/cms/static/js/spec/video/transcripts/utils_spec.js b/cms/static/js/spec/video/transcripts/utils_spec.js index 13f948bbbd..923f9b4427 100644 --- a/cms/static/js/spec/video/transcripts/utils_spec.js +++ b/cms/static/js/spec/video/transcripts/utils_spec.js @@ -104,7 +104,7 @@ define( ]; $.each(wrongArgumentLists, function(index, element) { - it(element.argName + ' argument(s) is/are absent', function() { + it(`${element.argName} argument(s) is/are absent`, function() { var result = Utils.getField.apply(this, element.list); expect(result).toBeUndefined(); @@ -221,7 +221,7 @@ define( it('Method: getYoutubeLink', function() { var videoId = 'video_id', result = Utils.getYoutubeLink(videoId), - expectedResult = 'http://youtu.be/' + videoId; + expectedResult = `http://youtu.be/${videoId}`; expect(result).toBe(expectedResult); }); @@ -263,7 +263,7 @@ define( describe('Wrong arguments ', function() { it('youtube videoId is wrong', function() { var videoId = 'wrong_id', - link = 'http://youtu.be/' + videoId, + link = `http://youtu.be/${videoId}`, result = Utils.parseLink(link); expect(result).toEqual({mode: 'incorrect'}); diff --git a/cms/static/js/spec/video/translations_editor_spec.js b/cms/static/js/spec/video/translations_editor_spec.js index 50f96d6885..59d8dc0637 100644 --- a/cms/static/js/spec/video/translations_editor_spec.js +++ b/cms/static/js/spec/video/translations_editor_spec.js @@ -65,7 +65,7 @@ define( return { pass: passed, - message: 'Expected ' + actual + (passed ? '' : ' not') + ' to equal ' + expected + message: `Expected ${actual}${passed ? '' : ' not'} to equal ${expected}` }; } }; @@ -83,7 +83,7 @@ define( return { pass: passed, - message: 'Expected ' + actual + (passed ? '' : ' not') + ' to equal ' + expected + message: `Expected ${actual}${passed ? '' : ' not'} to equal ${expected}` }; } }; diff --git a/cms/static/js/spec/views/active_video_upload_list_spec.js b/cms/static/js/spec/views/active_video_upload_list_spec.js index 0ae632868c..c340202688 100644 --- a/cms/static/js/spec/views/active_video_upload_list_spec.js +++ b/cms/static/js/spec/views/active_video_upload_list_spec.js @@ -117,7 +117,7 @@ define( }); makeUploadUrl = function(fileName) { - return 'http://www.example.com/test_url/' + fileName; + return `http://www.example.com/test_url/${fileName}`; }; getSentRequests = function() { @@ -222,7 +222,7 @@ define( fileInfo ] }, - S3Url = 'http://s3.aws.com/upload/videos/' + fileInfo.name, + S3Url = `http://s3.aws.com/upload/videos/${fileInfo.name}`, requests; // this is required so that we can use AjaxHelpers ajax mock utils instead of jasmine mock-ajax.js @@ -356,7 +356,7 @@ define( {desc: 'smaller than', additionalBytes: -1} ], function(caseInfo) { - it(caseInfo.desc + 'max file size', function() { + it(`${caseInfo.desc}max file size`, function() { var maxFileSizeInBytes = this.view.getMaxFileSizeInBytes(), fileSize = maxFileSizeInBytes + caseInfo.additionalBytes, fileToUpload = { @@ -374,7 +374,7 @@ define( verifyUploadViewInfo( uploadView, 'Your file could not be uploaded', - 'file.mp4 exceeds maximum size of ' + videoUploadMaxFileSizeInGB + ' GB.' + `file.mp4 exceeds maximum size of ${videoUploadMaxFileSizeInGB} GB.` ); verifyA11YMessage( StringUtils.interpolate( @@ -415,10 +415,10 @@ define( function(caseInfo) { var fileNames = _.map( _.range(caseInfo.numFiles), - function(i) { return 'test' + i + '.mp4'; } + function(i) { return `test${i}.mp4`; } ); - describe('on selection of ' + caseInfo.desc, function() { + describe(`on selection of ${caseInfo.desc}`, function() { beforeEach(function() { // The files property cannot be set on a file input for // security reasons, so we must mock the access mechanism @@ -512,7 +512,7 @@ define( var refreshDescription = isViewRefresh ? ' (refreshed)' : ' (not refreshed)'; var subCases = [ { - desc: 'completion' + refreshDescription, + desc: `completion${refreshDescription}`, responseStatus: 204, statusText: ActiveVideoUpload.STATUS_COMPLETED, progressValue: 1, @@ -521,7 +521,7 @@ define( isViewRefresh: isViewRefresh }, { - desc: 'failure' + refreshDescription, + desc: `failure${refreshDescription}`, responseStatus: 500, statusText: ActiveVideoUpload.STATUS_FAILED, progressValue: 0, @@ -533,7 +533,7 @@ define( _.each(subCases, function(subCaseInfo) { - describe('and upload ' + subCaseInfo.desc, function() { + describe(`and upload ${subCaseInfo.desc}`, function() { var refreshSpy = null; beforeEach(function() { diff --git a/cms/static/js/spec/views/assets_spec.js b/cms/static/js/spec/views/assets_spec.js index e2105df2d7..9d45936714 100644 --- a/cms/static/js/spec/views/assets_spec.js +++ b/cms/static/js/spec/views/assets_spec.js @@ -276,7 +276,7 @@ function($, AjaxHelpers, URI, AssetsView, AssetCollection, ViewHelpers) { expect(assetsView).toBeDefined(); var requests = AjaxHelpers.requests(this); $.each(assetsView.pagingView.filterableColumns, function(columnID, columnData) { - var $typeColumn = $('#' + columnID); + var $typeColumn = $(`#${columnID}`); assetsView.pagingView.setPage(1); respondWithMockAssets(requests); var assetsNumber = assetsView.collection.length; @@ -292,7 +292,7 @@ function($, AjaxHelpers, URI, AssetsView, AssetCollection, ViewHelpers) { expect(assetsView).toBeDefined(); setup.call(this, mockExampleAssetsResponse); $.each(assetsView.pagingView.filterableColumns, function(columnID, columnData) { - var $typeColumn = $('#' + columnID); + var $typeColumn = $(`#${columnID}`); expect($typeColumn).toBeVisible(); var assetsNumber = $('#asset-table-body .type-col').length; assetsView.openFilterColumn($typeColumn); @@ -327,7 +327,7 @@ function($, AjaxHelpers, URI, AssetsView, AssetCollection, ViewHelpers) { $.each(assetsView.pagingView.filterableColumns, function(columnID, columnData) { assetsView.pagingView.setPage(1); respondWithMockAssets(requests); - var $typeColumn = $('#' + columnID); + var $typeColumn = $(`#${columnID}`); expect($typeColumn).toBeVisible(); var assetsNumber = assetsView.collection.length; $typeColumn.trigger('click'); diff --git a/cms/static/js/spec/views/container_spec.js b/cms/static/js/spec/views/container_spec.js index f963353cc3..eadff855b5 100644 --- a/cms/static/js/spec/views/container_spec.js +++ b/cms/static/js/spec/views/container_spec.js @@ -15,7 +15,7 @@ describe('Container View', () => { verifyRequest, verifyNumReorderCalls, respondToRequest, notificationSpy, rootLocator = 'locator-container', - containerTestUrl = '/xblock/' + rootLocator, + containerTestUrl = `/xblock/${rootLocator}`, groupAUrl = '/xblock/locator-group-A', groupA = 'locator-group-A', @@ -34,7 +34,7 @@ describe('Container View', () => { beforeEach(() => { EditHelpers.installMockXBlock(); EditHelpers.installViewTemplates(); - appendSetFixtures('
'); + appendSetFixtures(`
`); notificationSpy = EditHelpers.createNotificationSpy(); model = new XBlockInfo({ id: rootLocator, @@ -80,7 +80,7 @@ describe('Container View', () => { }; getComponent = function(locator) { - return containerView.$('.studio-xblock-wrapper[data-locator="' + locator + '"]'); + return containerView.$(`.studio-xblock-wrapper[data-locator="${locator}"]`); }; getDragHandle = function(locator) { diff --git a/cms/static/js/spec/views/course_video_settings_spec.js b/cms/static/js/spec/views/course_video_settings_spec.js index 3a2123d0fe..d4d2940867 100644 --- a/cms/static/js/spec/views/course_video_settings_spec.js +++ b/cms/static/js/spec/views/course_video_settings_spec.js @@ -150,10 +150,10 @@ define( verifyMessage = function(state, message) { var icon = state === 'error' ? 'fa-info-circle' : 'fa-check-circle'; - expect($courseVideoSettingsEl.find('.course-video-settings-message-wrapper.' + state).html()).toEqual( + expect($courseVideoSettingsEl.find(`.course-video-settings-message-wrapper.${state}`).html()).toEqual( '
' - + '' - + '' + message + '' + + `` + + `${message}` + '
' ); }; @@ -163,7 +163,7 @@ define( // Check None provider is selected. expect($transcriptProvidersListEl.find('input[type=radio]:checked').val()).toEqual(selectedProvider.value); // eslint-disable-line max-len _.each(providers, function(provider, key) { - $transcriptProvidersListEl.find('label[for=transcript-provider-' + key + ']').val(provider.displayName); // eslint-disable-line max-len + $transcriptProvidersListEl.find(`label[for=transcript-provider-${key}]`).val(provider.displayName); // eslint-disable-line max-len }); }; @@ -219,15 +219,15 @@ define( }; verifyOrganizationCredentialField = function(fieldName, label) { - var elementSelector = courseVideoSettingsView.selectedProvider + '-' + fieldName; + var elementSelector = `${courseVideoSettingsView.selectedProvider}-${fieldName}`; // Verify that correct label is shown. expect( - $courseVideoSettingsEl.find('.' + elementSelector + '-wrapper label .title').html() + $courseVideoSettingsEl.find(`.${elementSelector}-wrapper label .title`).html() ).toEqual(label); // Verify that credential field is shown. expect( - $courseVideoSettingsEl.find('.' + elementSelector + '-wrapper .' + elementSelector) + $courseVideoSettingsEl.find(`.${elementSelector}-wrapper .${elementSelector}`) ).toExist(); }; @@ -235,7 +235,7 @@ define( // Verify that success message is shown. verifyMessage( 'success', - transcriptionPlans[courseVideoSettingsView.selectedProvider].display_name + ' credentials saved' + `${transcriptionPlans[courseVideoSettingsView.selectedProvider].display_name} credentials saved` ); // Also verify that transcript credential state is updated. @@ -253,7 +253,7 @@ define( if ($courseVideoSettingsEl.find('.selected-transcript-provider').length) { $courseVideoSettingsEl.find('.selected-transcript-provider .action-change-provider').click(); } - $courseVideoSettingsEl.find('#transcript-provider-' + selectedProvider).click(); + $courseVideoSettingsEl.find(`#transcript-provider-${selectedProvider}`).click(); }; resetProvider = function() { @@ -279,7 +279,7 @@ define( // Provide organization credentials. _.each(fieldValues, function(key) { - $courseVideoSettingsEl.find('.' + courseVideoSettingsView.selectedProvider + '-' + key).val(key); + $courseVideoSettingsEl.find(`.${courseVideoSettingsView.selectedProvider}-${key}`).val(key); }); // Click save organization credentials button to save credentials. $courseVideoSettingsEl.find('.action-update-org-credentials').click(); @@ -714,8 +714,8 @@ define( expect($courseVideoSettingsEl.find('.transcription-account-details.warning')).toExist(); // Verify message expect($courseVideoSettingsEl.find('.transcription-account-details').html()).toEqual( - 'This action updates the ' + courseVideoSettingsView.selectedProvider - + ' information for your entire organization.' + `This action updates the ${courseVideoSettingsView.selectedProvider + } information for your entire organization.` ); }); @@ -740,12 +740,12 @@ define( $courseVideoSettingsEl.find('.action-update-org-credentials').click(); verifyPreferanceErrorState( - $courseVideoSettingsEl.find('.' + courseVideoSettingsView.selectedProvider + '-api-key-wrapper'), + $courseVideoSettingsEl.find(`.${courseVideoSettingsView.selectedProvider}-api-key-wrapper`), true ); verifyPreferanceErrorState( - $courseVideoSettingsEl.find('.' + courseVideoSettingsView.selectedProvider + '-api-secret-wrapper'), + $courseVideoSettingsEl.find(`.${courseVideoSettingsView.selectedProvider}-api-secret-wrapper`), true ); }); diff --git a/cms/static/js/spec/views/group_configuration_spec.js b/cms/static/js/spec/views/group_configuration_spec.js index d197c64d10..b6f44f0fc3 100644 --- a/cms/static/js/spec/views/group_configuration_spec.js +++ b/cms/static/js/spec/views/group_configuration_spec.js @@ -675,9 +675,9 @@ define([ verifyEditingGroup, respondToSave, expectGroupsVisible, correctValidationError; scopedGroupSelector = function(groupIndex, additionalSelectors) { - var groupSelector = '.partition-groups-list-item-' + groupIndex; + var groupSelector = `.partition-groups-list-item-${groupIndex}`; if (additionalSelectors) { - return groupSelector + ' ' + additionalSelectors; + return `${groupSelector} ${additionalSelectors}`; } else { return groupSelector; } @@ -860,7 +860,7 @@ define([ var requests = AjaxHelpers.requests(this), newGroupName = 'New Group Name', view = renderView(); - editNewGroup(view, {newName: ' ' + newGroupName + ' ', save: true}); + editNewGroup(view, {newName: ` ${newGroupName} `, save: true}); respondToSave(requests, view); expect(view.collection.at(0).get('name')).toBe(newGroupName); }); diff --git a/cms/static/js/spec/views/modals/move_xblock_modal_spec.js b/cms/static/js/spec/views/modals/move_xblock_modal_spec.js index 747fd7875b..6728923316 100644 --- a/cms/static/js/spec/views/modals/move_xblock_modal_spec.js +++ b/cms/static/js/spec/views/modals/move_xblock_modal_spec.js @@ -48,7 +48,7 @@ function($, _, AjaxHelpers, TemplateHelpers, ViewHelpers, MoveXBlockModal, XBloc showModal(); expect( modal.$el.find('.modal-header .title').contents().get(0).nodeValue.trim() - ).toEqual('Move: ' + DISPLAY_NAME); + ).toEqual(`Move: ${DISPLAY_NAME}`); expect( modal.$el.find('.modal-sr-title').text().trim() ).toEqual('Choose a location to move your component to'); diff --git a/cms/static/js/spec/views/module_edit_spec.js b/cms/static/js/spec/views/module_edit_spec.js index c46cb2b873..68ef8daeff 100644 --- a/cms/static/js/spec/views/module_edit_spec.js +++ b/cms/static/js/spec/views/module_edit_spec.js @@ -64,7 +64,7 @@ describe('ModuleEdit', function() { }); }); describe('render', function() { - beforeEach(function () { + beforeEach(function() { edit_helpers.installEditTemplates(true); spyOn(this.moduleEdit, 'loadDisplay'); spyOn(this.moduleEdit, 'delegateEvents'); @@ -124,7 +124,7 @@ describe('ModuleEdit', function() { }); it('loads the module preview via ajax on the view element', function() { expect($.ajax).toHaveBeenCalledWith({ - url: '/xblock/' + this.moduleEdit.model.id + '/student_view', + url: `/xblock/${this.moduleEdit.model.id}/student_view`, type: 'GET', cache: false, headers: { @@ -133,7 +133,7 @@ describe('ModuleEdit', function() { success: jasmine.any(Function) }); expect($.ajax).not.toHaveBeenCalledWith({ - url: '/xblock/' + this.moduleEdit.model.id + '/studio_view', + url: `/xblock/${this.moduleEdit.model.id}/studio_view`, type: 'GET', headers: { Accept: 'application/json' @@ -146,7 +146,7 @@ describe('ModuleEdit', function() { it('loads the editing view via ajax on demand', function() { var mockXBlockEditorHtml; expect($.ajax).not.toHaveBeenCalledWith({ - url: '/xblock/' + this.moduleEdit.model.id + '/studio_view', + url: `/xblock/${this.moduleEdit.model.id}/studio_view`, type: 'GET', cache: false, headers: { @@ -201,7 +201,7 @@ describe('ModuleEdit', function() { ] }); expect($.ajax).toHaveBeenCalledWith({ - url: '/xblock/' + this.moduleEdit.model.id + '/studio_view', + url: `/xblock/${this.moduleEdit.model.id}/studio_view`, type: 'GET', cache: false, headers: { diff --git a/cms/static/js/spec/views/move_xblock_spec.js b/cms/static/js/spec/views/move_xblock_spec.js index fa1eaba99b..666833ff5b 100644 --- a/cms/static/js/spec/views/move_xblock_spec.js +++ b/cms/static/js/spec/views/move_xblock_spec.js @@ -144,8 +144,8 @@ describe('MoveXBlock', function() { createChildXBlockInfo = function(category, outlineOptions, xblockIndex) { var childInfo = { category: categoryMap[category], - display_name: category + '_display_name_' + xblockIndex, - id: category + '_ID_' + xblockIndex + display_name: `${category}_display_name_${xblockIndex}`, + id: `${category}_ID_${xblockIndex}` }; return createXBlockInfo(parentChildMap[category], outlineOptions, childInfo); }; @@ -236,11 +236,11 @@ describe('MoveXBlock', function() { */ verifyListViewInfo = function(category, expectedXBlocksCount, hasCurrentLocation) { var displayedInfo = getDisplayedInfo(); - expect(displayedInfo.categoryText).toEqual(modal.moveXBlockListView.categoriesText[category] + ':'); + expect(displayedInfo.categoryText).toEqual(`${modal.moveXBlockListView.categoriesText[category]}:`); expect(displayedInfo.xblockCount).toEqual(expectedXBlocksCount); expect(displayedInfo.xblockDisplayNames).toEqual( _.map(_.range(expectedXBlocksCount), function(xblockIndex) { - return category + '_display_name_' + xblockIndex; + return `${category}_display_name_${xblockIndex}`; }) ); if (category === 'component') { @@ -276,7 +276,7 @@ describe('MoveXBlock', function() { expect(displayedBreadcrumbs).toEqual( _.map(visitedCategories, function(visitedCategory) { return visitedCategory === 'course' - ? 'Course Outline' : visitedCategory + '_display_name_' + xblockIndex; + ? 'Course Outline' : `${visitedCategory}_display_name_${xblockIndex}`; }) ); }; @@ -288,7 +288,7 @@ describe('MoveXBlock', function() { */ clickForwardButton = function(buttonIndex) { buttonIndex = buttonIndex || 0; // eslint-disable-line no-param-reassign - modal.moveXBlockListView.$el.find('[data-item-index="' + buttonIndex + '"] button').click(); + modal.moveXBlockListView.$el.find(`[data-item-index="${buttonIndex}"] button`).click(); }; /** @@ -429,7 +429,7 @@ describe('MoveXBlock', function() { }); modal.$el.find('.modal-actions .action-move').click(); sendMoveXBlockRequest(requests, sourceLocator); - AjaxHelpers.expectJsonRequest(requests, 'GET', '/xblock/' + sourceParentLocator); + AjaxHelpers.expectJsonRequest(requests, 'GET', `/xblock/${sourceParentLocator}`); AjaxHelpers.respondWithJson(requests, sourceParentXBlockInfo); expect(getMovedAlertNotification().html().length).not.toEqual(0); verifyConfirmationFeedbackTitleText(sourceDisplayName); diff --git a/cms/static/js/spec/views/paged_container_spec.js b/cms/static/js/spec/views/paged_container_spec.js index ad9c5891ab..37083e6418 100644 --- a/cms/static/js/spec/views/paged_container_spec.js +++ b/cms/static/js/spec/views/paged_container_spec.js @@ -19,9 +19,9 @@ function($, _, AjaxHelpers, URI, XBlockInfo, PagedContainer, PagingHeader, Pagin }; var options = _.extend(default_options, override_options); return '
' - + '
' - + htmlResponseTpl(options) - + '' + + `
${ + htmlResponseTpl(options) + }` + '
'; } @@ -506,7 +506,7 @@ function($, _, AjaxHelpers, URI, XBlockInfo, PagedContainer, PagingHeader, Pagin defaultUrl = '/preview/xblock/handler/trigger_previews'; testSendsAjax = function(show_previews) { - it('should send ' + (!show_previews) + ' when showChildrenPreviews was ' + show_previews, function() { + it(`should send ${!show_previews} when showChildrenPreviews was ${show_previews}`, function() { var requests = AjaxHelpers.requests(this); pagingContainer.collection.showChildrenPreviews = show_previews; pagingContainer.togglePreviews(); diff --git a/cms/static/js/spec/views/pages/container_spec.js b/cms/static/js/spec/views/pages/container_spec.js index 642d092de4..7907060687 100644 --- a/cms/static/js/spec/views/pages/container_spec.js +++ b/cms/static/js/spec/views/pages/container_spec.js @@ -15,7 +15,7 @@ import Course from 'js/models/course'; import 'jquery.simulate'; function parameterized_suite(label, globalPageOptions) { - describe(label + ' ContainerPage', function() { + describe(`${label} ContainerPage`, function() { var getContainerPage, renderContainerPage, handleContainerPageRefresh, expectComponents, respondWithHtml, model, containerPage, requests, initialDisplayName, mockContainerPage = readFixtures('templates/mock/mock-container-page.underscore'), @@ -344,12 +344,12 @@ function parameterized_suite(label, globalPageOptions) { allComponentsInGroup = _.map( _.range(NUM_COMPONENTS_PER_GROUP), function(index) { - return 'locator-component-' + GROUP_TO_TEST + (index + 1); + return `locator-component-${GROUP_TO_TEST}${index + 1}`; } ); getGroupElement = function() { - return containerPage.$("[data-locator='locator-group-" + GROUP_TO_TEST + "']"); + return containerPage.$(`[data-locator='locator-group-${GROUP_TO_TEST}']`); }; describe('Deleting an xblock', function() { @@ -377,7 +377,7 @@ function parameterized_suite(label, globalPageOptions) { // first request to delete the component AjaxHelpers.expectJsonRequest(requests, 'DELETE', - '/xblock/locator-component-' + GROUP_TO_TEST + (componentIndex + 1), + `/xblock/locator-component-${GROUP_TO_TEST}${componentIndex + 1}`, null); AjaxHelpers.respondWithNoContent(requests); @@ -489,8 +489,8 @@ function parameterized_suite(label, globalPageOptions) { // verify content of request AjaxHelpers.expectJsonRequest(requests, 'POST', '/xblock/', { - duplicate_source_locator: 'locator-component-' + GROUP_TO_TEST + (componentIndex + 1), - parent_locator: 'locator-group-' + GROUP_TO_TEST + duplicate_source_locator: `locator-component-${GROUP_TO_TEST}${componentIndex + 1}`, + parent_locator: `locator-group-${GROUP_TO_TEST}` }); // send the response @@ -568,7 +568,7 @@ function parameterized_suite(label, globalPageOptions) { }); var updatePreviewButtonTest = function(show_previews, expected_text) { - it('can set preview button to "' + expected_text + '"', function() { + it(`can set preview button to "${expected_text}"`, function() { containerPage = getContainerPage(); containerPage.updatePreviewButton(show_previews); expect(getButtonText(containerPage)).toBe(expected_text); diff --git a/cms/static/js/spec/views/pages/container_subviews_spec.js b/cms/static/js/spec/views/pages/container_subviews_spec.js index d3860e8530..cde0b42d81 100644 --- a/cms/static/js/spec/views/pages/container_subviews_spec.js +++ b/cms/static/js/spec/views/pages/container_subviews_spec.js @@ -343,15 +343,15 @@ describe('Container Subviews', function() { it('renders the last published date and user when there are no changes', function() { renderContainerPage(this, mockContainerXBlockHtml); fetch({published_on: 'Jul 01, 2014 at 12:45 UTC', published_by: 'amako'}); - expect(containerPage.$(lastDraftCss).text()). - toContain('Last published Jul 01, 2014 at 12:45 UTC by amako'); + expect(containerPage.$(lastDraftCss).text()) + .toContain('Last published Jul 01, 2014 at 12:45 UTC by amako'); }); it('renders the last saved date and user when there are changes', function() { renderContainerPage(this, mockContainerXBlockHtml); fetch({has_changes: true, edited_on: 'Jul 02, 2014 at 14:20 UTC', edited_by: 'joe'}); - expect(containerPage.$(lastDraftCss).text()). - toContain('Draft saved on Jul 02, 2014 at 14:20 UTC by joe'); + expect(containerPage.$(lastDraftCss).text()) + .toContain('Draft saved on Jul 02, 2014 at 14:20 UTC by joe'); }); describe('Release Date', function() { @@ -596,8 +596,8 @@ describe('Container Subviews', function() { fetch({ published: true, published_on: 'Jul 01, 2014 at 12:45 UTC', published_by: 'amako' }); - expect(containerPage.$(lastPublishCss).text()). - toContain('Last published Jul 01, 2014 at 12:45 UTC by amako'); + expect(containerPage.$(lastPublishCss).text()) + .toContain('Last published Jul 01, 2014 at 12:45 UTC by amako'); }); it('renders correctly when the block is published without publish info', function() { diff --git a/cms/static/js/spec/views/pages/course_outline_spec.js b/cms/static/js/spec/views/pages/course_outline_spec.js index 327e5ec21d..8855554e61 100644 --- a/cms/static/js/spec/views/pages/course_outline_spec.js +++ b/cms/static/js/spec/views/pages/course_outline_spec.js @@ -160,11 +160,11 @@ describe('CourseOutlinePage', function() { }; getItemsOfType = function(type) { - return outlinePage.$('.outline-' + type); + return outlinePage.$(`.outline-${type}`); }; getItemHeaders = function(type) { - return getItemsOfType(type).find('> .' + type + '-header'); + return getItemsOfType(type).find(`> .${type}-header`); }; verifyItemsExpanded = function(type, isExpanded) { @@ -210,7 +210,7 @@ describe('CourseOutlinePage', function() { setSelfPacedCustomPLS = function() { setSelfPaced(); course.set('is_custom_relative_dates_active', true); - } + }; createCourseOutlinePage = function(test, courseJSON, createOnly) { requests = AjaxHelpers.requests(test); @@ -247,7 +247,7 @@ describe('CourseOutlinePage', function() { createCourseOutlinePageAndShowUnit(this, mockCourseJSON); getItemHeaders(type).find('.publish-button').click(); $('.wrapper-modal-window .action-publish').click(); - AjaxHelpers.expectJsonRequest(requests, 'POST', '/xblock/mock-' + type, { + AjaxHelpers.expectJsonRequest(requests, 'POST', `/xblock/mock-${type}`, { publish: 'make_public' }); expect(requests[0].requestHeaders['X-HTTP-Method-Override']).toBe('PATCH'); @@ -688,7 +688,7 @@ describe('CourseOutlinePage', function() { var highlights = [], i; for (i = 0; i < numberOfHighlights; i++) { - highlights.push('Highlight' + (i + 1)); + highlights.push(`Highlight${i + 1}`); } return highlights; }; @@ -1073,7 +1073,7 @@ describe('CourseOutlinePage', function() { }; setContentVisibility = function(visibility) { - $('input[name=content-visibility][value=' + visibility + ']').prop('checked', true); + $(`input[name=content-visibility][value=${visibility}]`).prop('checked', true); }; selectDisableSpecialExams = function() { @@ -1122,7 +1122,7 @@ describe('CourseOutlinePage', function() { }; expectShowCorrectness = function(showCorrectness) { - expect($('input[name=show-correctness][value=' + showCorrectness + ']').is(':checked')).toBe(true); + expect($(`input[name=show-correctness][value=${showCorrectness}]`).is(':checked')).toBe(true); }; getMockNoPrereqOrExamsCourseJSON = function() { @@ -1440,7 +1440,7 @@ describe('CourseOutlinePage', function() { $('.wrapper-modal-window .action-save').click(); }); - it('can select the onboarding exam when a course supports onboarding', function () { + it('can select the onboarding exam when a course supports onboarding', function() { var mockCourseWithSpecialExamJSON = createMockCourseJSON({}, [ createMockSectionJSON({ has_changes: true, @@ -2090,12 +2090,12 @@ describe('CourseOutlinePage', function() { var setShowCorrectness; setShowCorrectness = function(showCorrectness) { - $('input[name=show-correctness][value=' + showCorrectness + ']').click(); + $(`input[name=show-correctness][value=${showCorrectness}]`).click(); }; describe('Show correctness set by subsection metadata.', function() { $.each(['always', 'never', 'past_due'], function(index, showCorrectness) { - it('show_correctness="' + showCorrectness + '"', function() { + it(`show_correctness="${showCorrectness}"`, function() { var mockCourseJSONCorrectness = createMockCourseJSON({}, [ createMockSectionJSON({}, [ createMockSubsectionJSON({show_correctness: showCorrectness}, []) @@ -2124,7 +2124,7 @@ describe('CourseOutlinePage', function() { }); $.each(['never', 'past_due'], function(index, showCorrectness) { - it('show_correctness="' + showCorrectness + '" updates settings, republishes', function() { + it(`show_correctness="${showCorrectness}" updates settings, republishes`, function() { var expectedSettings = $.extend(true, {}, defaultModalSettings, {publish: 'republish'}); expectedSettings.metadata.show_correctness = showCorrectness; @@ -2173,7 +2173,7 @@ describe('CourseOutlinePage', function() { expect($modalWindow.find('.outline-subsection')).not.toExist(); }); - describe('Self Paced with Custom Personalized Learner Schedules (PLS)', function () { + describe('Self Paced with Custom Personalized Learner Schedules (PLS)', function() { beforeEach(function() { var mockCourseJSON = createMockCourseJSON({}, [ createMockSectionJSON({}, [ @@ -2192,7 +2192,7 @@ describe('CourseOutlinePage', function() { selectRelativeWeeksSubsection = function(weeks) { $('#due_in').val(weeks).trigger('keyup'); - } + }; mockCustomPacingServerValuesJson = createMockSectionJSON({ release_date: 'Jan 01, 2970 at 05:00 UTC' @@ -2217,7 +2217,7 @@ describe('CourseOutlinePage', function() { ]) ]); - it('can show correct editors for self_paced course with custom pacing', function (){ + it('can show correct editors for self_paced course with custom pacing', function() { outlinePage.$('.outline-subsection .configure-button').click(); expect($('.edit-settings-release').length).toBe(0); // Due date input exists for custom pacing self paced courses @@ -2286,7 +2286,7 @@ describe('CourseOutlinePage', function() { $('#grading_type').val('notgraded').trigger('change'); $('#due_in').val('').trigger('change'); expect($('#relative_date_input').css('display')).toBe('none'); - }) + }); it('shows validation error on relative date', function() { outlinePage.$('.outline-subsection .configure-button').click(); @@ -2353,7 +2353,7 @@ describe('CourseOutlinePage', function() { 'Contains staff only content' ); }); - }) + }); }); // Note: most tests for units can be found in Bok Choy @@ -2452,7 +2452,7 @@ describe('CourseOutlinePage', function() { expect(messages).toContainText('Contains staff only content'); }); - describe('discussion settings', function () { + describe('discussion settings', function() { it('hides discussion settings if unit level discussions are disabled', function() { getUnitStatus({}, {unit_level_discussions: false}); outlinePage.$('.outline-unit .configure-button').click(); diff --git a/cms/static/js/spec/views/pages/library_users_spec.js b/cms/static/js/spec/views/pages/library_users_spec.js index 4d8f8463eb..14aa3d75bf 100644 --- a/cms/static/js/spec/views/pages/library_users_spec.js +++ b/cms/static/js/spec/views/pages/library_users_spec.js @@ -10,8 +10,8 @@ function($, AjaxHelpers, ViewHelpers, ManageUsersFactory, ViewUtils) { var team_member_fixture = readFixtures('team-member.underscore'); function setRole(email, role) { - var $user_li = $('li.user-item[data-email="' + email + '"]'); - var $role_action = $('li.action-role a.make-' + role, $user_li); + var $user_li = $(`li.user-item[data-email="${email}"]`); + var $role_action = $(`li.action-role a.make-${role}`, $user_li); expect($role_action).toBeVisible(); $role_action.click(); } @@ -110,7 +110,7 @@ function($, AjaxHelpers, ViewHelpers, ManageUsersFactory, ViewUtils) { var promptSpy = ViewHelpers.createPromptSpy(); var reloadSpy = spyOn(ViewUtils, 'reload'); var email = 'honor@example.com'; - $('.user-item[data-email="' + email + '"] .action-delete .delete').click(); + $(`.user-item[data-email="${email}"] .action-delete .delete`).click(); ViewHelpers.verifyPromptShowing(promptSpy, 'Are you sure?'); ViewHelpers.confirmPrompt(promptSpy); ViewHelpers.verifyPromptHidden(promptSpy); diff --git a/cms/static/js/spec/views/paging_spec.js b/cms/static/js/spec/views/paging_spec.js index f01edf9fed..1d7c5a2ed4 100644 --- a/cms/static/js/spec/views/paging_spec.js +++ b/cms/static/js/spec/views/paging_spec.js @@ -10,7 +10,7 @@ function($, URI, AjaxHelpers, PagingCollection, PagingView, PagingHeader) { 'use strict'; var createPageableItem = function(index) { - var id = 'item_' + index; + var id = `item_${index}`; return { id: id, display_name: id, diff --git a/cms/static/js/spec/views/previous_video_upload_list_spec.js b/cms/static/js/spec/views/previous_video_upload_list_spec.js index 01a0dd1ca7..88576f2421 100644 --- a/cms/static/js/spec/views/previous_video_upload_list_spec.js +++ b/cms/static/js/spec/views/previous_video_upload_list_spec.js @@ -20,7 +20,7 @@ define( _.range(numModels), function(num, index) { return new Backbone.Model( - _.extend({}, modelData, {edx_video_id: 'dummy_id_' + index}) + _.extend({}, modelData, {edx_video_id: `dummy_id_${index}`}) ); } ) @@ -66,7 +66,7 @@ define( if (confirmRemove) { // click on Remove button on confirmation popup $('.action-primary').click(); - AjaxHelpers.expectJsonRequest(requests, 'DELETE', videoHandlerUrl + '/dummy_id_0'); + AjaxHelpers.expectJsonRequest(requests, 'DELETE', `${videoHandlerUrl}/dummy_id_0`); AjaxHelpers.respondWithNoContent(requests); numVideos -= 1; firstVideoId = 'dummy_id_1'; diff --git a/cms/static/js/spec/views/video_thumbnail_spec.js b/cms/static/js/spec/views/video_thumbnail_spec.js index 31e0ea1e3f..cf1a2fc6f0 100644 --- a/cms/static/js/spec/views/video_thumbnail_spec.js +++ b/cms/static/js/spec/views/video_thumbnail_spec.js @@ -49,7 +49,7 @@ define( }, collection = new Backbone.Collection(_.map(_.range(numVideos), function(num, index) { return new Backbone.Model( - _.extend({}, defaultData, {edx_video_id: 'dummy_id_' + index}, modelData) + _.extend({}, defaultData, {edx_video_id: `dummy_id_${index}`}, modelData) ); })); videoListView = new PreviousVideoUploadListView({ @@ -192,7 +192,7 @@ define( AjaxHelpers.expectRequest( requests, 'POST', - IMAGE_UPLOAD_URL + '/dummy_id_' + videoViewIndex, + `${IMAGE_UPLOAD_URL}/dummy_id_${videoViewIndex}`, new FormData() ); @@ -221,7 +221,7 @@ define( it('calls readMessage with correct message', function() { var errorMessage = 'Image upload failed. This image file type is not supported. Supported file ' - + 'types are ' + videoThumbnailView.getVideoImageSupportedFileFormats().humanize + '.', + + `types are ${videoThumbnailView.getVideoImageSupportedFileFormats().humanize}.`, successData = { files: [createFakeImageFile()], submit: function() {} @@ -270,8 +270,8 @@ define( // Verify error message expect($videoListEl.find('.thumbnail-error-wrapper').find('.action-text').html() .trim()).toEqual( - 'Image upload failed. The selected image must be larger than ' - + videoThumbnailView.getVideoImageMinSize().humanize + '.' + `Image upload failed. The selected image must be larger than ${ + videoThumbnailView.getVideoImageMinSize().humanize}.` ); }); @@ -285,8 +285,8 @@ define( // Verify error message expect($videoListEl.find('.thumbnail-error-wrapper').find('.action-text').html() .trim()).toEqual( - 'Image upload failed. The selected image must be smaller than ' - + videoThumbnailView.getVideoImageMaxSize().humanize + '.' + `Image upload failed. The selected image must be smaller than ${ + videoThumbnailView.getVideoImageMaxSize().humanize}.` ); }); @@ -322,8 +322,8 @@ define( // Verify error message expect($videoListEl.find('.thumbnail-error-wrapper').find('.action-text').html() .trim()).toEqual( - 'Image upload failed. This image file type is not supported. Supported file types are ' - + videoThumbnailView.getVideoImageSupportedFileFormats().humanize + '.' + `Image upload failed. This image file type is not supported. Supported file types are ${ + videoThumbnailView.getVideoImageSupportedFileFormats().humanize}.` ); }); diff --git a/cms/static/js/spec/views/video_transcripts_spec.js b/cms/static/js/spec/views/video_transcripts_spec.js index c485d1bec9..c0e684d23a 100644 --- a/cms/static/js/spec/views/video_transcripts_spec.js +++ b/cms/static/js/spec/views/video_transcripts_spec.js @@ -61,7 +61,7 @@ define( expect(downloadTranscriptActionEl.html().trim(), 'Download'); expect( downloadTranscriptActionEl.attr('href'), - TRANSCRIPT_DOWNLOAD_URL + '?edx_video_id=' + edxVideoID + '&language_code=' + transcriptLanguage + `${TRANSCRIPT_DOWNLOAD_URL}?edx_video_id=${edxVideoID}&language_code=${transcriptLanguage}` ); expect(uploadTranscriptActionEl.html().trim(), 'Replace'); @@ -143,7 +143,7 @@ define( videoTranscriptsView.$el.find('.video-transcripts-wrapper').hasClass('hidden') ).toEqual(true); expect(videoTranscriptsView.$el.find('.toggle-show-transcripts-button-text').html().trim()).toEqual( - 'Show transcripts (' + transcripts.length + ')' + `Show transcripts (${transcripts.length})` ); }); @@ -155,7 +155,7 @@ define( // Verify initial button text expect(videoTranscriptsView.$el.find('.toggle-show-transcripts-button-text').html().trim()).toEqual( - 'Show transcripts (' + transcripts.length + ')' + `Show transcripts (${transcripts.length})` ); videoTranscriptsView.$el.find('.toggle-show-transcripts-button').click(); @@ -166,7 +166,7 @@ define( // Verify button text is changed. expect(videoTranscriptsView.$el.find('.toggle-show-transcripts-button-text').html().trim()).toEqual( - 'Hide transcripts (' + transcripts.length + ')' + `Hide transcripts (${transcripts.length})` ); }); @@ -176,7 +176,7 @@ define( // Verify button text. expect(videoTranscriptsView.$el.find('.toggle-show-transcripts-button-text').html().trim()).toEqual( - 'Hide transcripts (' + transcripts.length + ')' + `Hide transcripts (${transcripts.length})` ); // Verify transcript container is not hidden @@ -188,7 +188,7 @@ define( // Verify button text is changed. expect(videoTranscriptsView.$el.find('.toggle-show-transcripts-button-text').html().trim()).toEqual( - 'Show transcripts (' + transcripts.length + ')' + `Show transcripts (${transcripts.length})` ); // Verify transcript container is hidden @@ -216,10 +216,10 @@ define( ); _.each(transcripts, function(languageCode) { - $transcriptEl = videoTranscriptsView.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + $transcriptEl = videoTranscriptsView.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len // Verify correct transcript title is set. expect($transcriptEl.find('.transcript-title').html()).toEqual( - 'Video client title n_' + languageCode + '.' + TRANSCRIPT_DOWNLOAD_FILE_FORMAT + `Video client title n_${languageCode}.${TRANSCRIPT_DOWNLOAD_FILE_FORMAT}` ); // Verify transcript is rendered with correct info. verifyTranscriptStateInfo($transcriptEl, languageCode); @@ -230,11 +230,11 @@ define( var languageCode = 'en', newLanguageCode = 'ar', requests = AjaxHelpers.requests(this), - $transcriptEl = videoTranscriptsView.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + $transcriptEl = videoTranscriptsView.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len // Verify correct transcript title is set. expect($transcriptEl.find('.transcript-title').html()).toEqual( - 'Video client title n_' + languageCode + '.' + TRANSCRIPT_DOWNLOAD_FILE_FORMAT + `Video client title n_${languageCode}.${TRANSCRIPT_DOWNLOAD_FILE_FORMAT}` ); // Select a language @@ -257,7 +257,7 @@ define( // Verify correct transcript title is set. expect($transcriptEl.find('.transcript-title').html()).toEqual( - 'Video client title n_' + newLanguageCode + '.' + TRANSCRIPT_DOWNLOAD_FILE_FORMAT + `Video client title n_${newLanguageCode}.${TRANSCRIPT_DOWNLOAD_FILE_FORMAT}` ); verifyMessage($transcriptEl, 'uploaded'); @@ -269,11 +269,11 @@ define( it('can delete transcript', function() { var languageCode = 'en', requests = AjaxHelpers.requests(this), - $transcriptEl = videoTranscriptsView.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + $transcriptEl = videoTranscriptsView.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len // Verify correct transcript title is set. expect($transcriptEl.find('.transcript-title').html()).toEqual( - 'Video client title n_' + languageCode + '.' + TRANSCRIPT_DOWNLOAD_FILE_FORMAT + `Video client title n_${languageCode}.${TRANSCRIPT_DOWNLOAD_FILE_FORMAT}` ); $transcriptEl.find('.delete-transcript-button').click(); @@ -285,7 +285,7 @@ define( AjaxHelpers.expectRequest( requests, 'DELETE', - TRANSCRIPT_DELETE_URL + '/' + edxVideoID + '/' + languageCode + `${TRANSCRIPT_DELETE_URL}/${edxVideoID}/${languageCode}` ); // Send successful delete response @@ -293,7 +293,7 @@ define( // Verify English transcript is not present. expect(videoTranscriptsView.$el.find( - '.video-transcript-content[data-language-code="' + languageCode + '"]' + `.video-transcript-content[data-language-code="${languageCode}"]` )).not.toExist(); // Verify transcripts view is rendered with transcript deleted for English. @@ -305,11 +305,11 @@ define( it('should show error message when deleting a transcript in case of server error', function() { var languageCode = 'en', requests = AjaxHelpers.requests(this), - $transcriptEl = videoTranscriptsView.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + $transcriptEl = videoTranscriptsView.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len // Verify correct transcript title is set. expect($transcriptEl.find('.transcript-title').html()).toEqual( - 'Video client title n_' + languageCode + '.' + TRANSCRIPT_DOWNLOAD_FILE_FORMAT + `Video client title n_${languageCode}.${TRANSCRIPT_DOWNLOAD_FILE_FORMAT}` ); $transcriptEl.find('.delete-transcript-button').click(); @@ -331,7 +331,7 @@ define( AjaxHelpers.expectRequest( requests, 'DELETE', - TRANSCRIPT_DELETE_URL + '/' + edxVideoID + '/' + languageCode + `${TRANSCRIPT_DELETE_URL}/${edxVideoID}/${languageCode}` ); AjaxHelpers.respondWithError(requests, 500); @@ -343,7 +343,7 @@ define( // Verify English transcript container is not removed. expect(videoTranscriptsView.$el.find( - '.video-transcript-content[data-language-code="' + languageCode + '"]' + `.video-transcript-content[data-language-code="${languageCode}"]` )).toExist(); // Verify transcripts count is correct. @@ -356,7 +356,7 @@ define( var languageCode = 'en', requests = AjaxHelpers.requests(this), errorMessage = 'Transcript failed error message', - $transcriptEl = videoTranscriptsView.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + $transcriptEl = videoTranscriptsView.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len $transcriptEl.find('.upload-transcript-button').click(); @@ -382,7 +382,7 @@ define( it('should show error message in case of server error', function() { var languageCode = 'en', requests = AjaxHelpers.requests(this), - $transcriptEl = videoTranscriptsView.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + $transcriptEl = videoTranscriptsView.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len $transcriptEl.find('.upload-transcript-button').click(); @@ -407,8 +407,8 @@ define( it('should show error message in case of unsupported transcript file format', function() { var languageCode = 'en', transcriptFileName = 'unsupported-transcript-file-format.txt', - errorMessage = 'This file type is not supported. Supported file type is ' + TRANSCRIPT_DOWNLOAD_FILE_FORMAT + '.', // eslint-disable-line max-len - $transcriptEl = videoTranscriptsView.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + errorMessage = `This file type is not supported. Supported file type is ${TRANSCRIPT_DOWNLOAD_FILE_FORMAT}.`, // eslint-disable-line max-len + $transcriptEl = videoTranscriptsView.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len $transcriptEl.find('.upload-transcript-button').click(); diff --git a/cms/static/js/spec/views/xblock_string_field_editor_spec.js b/cms/static/js/spec/views/xblock_string_field_editor_spec.js index 9121b0e334..80fd01fb36 100644 --- a/cms/static/js/spec/views/xblock_string_field_editor_spec.js +++ b/cms/static/js/spec/views/xblock_string_field_editor_spec.js @@ -36,7 +36,7 @@ describe('XBlockStringFieldEditorView', function() { '
' + '

' - + '' + initialDisplayName + '' + + `${initialDisplayName}` + '

' + '
' ); @@ -149,11 +149,11 @@ describe('XBlockStringFieldEditorView', function() { }); it('renders open angle bracket in input field', function() { - expectInputMatchesModelDisplayName(updatedDisplayName + '<'); + expectInputMatchesModelDisplayName(`${updatedDisplayName}<`); }); it('renders close angle bracket in input field', function() { - expectInputMatchesModelDisplayName('>' + updatedDisplayName); + expectInputMatchesModelDisplayName(`>${updatedDisplayName}`); }); }); }); diff --git a/cms/static/js/spec/views/xblock_validation_spec.js b/cms/static/js/spec/views/xblock_validation_spec.js index 577f16eeb6..16473b9deb 100644 --- a/cms/static/js/spec/views/xblock_validation_spec.js +++ b/cms/static/js/spec/views/xblock_validation_spec.js @@ -110,8 +110,8 @@ define(['jquery', 'js/models/xblock_validation', 'js/views/xblock_validation', ' it('renders action info', function() { expect(view.$('a.edit-button .action-button-text').text()).toContain('Summary Action'); - expect(view.$('a.notification-action-button .action-button-text').text()). - toContain('First Message Action'); + expect(view.$('a.notification-action-button .action-button-text').text()) + .toContain('First Message Action'); expect(view.$('a.notification-action-button').data('notification-action')).toBe('fix-up'); }); diff --git a/cms/static/js/spec_helpers/edit_helpers.js b/cms/static/js/spec_helpers/edit_helpers.js index 217a067e87..0fa81b1e5a 100644 --- a/cms/static/js/spec_helpers/edit_helpers.js +++ b/cms/static/js/spec_helpers/edit_helpers.js @@ -138,4 +138,4 @@ export { installEditTemplates, showEditModal, verifyXBlockRequest, -} +}; diff --git a/cms/static/js/spec_helpers/modal_helpers.js b/cms/static/js/spec_helpers/modal_helpers.js index 3b6c154cb3..50996957f5 100644 --- a/cms/static/js/spec_helpers/modal_helpers.js +++ b/cms/static/js/spec_helpers/modal_helpers.js @@ -46,7 +46,7 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'common/js/spec_hel pressModalButton = function(selector, modal) { var modalElement, button; modalElement = getModalElement(modal); - button = modalElement.find(selector + ':visible'); + button = modalElement.find(`${selector}:visible`); expect(button.length).toBe(1); button.click(); }; diff --git a/cms/static/js/utils/date_utils.js b/cms/static/js/utils/date_utils.js index a335adb01b..00f2e06def 100644 --- a/cms/static/js/utils/date_utils.js +++ b/cms/static/js/utils/date_utils.js @@ -77,10 +77,10 @@ define(['jquery', 'date', 'js/utils/change_on_enter', 'jquery.ui', 'jquery.timep var currentDate; if (typeof index !== 'undefined' && view.hasOwnProperty('collection')) { cacheModel = view.collection.models[index]; - div = view.$el.find('#' + view.collectionSelector(cacheModel.cid)); + div = view.$el.find(`#${view.collectionSelector(cacheModel.cid)}`); } else { cacheModel = view.model; - div = view.$el.find('#' + view.fieldToSelectorMap[fieldName]); + div = view.$el.find(`#${view.fieldToSelectorMap[fieldName]}`); } datefield = $(div).find('input.date'); timefield = $(div).find('input.time'); diff --git a/cms/static/js/utils/drag_and_drop.js b/cms/static/js/utils/drag_and_drop.js index 88c1301999..00aa1afa3b 100644 --- a/cms/static/js/utils/drag_and_drop.js +++ b/cms/static/js/utils/drag_and_drop.js @@ -212,7 +212,7 @@ function($, ui, _, gettext, Draggabilly, ModuleUtils, NotificationView) { // Mark the new destination if (destinationEle && this.pointerInBounds(pointer, $ele)) { $ele.addClass(this.validDropClass); - destinationEle.addClass('drop-target drop-target-' + destinationInfo.attachMethod); + destinationEle.addClass(`drop-target drop-target-${destinationInfo.attachMethod}`); this.dragState.attachMethod = destinationInfo.attachMethod; this.dragState.dropDestination = destinationEle; } else { diff --git a/cms/static/js/utils/handle_iframe_binding.js b/cms/static/js/utils/handle_iframe_binding.js index b4527afd85..c708093209 100644 --- a/cms/static/js/utils/handle_iframe_binding.js +++ b/cms/static/js/utils/handle_iframe_binding.js @@ -26,7 +26,7 @@ define(['jquery'], function($) { if (getQString[1].search('wmode=transparent') === -1) { var oldString = getQString[1]; var newString = getQString[0]; - $(this).attr('src', newString + '?' + wmode + '&' + oldString); + $(this).attr('src', `${newString}?${wmode}&${oldString}`); } // eslint-disable-next-line brace-style } @@ -34,7 +34,7 @@ define(['jquery'], function($) { // removed we execute this code. To avoid throwing an error when setting the // attr, check that the source doesn't start with the value specified by TinyMCE ('javascript:""'). else if (ifr_source.lastIndexOf('javascript:', 0) !== 0) { - $(this).attr('src', ifr_source + '?' + wmode); + $(this).attr('src', `${ifr_source}?${wmode}`); } } } else { diff --git a/cms/static/js/utils/module.js b/cms/static/js/utils/module.js index 3d965748c5..f6fdcc1475 100644 --- a/cms/static/js/utils/module.js +++ b/cms/static/js/utils/module.js @@ -12,9 +12,9 @@ define(['underscore'], function(_) { var getUpdateUrl = function(locator) { if (_.isUndefined(locator)) { - return urlRoot + '/'; + return `${urlRoot}/`; } else { - return urlRoot + '/' + locator; + return `${urlRoot}/${locator}`; } }; return { diff --git a/cms/static/js/utils/templates.js b/cms/static/js/utils/templates.js index 578fd76ea4..58d66fd0b9 100644 --- a/cms/static/js/utils/templates.js +++ b/cms/static/js/utils/templates.js @@ -5,10 +5,10 @@ define(['jquery', 'underscore'], function($, _) { * @returns The loaded template. */ var loadTemplate = function(name) { - var templateSelector = '#' + name + '-tpl', + var templateSelector = `#${name}-tpl`, templateText = $(templateSelector).text(); if (!templateText) { - console.error('Failed to load ' + name + ' template'); + console.error(`Failed to load ${name} template`); } return _.template(templateText); }; diff --git a/cms/static/js/views/abstract_editor.js b/cms/static/js/views/abstract_editor.js index 30ce785806..59ca555c29 100644 --- a/cms/static/js/views/abstract_editor.js +++ b/cms/static/js/views/abstract_editor.js @@ -6,7 +6,7 @@ define(['js/views/baseview', 'underscore'], function(BaseView, _) { var self = this; var templateName = _.result(this, 'templateName'); // Backbone model cid is only unique within the collection. - this.uniqueId = _.uniqueId(templateName + '_'); + this.uniqueId = _.uniqueId(`${templateName}_`); this.template = this.loadTemplate(templateName); // xss-lint: disable=javascript-jquery-html this.$el.html(this.template({model: this.model, uniqueId: this.uniqueId})); @@ -87,10 +87,10 @@ define(['js/views/baseview', 'underscore'], function(BaseView, _) { * @returns The loaded template. */ loadTemplate: function(name) { - var templateSelector = '#' + name, + var templateSelector = `#${name}`, templateText = $(templateSelector).text(); if (!templateText) { - console.error('Failed to load ' + name + ' template'); + console.error(`Failed to load ${name} template`); } return _.template(templateText); } diff --git a/cms/static/js/views/assets.js b/cms/static/js/views/assets.js index 5aaccda82f..f262821a02 100644 --- a/cms/static/js/views/assets.js +++ b/cms/static/js/views/assets.js @@ -203,7 +203,7 @@ function($, _, gettext, HtmlUtils, BaseView, AssetModel, PagingView, AssetView, if (self.maxFileSizeRedirectUrl) { var instructions = gettext('Please follow the instructions here to upload a file elsewhere and link to it: {maxFileSizeRedirectUrl}') .replace('{maxFileSizeRedirectUrl}', self.maxFileSizeRedirectUrl); - error = error + ' ' + instructions; + error = `${error} ${instructions}`; } self.largeFileErrorMsg = new NotificationView.Error({ @@ -262,7 +262,7 @@ function($, _, gettext, HtmlUtils, BaseView, AssetModel, PagingView, AssetView, }, showUploadFeedback: function(event, percentComplete) { - var percentVal = percentComplete + '%', + var percentVal = `${percentComplete}%`, $progressFill = $('.upload-modal .progress-fill'); $progressFill.width(percentVal); @@ -319,7 +319,7 @@ function($, _, gettext, HtmlUtils, BaseView, AssetModel, PagingView, AssetView, this.pagingView.filterableColumns['js-asset-type-col'].displayName = assettypeLabel; this.pagingView.selectFilter('js-asset-type-col'); this.closeFilterPopup(this.$el.find( - '.column-filter-link[data-assetfilter="' + assettype + '"]')); + `.column-filter-link[data-assetfilter="${assettype}"]`)); }, closeFilterPopup: function(element) { diff --git a/cms/static/js/views/components/add_xblock.js b/cms/static/js/views/components/add_xblock.js index 5f49111669..9b2b0fdf25 100644 --- a/cms/static/js/views/components/add_xblock.js +++ b/cms/static/js/views/components/add_xblock.js @@ -46,8 +46,8 @@ function($, _, gettext, BaseView, ViewUtils, AddXBlockButton, AddXBlockMenu, Htm event.stopPropagation(); type = $(event.currentTarget).data('type'); this.$('.new-component').slideUp(250); - this.$('.new-component-' + type).slideDown(250); - this.$('.new-component-' + type + ' div').focus(); + this.$(`.new-component-${type}`).slideDown(250); + this.$(`.new-component-${type} div`).focus(); }, closeNewComponent: function(event) { @@ -57,7 +57,7 @@ function($, _, gettext, BaseView, ViewUtils, AddXBlockButton, AddXBlockMenu, Htm type = $(event.currentTarget).data('type'); this.$('.new-component').slideDown(250); this.$('.new-component-templates').slideUp(250); - this.$('ul.new-component-type li button[data-type=' + type + ']').focus(); + this.$(`ul.new-component-type li button[data-type=${type}]`).focus(); }, createNewComponent: function(event) { diff --git a/cms/static/js/views/components/add_xblock_menu.js b/cms/static/js/views/components/add_xblock_menu.js index e3945e42de..d61d9d7df9 100644 --- a/cms/static/js/views/components/add_xblock_menu.js +++ b/cms/static/js/views/components/add_xblock_menu.js @@ -2,7 +2,7 @@ define(['jquery', 'js/views/baseview', 'edx-ui-toolkit/js/utils/html-utils'], function($, BaseView, HtmlUtils) { return BaseView.extend({ className: function() { - return 'new-component-templates new-component-' + this.model.type; + return `new-component-templates new-component-${this.model.type}`; }, initialize: function() { BaseView.prototype.initialize.call(this); diff --git a/cms/static/js/views/course_info_update.js b/cms/static/js/views/course_info_update.js index 6468a0f4f9..daf9aa354b 100644 --- a/cms/static/js/views/course_info_update.js +++ b/cms/static/js/views/course_info_update.js @@ -72,7 +72,7 @@ function(CodeMirror, ModalUtils, DateUtils, HtmlUtils, CourseInfoHelper, Validat }, collectionSelector: function(uid) { - return 'course-update-list li[name=' + uid + ']'; + return `course-update-list li[name=${uid}]`; }, setAndValidate: function(attr, value, event) { @@ -96,13 +96,13 @@ function(CodeMirror, ModalUtils, DateUtils, HtmlUtils, CourseInfoHelper, Validat handleValidationError: function(model, error) { var self = this, - $validationElement = this.$el.find('#course-update-list li[name="' + model.cid + '"]'); + $validationElement = this.$el.find(`#course-update-list li[name="${model.cid}"]`); $validationElement.find('.message-error').remove(); Object.keys(error).forEach(function(field) { if (error.hasOwnProperty(field)) { HtmlUtils.append( - $validationElement.find('#update-date-' + model.cid).parent(), + $validationElement.find(`#update-date-${model.cid}`).parent(), self.errorTemplate({message: error[field]}) ); HtmlUtils.append( @@ -116,7 +116,7 @@ function(CodeMirror, ModalUtils, DateUtils, HtmlUtils, CourseInfoHelper, Validat }, validateModel: function(model) { - var $validationElement = this.$el.find('#course-update-list li[name="' + model.cid + '"]'); + var $validationElement = this.$el.find(`#course-update-list li[name="${model.cid}"]`); if (model.isValid()) { $validationElement.find('.message-error').remove(); $validationElement.find('.save-button').removeClass('is-disabled'); diff --git a/cms/static/js/views/course_video_settings.js b/cms/static/js/views/course_video_settings.js index 4fe5586e12..81e6e96a56 100644 --- a/cms/static/js/views/course_video_settings.js +++ b/cms/static/js/views/course_video_settings.js @@ -612,7 +612,7 @@ function($, Backbone, _, gettext, moment, ViewUtils, HtmlUtils, StringUtils, Tra var $OrganizationApiSecretWrapperEl, $OrganizationUsernameWrapperEl, isValid = true, - $OrganizationApiKeyWrapperEl = this.$el.find('.' + this.selectedProvider + '-api-key-wrapper'); + $OrganizationApiKeyWrapperEl = this.$el.find(`.${this.selectedProvider}-api-key-wrapper`); // Explicit None selected case. if (this.selectedProvider === '') { @@ -627,7 +627,7 @@ function($, Backbone, _, gettext, moment, ViewUtils, HtmlUtils, StringUtils, Tra } if (this.selectedProvider === THREE_PLAY_MEDIA) { - $OrganizationApiSecretWrapperEl = this.$el.find('.' + this.selectedProvider + '-api-secret-wrapper'); + $OrganizationApiSecretWrapperEl = this.$el.find(`.${this.selectedProvider}-api-secret-wrapper`); if ($OrganizationApiSecretWrapperEl.find('input').val() === '') { isValid = false; this.addErrorState($OrganizationApiSecretWrapperEl); @@ -635,7 +635,7 @@ function($, Backbone, _, gettext, moment, ViewUtils, HtmlUtils, StringUtils, Tra this.clearPreferenceErrorState($OrganizationApiSecretWrapperEl); } } else { - $OrganizationUsernameWrapperEl = this.$el.find('.' + this.selectedProvider + '-username-wrapper'); + $OrganizationUsernameWrapperEl = this.$el.find(`.${this.selectedProvider}-username-wrapper`); if ($OrganizationUsernameWrapperEl.find('input').val() === '') { isValid = false; this.addErrorState($OrganizationUsernameWrapperEl); @@ -688,15 +688,15 @@ function($, Backbone, _, gettext, moment, ViewUtils, HtmlUtils, StringUtils, Tra var self = this, username, apiSecret, - apiKey = this.$el.find('.' + this.selectedProvider + '-api-key').val(); + apiKey = this.$el.find(`.${this.selectedProvider}-api-key`).val(); // First clear response status if present already this.clearResponseStatus(); if (this.selectedProvider === THREE_PLAY_MEDIA) { - apiSecret = this.$el.find('.' + this.selectedProvider + '-api-secret').val(); + apiSecret = this.$el.find(`.${this.selectedProvider}-api-secret`).val(); } else { - username = this.$el.find('.' + this.selectedProvider + '-username').val(); + username = this.$el.find(`.${this.selectedProvider}-username`).val(); } $.postJSON(self.transcriptCredentialsHandlerUrl, { diff --git a/cms/static/js/views/course_video_sharing_enable.js b/cms/static/js/views/course_video_sharing_enable.js index 964bfc44d1..e8a0d057c5 100644 --- a/cms/static/js/views/course_video_sharing_enable.js +++ b/cms/static/js/views/course_video_sharing_enable.js @@ -1,55 +1,56 @@ define([ - "jquery", - "underscore", - "backbone", - "js/views/utils/xblock_utils", - "js/utils/templates", - "js/views/modals/course_outline_modals", - "edx-ui-toolkit/js/utils/html-utils", -], function ($, _, Backbone, XBlockViewUtils, TemplateUtils, CourseOutlineModalsFactory, HtmlUtils) { - "use strict"; - var CourseVideoSharingEnableView = Backbone.View.extend({ - events: { - "change #video-sharing-configuration-options": "handleVideoSharingConfigurationChange", - }, + 'jquery', + 'underscore', + 'backbone', + 'js/views/utils/xblock_utils', + 'js/utils/templates', + 'js/views/modals/course_outline_modals', + 'edx-ui-toolkit/js/utils/html-utils', +], function($, _, Backbone, XBlockViewUtils, TemplateUtils, CourseOutlineModalsFactory, HtmlUtils) { + 'use strict'; - initialize: function () { - this.template = TemplateUtils.loadTemplate("course-video-sharing-enable"); - }, - - getRequestData: function (value) { - return { - metadata: { - 'video_sharing_options': value, + var CourseVideoSharingEnableView = Backbone.View.extend({ + events: { + 'change #video-sharing-configuration-options': 'handleVideoSharingConfigurationChange', }, - }; - }, - handleVideoSharingConfigurationChange: function (event) { - if (event.type === "change") { - event.preventDefault(); - this.updateVideoSharingConfiguration(event.target.value); - } - }, + initialize: function() { + this.template = TemplateUtils.loadTemplate('course-video-sharing-enable'); + }, - updateVideoSharingConfiguration: function (value) { - XBlockViewUtils.updateXBlockFields(this.model, this.getRequestData(value), { - success: this.refresh.bind(this) - }); - }, + getRequestData: function(value) { + return { + metadata: { + video_sharing_options: value, + }, + }; + }, - refresh: function () { - this.model.fetch({ - success: this.render.bind(this), - }); - }, + handleVideoSharingConfigurationChange: function(event) { + if (event.type === 'change') { + event.preventDefault(); + this.updateVideoSharingConfiguration(event.target.value); + } + }, - render: function () { - var html = this.template(this.model.attributes); - HtmlUtils.setHtml(this.$el, HtmlUtils.HTML(html)); - return this; - }, - }); + updateVideoSharingConfiguration: function(value) { + XBlockViewUtils.updateXBlockFields(this.model, this.getRequestData(value), { + success: this.refresh.bind(this) + }); + }, - return CourseVideoSharingEnableView; + refresh: function() { + this.model.fetch({ + success: this.render.bind(this), + }); + }, + + render: function() { + var html = this.template(this.model.attributes); + HtmlUtils.setHtml(this.$el, HtmlUtils.HTML(html)); + return this; + }, + }); + + return CourseVideoSharingEnableView; }); diff --git a/cms/static/js/views/edit_chapter.js b/cms/static/js/views/edit_chapter.js index 95ea31add4..165e170fc1 100644 --- a/cms/static/js/views/edit_chapter.js +++ b/cms/static/js/views/edit_chapter.js @@ -12,7 +12,7 @@ function(_, $, gettext, HtmlUtils, BaseView, FileUploadModel, UploadDialogView, }, tagName: 'li', className: function() { - return 'field-group chapter chapter' + this.model.get('order'); + return `field-group chapter chapter${this.model.get('order')}`; }, render: function() { HtmlUtils.setHtml( diff --git a/cms/static/js/views/experiment_group_edit.js b/cms/static/js/views/experiment_group_edit.js index 48abd6c771..c9e2180625 100644 --- a/cms/static/js/views/experiment_group_edit.js +++ b/cms/static/js/views/experiment_group_edit.js @@ -19,7 +19,7 @@ function(BaseView, _, str, gettext, groupEditTemplate) { className: function() { var index = this.model.collection.indexOf(this.model); - return 'field-group group group-' + index; + return `field-group group group-${index}`; }, initialize: function() { diff --git a/cms/static/js/views/export.js b/cms/static/js/views/export.js index 73007363b9..fe5e8dcf0d 100644 --- a/cms/static/js/views/export.js +++ b/cms/static/js/views/export.js @@ -118,7 +118,7 @@ define([ $dom.successStage .find('.item-progresspoint-success-date') - .text('(' + date + ' at ' + time + ' UTC)'); + .text(`(${date} at ${time} UTC)`); break; @@ -343,7 +343,7 @@ define([ + 'and try again.'); action = gettext('Take me to the main course page'); } - msg += ' ' + gettext('The raw error message is:') + ' ' + errMsg; + msg += ` ${gettext('The raw error message is:')} ${errMsg}`; dialog = new PromptView({ title: gettext('There has been an error with your export.'), message: msg, diff --git a/cms/static/js/views/group_configuration_details.js b/cms/static/js/views/group_configuration_details.js index 133f464cf9..aa46944279 100644 --- a/cms/static/js/views/group_configuration_details.js +++ b/cms/static/js/views/group_configuration_details.js @@ -23,7 +23,7 @@ function(BaseView, _, gettext, str, StringUtils, HtmlUtils) { return [ 'collection', 'group-configuration-details', - 'group-configuration-details-' + index + `group-configuration-details-${index}` ].join(' '); }, diff --git a/cms/static/js/views/group_configuration_editor.js b/cms/static/js/views/group_configuration_editor.js index e4187475d2..59bb2adcf1 100644 --- a/cms/static/js/views/group_configuration_editor.js +++ b/cms/static/js/views/group_configuration_editor.js @@ -27,7 +27,7 @@ function(ListItemEditorView, _, $, gettext, ExperimentGroupEditView) { return [ 'collection-edit', 'group-configuration-edit', - 'group-configuration-edit-' + index + `group-configuration-edit-${index}` ].join(' '); }, diff --git a/cms/static/js/views/list_item.js b/cms/static/js/views/list_item.js index 22327ebbc7..02e95a74a2 100644 --- a/cms/static/js/views/list_item.js +++ b/cms/static/js/views/list_item.js @@ -33,10 +33,10 @@ define([ return [ 'wrapper-collection', - 'wrapper-collection-' + index, + `wrapper-collection-${index}`, this.baseClassName, - this.baseClassName + 's-list-item', - this.baseClassName + 's-list-item-' + index + `${this.baseClassName}s-list-item`, + `${this.baseClassName}s-list-item-${index}` ].join(' '); }, diff --git a/cms/static/js/views/manage_users_and_roles.js b/cms/static/js/views/manage_users_and_roles.js index fd34945c67..6d6c530943 100644 --- a/cms/static/js/views/manage_users_and_roles.js +++ b/cms/static/js/views/manage_users_and_roles.js @@ -103,7 +103,7 @@ function($, _, gettext, BaseView, PromptView, ViewUtils, HtmlUtils) { var self = this; for (var i = 0; i < self.options.roles.length; i++) { var role_name = self.options.roles[i].key; - var role_selector = 'click .user-actions .make-' + role_name; + var role_selector = `click .user-actions .make-${role_name}`; (function(role) { roleEvents[role_selector] = function(event) { self.handleRoleButtonClick(event.target, role); }; diff --git a/cms/static/js/views/metadata.js b/cms/static/js/views/metadata.js index c56363ef7c..b03a485b9c 100644 --- a/cms/static/js/views/metadata.js +++ b/cms/static/js/views/metadata.js @@ -112,7 +112,7 @@ define( // If the model has property `non editable` equals `true`, // the field is disabled, but user is able to clear it. if (this.model.get('non_editable')) { - this.$el.find('#' + this.uniqueId) + this.$el.find(`#${this.uniqueId}`) .prop('readonly', true) .addClass('is-disabled') .attr('aria-disabled', true); @@ -120,7 +120,7 @@ define( }, getValueFromEditor: function() { - return this.$el.find('#' + this.uniqueId).val(); + return this.$el.find(`#${this.uniqueId}`).val(); }, setValueInEditor: function(value) { @@ -215,7 +215,7 @@ define( templateName: 'metadata-number-entry', getValueFromEditor: function() { - return this.$el.find('#' + this.uniqueId).val(); + return this.$el.find(`#${this.uniqueId}`).val(); }, setValueInEditor: function(value) { @@ -274,7 +274,7 @@ define( templateName: 'metadata-option-entry', getValueFromEditor: function() { - var selectedText = this.$el.find('#' + this.uniqueId).find(':selected').text(); + var selectedText = this.$el.find(`#${this.uniqueId}`).find(':selected').text(); var selectedValue; _.each(this.model.getOptions(), function(modelValue) { if (modelValue === selectedText) { @@ -294,7 +294,7 @@ define( value = modelValue.display_name; } }); - this.$el.find('#' + this.uniqueId + ' option').filter(function() { + this.$el.find(`#${this.uniqueId} option`).filter(function() { return $(this).text() === value; }).prop('selected', true); } @@ -407,7 +407,7 @@ define( templateName: 'metadata-string-entry', getValueFromEditor: function() { - var $input = this.$el.find('#' + this.uniqueId); + var $input = this.$el.find(`#${this.uniqueId}`); return $input.val(); }, @@ -433,7 +433,7 @@ define( parseRelativeTime: function(value) { // This function ensure you have two-digits var pad = function(number) { - return (number < 10) ? '0' + number : number; + return (number < 10) ? `0${number}` : number; }, // Removes all white-spaces and splits by `:`. list = value.replace(/\s+/g, '').split(':'), @@ -584,7 +584,7 @@ define( }, getValueFromEditor: function() { - return this.$('#' + this.uniqueId).val(); + return this.$(`#${this.uniqueId}`).val(); }, setValueInEditor: function(value) { @@ -593,14 +593,14 @@ define( uniqueId: this.uniqueId }); - this.$('#' + this.uniqueId).val(value); + this.$(`#${this.uniqueId}`).val(value); this.$('.wrapper-uploader-actions').html(HtmlUtils.HTML((html)).toString()); }, upload: function(event) { var self = this, $target = $(event.currentTarget), - url = '/assets/' + this.options.courseKey + '/', + url = `/assets/${this.options.courseKey}/`, model = new FileUpload({ title: gettext('Upload File') }), diff --git a/cms/static/js/views/modals/base_modal.js b/cms/static/js/views/modals/base_modal.js index 65b7f06ae0..3e3921f0ec 100644 --- a/cms/static/js/views/modals/base_modal.js +++ b/cms/static/js/views/modals/base_modal.js @@ -156,22 +156,22 @@ define(['jquery', 'underscore', 'gettext', 'js/views/baseview'], * Returns the action bar that contains the modal's action buttons. */ getActionBar: function() { - return this.$(this.options.modalWindowClass + ' > div > .modal-actions'); + return this.$(`${this.options.modalWindowClass} > div > .modal-actions`); }, /** * Returns the action button of the specified type. */ getActionButton: function(type) { - return this.getActionBar().find('.action-' + type); + return this.getActionBar().find(`.action-${type}`); }, enableActionButton: function(type) { - this.getActionBar().find('.action-' + type).prop('disabled', false).removeClass('is-disabled'); + this.getActionBar().find(`.action-${type}`).prop('disabled', false).removeClass('is-disabled'); }, disableActionButton: function(type) { - this.getActionBar().find('.action-' + type).prop('disabled', true).addClass('is-disabled'); + this.getActionBar().find(`.action-${type}`).prop('disabled', true).addClass('is-disabled'); }, resize: function() { diff --git a/cms/static/js/views/modals/course_outline_modals.js b/cms/static/js/views/modals/course_outline_modals.js index aefb13d286..5b6174320e 100644 --- a/cms/static/js/views/modals/course_outline_modals.js +++ b/cms/static/js/views/modals/course_outline_modals.js @@ -138,7 +138,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', _.map(tab.editors, function(Editor) { return new Editor({ parent: this, - parentElement: this.$('.modal-section .' + tab.name), + parentElement: this.$(`.modal-section .${tab.name}`), model: this.model, xblockType: this.options.xblockType, enable_proctored_exams: this.options.enable_proctored_exams, @@ -180,9 +180,9 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', showTab: function(tab) { this.$('.modal-section .settings-tab-button').removeClass('active'); - this.$('.modal-section .settings-tab-button[data-tab="' + tab + '"]').addClass('active'); + this.$(`.modal-section .settings-tab-button[data-tab="${tab}"]`).addClass('active'); this.$('.modal-section .settings-tab').hide(); - this.$('.modal-section .' + tab).show(); + this.$(`.modal-section .${tab}`).show(); } }); @@ -194,7 +194,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', initialize: function() { CourseOutlineXBlockModal.prototype.initialize.call(this); if (this.options.xblockType) { - this.options.modalName = 'bulkpublish-' + this.options.xblockType; + this.options.modalName = `bulkpublish-${this.options.xblockType}`; } }, @@ -228,7 +228,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', initialize: function() { CourseOutlineXBlockModal.prototype.initialize.call(this); if (this.options.xblockType) { - this.options.modalName = 'highlights-' + this.options.xblockType; + this.options.modalName = `highlights-${this.options.xblockType}`; } }, @@ -245,7 +245,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', callAnalytics: function(event) { event.preventDefault(); - window.analytics.track('edx.bi.highlights.' + event.target.innerText.toLowerCase()); + window.analytics.track(`edx.bi.highlights.${event.target.innerText.toLowerCase()}`); if (event.target.className.indexOf('save') !== -1) { this.save(event); } else { @@ -269,7 +269,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', initialize: function() { CourseOutlineXBlockModal.prototype.initialize.call(this); if (this.options.xblockType) { - this.options.modalName = 'highlights-enable-' + this.options.xblockType; + this.options.modalName = `highlights-enable-${this.options.xblockType}`; } }, @@ -283,7 +283,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', callAnalytics: function(event) { event.preventDefault(); - window.analytics.track('edx.bi.highlights_enable.' + event.target.innerText.toLowerCase()); + window.analytics.track(`edx.bi.highlights_enable.${event.target.innerText.toLowerCase()}`); if (event.target.className.indexOf('save') !== -1) { this.save(event); } else { @@ -408,13 +408,13 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', if (!this.getValue() || !course.get('start')) { return; } var startDate = new Date(course.get('start')); // The value returned by toUTCString() is a string in the form Www, dd Mmm yyyy hh:mm:ss GMT - var startDateList = startDate.toUTCString().split(' ') + var startDateList = startDate.toUTCString().split(' '); // This text will look like Mmm dd, yyyy (i.e. Jul 26, 2021) - this.$('#relative_weeks_due_start_date').text(startDateList[2] + ' ' + startDateList[1] + ', ' + startDateList[3]); - var projectedDate = new Date(startDate) - projectedDate.setDate(projectedDate.getDate() + this.getValue()*7); + this.$('#relative_weeks_due_start_date').text(`${startDateList[2]} ${startDateList[1]}, ${startDateList[3]}`); + var projectedDate = new Date(startDate); + projectedDate.setDate(projectedDate.getDate() + this.getValue() * 7); var projectedDateList = projectedDate.toUTCString().split(' '); - this.$('#relative_weeks_due_projected_due_in').text(projectedDateList[2] + ' ' + projectedDateList[1] + ', ' + projectedDateList[3]); + this.$('#relative_weeks_due_projected_due_in').text(`${projectedDateList[2]} ${projectedDateList[1]}, ${projectedDateList[3]}`); this.$('#relative_weeks_due_projected').show(); }, @@ -433,9 +433,9 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', afterRender: function() { AbstractEditor.prototype.afterRender.call(this); if (this.model.get('graded')) { - this.$('#relative_date_input').show() + this.$('#relative_date_input').show(); } else { - this.$('#relative_date_input').hide() + this.$('#relative_date_input').hide(); } this.$('.field-due-in input').val(this.model.get('relative_weeks_due')); this.$('#relative_weeks_due_projected').hide(); @@ -444,12 +444,12 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', getRequestData: function() { // Grab all the sections, map them to their block_ids, then return as an Array - var sectionIds = $('.outline-section').map(function(){ return this.id; }).get() + var sectionIds = $('.outline-section').map(function() { return this.id; }).get(); // Grab all the subsections, map them to their block_ids, then return as an Array - var subsectionIds = $('.outline-subsection').map(function(){ return this.id; }).get() + var subsectionIds = $('.outline-subsection').map(function() { return this.id; }).get(); var relative_weeks_due = null; if (this.getValue() > 0 && $('#grading_type').val() !== 'notgraded') { - relative_weeks_due = this.getValue() + relative_weeks_due = this.getValue(); } window.analytics.track('edx.bi.studio.relative_date.saved', { block_id: this.model.get('id'), @@ -613,11 +613,11 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', return this.$('.field-time-limit input').val(); }, convertTimeLimitMinutesToString: function(timeLimitMinutes) { - var hoursStr = '' + Math.floor(timeLimitMinutes / 60); - var actualMinutesStr = '' + (timeLimitMinutes % 60); + var hoursStr = `${Math.floor(timeLimitMinutes / 60)}`; + var actualMinutesStr = `${timeLimitMinutes % 60}`; hoursStr = '00'.substring(0, 2 - hoursStr.length) + hoursStr; actualMinutesStr = '00'.substring(0, 2 - actualMinutesStr.length) + actualMinutesStr; - return hoursStr + ':' + actualMinutesStr; + return `${hoursStr}:${actualMinutesStr}`; }, convertTimeLimitToMinutes: function(timeLimit) { var time = timeLimit.split(':'); @@ -673,7 +673,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', prereqMinScore = this.model.get('prereq_min_score') || '100'; prereqMinCompletion = this.model.get('prereq_min_completion') || '100'; this.$('#is_prereq').prop('checked', this.model.get('is_prereq')); - this.$('#prereq option[value="' + prereq + '"]').prop('selected', true); + this.$(`#prereq option[value="${prereq}"]`).prop('selected', true); this.$('#prereq_min_score').val(prereqMinScore); this.$('#prereq_min_score_input').toggle(prereq.length > 0); this.$('#prereq_min_completion').val(prereqMinCompletion); @@ -859,7 +859,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', if (keys.length === 1) { // should be only one partition key if (groupAccess.hasOwnProperty(keys[0]) && groupAccess[keys[0]].length > 0) { // Select the option that has group access, provided there is a specific group within the scheme - this.$('.user-partition-select option[value=' + keys[0] + ']').prop('selected', true); + this.$(`.user-partition-select option[value=${keys[0]}]`).prop('selected', true); this.showSelectedDiv(keys[0]); // Change default option to 'All Learners and Staff' if unit is currently restricted this.$('#partition-select option:first').text(gettext('All Learners and Staff')); @@ -877,7 +877,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', }, getSelectedCheckboxesByDivId: function(contentGroupId) { - var $checkboxes = $('#' + contentGroupId + '-checkboxes input:checked'), + var $checkboxes = $(`#${contentGroupId}-checkboxes input:checked`), selectedCheckboxValues = [], i; for (i = 0; i < $checkboxes.length; i++) { @@ -887,7 +887,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', }, showSelectedDiv: function(contentGroupId) { - $('#' + contentGroupId + '-checkboxes').show(); + $(`#${contentGroupId}-checkboxes`).show(); }, hideCheckboxDivs: function() { @@ -944,16 +944,16 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', showTipText: function() { if (this.model.get('published')) { - $('.un-published-tip').hide() + $('.un-published-tip').hide(); } else { - $('.un-published-tip').show() + $('.un-published-tip').show(); } - let enabledForGraded = course.get('discussions_settings').enable_graded_units + let enabledForGraded = course.get('discussions_settings').enable_graded_units; if (this.model.get('graded') && !enabledForGraded) { $('#discussion_enabled').prop('disabled', true); - $('.graded-tip').show() + $('.graded-tip').show(); } else { - $('.graded-tip').hide() + $('.graded-tip').hide(); } }, @@ -1012,7 +1012,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', }, setVisibility: function(value) { - this.$('input[name=content-visibility][value=' + value + ']').prop('checked', true); + this.$(`input[name=content-visibility][value=${value}]`).prop('checked', true); }, currentVisibility: function() { @@ -1085,7 +1085,7 @@ define(['jquery', 'backbone', 'underscore', 'gettext', 'js/views/baseview', }, setValue: function(value) { - this.$('input[name=show-correctness][value=' + value + ']').prop('checked', true); + this.$(`input[name=show-correctness][value=${value}]`).prop('checked', true); }, currentValue: function() { diff --git a/cms/static/js/views/modals/edit_xblock.js b/cms/static/js/views/modals/edit_xblock.js index 7182d8b0e5..304ef714db 100644 --- a/cms/static/js/views/modals/edit_xblock.js +++ b/cms/static/js/views/modals/edit_xblock.js @@ -163,7 +163,7 @@ function($, _, Backbone, gettext, BaseModal, ViewUtils, XBlockViewUtils, XBlockE editorView.selectMode(mode); this.$('.editor-modes a').removeClass('is-set'); if (mode) { - buttonSelector = '.' + mode + '-button'; + buttonSelector = `.${mode}-button`; this.$(buttonSelector).addClass('is-set'); } }, diff --git a/cms/static/js/views/modals/move_xblock_modal.js b/cms/static/js/views/modals/move_xblock_modal.js index 8b3abad070..64096eae73 100644 --- a/cms/static/js/views/modals/move_xblock_modal.js +++ b/cms/static/js/views/modals/move_xblock_modal.js @@ -178,7 +178,7 @@ function($, Backbone, _, gettext, BaseView, XBlockViewUtils, MoveXBlockUtils, Ht moveXBlock: function() { MoveXBlockUtils.moveXBlock( { - sourceXBlockElement: $("li.studio-xblock-wrapper[data-locator='" + this.sourceXBlockInfo.id + "']"), + sourceXBlockElement: $(`li.studio-xblock-wrapper[data-locator='${this.sourceXBlockInfo.id}']`), sourceDisplayName: this.sourceXBlockInfo.get('display_name'), sourceLocator: this.sourceXBlockInfo.id, sourceParentLocator: this.sourceParentXBlockInfo.id, diff --git a/cms/static/js/views/module_edit.js b/cms/static/js/views/module_edit.js index fe3bba5821..ce1166bb3a 100644 --- a/cms/static/js/views/module_edit.js +++ b/cms/static/js/views/module_edit.js @@ -57,7 +57,7 @@ callback = function() {}; } payload.parent_locator = parent; - return $.postJSON(this.model.urlRoot + '/', payload, function(data) { + return $.postJSON(`${this.model.urlRoot}/`, payload, function(data) { _this.model.set({ id: data.locator }); @@ -71,7 +71,7 @@ var _this = this; if (this.model.id) { return $.ajax({ - url: '' + (decodeURIComponent(this.model.url())) + '/' + viewName, + url: `${decodeURIComponent(this.model.url())}/${viewName}`, type: 'GET', cache: false, headers: { diff --git a/cms/static/js/views/paged_container.js b/cms/static/js/views/paged_container.js index 31c123ad12..a93c19b69e 100644 --- a/cms/static/js/views/paged_container.js +++ b/cms/static/js/views/paged_container.js @@ -90,7 +90,7 @@ function($, _, ViewUtils, ContainerView, ModuleUtils, gettext, NotificationView, xblockUrl = xblockInfo.url(); return $.ajax({ - url: decodeURIComponent(xblockUrl) + '/' + view, + url: `${decodeURIComponent(xblockUrl)}/${view}`, type: 'GET', cache: false, data: this.getRenderParameters(options.page_number, options.force_render), @@ -102,14 +102,14 @@ function($, _, ViewUtils, ContainerView, ModuleUtils, gettext, NotificationView, self.page.updatePreviewButton(self.collection.showChildrenPreviews); self.page.renderAddXBlockComponents(); if (options.force_render) { - var $target = $('.studio-xblock-wrapper[data-locator="' + options.force_render + '"]'); + var $target = $(`.studio-xblock-wrapper[data-locator="${options.force_render}"]`); // Scroll us to the element with a little buffer at the top for context. ViewUtils.setScrollOffset($target, ($(window).height() * 0.10)); } if (originalDone) { originalDone(); } - } + }; self.handleXBlockFragment(fragment, options); } }); @@ -265,7 +265,7 @@ function($, _, ViewUtils, ContainerView, ModuleUtils, gettext, NotificationView, xblockUrl = this.model.url(); return $.ajax({ // No runtime, so can't get this via the handler() call. - url: '/preview' + decodeURIComponent(xblockUrl) + '/handler/trigger_previews', + url: `/preview${decodeURIComponent(xblockUrl)}/handler/trigger_previews`, type: 'POST', data: JSON.stringify({showChildrenPreviews: !this.collection.showChildrenPreviews}), dataType: 'json' diff --git a/cms/static/js/views/pages/container.js b/cms/static/js/views/pages/container.js index 1793f28e75..304367cb1e 100644 --- a/cms/static/js/views/pages/container.js +++ b/cms/static/js/views/pages/container.js @@ -265,19 +265,19 @@ function($, _, Backbone, gettext, BasePage, ViewUtils, ContainerView, XBlockView editXBlock: function(event, options) { event.preventDefault(); - if(!options || options.view !== 'visibility_view' ){ - const primaryHeader = $(event.target).closest('.xblock-header-primary') + if (!options || options.view !== 'visibility_view') { + const primaryHeader = $(event.target).closest('.xblock-header-primary'); var useNewTextEditor = primaryHeader.attr('use-new-editor-text'), useNewVideoEditor = primaryHeader.attr('use-new-editor-video'), useNewProblemEditor = primaryHeader.attr('use-new-editor-problem'), blockType = primaryHeader.attr('data-block-type'); - if( (useNewTextEditor === 'True' && blockType === 'html') + if((useNewTextEditor === 'True' && blockType === 'html') || (useNewVideoEditor === 'True' && blockType === 'video') || (useNewProblemEditor === 'True' && blockType === 'problem') ) { - var destinationUrl = primaryHeader.attr('authoring_MFE_base_url') + '/' + blockType + '/' + encodeURI(primaryHeader.attr('data-usage-id')); + var destinationUrl = `${primaryHeader.attr('authoring_MFE_base_url')}/${blockType}/${encodeURI(primaryHeader.attr('data-usage-id'))}`; window.location.href = destinationUrl; return; } @@ -365,7 +365,7 @@ function($, _, Backbone, gettext, BasePage, ViewUtils, ContainerView, XBlockView }), placeholderElement; placeholderElement = $placeholderEl.appendTo(listPanel); - return $.postJSON(this.getURLRoot() + '/', requestData, + return $.postJSON(`${this.getURLRoot()}/`, requestData, _.bind(this.onNewXBlock, this, placeholderElement, scrollOffset, false)) .fail(function() { // Remove the placeholder if the update failed @@ -476,15 +476,15 @@ function($, _, Backbone, gettext, BasePage, ViewUtils, ContainerView, XBlockView useNewProblemEditor = this.$('.xblock-header-primary').attr('use-new-editor-problem'); // find the block type in the locator if availible - if(data.hasOwnProperty('locator')){ + if(data.hasOwnProperty('locator')) { var matchBlockTypeFromLocator = /\@(.*?)\+/; var blockType = data.locator.match(matchBlockTypeFromLocator); } if((useNewTextEditor === 'True' && blockType.includes('html')) || (useNewVideoEditor === 'True' && blockType.includes('video')) - ||(useNewProblemEditor === 'True' && blockType.includes('problem')) - ){ - var destinationUrl = this.$('.xblock-header-primary').attr('authoring_MFE_base_url') + '/' + blockType[1] + '/' + encodeURI(data.locator); + || (useNewProblemEditor === 'True' && blockType.includes('problem')) + ) { + var destinationUrl = `${this.$('.xblock-header-primary').attr('authoring_MFE_base_url')}/${blockType[1]}/${encodeURI(data.locator)}`; window.location.href = destinationUrl; return; } diff --git a/cms/static/js/views/pages/course_outline.js b/cms/static/js/views/pages/course_outline.js index 78a69baa9a..31227f4aa1 100644 --- a/cms/static/js/views/pages/course_outline.js +++ b/cms/static/js/views/pages/course_outline.js @@ -125,7 +125,7 @@ function($, _, gettext, BasePage, XBlockViewUtils, CourseOutlineView, ViewUtils, * at 100 millisecond intervals until element is found or * Polling is reached */ - scrollToElement: function () { + scrollToElement: function() { this.findElementPollingTimeout -= this.pollingDelay; const elementID = window.location.hash.replace('#', ''); diff --git a/cms/static/js/views/pages/group_configurations.js b/cms/static/js/views/pages/group_configurations.js index 680bbda659..0336ae3db0 100644 --- a/cms/static/js/views/pages/group_configurations.js +++ b/cms/static/js/views/pages/group_configurations.js @@ -43,7 +43,7 @@ function($, _, gettext, BasePage, GroupConfigurationsListView, PartitionGroupLis // Render the remaining Configuration groups for (i = 0; i < this.allGroupViewList.length; i++) { - currentClass = '.wrapper-groups.content-groups.' + this.allGroupViewList[i].scheme; + currentClass = `.wrapper-groups.content-groups.${this.allGroupViewList[i].scheme}`; this.$(currentClass).append(this.allGroupViewList[i].render().el); } @@ -103,7 +103,7 @@ function($, _, gettext, BasePage, GroupConfigurationsListView, PartitionGroupLis if (groupConfig) { groupConfig.set('showGroups', true); - this.$('#' + id).focus(); + this.$(`#${id}`).focus(); } } }); diff --git a/cms/static/js/views/paging.js b/cms/static/js/views/paging.js index 3b8abb4f17..b0df084707 100644 --- a/cms/static/js/views/paging.js +++ b/cms/static/js/views/paging.js @@ -26,7 +26,7 @@ var sortColumn = this.collection.sortColumn; this.renderPageItems(); this.$('.column-sort-link').removeClass('current-sort'); - this.$('#' + sortColumn).addClass('current-sort'); + this.$(`#${sortColumn}`).addClass('current-sort'); }, onError: function() { @@ -55,7 +55,7 @@ filterableColumnInfo: function(filterColumn) { var filterInfo = this.filterableColumns[filterColumn]; if (!filterInfo) { - throw "Unregistered filter column '" + filterInfo + '"'; + throw `Unregistered filter column '${filterInfo}"`; } return filterInfo; }, @@ -91,7 +91,7 @@ sortableColumnInfo: function(sortColumn) { var sortInfo = this.sortableColumns[sortColumn]; if (!sortInfo) { - throw "Unregistered sort column '" + sortColumn + '"'; + throw `Unregistered sort column '${sortColumn}"`; } return sortInfo; }, diff --git a/cms/static/js/views/partition_group_details.js b/cms/static/js/views/partition_group_details.js index 4740e460b5..95cdcaf2a0 100644 --- a/cms/static/js/views/partition_group_details.js +++ b/cms/static/js/views/partition_group_details.js @@ -22,7 +22,7 @@ define([ return [ 'collection', 'partition-group-details', - 'partition-group-details-' + index + `partition-group-details-${index}` ].join(' '); }, diff --git a/cms/static/js/views/previous_video_upload.js b/cms/static/js/views/previous_video_upload.js index bc2cb2b0d6..4632c91b69 100644 --- a/cms/static/js/views/previous_video_upload.js +++ b/cms/static/js/views/previous_video_upload.js @@ -81,7 +81,7 @@ define( gettext('Removing'), function() { return $.ajax({ - url: videoView.videoHandlerUrl + '/' + videoView.model.get('edx_video_id'), + url: `${videoView.videoHandlerUrl}/${videoView.model.get('edx_video_id')}`, type: 'DELETE' }).done(function() { videoView.remove(); diff --git a/cms/static/js/views/settings/advanced.js b/cms/static/js/views/settings/advanced.js index 0a3eaf82ae..03b6ad4046 100644 --- a/cms/static/js/views/settings/advanced.js +++ b/cms/static/js/views/settings/advanced.js @@ -91,7 +91,7 @@ function(ValidatingView, $, _, gettext, CodeMirror, ValidationErrorModal, HtmlUt var firstNonWhite = stringValue.substring(0, 1); if (firstNonWhite !== '{' && firstNonWhite !== '[' && firstNonWhite !== "'") { try { - stringValue = '"' + stringValue + '"'; + stringValue = `"${stringValue}"`; JSONValue = JSON.parse(stringValue); mirror.setValue(stringValue); } catch (quotedE) { diff --git a/cms/static/js/views/settings/grading.js b/cms/static/js/views/settings/grading.js index fea7dd78e0..60b817c940 100644 --- a/cms/static/js/views/settings/grading.js +++ b/cms/static/js/views/settings/grading.js @@ -114,11 +114,11 @@ function(ValidatingView, _, $, ui, GraderView, StringUtils, HtmlUtils) { }, renderGracePeriod: function() { var format = function(time) { - return time >= 10 ? time.toString() : '0' + time; + return time >= 10 ? time.toString() : `0${time}`; }; var grace_period = this.model.get('grace_period'); this.$el.find('#course-grading-graceperiod').val( - format(grace_period.hours) + ':' + format(grace_period.minutes) + `${format(grace_period.hours)}:${format(grace_period.minutes)}` ); }, renderMinimumGradeCredit: function() { @@ -266,7 +266,7 @@ function(ValidatingView, _, $, ui, GraderView, StringUtils, HtmlUtils) { this.$el.find('.range').each(function(i) { var min = (i < cutoffs.length ? cutoffs[i].cutoff : 0); var max = (i > 0 ? cutoffs[i - 1].cutoff : 100); - $(this).text(min + '-' + max); + $(this).text(`${min}-${max}`); }); }, diff --git a/cms/static/js/views/settings/main.js b/cms/static/js/views/settings/main.js index 4f5b358cdc..a713e41b01 100644 --- a/cms/static/js/views/settings/main.js +++ b/cms/static/js/views/settings/main.js @@ -87,33 +87,33 @@ function(ValidatingView, CodeMirror, _, $, ui, DateUtils, FileUploadModel, DateUtils.setupDatePicker('enrollment_end', this); DateUtils.setupDatePicker('upgrade_deadline', this); - this.$el.find('#' + this.fieldToSelectorMap.overview).val(this.model.get('overview')); + this.$el.find(`#${this.fieldToSelectorMap.overview}`).val(this.model.get('overview')); this.codeMirrorize(null, $('#course-overview')[0]); if (this.model.get('title') !== '') { - this.$el.find('#' + this.fieldToSelectorMap.title).val(this.model.get('title')); + this.$el.find(`#${this.fieldToSelectorMap.title}`).val(this.model.get('title')); } else { - var displayName = this.$el.find('#' + this.fieldToSelectorMap.title).attr('data-display-name'); - this.$el.find('#' + this.fieldToSelectorMap.title).val(displayName); + var displayName = this.$el.find(`#${this.fieldToSelectorMap.title}`).attr('data-display-name'); + this.$el.find(`#${this.fieldToSelectorMap.title}`).val(displayName); } - this.$el.find('#' + this.fieldToSelectorMap.subtitle).val(this.model.get('subtitle')); - this.$el.find('#' + this.fieldToSelectorMap.duration).val(this.model.get('duration')); - this.$el.find('#' + this.fieldToSelectorMap.description).val(this.model.get('description')); + this.$el.find(`#${this.fieldToSelectorMap.subtitle}`).val(this.model.get('subtitle')); + this.$el.find(`#${this.fieldToSelectorMap.duration}`).val(this.model.get('duration')); + this.$el.find(`#${this.fieldToSelectorMap.description}`).val(this.model.get('description')); - this.$el.find('#' + this.fieldToSelectorMap.short_description).val(this.model.get('short_description')); - this.$el.find('#' + this.fieldToSelectorMap.about_sidebar_html).val( + this.$el.find(`#${this.fieldToSelectorMap.short_description}`).val(this.model.get('short_description')); + this.$el.find(`#${this.fieldToSelectorMap.about_sidebar_html}`).val( this.model.get('about_sidebar_html') ); this.codeMirrorize(null, $('#course-about-sidebar-html')[0]); this.$el.find('.current-course-introduction-video iframe').attr('src', this.model.videosourceSample()); - this.$el.find('#' + this.fieldToSelectorMap.intro_video).val(this.model.get('intro_video') || ''); + this.$el.find(`#${this.fieldToSelectorMap.intro_video}`).val(this.model.get('intro_video') || ''); if (this.model.has('intro_video')) { this.$el.find('.remove-course-introduction-video').show(); } else { this.$el.find('.remove-course-introduction-video').hide(); } - this.$el.find('#' + this.fieldToSelectorMap.effort).val(this.model.get('effort')); - this.$el.find('#' + this.fieldToSelectorMap.certificates_display_behavior).val(this.model.get('certificates_display_behavior')); + this.$el.find(`#${this.fieldToSelectorMap.effort}`).val(this.model.get('effort')); + this.$el.find(`#${this.fieldToSelectorMap.certificates_display_behavior}`).val(this.model.get('certificates_display_behavior')); this.updateCertificatesDisplayBehavior(); var courseImageURL = this.model.get('course_image_asset_path'); @@ -130,16 +130,16 @@ function(ValidatingView, CodeMirror, _, $, ui, DateUtils, FileUploadModel, var pre_requisite_courses = this.model.get('pre_requisite_courses'); pre_requisite_courses = pre_requisite_courses.length > 0 ? pre_requisite_courses : ''; - this.$el.find('#' + this.fieldToSelectorMap.pre_requisite_courses).val(pre_requisite_courses); + this.$el.find(`#${this.fieldToSelectorMap.pre_requisite_courses}`).val(pre_requisite_courses); if (this.model.get('entrance_exam_enabled') == 'true') { - this.$('#' + this.fieldToSelectorMap.entrance_exam_enabled).attr('checked', this.model.get('entrance_exam_enabled')); + this.$(`#${this.fieldToSelectorMap.entrance_exam_enabled}`).attr('checked', this.model.get('entrance_exam_enabled')); this.$('.div-grade-requirements').show(); } else { - this.$('#' + this.fieldToSelectorMap.entrance_exam_enabled).removeAttr('checked'); + this.$(`#${this.fieldToSelectorMap.entrance_exam_enabled}`).removeAttr('checked'); this.$('.div-grade-requirements').hide(); } - this.$('#' + this.fieldToSelectorMap.entrance_exam_minimum_score_pct).val(this.model.get('entrance_exam_minimum_score_pct')); + this.$(`#${this.fieldToSelectorMap.entrance_exam_minimum_score_pct}`).val(this.model.get('entrance_exam_minimum_score_pct')); var selfPacedButton = this.$('#course-pace-self-paced'), instructorPacedButton = this.$('#course-pace-instructor-paced'), @@ -233,16 +233,16 @@ function(ValidatingView, CodeMirror, _, $, ui, DateUtils, FileUploadModel, var value; var index = event.currentTarget.getAttribute('data-index'); switch (event.currentTarget.id) { - case 'course-learning-info-' + index: + case `course-learning-info-${index}`: value = $(event.currentTarget).val(); var learningInfo = this.model.get('learning_info'); learningInfo[index] = value; this.showNotificationBar(); break; - case 'course-instructor-name-' + index: - case 'course-instructor-title-' + index: - case 'course-instructor-organization-' + index: - case 'course-instructor-bio-' + index: + case `course-instructor-name-${index}`: + case `course-instructor-title-${index}`: + case `course-instructor-organization-${index}`: + case `course-instructor-bio-${index}`: value = $(event.currentTarget).val(); var field = event.currentTarget.getAttribute('data-field'), instructors = this.model.get('instructor_info').instructors.slice(0); @@ -250,12 +250,12 @@ function(ValidatingView, CodeMirror, _, $, ui, DateUtils, FileUploadModel, this.model.set('instructor_info', {instructors: instructors}); this.showNotificationBar(); break; - case 'course-instructor-image-' + index: + case `course-instructor-image-${index}`: instructors = this.model.get('instructor_info').instructors.slice(0); instructors[index].image = $(event.currentTarget).val(); this.model.set('instructor_info', {instructors: instructors}); this.showNotificationBar(); - this.updateImagePreview(event.currentTarget, '#course-instructor-image-preview-' + index); + this.updateImagePreview(event.currentTarget, `#course-instructor-image-preview-${index}`); break; case 'course-image-url': this.updateImageField(event, 'course_image_name', '#course-image'); @@ -345,7 +345,7 @@ function(ValidatingView, CodeMirror, _, $, ui, DateUtils, FileUploadModel, if (this.model.has('intro_video')) { this.model.set_videosource(null); this.$el.find('.current-course-introduction-video iframe').attr('src', ''); - this.$el.find('#' + this.fieldToSelectorMap.intro_video).val(''); + this.$el.find(`#${this.fieldToSelectorMap.intro_video}`).val(''); this.$el.find('.remove-course-introduction-video').hide(); } }, @@ -379,7 +379,7 @@ function(ValidatingView, CodeMirror, _, $, ui, DateUtils, FileUploadModel, } }); cmTextArea = this.codeMirrors[thisTarget.id].getInputField(); - cmTextArea.setAttribute('id', thisTarget.id + '-cm-textarea'); + cmTextArea.setAttribute('id', `${thisTarget.id}-cm-textarea`); } }, @@ -388,7 +388,7 @@ function(ValidatingView, CodeMirror, _, $, ui, DateUtils, FileUploadModel, Hides and clears the certificate available date field if a display behavior that doesn't use it is chosen. Because we are clearing it, toggling back to "end_with_date" will require re-entering the date */ - if (!this.useV2CertDisplaySettings){ + if (!this.useV2CertDisplaySettings) { return; } let showDatepicker = this.model.get('certificates_display_behavior') == 'end_with_date'; @@ -402,7 +402,7 @@ function(ValidatingView, CodeMirror, _, $, ui, DateUtils, FileUploadModel, datepicker.prop('disabled', true); datepicker.val(null); this.clearValidationErrors(); - this.setAndValidate('certificate_available_date', null) + this.setAndValidate('certificate_available_date', null); certificateAvailableDateField.addClass('hidden'); } }, diff --git a/cms/static/js/views/utils/move_xblock_utils.js b/cms/static/js/views/utils/move_xblock_utils.js index 9bde9c6d08..96ac0d1754 100644 --- a/cms/static/js/views/utils/move_xblock_utils.js +++ b/cms/static/js/views/utils/move_xblock_utils.js @@ -92,7 +92,7 @@ function($, _, Backbone, Feedback, AlertView, XBlockViewUtils, MoveXBlockUtils, text: gettext('Take me to the new location'), class: 'action-cancel', click: function() { - redirectLink('/container/' + data.targetParentLocator); + redirectLink(`/container/${data.targetParentLocator}`); } } ] diff --git a/cms/static/js/views/utils/xblock_utils.js b/cms/static/js/views/utils/xblock_utils.js index d3c1fce9e0..9b56b2d2e5 100644 --- a/cms/static/js/views/utils/xblock_utils.js +++ b/cms/static/js/views/utils/xblock_utils.js @@ -52,7 +52,7 @@ function($, _, gettext, ViewUtils, ModuleUtils, XBlockInfo, StringUtils) { return ViewUtils.runOperationShowingMessage(gettext('Adding'), function() { var addOperation = $.Deferred(); - analytics.track('Created a ' + category, { + analytics.track(`Created a ${category}`, { course: course_location_analytics, display_name: displayName }); @@ -151,7 +151,7 @@ function($, _, gettext, ViewUtils, ModuleUtils, XBlockInfo, StringUtils) { ); if (xblockInfo.get('is_prereq')) { - messageBody += ' ' + gettext('Any content that has listed this content as a prerequisite will also have access limitations removed.'); // eslint-disable-line max-len + messageBody += ` ${gettext('Any content that has listed this content as a prerequisite will also have access limitations removed.')}`; // eslint-disable-line max-len ViewUtils.confirmThenRunOperation( StringUtils.interpolate( gettext('Delete this {xblock_type} (and prerequisite)?'), diff --git a/cms/static/js/views/validation.js b/cms/static/js/views/validation.js index 1cc8635ffb..d8974b3540 100644 --- a/cms/static/js/views/validation.js +++ b/cms/static/js/views/validation.js @@ -38,7 +38,7 @@ function(HtmlUtils, BaseView, _, $, gettext, NotificationView, AlertView) { this.clearValidationErrors(); // error is object w/ fields and error strings for (var field in error) { - var ele = this.$el.find('#' + this.fieldToSelectorMap[field]); + var ele = this.$el.find(`#${this.fieldToSelectorMap[field]}`); this._cacheValidationErrors.push(ele); this.getInputElements(ele).addClass('error'); HtmlUtils.append($(ele).parent(), this.errorTemplate({message: error[field]})); @@ -79,10 +79,10 @@ function(HtmlUtils, BaseView, _, $, gettext, NotificationView, AlertView) { }, // these should perhaps go into a superclass but lack of event hash inheritance demotivates me inputFocus: function(event) { - $("label[for='" + event.currentTarget.id + "']").addClass('is-focused'); + $(`label[for='${event.currentTarget.id}']`).addClass('is-focused'); }, inputUnfocus: function(event) { - $("label[for='" + event.currentTarget.id + "']").removeClass('is-focused'); + $(`label[for='${event.currentTarget.id}']`).removeClass('is-focused'); }, getInputElements: function(ele) { diff --git a/cms/static/js/views/video/transcripts/file_uploader.js b/cms/static/js/views/video/transcripts/file_uploader.js index 5c635fdc4d..b7cc882a1f 100644 --- a/cms/static/js/views/video/transcripts/file_uploader.js +++ b/cms/static/js/views/video/transcripts/file_uploader.js @@ -176,7 +176,7 @@ define( * */ xhrProgressHandler: function(event, position, total, percentComplete) { - var percentVal = percentComplete + '%'; + var percentVal = `${percentComplete}%`; this.$progress .width(percentVal) diff --git a/cms/static/js/views/video/transcripts/utils.js b/cms/static/js/views/video/transcripts/utils.js index fae39400bd..2d6573dfce 100644 --- a/cms/static/js/views/video/transcripts/utils.js +++ b/cms/static/js/views/video/transcripts/utils.js @@ -204,7 +204,7 @@ define(['jquery', 'underscore', 'jquery.ajaxQueue'], function($) { * _getYoutubeLink('OEoXaMPEzfM'); => 'http://youtu.be/OEoXaMPEzfM' */ var _getYoutubeLink = function(video_id) { - return 'http://youtu.be/' + video_id; + return `http://youtu.be/${video_id}`; }; /** @@ -302,7 +302,7 @@ define(['jquery', 'underscore', 'jquery.ajaxQueue'], function($) { ); xhr = $.ajaxQueue({ - url: '/transcripts/' + action, + url: `/transcripts/${action}`, data: {data: JSON.stringify(data)}, notifyOnError: false, type: 'get' diff --git a/cms/static/js/views/video/translations_editor.js b/cms/static/js/views/video/translations_editor.js index 89df139e7b..4663df1654 100644 --- a/cms/static/js/views/video/translations_editor.js +++ b/cms/static/js/views/video/translations_editor.js @@ -35,7 +35,7 @@ define( languageMap = {}; if (!tpl) { - console.error("Couldn't load template for item: " + templateName); + console.error(`Couldn't load template for item: ${templateName}`); } this.templateItem = _.template(tpl); diff --git a/cms/static/js/views/video_thumbnail.js b/cms/static/js/views/video_thumbnail.js index 2089b8a18c..48fa447a5f 100644 --- a/cms/static/js/views/video_thumbnail.js +++ b/cms/static/js/views/video_thumbnail.js @@ -105,21 +105,21 @@ define( return item === '.bmp2' || item === '.jpeg'; }).sort(); return { - humanize: supportedFormats.slice(0, -1).join(', ') + ' or ' + supportedFormats.slice(-1), + humanize: `${supportedFormats.slice(0, -1).join(', ')} or ${supportedFormats.slice(-1)}`, machine: _.values(this.videoImageSettings.supported_file_formats) }; }, getVideoImageMaxSize: function() { return { - humanize: this.videoImageSettings.max_size / (1024 * 1024) + ' MB', + humanize: `${this.videoImageSettings.max_size / (1024 * 1024)} MB`, machine: this.videoImageSettings.max_size }; }, getVideoImageMinSize: function() { return { - humanize: this.videoImageSettings.min_size / 1024 + ' KB', + humanize: `${this.videoImageSettings.min_size / 1024} KB`, machine: this.videoImageSettings.min_size }; }, @@ -210,12 +210,12 @@ define( getDurationTextMachine: function(durationSeconds) { var minutes = Math.floor(durationSeconds / 60), seconds = Math.floor(durationSeconds - minutes * 60); - return minutes + ':' + (seconds < 10 ? '0' : '') + seconds; + return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`; }, chooseFile: function() { this.$('.upload-image-input').fileupload({ - url: this.imageUploadURL + '/' + encodeURIComponent(this.model.get('edx_video_id')), + url: `${this.imageUploadURL}/${encodeURIComponent(this.model.get('edx_video_id'))}`, add: this.imageSelected, done: this.imageUploadSucceeded, fail: this.imageUploadFailed @@ -346,7 +346,7 @@ define( }, clearErrorMessage: function(videoId) { - var $thumbnailWrapperEl = $('.thumbnail-error-wrapper[data-video-id="' + videoId + '"]'); + var $thumbnailWrapperEl = $(`.thumbnail-error-wrapper[data-video-id="${videoId}"]`); if ($thumbnailWrapperEl.length) { $thumbnailWrapperEl.remove(); } diff --git a/cms/static/js/views/video_transcripts.js b/cms/static/js/views/video_transcripts.js index 0aa57cbb83..eb3944285b 100644 --- a/cms/static/js/views/video_transcripts.js +++ b/cms/static/js/views/video_transcripts.js @@ -211,7 +211,7 @@ define( transcriptUploadSucceeded: function(event, data) { var languageCode = data.formData.language_code, newLanguageCode = data.formData.new_language_code, - $transcriptContainer = this.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + $transcriptContainer = this.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len $transcriptContainer.attr('data-language-code', newLanguageCode); $transcriptContainer.find('.download-transcript-button').attr( @@ -240,7 +240,7 @@ define( transcriptUploadFailed: function(event, data) { var errorMessage, languageCode = data.formData.language_code, - $transcriptContainer = this.$el.find('.video-transcript-content[data-language-code="' + languageCode + '"]'); // eslint-disable-line max-len + $transcriptContainer = this.$el.find(`.video-transcript-content[data-language-code="${languageCode}"]`); // eslint-disable-line max-len try { errorMessage = JSON.parse(data.jqXHR.responseText).error; diff --git a/cms/static/js/views/xblock.js b/cms/static/js/views/xblock.js index 2330c9deb5..e533475ef0 100644 --- a/cms/static/js/views/xblock.js +++ b/cms/static/js/views/xblock.js @@ -25,7 +25,7 @@ function($, _, ViewUtils, BaseView, XBlock, HtmlUtils) { xblockInfo = this.model, xblockUrl = xblockInfo.url(); return $.ajax({ - url: decodeURIComponent(xblockUrl) + '/' + view, + url: `${decodeURIComponent(xblockUrl)}/${view}`, type: 'GET', cache: false, headers: {Accept: 'application/json'}, @@ -220,15 +220,15 @@ function($, _, ViewUtils, BaseView, XBlock, HtmlUtils) { if (mimetype === 'text/css') { if (kind === 'text') { // xss-lint: disable=javascript-jquery-append,javascript-concat-html - $head.append(''); + $head.append(``); } else if (kind === 'url') { // xss-lint: disable=javascript-jquery-append,javascript-concat-html - $head.append(''); + $head.append(``); } } else if (mimetype === 'application/javascript') { if (kind === 'text') { // xss-lint: disable=javascript-jquery-append,javascript-concat-html - $head.append(''); + $head.append(``); } else if (kind === 'url') { return ViewUtils.loadJavaScript(data); } diff --git a/cms/static/js/views/xblock_outline.js b/cms/static/js/views/xblock_outline.js index c3ab7a8b0c..ac4005f378 100644 --- a/cms/static/js/views/xblock_outline.js +++ b/cms/static/js/views/xblock_outline.js @@ -253,12 +253,12 @@ function($, _, gettext, BaseView, ViewUtils, XBlockViewUtils, XBlockStringFieldE if (locatorToShow === this.model.id) { locatorElement = this.$el; } else { - locatorElement = this.$('.outline-item[data-locator="' + locatorToShow + '"]'); + locatorElement = this.$(`.outline-item[data-locator="${locatorToShow}"]`); } if (locatorElement.length > 0) { ViewUtils.setScrollOffset(locatorElement, scrollOffset); } else { - console.error('Failed to show item with locator ' + locatorToShow + ''); + console.error(`Failed to show item with locator ${locatorToShow}`); } if (editDisplayName) { locatorElement.find('> div[class$="header"] .xblock-field-value-edit').click(); @@ -285,7 +285,7 @@ function($, _, gettext, BaseView, ViewUtils, XBlockViewUtils, XBlockStringFieldE }, onUnitAdded: function(locator) { - ViewUtils.redirect('/container/' + locator + '?action=new'); + ViewUtils.redirect(`/container/${locator}?action=new`); }, onChildDeleted: function() { @@ -317,7 +317,7 @@ function($, _, gettext, BaseView, ViewUtils, XBlockViewUtils, XBlockStringFieldE section: 'course' }, parentXblockType = xblockMap[xblockType]; - return xblockElement.closest('.outline-' + parentXblockType); + return xblockElement.closest(`.outline-${parentXblockType}`); }, /** diff --git a/cms/static/js/views/xblock_string_field_editor.js b/cms/static/js/views/xblock_string_field_editor.js index 4180422d30..ac69435ab3 100644 --- a/cms/static/js/views/xblock_string_field_editor.js +++ b/cms/static/js/views/xblock_string_field_editor.js @@ -27,7 +27,7 @@ define(['js/views/baseview', 'js/views/utils/xblock_utils', 'edx-ui-toolkit/js/u this.fieldName = this.$el.data('field'); this.fieldDisplayName = this.$el.data('field-display-name'); this.template = this.loadTemplate('xblock-string-field-editor'); - this.model.on('change:' + this.fieldName, this.onChangeField, this); + this.model.on(`change:${this.fieldName}`, this.onChangeField, this); }, render: function() { diff --git a/cms/static/js/xblock/authoring.js b/cms/static/js/xblock/authoring.js index 0b220004ca..52cf679a67 100644 --- a/cms/static/js/xblock/authoring.js +++ b/cms/static/js/xblock/authoring.js @@ -21,7 +21,7 @@ // Otherwise get the checked groups within the selected partition. element.find( - '.partition-group-visibility-' + partitionId + ' input:checked' + `.partition-group-visibility-${partitionId} input:checked` ).each(function(index, input) { groupId = parseInt($(input).val(), 10); @@ -44,7 +44,7 @@ // If a partition is selected, display its groups. partitionId = parseInt($(event.target).val(), 10); if (partitionId >= 0) { - element.find('.partition-group-control-' + partitionId).removeClass('is-hidden'); + element.find(`.partition-group-control-${partitionId}`).removeClass('is-hidden'); } }); } diff --git a/cms/static/karma_cms.conf.js b/cms/static/karma_cms.conf.js index 16d2cc6f4c..6d6451ebd4 100644 --- a/cms/static/karma_cms.conf.js +++ b/cms/static/karma_cms.conf.js @@ -6,6 +6,7 @@ 'use strict'; var path = require('path'); + var configModule = require(path.join(__dirname, '../../common/static/common/js/karma.common.conf.js')); var options = { diff --git a/cms/static/karma_cms_squire.conf.js b/cms/static/karma_cms_squire.conf.js index f8c0260fde..9a83a189be 100644 --- a/cms/static/karma_cms_squire.conf.js +++ b/cms/static/karma_cms_squire.conf.js @@ -6,6 +6,7 @@ 'use strict'; var path = require('path'); + var configModule = require(path.join(__dirname, '../../common/static/common/js/karma.common.conf.js')); var options = { diff --git a/cms/static/karma_cms_webpack.conf.js b/cms/static/karma_cms_webpack.conf.js index 91650cc5b1..60c228e36c 100644 --- a/cms/static/karma_cms_webpack.conf.js +++ b/cms/static/karma_cms_webpack.conf.js @@ -6,6 +6,7 @@ 'use strict'; var path = require('path'); + var configModule = require(path.join(__dirname, '../../common/static/common/js/karma.common.conf.js')); var options = { diff --git a/common/static/common/js/components/ExperimentalCarousel.jsx b/common/static/common/js/components/ExperimentalCarousel.jsx index 1f954d3206..d56ce7a7f1 100644 --- a/common/static/common/js/components/ExperimentalCarousel.jsx +++ b/common/static/common/js/components/ExperimentalCarousel.jsx @@ -11,7 +11,7 @@ function NextArrow(props) { } = props; const showArrow = slideCount - currentSlide > displayedSlides; const opts = { - className: classNames('js-carousel-nav', 'carousel-arrow', 'next', 'btn btn-secondary', {'active': showArrow}), + className: classNames('js-carousel-nav', 'carousel-arrow', 'next', 'btn btn-secondary', {active: showArrow}), onClick }; @@ -32,7 +32,7 @@ function PrevArrow(props) { const {currentSlide, onClick} = props; const showArrow = currentSlide > 0; const opts = { - className: classNames('js-carousel-nav', 'carousel-arrow', 'prev', 'btn btn-secondary', {'active': showArrow}), + className: classNames('js-carousel-nav', 'carousel-arrow', 'prev', 'btn btn-secondary', {active: showArrow}), onClick }; @@ -87,7 +87,7 @@ export default class ExperimentalCarousel extends React.Component { }, tabIndex: tabIndex, className: 'carousel-item' - } + }; return (
diff --git a/common/static/common/js/components/views/feedback.js b/common/static/common/js/components/views/feedback.js index 7d49756a85..7aaa130d46 100644 --- a/common/static/common/js/components/views/feedback.js +++ b/common/static/common/js/components/views/feedback.js @@ -66,14 +66,14 @@ initialize: function(options) { this.options = _.extend({}, this.options, options); if (!this.options.type) { - throw 'SystemFeedback: type required (given ' // eslint-disable-line no-throw-literal - + JSON.stringify(this.options) + ')'; + throw `SystemFeedback: type required (given ${// eslint-disable-line no-throw-literal + JSON.stringify(this.options)})`; } if (!this.options.intent) { - throw 'SystemFeedback: intent required (given ' // eslint-disable-line no-throw-literal - + JSON.stringify(this.options) + ')'; + throw `SystemFeedback: intent required (given ${// eslint-disable-line no-throw-literal + JSON.stringify(this.options)})`; } - this.setElement($('#page-' + this.options.type)); + this.setElement($(`#page-${this.options.type}`)); // handle single "secondary" action if (this.options.actions && this.options.actions.secondary && !_.isArray(this.options.actions.secondary)) { @@ -154,13 +154,13 @@ // there can be only one active view of a given type at a time: only // one alert, only one notification, only one prompt. Therefore, we'll // use a singleton approach. - var singleton = SystemFeedback['active_' + this.options.type]; + var singleton = SystemFeedback[`active_${this.options.type}`]; if (singleton && singleton !== this) { singleton.stopListening(); singleton.undelegateEvents(); } HtmlUtils.setHtml(this.$el, HtmlUtils.template(systemFeedbackTemplate)(this.options)); - SystemFeedback['active_' + this.options.type] = this; + SystemFeedback[`active_${this.options.type}`] = this; return this; }, diff --git a/common/static/common/js/components/views/paginated_view.js b/common/static/common/js/components/views/paginated_view.js index e59328a5ab..58c8e84740 100644 --- a/common/static/common/js/components/views/paginated_view.js +++ b/common/static/common/js/components/views/paginated_view.js @@ -30,14 +30,14 @@ initialize: function() { var ItemListView = this.listViewClass.extend({ tagName: 'div', - className: this.type + '-container', + className: `${this.type}-container`, itemViewClass: this.itemViewClass }); this.listView = new ItemListView({collection: this.collection}); this.headerView = this.createHeaderView(); this.footerView = this.createFooterView(); this.collection.on('page_changed', function() { - this.$('.sr-is-focusable.sr-' + this.type + '-view').focus(); + this.$(`.sr-is-focusable.sr-${this.type}-view`).focus(); }, this); }, @@ -61,12 +61,12 @@ render: function() { HtmlUtils.setHtml(this.$el, HtmlUtils.template(this.viewTemplate)({type: this.type})); - this.assign(this.listView, '.' + this.type + '-list'); + this.assign(this.listView, `.${this.type}-list`); if (this.headerView) { - this.assign(this.headerView, '.' + this.type + '-paging-header'); + this.assign(this.headerView, `.${this.type}-paging-header`); } if (this.footerView) { - this.assign(this.footerView, '.' + this.type + '-paging-footer'); + this.assign(this.footerView, `.${this.type}-paging-footer`); } return this; }, diff --git a/common/static/common/js/components/views/tabbed_view.js b/common/static/common/js/components/views/tabbed_view.js index 9a79e7834c..1482d2b067 100644 --- a/common/static/common/js/components/views/tabbed_view.js +++ b/common/static/common/js/components/views/tabbed_view.js @@ -21,7 +21,7 @@ HtmlUtils ) { var getTabPanelId = function(id) { - return 'tabpanel-' + id; + return `tabpanel-${id}`; }; var TabPanelView = Backbone.View.extend({ @@ -164,7 +164,7 @@ if (index === 0) { $tab = $(focused).parent().find('.tab').last(); } else { - $tab = $(focused).parent().find('.tab:eq(' + index + ')').prev(); + $tab = $(focused).parent().find(`.tab:eq(${index})`).prev(); } $panel = $($tab).data('index'); @@ -180,7 +180,7 @@ if (index === total) { $tab = $(focused).parent().find('.tab').first(); } else { - $tab = $(focused).parent().find('.tab:eq(' + index + ')').next(); + $tab = $(focused).parent().find(`.tab:eq(${index})`).next(); } $panel = $($tab).data('index'); @@ -229,10 +229,10 @@ if (typeof tabNameOrIndex === 'string') { tab = this.urlMap[tabNameOrIndex]; - $element = this.$('button[data-url=' + tabNameOrIndex + ']'); + $element = this.$(`button[data-url=${tabNameOrIndex}]`); } else { tab = this.tabs[tabNameOrIndex]; - $element = this.$('button[data-index=' + tabNameOrIndex + ']'); + $element = this.$(`button[data-index=${tabNameOrIndex}]`); } return {tab: tab, element: $element}; } diff --git a/common/static/common/js/discussion/content.js b/common/static/common/js/discussion/content.js index 905271358f..758d46aa85 100644 --- a/common/static/common/js/discussion/content.js +++ b/common/static/common/js/discussion/content.js @@ -208,7 +208,7 @@ Content.prototype.incrementVote = function(increment) { var newVotes; newVotes = _.clone(this.get('votes')); - newVotes.up_count = newVotes.up_count + increment; + newVotes.up_count += increment; return this.set('votes', newVotes); }; @@ -237,13 +237,13 @@ return DiscussionUtil.urlFor('create_comment', this.id); }, unvote: function() { - return DiscussionUtil.urlFor('undo_vote_for_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`undo_vote_for_${this.get('type')}`, this.id); }, upvote: function() { - return DiscussionUtil.urlFor('upvote_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`upvote_${this.get('type')}`, this.id); }, downvote: function() { - return DiscussionUtil.urlFor('downvote_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`downvote_${this.get('type')}`, this.id); }, close: function() { return DiscussionUtil.urlFor('openclose_thread', this.id); @@ -261,10 +261,10 @@ return DiscussionUtil.urlFor('unfollow_thread', this.id); }, flagAbuse: function() { - return DiscussionUtil.urlFor('flagAbuse_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`flagAbuse_${this.get('type')}`, this.id); }, unFlagAbuse: function() { - return DiscussionUtil.urlFor('unFlagAbuse_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`unFlagAbuse_${this.get('type')}`, this.id); }, pinThread: function() { return DiscussionUtil.urlFor('pin_thread', this.id); @@ -350,13 +350,13 @@ return DiscussionUtil.urlFor('create_sub_comment', this.id); }, unvote: function() { - return DiscussionUtil.urlFor('undo_vote_for_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`undo_vote_for_${this.get('type')}`, this.id); }, upvote: function() { - return DiscussionUtil.urlFor('upvote_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`upvote_${this.get('type')}`, this.id); }, downvote: function() { - return DiscussionUtil.urlFor('downvote_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`downvote_${this.get('type')}`, this.id); }, endorse: function() { return DiscussionUtil.urlFor('endorse_comment', this.id); @@ -368,10 +368,10 @@ return DiscussionUtil.urlFor('delete_comment', this.id); }, flagAbuse: function() { - return DiscussionUtil.urlFor('flagAbuse_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`flagAbuse_${this.get('type')}`, this.id); }, unFlagAbuse: function() { - return DiscussionUtil.urlFor('unFlagAbuse_' + (this.get('type')), this.id); + return DiscussionUtil.urlFor(`unFlagAbuse_${this.get('type')}`, this.id); } }; diff --git a/common/static/common/js/discussion/utils.js b/common/static/common/js/discussion/utils.js index bc9a99f14f..63ccb4c797 100644 --- a/common/static/common/js/discussion/utils.js +++ b/common/static/common/js/discussion/utils.js @@ -12,7 +12,7 @@ DiscussionUtil.rightKey = 39; DiscussionUtil.getTemplate = function(id) { - return $('script#' + id).html(); + return $(`script#${id}`).html(); }; DiscussionUtil.setUser = function(user) { @@ -33,7 +33,7 @@ userId = this.user ? this.user.id : void 0; } if(_.isUndefined(this.roleIds)) { - this.roleIds = {} + this.roleIds = {}; } staff = _.union(this.roleIds.Moderator, this.roleIds.Administrator); return _.include(staff, parseInt(userId)); @@ -77,44 +77,46 @@ DiscussionUtil.generateDiscussionLink = function(cls, txt, handler) { return $('') .addClass('discussion-link').attr('href', '#') - .addClass(cls).text(txt).click(function() { return handler(this); }); + .addClass(cls) + .text(txt) + .click(function() { return handler(this); }); }; DiscussionUtil.urlFor = function(name, param, param1, param2) { return { - follow_discussion: '/courses/' + $$course_id + '/discussion/' + param + '/follow', - unfollow_discussion: '/courses/' + $$course_id + '/discussion/' + param + '/unfollow', - create_thread: '/courses/' + $$course_id + '/discussion/' + param + '/threads/create', - update_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/update', - create_comment: '/courses/' + $$course_id + '/discussion/threads/' + param + '/reply', - delete_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/delete', - flagAbuse_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/flagAbuse', - unFlagAbuse_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/unFlagAbuse', - flagAbuse_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/flagAbuse', - unFlagAbuse_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/unFlagAbuse', - upvote_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/upvote', - downvote_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/downvote', - pin_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/pin', - un_pin_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/unpin', - undo_vote_for_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/unvote', - follow_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/follow', - unfollow_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/unfollow', - update_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/update', - endorse_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/endorse', - create_sub_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/reply', - delete_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/delete', - upvote_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/upvote', - downvote_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/downvote', - undo_vote_for_comment: '/courses/' + $$course_id + '/discussion/comments/' + param + '/unvote', - upload: '/courses/' + $$course_id + '/discussion/upload', - users: '/courses/' + $$course_id + '/discussion/users', - search: '/courses/' + $$course_id + '/discussion/forum/search', - retrieve_discussion: '/courses/' + $$course_id + '/discussion/forum/' + param + '/inline', - retrieve_single_thread: '/courses/' + $$course_id + '/discussion/forum/' + param + '/threads/' + param1, - openclose_thread: '/courses/' + $$course_id + '/discussion/threads/' + param + '/close', - user_profile: '/courses/' + $$course_id + '/discussion/forum/users/' + param, - followed_threads: '/courses/' + $$course_id + '/discussion/forum/users/' + param + '/followed', - threads: '/courses/' + $$course_id + '/discussion/forum', + follow_discussion: `/courses/${$$course_id}/discussion/${param}/follow`, + unfollow_discussion: `/courses/${$$course_id}/discussion/${param}/unfollow`, + create_thread: `/courses/${$$course_id}/discussion/${param}/threads/create`, + update_thread: `/courses/${$$course_id}/discussion/threads/${param}/update`, + create_comment: `/courses/${$$course_id}/discussion/threads/${param}/reply`, + delete_thread: `/courses/${$$course_id}/discussion/threads/${param}/delete`, + flagAbuse_thread: `/courses/${$$course_id}/discussion/threads/${param}/flagAbuse`, + unFlagAbuse_thread: `/courses/${$$course_id}/discussion/threads/${param}/unFlagAbuse`, + flagAbuse_comment: `/courses/${$$course_id}/discussion/comments/${param}/flagAbuse`, + unFlagAbuse_comment: `/courses/${$$course_id}/discussion/comments/${param}/unFlagAbuse`, + upvote_thread: `/courses/${$$course_id}/discussion/threads/${param}/upvote`, + downvote_thread: `/courses/${$$course_id}/discussion/threads/${param}/downvote`, + pin_thread: `/courses/${$$course_id}/discussion/threads/${param}/pin`, + un_pin_thread: `/courses/${$$course_id}/discussion/threads/${param}/unpin`, + undo_vote_for_thread: `/courses/${$$course_id}/discussion/threads/${param}/unvote`, + follow_thread: `/courses/${$$course_id}/discussion/threads/${param}/follow`, + unfollow_thread: `/courses/${$$course_id}/discussion/threads/${param}/unfollow`, + update_comment: `/courses/${$$course_id}/discussion/comments/${param}/update`, + endorse_comment: `/courses/${$$course_id}/discussion/comments/${param}/endorse`, + create_sub_comment: `/courses/${$$course_id}/discussion/comments/${param}/reply`, + delete_comment: `/courses/${$$course_id}/discussion/comments/${param}/delete`, + upvote_comment: `/courses/${$$course_id}/discussion/comments/${param}/upvote`, + downvote_comment: `/courses/${$$course_id}/discussion/comments/${param}/downvote`, + undo_vote_for_comment: `/courses/${$$course_id}/discussion/comments/${param}/unvote`, + upload: `/courses/${$$course_id}/discussion/upload`, + users: `/courses/${$$course_id}/discussion/users`, + search: `/courses/${$$course_id}/discussion/forum/search`, + retrieve_discussion: `/courses/${$$course_id}/discussion/forum/${param}/inline`, + retrieve_single_thread: `/courses/${$$course_id}/discussion/forum/${param}/threads/${param1}`, + openclose_thread: `/courses/${$$course_id}/discussion/threads/${param}/close`, + user_profile: `/courses/${$$course_id}/discussion/forum/users/${param}`, + followed_threads: `/courses/${$$course_id}/discussion/forum/users/${param}/followed`, + threads: `/courses/${$$course_id}/discussion/forum`, enable_notifications: '/notification_prefs/enable/', disable_notifications: '/notification_prefs/disable/', notifications_status: '/notification_prefs/status/' @@ -312,11 +314,11 @@ return this.processEachMathAndCode(htmlSnippet, function(s, type) { if (type === 'display') { return s.replace(RE_DISPLAYMATH, function($0, $1) { - return '\\[' + $1 + '\\]'; + return `\\[${$1}\\]`; }); } else if (type === 'inline') { return s.replace(RE_INLINEMATH, function($0, $1) { - return '\\(' + $1 + '\\)'; + return `\\(${$1}\\)`; }); } else { return s; @@ -326,10 +328,10 @@ DiscussionUtil.makeWmdEditor = function($content, $local, cls_identifier) { var appended_id, editor, elem, id, imageUploadUrl, placeholder, _processor; - elem = $local('.' + cls_identifier); + elem = $local(`.${cls_identifier}`); placeholder = elem.data('placeholder'); id = elem.data('id'); - appended_id = '-' + cls_identifier + '-' + id; + appended_id = `-${cls_identifier}-${id}`; imageUploadUrl = this.urlFor('upload'); _processor = function(self) { return function(text) { @@ -338,25 +340,25 @@ }; }; editor = Markdown.makeWmdEditor(elem, appended_id, imageUploadUrl, _processor(this)); - this.wmdEditors['' + cls_identifier + '-' + id] = editor; + this.wmdEditors[`${cls_identifier}-${id}`] = editor; if (placeholder) { - elem.find('#wmd-input' + appended_id).attr('placeholder', placeholder); + elem.find(`#wmd-input${appended_id}`).attr('placeholder', placeholder); } return editor; }; DiscussionUtil.getWmdEditor = function($content, $local, cls_identifier) { var elem, id; - elem = $local('.' + cls_identifier); + elem = $local(`.${cls_identifier}`); id = elem.attr('data-id'); - return this.wmdEditors['' + cls_identifier + '-' + id]; + return this.wmdEditors[`${cls_identifier}-${id}`]; }; DiscussionUtil.getWmdInput = function($content, $local, cls_identifier) { var elem, id; - elem = $local('.' + cls_identifier); + elem = $local(`.${cls_identifier}`); id = elem.attr('data-id'); - return $local('#wmd-input-' + cls_identifier + '-' + id); + return $local(`#wmd-input-${cls_identifier}-${id}`); }; DiscussionUtil.getWmdContent = function($content, $local, cls_identifier) { @@ -395,7 +397,7 @@ while (true) { if (RE_INLINEMATH.test(htmlString)) { htmlString = htmlString.replace(RE_INLINEMATH, function($0, $1, $2, $3) { - processedHtmlString += $1 + processor('$' + $2 + '$', 'inline'); + processedHtmlString += $1 + processor(`$${$2}$`, 'inline'); return $3; }); } else if (RE_DISPLAYMATH.test(htmlString)) { @@ -403,7 +405,7 @@ /* corrected mathjax rendering in preview */ - processedHtmlString += $1 + processor('$$' + $2 + '$$', 'display'); + processedHtmlString += $1 + processor(`$$${$2}$$`, 'display'); return $3; }); } else { @@ -416,7 +418,7 @@ htmlString = htmlString.replace(new RegExp(ESCAPED_DOLLAR, 'g'), '\\$'); htmlString = htmlString.replace(/\\\\\\\\/g, ESCAPED_BACKSLASH); htmlString = htmlString.replace(/\\begin\{([a-z]*\*?)\}([\s\S]*?)\\end\{\1\}/img, function($0, $1, $2) { - return processor(('\\begin{' + $1 + '}') + $2 + ('\\end{' + $1 + '}')); + return processor(`\\begin{${$1}}${$2}\\end{${$1}}`); }); htmlString = htmlString.replace(new RegExp(ESCAPED_BACKSLASH, 'g'), '\\\\\\\\'); htmlString = htmlString.replace(new RegExp(LATEX_SCRIPT, 'g'), '{}'); diff --git a/common/static/common/js/discussion/views/discussion_content_view.js b/common/static/common/js/discussion/views/discussion_content_view.js index 82f59a4ce5..136811cb25 100644 --- a/common/static/common/js/discussion/views/discussion_content_view.js +++ b/common/static/common/js/discussion/views/discussion_content_view.js @@ -236,10 +236,10 @@ var funcName, selector; selector = event[0]; funcName = event[1]; - obj['click ' + selector] = function(event) { + obj[`click ${selector}`] = function(event) { return this[funcName](event); }; - obj['keydown ' + selector] = function(event) { + obj[`keydown ${selector}`] = function(event) { return DiscussionUtil.activateOnSpace(event, this[funcName]); }; return obj; diff --git a/common/static/common/js/discussion/views/discussion_inline_view.js b/common/static/common/js/discussion/views/discussion_inline_view.js index 7d87a69bca..6f20bb1f65 100644 --- a/common/static/common/js/discussion/views/discussion_inline_view.js +++ b/common/static/common/js/discussion/views/discussion_inline_view.js @@ -51,8 +51,8 @@ loadDiscussions: function($elem, error) { var discussionId = this.$el.data('discussion-id'), - url = DiscussionUtil.urlFor('retrieve_discussion', discussionId) + ('?page=' + this.page) - + ('&sort_key=' + this.defaultSortKey) + ('&sort_order=' + this.defaultSortOrder), + url = `${DiscussionUtil.urlFor('retrieve_discussion', discussionId)}?page=${this.page}` + + `&sort_key=${this.defaultSortKey}` + `&sort_order=${this.defaultSortOrder}`, self = this; DiscussionUtil.safeAjax({ @@ -154,7 +154,7 @@ }); this.threadView.render(); this.listenTo(this.threadView.showView, 'thread:_delete', this.navigateToAllPosts); - this.$(".forum-nav-thread[data-id='" + threadId + "']").removeClass('never-read'); + this.$(`.forum-nav-thread[data-id='${threadId}']`).removeClass('never-read'); this.threadListView.$el.addClass('is-hidden'); this.$('.inline-thread').removeClass('is-hidden'); }, diff --git a/common/static/common/js/discussion/views/discussion_thread_edit_view.js b/common/static/common/js/discussion/views/discussion_thread_edit_view.js index ca1c2043e3..564162baea 100644 --- a/common/static/common/js/discussion/views/discussion_thread_edit_view.js +++ b/common/static/common/js/discussion/views/discussion_thread_edit_view.js @@ -37,7 +37,7 @@ this.container.append(this.$el); this.$submitBtn = this.$('.post-update'); this.addField($threadTypeSelector); - this.$('#' + formId + '-post-type-' + this.threadType).attr('checked', true); + this.$(`#${formId}-post-type-${this.threadType}`).attr('checked', true); // Only allow the topic field for course threads, as standalone threads // cannot be moved. if (this.isTabMode()) { diff --git a/common/static/common/js/discussion/views/discussion_thread_list_view.js b/common/static/common/js/discussion/views/discussion_thread_list_view.js index 1717bb0009..187144153e 100644 --- a/common/static/common/js/discussion/views/discussion_thread_list_view.js +++ b/common/static/common/js/discussion/views/discussion_thread_list_view.js @@ -122,13 +122,13 @@ css_class: searchAlert.attributes.css_class }); edx.HtmlUtils.append(self.$('.search-alerts'), content); - return self.$('#search-alert-' + searchAlert.cid + ' .dismiss') + return self.$(`#search-alert-${searchAlert.cid} .dismiss`) .bind('click', searchAlert, function(event) { return self.removeSearchAlert(event.data.cid); }); }); this.searchAlertCollection.on('remove', function(searchAlert) { - return self.$('#search-alert-' + searchAlert.cid).remove(); + return self.$(`#search-alert-${searchAlert.cid}`).remove(); }); this.searchAlertCollection.on('reset', function() { return self.$('.search-alerts').empty(); @@ -163,7 +163,7 @@ this.clearSearchAlerts(); threadId = thread.get('id'); $content = this.renderThread(thread); - $currentElement = this.$('.forum-nav-thread[data-id=' + threadId + ']'); + $currentElement = this.$(`.forum-nav-thread[data-id=${threadId}]`); active = $currentElement.has('.forum-nav-thread-link.is-active').length !== 0; $currentElement.replaceWith($content); this.showMetadataAccordingToSort(); @@ -203,7 +203,7 @@ this.$('.forum-nav-filter-main').addClass('is-hidden'); } this.$('.forum-nav-sort-control option').removeProp('selected'); - this.$('.forum-nav-sort-control option[value=' + this.collection.sort_preference + ']') + this.$(`.forum-nav-sort-control option[value=${this.collection.sort_preference}]`) .prop('selected', true); this.displayedCollection.on('reset', this.renderThreads); this.displayedCollection.on('thread:remove', this.renderThreads); @@ -308,7 +308,7 @@ lastThread = ref ? ref.get('id') : void 0; if (lastThread) { this.once('threads:rendered', function() { - var classSelector = ".forum-nav-thread[data-id='" + lastThread + "'] + .forum-nav-thread " + var classSelector = `.forum-nav-thread[data-id='${lastThread}'] + .forum-nav-thread ` + '.forum-nav-thread-link'; return $(classSelector).focus(); }); @@ -383,14 +383,14 @@ DiscussionThreadListView.prototype.setActiveThread = function(threadId) { var $srElem; this.$('.forum-nav-thread-link').find('.sr').remove(); - this.$(".forum-nav-thread[data-id!='" + threadId + "'] .forum-nav-thread-link") + this.$(`.forum-nav-thread[data-id!='${threadId}'] .forum-nav-thread-link`) .removeClass('is-active'); $srElem = edx.HtmlUtils.joinHtml( edx.HtmlUtils.HTML(''), edx.HtmlUtils.ensureHtml(gettext('Current conversation')), edx.HtmlUtils.HTML('') ).toString(); - this.$(".forum-nav-thread[data-id='" + threadId + "'] .forum-nav-thread-link") + this.$(`.forum-nav-thread[data-id='${threadId}'] .forum-nav-thread-link`) .addClass('is-active').find('.forum-nav-thread-wrapper-1') .prepend($srElem); }; diff --git a/common/static/common/js/discussion/views/discussion_thread_show_view.js b/common/static/common/js/discussion/views/discussion_thread_show_view.js index 783c309134..6de3c1ae4e 100644 --- a/common/static/common/js/discussion/views/discussion_thread_show_view.js +++ b/common/static/common/js/discussion/views/discussion_thread_show_view.js @@ -34,7 +34,7 @@ this.startHeader = options.startHeader; this.is_commentable_divided = options.is_commentable_divided; if ((_ref = this.mode) !== 'tab' && _ref !== 'inline') { - throw new Error('invalid mode: ' + this.mode); + throw new Error(`invalid mode: ${this.mode}`); } }; diff --git a/common/static/common/js/discussion/views/discussion_thread_view.js b/common/static/common/js/discussion/views/discussion_thread_view.js index c6ca802a77..0825d2b51f 100644 --- a/common/static/common/js/discussion/views/discussion_thread_view.js +++ b/common/static/common/js/discussion/views/discussion_thread_view.js @@ -86,7 +86,7 @@ this.options = _.extend({}, options); this.startHeader = options.startHeader; if ((_ref = this.mode) !== 'tab' && _ref !== 'inline') { - throw new Error('invalid mode: ' + this.mode); + throw new Error(`invalid mode: ${this.mode}`); } this.readOnly = $('.discussion-module').data('read-only'); this.model.collection.on('reset', function(collection) { diff --git a/common/static/common/js/discussion/views/discussion_topic_menu_view.js b/common/static/common/js/discussion/views/discussion_topic_menu_view.js index 2799da832b..bc924494e5 100644 --- a/common/static/common/js/discussion/views/discussion_topic_menu_view.js +++ b/common/static/common/js/discussion/views/discussion_topic_menu_view.js @@ -34,7 +34,7 @@ if (this.getCurrentTopicId()) { this.setTopic(this.$('.post-topic option').filter( - '[data-discussion-id="' + this.getCurrentTopicId() + '"]' + `[data-discussion-id="${this.getCurrentTopicId()}"]` )); } else if ($general.length > 0) { this.setTopic($general.first()); @@ -101,7 +101,7 @@ if (topicElement) { name = topicElement.html(); _.each(topicElement.parents('optgroup'), function(item) { - name = $(item).attr('label') + ' / ' + name; + name = `${$(item).attr('label')} / ${name}`; }); return name; } else { diff --git a/common/static/common/js/discussion/views/new_post_view.js b/common/static/common/js/discussion/views/new_post_view.js index 106c4daf13..e487e2adb0 100644 --- a/common/static/common/js/discussion/views/new_post_view.js +++ b/common/static/common/js/discussion/views/new_post_view.js @@ -39,7 +39,7 @@ this.mode = options.mode || 'inline'; this.startHeader = options.startHeader; if ((_ref = this.mode) !== 'tab' && _ref !== 'inline') { - throw new Error('invalid mode: ' + this.mode); + throw new Error(`invalid mode: ${this.mode}`); } this.course_settings = options.course_settings; this.is_commentable_divided = options.is_commentable_divided; @@ -58,7 +58,7 @@ is_discussion_division_enabled: this.course_settings.get('is_discussion_division_enabled'), mode: this.mode, startHeader: this.startHeader, - form_id: this.mode + (this.topicId ? '-' + this.topicId : '') + form_id: this.mode + (this.topicId ? `-${this.topicId}` : '') }); edx.HtmlUtils.setHtml( this.$el, diff --git a/common/static/common/js/discussion/views/thread_response_view.js b/common/static/common/js/discussion/views/thread_response_view.js index d31bf61ba8..79f357ce08 100644 --- a/common/static/common/js/discussion/views/thread_response_view.js +++ b/common/static/common/js/discussion/views/thread_response_view.js @@ -82,7 +82,7 @@ }; ThreadResponseView.prototype.render = function() { - this.$el.addClass('response_' + this.model.get('id')); + this.$el.addClass(`response_${this.model.get('id')}`); edx.HtmlUtils.setHtml(this.$el, edx.HtmlUtils.HTML(this.renderTemplate())); this.delegateEvents(); this.renderShowView(); diff --git a/common/static/common/js/jasmine_stack_trace.js b/common/static/common/js/jasmine_stack_trace.js index 5cd73ff287..f61d591f0a 100644 --- a/common/static/common/js/jasmine_stack_trace.js +++ b/common/static/common/js/jasmine_stack_trace.js @@ -3,8 +3,8 @@ initialized we can't override the ExceptionFormatter as Jasmine then uses the stored reference to the function */ (function() { /* globals jasmineRequire */ - -'use strict'; + + 'use strict'; var OldExceptionFormatter = jasmineRequire.ExceptionFormatter(), oldExceptionFormatter = new OldExceptionFormatter(), diff --git a/common/static/common/js/karma.common.conf.js b/common/static/common/js/karma.common.conf.js index 41936aeb9b..429184ba4c 100644 --- a/common/static/common/js/karma.common.conf.js +++ b/common/static/common/js/karma.common.conf.js @@ -40,9 +40,11 @@ var path = require('path'); var _ = require('underscore'); + var appRoot = path.join(__dirname, '../../../../'); var webdriver = require('selenium-webdriver'); var firefox = require('selenium-webdriver/firefox'); + var webpackConfig = require(path.join(appRoot, 'webpack.dev.config.js')); // The following crazy bit is to work around the webpack.optimize.CommonsChunkPlugin @@ -90,7 +92,7 @@ delete webpackConfig[0].entry; * @return {String} */ function junitNameFormatter(browser, result) { - return result.suite[0] + ': ' + result.description; + return `${result.suite[0]}: ${result.description}`; } /** @@ -99,7 +101,7 @@ function junitNameFormatter(browser, result) { * @return {String} */ function junitClassNameFormatter(browser) { - return 'Javascript.' + browser.name.split(' ')[0]; + return `Javascript.${browser.name.split(' ')[0]}`; } /** @@ -184,10 +186,10 @@ function junitSettings(config) { function defaultNormalizeFunc(appRoot, pattern) { // eslint-disable-line no-shadow var pat = pattern; if (pat.match(/^common\/js/)) { - pat = path.join(appRoot, '/common/static/' + pat); + pat = path.join(appRoot, `/common/static/${pat}`); } else if (pat.match(/^xmodule_js\/common_static/)) { - pat = path.join(appRoot, '/common/static/' - + pat.replace(/^xmodule_js\/common_static\//, '')); + pat = path.join(appRoot, `/common/static/${ + pat.replace(/^xmodule_js\/common_static\//, '')}`); } return pat; } diff --git a/common/static/common/js/spec/components/paginated_view_spec.js b/common/static/common/js/spec/components/paginated_view_spec.js index 21797a854a..9f0aed377d 100644 --- a/common/static/common/js/spec/components/paginated_view_spec.js +++ b/common/static/common/js/spec/components/paginated_view_spec.js @@ -29,7 +29,7 @@ define([ generateItems = function(numItems) { return _.map(_.range(numItems), function(i) { return { - text: 'item ' + i + text: `item ${i}` }; }); }; @@ -84,7 +84,7 @@ define([ function expectFooter(options) { var footerEl = testView.$('.test-paging-footer'); expect(footerEl.text()) - .toMatch(new RegExp(options.currentPage + '\\s+out of\\s+\/\\s+' + options.totalPages)); + .toMatch(new RegExp(`${options.currentPage}\\s+out of\\s+\/\\s+${options.totalPages}`)); expect(footerEl.hasClass('hidden')).toBe(options.isHidden); } diff --git a/common/static/common/js/spec/discussion/view/discussion_thread_list_view_spec.js b/common/static/common/js/spec/discussion/view/discussion_thread_list_view_spec.js index 50569246f6..3bdd523a50 100644 --- a/common/static/common/js/spec/discussion/view/discussion_thread_list_view_spec.js +++ b/common/static/common/js/spec/discussion/view/discussion_thread_list_view_spec.js @@ -226,7 +226,7 @@ describe('should filter correctly', function() { return _.each(['all', 'unread', 'unanswered', 'flagged'], function(filterVal) { - it('for ' + filterVal, function() { + it(`for ${filterVal}`, function() { expectFilter(filterVal); this.view.$('.forum-nav-filter-main-control').val(filterVal).change(); return expect($.ajax).toHaveBeenCalled(); @@ -734,7 +734,7 @@ .first() .text() .trim() - ).toEqual(newCommentsOnUnreadThread + ' new'); + ).toEqual(`${newCommentsOnUnreadThread} new`); }); it('should display every thread as read if hideReadState: true is passed to the constructor', function() { diff --git a/common/static/common/js/spec/discussion/view/discussion_thread_profile_view_spec.js b/common/static/common/js/spec/discussion/view/discussion_thread_profile_view_spec.js index fa1079c747..33e43790d8 100644 --- a/common/static/common/js/spec/discussion/view/discussion_thread_profile_view_spec.js +++ b/common/static/common/js/spec/discussion/view/discussion_thread_profile_view_spec.js @@ -47,7 +47,7 @@ expectedText = ''; if (truncatedText) { testText = new Array(100).join('test '); - expectedText = testText.substring(0, 139) + '…'; + expectedText = `${testText.substring(0, 139)}…`; } else { testText = 'Test body'; expectedText = 'Test body'; @@ -57,20 +57,20 @@ _ref >= 0 ? _i <= _ref : _i >= _ref; i = _ref >= 0 ? ++_i : --_i ) { - threadData.body = threadData.body + imageTag; + threadData.body += imageTag; if (i === 0) { - expectedHtml = expectedHtml + imageTag; + expectedHtml += imageTag; } else { - expectedHtml = expectedHtml + 'image omitted'; + expectedHtml = `${expectedHtml}image omitted`; } } } - threadData.body = threadData.body + '' + testText + '

'; + threadData.body = `${threadData.body}${testText}

`; if (numberOfImages > 1) { - expectedHtml = expectedHtml + '' + expectedText - + '

Some images in this post have been omitted

'; + expectedHtml = `${expectedHtml}${expectedText + }

Some images in this post have been omitted

`; } else { - expectedHtml = expectedHtml + '' + expectedText + '

'; + expectedHtml = `${expectedHtml}${expectedText}

`; } view = makeView(makeThread(threadData)); view.render(); @@ -89,7 +89,7 @@ outputHtmlStripped = outputHtmlStripped.replace('Some images in this post have been omitted', ''); outputHtmlStripped = outputHtmlStripped.replace('image omitted', ''); inputHtmlStripped = threadData.body.replace(/(<([^>]+)>)/ig, ''); - expectedOutput = inputHtmlStripped.substring(0, 139) + '…'; + expectedOutput = `${inputHtmlStripped.substring(0, 139)}…`; expect(outputHtmlStripped).toEqual(expectedOutput); return expect(view.$el.find('.post-body').html().indexOf('…')).toBeGreaterThan(0); } @@ -110,14 +110,14 @@ }); it('untruncated text with markdown body', function() { var view; - this.threadData.body = '

' + this.imageTag + 'Google top search engine

'; + this.threadData.body = `

${this.imageTag}Google top search engine

`; view = makeView(makeThread(this.threadData)); return checkBody(false, view, this.threadData); }); it('truncated text with markdown body', function() { var testText, view; testText = new Array(100).join('test '); - this.threadData.body = '

' + this.imageTag + this.imageTag + '' + testText + '

'; + this.threadData.body = `

${this.imageTag}${this.imageTag}${testText}

`; view = makeView(makeThread(this.threadData)); return checkBody(true, view, this.threadData); }); @@ -128,8 +128,8 @@ for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { truncatedText = _ref1[_j]; it( - 'body with ' + numImages + ' images and ' + (truncatedText ? 'truncated' : 'untruncated') - + ' text', + `body with ${numImages} images and ${truncatedText ? 'truncated' : 'untruncated' + } text`, // eslint-disable no-loop-func function() { return checkPostWithImages(numImages, truncatedText, this.threadData, this.imageTag); diff --git a/common/static/common/js/spec/discussion/view/discussion_thread_view_spec.js b/common/static/common/js/spec/discussion/view/discussion_thread_view_spec.js index 44b5c4f124..34be53798e 100644 --- a/common/static/common/js/spec/discussion/view/discussion_thread_view_spec.js +++ b/common/static/common/js/spec/discussion/view/discussion_thread_view_spec.js @@ -57,8 +57,8 @@ createTestResponseJson = function(index) { return { user_id: window.user.id, - body: 'Response ' + index, - id: 'id_' + index, + body: `Response ${index}`, + id: `id_${index}`, created_at: '2015-01-01T22:20:28Z' }; }; @@ -300,8 +300,8 @@ expect(view.$('.js-marked-answer-list .discussion-response').length).toEqual(numEndorsed); expect(view.$('.js-response-list .discussion-response').length).toEqual(numNonEndorsed); return assertResponseCountAndPaginationCorrect( - view, '' + numNonEndorsed + ' ' + (numEndorsed ? 'other ' : '') - + (numNonEndorsed === 1 ? 'response' : 'responses'), + view, `${numNonEndorsed} ${numEndorsed ? 'other ' : '' + }${numNonEndorsed === 1 ? 'response' : 'responses'}`, numNonEndorsed ? 'Showing all responses' : null, null ); }; @@ -316,8 +316,8 @@ many: 5 }, function(numNonEndorsed, nonEndorsedDesc) { it( - 'renders correctly with ' + endorsedDesc + ' marked answer(s) and ' + nonEndorsedDesc - + ' response(s)', + `renders correctly with ${endorsedDesc} marked answer(s) and ${nonEndorsedDesc + } response(s)`, function() { return renderTestCase(this.view, numEndorsed, numNonEndorsed); } ); }); diff --git a/common/static/common/js/spec/discussion/view/discussion_view_spec_helper.js b/common/static/common/js/spec/discussion/view/discussion_view_spec_helper.js index cca39d0c56..ae5b66b86e 100644 --- a/common/static/common/js/spec/discussion/view/discussion_view_spec_helper.js +++ b/common/static/common/js/spec/discussion/view/discussion_view_spec_helper.js @@ -58,9 +58,9 @@ button = view.$el.find('.action-vote'); expect(button.hasClass('is-checked')).toBe(user.voted(model)); expect(button.attr('aria-checked')).toEqual(user.voted(model).toString()); - expect(button.find('.vote-count').text()).toMatch('^' + (model.get('votes').up_count) + ' Votes?$'); + expect(button.find('.vote-count').text()).toMatch(`^${model.get('votes').up_count} Votes?$`); return expect(button.find('.sr.js-sr-vote-count').text()) - .toMatch('^there are currently ' + (model.get('votes').up_count) + ' votes?$'); + .toMatch(`^there are currently ${model.get('votes').up_count} votes?$`); }; DiscussionViewSpecHelper.checkRenderVote = function(view, model) { @@ -91,7 +91,7 @@ var initialVoteCount, _ref, _ref1; expect((_ref = model.id, __indexOf.call(user.get('upvoted_ids'), _ref) >= 0)).toBe(false); initialVoteCount = model.get('votes').up_count; - triggerVoteEvent(view, event, DiscussionUtil.urlFor('upvote_' + (model.get('type')), model.id) + '?ajax=1'); + triggerVoteEvent(view, event, `${DiscussionUtil.urlFor(`upvote_${model.get('type')}`, model.id)}?ajax=1`); expect((_ref1 = model.id, __indexOf.call(user.get('upvoted_ids'), _ref1) >= 0)).toBe(true); return expect(model.get('votes').up_count).toEqual(initialVoteCount + 1); }; @@ -102,7 +102,7 @@ expect((_ref = model.id, __indexOf.call(user.get('upvoted_ids'), _ref) >= 0)).toBe(true); initialVoteCount = model.get('votes').up_count; triggerVoteEvent( - view, event, DiscussionUtil.urlFor('undo_vote_for_' + (model.get('type')), model.id) + '?ajax=1' + view, event, `${DiscussionUtil.urlFor(`undo_vote_for_${model.get('type')}`, model.id)}?ajax=1` ); expect(user.get('upvoted_ids')).toEqual([]); return expect(model.get('votes').up_count).toEqual(initialVoteCount - 1); diff --git a/common/static/common/js/spec/discussion/view/new_post_view_spec.js b/common/static/common/js/spec/discussion/view/new_post_view_spec.js index b388526bef..d3dd2afb64 100644 --- a/common/static/common/js/spec/discussion/view/new_post_view_spec.js +++ b/common/static/common/js/spec/discussion/view/new_post_view_spec.js @@ -9,7 +9,7 @@ DiscussionSpecHelper.setUnderscoreFixtures(); window.$$course_id = 'edX/999/test'; spyOn(DiscussionUtil, 'makeWmdEditor').and.callFake(function($content, $local, cls_identifier) { - return $local('.' + cls_identifier).html(''); + return $local(`.${cls_identifier}`).html(''); }); this.discussion = new Discussion([], { pages: 1 @@ -254,7 +254,7 @@ } }; return _.each(['tab', 'inline'], function(mode) { - it('resets the form in ' + mode + ' mode', function() { + it(`resets the form in ${mode} mode`, function() { return checkPostCancelReset(mode, this.discussion, this.course_settings); }); }); diff --git a/common/static/common/js/spec/discussion/view/response_comment_view_spec.js b/common/static/common/js/spec/discussion/view/response_comment_view_spec.js index e7975947be..d0ca790d14 100644 --- a/common/static/common/js/spec/discussion/view/response_comment_view_spec.js +++ b/common/static/common/js/spec/discussion/view/response_comment_view_spec.js @@ -105,7 +105,7 @@ expect(this.view._delete).toHaveBeenCalled(); this.view.showView.trigger('comment:edit', DiscussionSpecHelper.makeEventSpy()); expect(this.view.edit).toHaveBeenCalled(); - return expect(this.view.$('.edit-post-form#comment_' + this.comment.id)) + return expect(this.view.$(`.edit-post-form#comment_${this.comment.id}`)) .not.toHaveClass('edit-post-form'); }); }); @@ -118,7 +118,7 @@ expect(this.view.update).toHaveBeenCalled(); this.view.editView.trigger('comment:cancel_edit', DiscussionSpecHelper.makeEventSpy()); expect(this.view.cancelEdit).toHaveBeenCalled(); - return expect(this.view.$('.edit-post-form#comment_' + this.comment.id)).toHaveClass('edit-post-form'); + return expect(this.view.$(`.edit-post-form#comment_${this.comment.id}`)).toHaveClass('edit-post-form'); }); }); describe('edit', function() { diff --git a/common/static/common/js/spec/discussion/view/thread_response_show_view_spec.js b/common/static/common/js/spec/discussion/view/thread_response_show_view_spec.js index 31a4599c5d..88d269aae6 100644 --- a/common/static/common/js/spec/discussion/view/thread_response_show_view_spec.js +++ b/common/static/common/js/spec/discussion/view/thread_response_show_view_spec.js @@ -71,7 +71,7 @@ }); this.view.render(); expect(this.view.$('.posted-details').text().replace(/\s+/g, ' ')) - .toMatch('marked as answer less than a minute ago by ' + endorsement.username); + .toMatch(`marked as answer less than a minute ago by ${endorsement.username}`); return expect(this.view.$('.posted-details > a').attr('href')) .toEqual('/courses/edX/999/test/discussion/forum/users/test_id'); }); @@ -104,7 +104,7 @@ }); this.view.render(); expect(this.view.$('.posted-details').text().replace(/\s+/g, ' ')) - .toMatch('endorsed less than a minute ago by ' + endorsement.username); + .toMatch(`endorsed less than a minute ago by ${endorsement.username}`); return expect(this.view.$('.posted-details > a').attr('href')) .toEqual('/courses/edX/999/test/discussion/forum/users/test_id'); }); diff --git a/common/static/common/js/spec/main_requirejs.js b/common/static/common/js/spec/main_requirejs.js index 8cf4eff51a..6ae02a3965 100644 --- a/common/static/common/js/spec/main_requirejs.js +++ b/common/static/common/js/spec/main_requirejs.js @@ -171,7 +171,7 @@ ]; for (i = 0; i < testFiles.length; i++) { - testFiles[i] = '/base/' + testFiles[i]; + testFiles[i] = `/base/${testFiles[i]}`; } specHelpers = [ diff --git a/common/static/common/js/spec/utils/edx.utils.validate_spec.js b/common/static/common/js/spec/utils/edx.utils.validate_spec.js index 740ad69373..699be74da6 100644 --- a/common/static/common/js/spec/utils/edx.utils.validate_spec.js +++ b/common/static/common/js/spec/utils/edx.utils.validate_spec.js @@ -19,7 +19,7 @@ CUSTOM_MESSAGE = 'custom message'; var createFixture = function(type, name, required, minlength, maxlength, value) { - setFixtures(''); + setFixtures(``); field = $('#field'); field.prop('required', required); diff --git a/common/static/common/js/spec_helpers/jasmine-stealth.js b/common/static/common/js/spec_helpers/jasmine-stealth.js index 506876f62d..b0ca2196de 100644 --- a/common/static/common/js/spec_helpers/jasmine-stealth.js +++ b/common/static/common/js/spec_helpers/jasmine-stealth.js @@ -45,11 +45,11 @@ } spies = { - constructor: jasmine.createSpy('' + classToFake + '\'s constructor') + constructor: jasmine.createSpy(`${classToFake}'s constructor`) }; _.each(methodsToSpy, function(methodName) { - spies[methodName] = jasmine.createSpy('' + classToFake + '#' + methodName); + spies[methodName] = jasmine.createSpy(`${classToFake}#${methodName}`); return fakeClass.prototype[methodName] = function() { return spies[methodName].apply(this, arguments); }; diff --git a/common/static/common/js/spec_helpers/template_helpers.js b/common/static/common/js/spec_helpers/template_helpers.js index 97ad290ae1..1f8eea4fa9 100644 --- a/common/static/common/js/spec_helpers/template_helpers.js +++ b/common/static/common/js/spec_helpers/template_helpers.js @@ -6,14 +6,14 @@ define(['jquery', 'underscore'], var installTemplate, installTemplates; installTemplate = function(templateFile, isFirst, templateId) { - var template = readFixtures(templateFile + '.underscore'), + var template = readFixtures(`${templateFile}.underscore`), templateName = templateFile, slashIndex = _.lastIndexOf(templateName, '/'); if (slashIndex >= 0) { templateName = templateFile.substring(slashIndex + 1); } if (!templateId) { - templateId = templateName + '-tpl'; + templateId = `${templateName}-tpl`; } if (isFirst) { diff --git a/common/static/common/js/utils/edx.utils.validate.js b/common/static/common/js/utils/edx.utils.validate.js index 1565e06dc8..c9908a09d5 100644 --- a/common/static/common/js/utils/edx.utils.validate.js +++ b/common/static/common/js/utils/edx.utils.validate.js @@ -125,7 +125,7 @@ getLabel: function(id) { // Extract the field label, remove the asterisk (if it appears) and any extra whitespace - return $('label[for=' + id + '] > span.label-text').text().split('*')[0].trim(); + return $(`label[for=${id}] > span.label-text`).text().split('*')[0].trim(); }, getMessage: function($el, tests) { @@ -140,8 +140,8 @@ _.each(tests, function(value, key) { if (!value) { label = _fn.validate.getLabel($el.attr('id')); - customMsg = $el.data('errormsg-' + key) || false; - liveValidationMsg = $('#' + $el.attr('id') + '-validation-error-msg').text() || false; + customMsg = $el.data(`errormsg-${key}`) || false; + liveValidationMsg = $(`#${$el.attr('id')}-validation-error-msg`).text() || false; // If the field has a custom error msg attached, use it if (customMsg) { diff --git a/common/static/common/js/xblock/core.js b/common/static/common/js/xblock/core.js index 1b0ab6dd84..b1c9c1e6e4 100644 --- a/common/static/common/js/xblock/core.js +++ b/common/static/common/js/xblock/core.js @@ -7,9 +7,9 @@ var selector; requestToken = requestToken || $(element).data('request-token'); if (requestToken) { - selector = '.' + blockClass + '[data-request-token="' + requestToken + '"]'; + selector = `.${blockClass}[data-request-token="${requestToken}"]`; } else { - selector = '.' + blockClass; + selector = `.${blockClass}`; } // After an element is initialized, a class is added to it. To avoid repeat initialization, no // elements with that class should be selected. @@ -26,11 +26,11 @@ initFnName = $element.data('init'); if (runtime && version && initFnName) { - return new window[runtime]['v' + version](); + return new window[runtime][`v${version}`](); } else { if (runtime || version || initFnName) { console.log( - 'Block ' + $element.outerHTML + ' is missing data-runtime, data-runtime-version or data-init, ' + `Block ${$element.outerHTML} is missing data-runtime, data-runtime-version or data-init, ` + 'and can\'t be initialized' ); } // else this XBlock doesn't have a JS init function. @@ -114,7 +114,7 @@ */ initializeAside: function(element) { var blockUsageId = $(element).data('block-id'); - var blockElement = $(element).siblings('[data-usage-id="' + blockUsageId + '"]')[0]; + var blockElement = $(element).siblings(`[data-usage-id="${blockUsageId}"]`)[0]; return constructBlock(element, [blockElement, initArgs(element)]); }, diff --git a/common/static/js/capa/chemical_equation_preview.js b/common/static/js/capa/chemical_equation_preview.js index d23d8e51d3..72cd165ac2 100644 --- a/common/static/js/capa/chemical_equation_preview.js +++ b/common/static/js/capa/chemical_equation_preview.js @@ -17,7 +17,7 @@ }); } - prev_id = '#' + this.id + '_preview'; + prev_id = `#${this.id}_preview`; preview_div = $(prev_id); // find the closest parent problems-wrapper and use that url diff --git a/common/static/js/capa/drag_and_drop/base_image.js b/common/static/js/capa/drag_and_drop/base_image.js index 736d8d3438..4f5be0ddaf 100644 --- a/common/static/js/capa/drag_and_drop/base_image.js +++ b/common/static/js/capa/drag_and_drop/base_image.js @@ -36,7 +36,7 @@ HtmlUtils.HTML('ERROR: Image "'), state.config.baseImage, HtmlUtils.HTML('" was not found!'), HtmlUtils.HTML('') ); - console.log('ERROR: Image "' + state.config.baseImage + '" was not found!'); + console.log(`ERROR: Image "${state.config.baseImage}" was not found!`); HtmlUtils.setHtml($baseImageElContainer, errorMsg); $baseImageElContainer.appendTo(state.containerEl); }); diff --git a/common/static/js/capa/drag_and_drop/config_parser.js b/common/static/js/capa/drag_and_drop/config_parser.js index bbd574b0d3..4821070afe 100644 --- a/common/static/js/capa/drag_and_drop/config_parser.js +++ b/common/static/js/capa/drag_and_drop/config_parser.js @@ -206,11 +206,11 @@ function attrIsString(obj, attr) { if (obj.hasOwnProperty(attr) === false) { - console.log('ERROR: Attribute "obj.' + attr + '" is not present.'); + console.log(`ERROR: Attribute "obj.${attr}" is not present.`); return false; } else if (typeof obj[attr] !== 'string') { - console.log('ERROR: Attribute "obj.' + attr + '" is not a string.'); + console.log(`ERROR: Attribute "obj.${attr}" is not a string.`); return false; } @@ -222,7 +222,7 @@ var tempInt; if (obj.hasOwnProperty(attr) === false) { - console.log('ERROR: Attribute "obj.' + attr + '" is not present.'); + console.log(`ERROR: Attribute "obj.${attr}" is not present.`); return false; } @@ -230,7 +230,7 @@ tempInt = parseInt(obj[attr], 10); if (isFinite(tempInt) === false) { - console.log('ERROR: Attribute "obj.' + attr + '" is not an integer.'); + console.log(`ERROR: Attribute "obj.${attr}" is not an integer.`); return false; } @@ -243,7 +243,7 @@ function attrIsBoolean(obj, attr, defaultVal) { if (obj.hasOwnProperty(attr) === false) { if (defaultVal === undefined) { - console.log('ERROR: Attribute "obj.' + attr + '" is not present.'); + console.log(`ERROR: Attribute "obj.${attr}" is not present.`); return false; } else { @@ -260,7 +260,7 @@ } else if ((obj[attr] === 'true') || (obj[attr] === true)) { obj[attr] = true; } else { - console.log('ERROR: Attribute "obj.' + attr + '" is not a boolean.'); + console.log(`ERROR: Attribute "obj.${attr}" is not a boolean.`); return false; } diff --git a/common/static/js/capa/drag_and_drop/container.js b/common/static/js/capa/drag_and_drop/container.js index 35107a8b0d..1d8d2e4f21 100644 --- a/common/static/js/capa/drag_and_drop/container.js +++ b/common/static/js/capa/drag_and_drop/container.js @@ -7,7 +7,7 @@ '
' ); - $('#inputtype_' + state.problemId).before(HtmlUtils.HTML(state.containerEl).toString()); + $(`#inputtype_${state.problemId}`).before(HtmlUtils.HTML(state.containerEl).toString()); } }); // End-of: define([], function () { }(RequireJS.requirejs, RequireJS.require, RequireJS.define)); // End-of: (function (requirejs, require, define) { diff --git a/common/static/js/capa/drag_and_drop/main.js b/common/static/js/capa/drag_and_drop/main.js index e7872b400d..9c93c05bdd 100644 --- a/common/static/js/capa/drag_and_drop/main.js +++ b/common/static/js/capa/drag_and_drop/main.js @@ -62,10 +62,10 @@ } try { - config = JSON.parse($('#drag_and_drop_json_' + problemId).html()); + config = JSON.parse($(`#drag_and_drop_json_${problemId}`).html()); } catch (err) { console.log('ERROR: Could not parse the JSON configuration options.'); - console.log('Error message: "' + err.message + '".'); + console.log(`Error message: "${err.message}".`); return; } diff --git a/common/static/js/capa/drag_and_drop/scroller.js b/common/static/js/capa/drag_and_drop/scroller.js index 943543e6fb..51f60ced1e 100644 --- a/common/static/js/capa/drag_and_drop/scroller.js +++ b/common/static/js/capa/drag_and_drop/scroller.js @@ -52,7 +52,7 @@ // We scroll by changing the 'margin-left' CSS property smoothly. state.sliderEl.animate({ - 'margin-left': showElLeftMargin + 'px' + 'margin-left': `${showElLeftMargin}px` }, 100, function() { updateArrowOpacity(); }); @@ -123,7 +123,7 @@ // We scroll by changing the 'margin-left' CSS property smoothly. state.sliderEl.animate({ - 'margin-left': showElLeftMargin + 'px' + 'margin-left': `${showElLeftMargin}px` }, 100, function() { updateArrowOpacity(); }); diff --git a/common/static/js/capa/drag_and_drop/state.js b/common/static/js/capa/drag_and_drop/state.js index 6ea9d5b623..d1a0db60dd 100644 --- a/common/static/js/capa/drag_and_drop/state.js +++ b/common/static/js/capa/drag_and_drop/state.js @@ -41,7 +41,7 @@ function getUniqueId() { this.uniqueId += 1; - return this.salt + '_' + this.uniqueId.toFixed(0); + return `${this.salt}_${this.uniqueId.toFixed(0)}`; } function makeSalt() { diff --git a/common/static/js/capa/drag_and_drop/update_input.js b/common/static/js/capa/drag_and_drop/update_input.js index 341e5a6726..c14fdc5135 100644 --- a/common/static/js/capa/drag_and_drop/update_input.js +++ b/common/static/js/capa/drag_and_drop/update_input.js @@ -50,7 +50,7 @@ }(0)); } - $('#input_' + state.problemId).val(JSON.stringify(draggables)); + $(`#input_${state.problemId}`).val(JSON.stringify(draggables)); } function addTargetRecursively(tempObj, draggable, target) { @@ -69,7 +69,7 @@ function check(state) { var inputElVal; - inputElVal = $('#input_' + state.problemId).val(); + inputElVal = $(`#input_${state.problemId}`).val(); if (inputElVal.length === 0) { return false; @@ -189,7 +189,7 @@ if (reportError !== false) { console.log( 'ERROR: In answer there exists a ' - + 'draggable ID "' + draggableId + '". No ' + + `draggable ID "${draggableId}". No ` + 'draggable with this ID could be found.' ); } @@ -201,7 +201,7 @@ if (reportError !== false) { console.log( 'ERROR: In answer there exists a target ' - + 'ID "' + targetId + '". No target with this ' + + `ID "${targetId}". No target with this ` + 'ID could be found.' ); } @@ -227,7 +227,7 @@ if ((draggable = getById(state, 'draggables', draggableId)) === null) { console.log( 'ERROR: In answer there exists a ' - + 'draggable ID "' + draggableId + '". No ' + + `draggable ID "${draggableId}". No ` + 'draggable with this ID could be found.' ); diff --git a/common/static/js/capa/jsinput/jsinput_example.js b/common/static/js/capa/jsinput/jsinput_example.js index f3ee144a2c..aaf8d1fbb0 100644 --- a/common/static/js/capa/jsinput/jsinput_example.js +++ b/common/static/js/capa/jsinput/jsinput_example.js @@ -32,7 +32,7 @@ } select.appendChild(option); } - feedback.innerText = "The currently selected answer is '" + state.selectedChoice + "'."; + feedback.innerText = `The currently selected answer is '${state.selectedChoice}'.`; } function getGrade() { @@ -74,8 +74,8 @@ select.addEventListener('change', function() { state.selectedChoice = select.options[select.selectedIndex].text; - feedback.innerText = "You have selected '" + state.selectedChoice - + "'. Click Submit to grade your answer."; + feedback.innerText = `You have selected '${state.selectedChoice + }'. Click Submit to grade your answer.`; }); return { diff --git a/common/static/js/capa/spec/formula_equation_preview_spec.js b/common/static/js/capa/spec/formula_equation_preview_spec.js index c52e953d03..52cea68ffe 100644 --- a/common/static/js/capa/spec/formula_equation_preview_spec.js +++ b/common/static/js/capa/spec/formula_equation_preview_spec.js @@ -64,7 +64,7 @@ describe('Formula Equation Preview', function() { this.oldDGEBI = document.getElementById; document.getElementById = function(id) { - return $('*#' + id)[0] || null; + return $(`*#${id}`)[0] || null; }; // Catch the AJAX requests @@ -195,7 +195,7 @@ describe('Formula Equation Preview', function() { var $input = $('#input_THE_ID'); var value; function inputAnother(iter) { - value = 'math input ' + iter; + value = `math input ${iter}`; $input.val(value).trigger('input'); } diff --git a/common/static/js/capa/src/formula_equation_preview.js b/common/static/js/capa/src/formula_equation_preview.js index ba0f7fc42e..151e3e43a7 100644 --- a/common/static/js/capa/src/formula_equation_preview.js +++ b/common/static/js/capa/src/formula_equation_preview.js @@ -20,17 +20,17 @@ function escapeSelector(id) { return '\uFFFD'; } // Control characters and (dependent upon position) numbers get escaped as code points - return ch.slice(0, -1) + '\\' + ch.charCodeAt(ch.length - 1).toString(16) + ' '; + return `${ch.slice(0, -1)}\\${ch.charCodeAt(ch.length - 1).toString(16)} `; } // Other potentially-special ASCII characters get backslash-escaped - return '\\' + ch; + return `\\${ch}`; } if (window.CSS && window.CSS.escape) { return window.CSS.escape(id); } else { // ensure string and then run the replacements - return (id + '').replace(rcssescape, fcssescape); + return (`${id}`).replace(rcssescape, fcssescape); } } @@ -49,7 +49,7 @@ formulaEquationPreview.enable = function() { function setupInput() { var $this = $(this); // cache the jQuery object - var $preview = $('#' + escapeSelector(this.id) + '_preview'); + var $preview = $(`#${escapeSelector(this.id)}_preview`); var inputData = { // These are the mutable values @@ -187,7 +187,7 @@ formulaEquationPreview.enable = function() { console.log('[FormulaEquationInput] Oops no mathjax for ', latex); // Fall back to modifying the actual element. var textNode = previewElement.childNodes[0]; - textNode.data = '\\(' + latex + '\\)'; + textNode.data = `\\(${latex}\\)`; MathJax.Hub.Queue(['Typeset', MathJax.Hub, previewElement]); } }); @@ -198,7 +198,7 @@ formulaEquationPreview.enable = function() { if (response.error) { inputData.$img.css('visibility', 'visible'); inputData.errorWaitTimeout = window.setTimeout(function() { - display('\\text{' + response.error + '}'); + display(`\\text{${response.error}}`); inputData.$img.css('visibility', 'hidden'); }, formulaEquationPreview.errorDelay); } else { diff --git a/common/static/js/capa/src/jschannel.js b/common/static/js/capa/src/jschannel.js index b5da3efb43..b26f8403d1 100644 --- a/common/static/js/capa/src/jschannel.js +++ b/common/static/js/capa/src/jschannel.js @@ -249,7 +249,7 @@ var Channel = (function() { exists = hasWin(s_boundChans[origin][scope]); } } - if (exists) { throw "A channel is already bound to the same window which overlaps with origin '" + origin + "' and has scope '" + scope + "'"; } + if (exists) { throw `A channel is already bound to the same window which overlaps with origin '${origin}' and has scope '${scope}'`; } if (typeof s_boundChans[origin] !== 'object') { s_boundChans[origin] = { }; } if (typeof s_boundChans[origin][scope] !== 'object') { s_boundChans[origin][scope] = []; } @@ -388,7 +388,7 @@ var Channel = (function() { if (cfg.debugOutput && window.console && window.console.log) { // try to stringify, if it doesn't work we'll let javascript's built in toString do its magic try { if (typeof m !== 'string') { m = JSON.stringify(m); } } catch (e) { } - console.log('[' + chanId + '] ' + m); + console.log(`[${chanId}] ${m}`); } }; @@ -455,11 +455,11 @@ var Channel = (function() { origin: origin, invoke: function(cbName, v) { // verify in table - if (!inTbl[id]) { throw 'attempting to invoke a callback of a nonexistent transaction: ' + id; } + if (!inTbl[id]) { throw `attempting to invoke a callback of a nonexistent transaction: ${id}`; } // verify that the callback name is valid var valid = false; for (var i = 0; i < callbacks.length; i++) { if (cbName === callbacks[i]) { valid = true; break; } } - if (!valid) { throw "request supports no such callback '" + cbName + "'"; } + if (!valid) { throw `request supports no such callback '${cbName}'`; } // send callback invocation postMessage({id: id, callback: cbName, params: v}); @@ -467,7 +467,7 @@ var Channel = (function() { error: function(error, message) { completed = true; // verify in table - if (!inTbl[id]) { throw 'error called for nonexistent message: ' + id; } + if (!inTbl[id]) { throw `error called for nonexistent message: ${id}`; } // remove transaction from table delete inTbl[id]; @@ -478,7 +478,7 @@ var Channel = (function() { complete: function(v) { completed = true; // verify in table - if (!inTbl[id]) { throw 'complete called for nonexistent message: ' + id; } + if (!inTbl[id]) { throw `complete called for nonexistent message: ${id}`; } // remove transaction from table delete inTbl[id]; // send complete @@ -500,7 +500,7 @@ var Channel = (function() { return window.setTimeout(function() { if (outTbl[transId]) { // XXX: what if client code raises an exception here? - var msg = 'timeout (' + timeout + "ms) exceeded on method '" + method + "'"; + var msg = `timeout (${timeout}ms) exceeded on method '${method}'`; (1, outTbl[transId].error)('timeout_error', msg); delete outTbl[transId]; delete s_transIds[transId]; @@ -518,7 +518,7 @@ var Channel = (function() { try { cfg.gotMessageObserver(origin, m); } catch (e) { - debug('gotMessageObserver() raised an exception: ' + e.toString()); + debug(`gotMessageObserver() raised an exception: ${e.toString()}`); } } @@ -590,14 +590,14 @@ var Channel = (function() { } } else if (m.id && m.callback) { if (!outTbl[m.id] || !outTbl[m.id].callbacks || !outTbl[m.id].callbacks[m.callback]) { - debug('ignoring invalid callback, id:' + m.id + ' (' + m.callback + ')'); + debug(`ignoring invalid callback, id:${m.id} (${m.callback})`); } else { // XXX: what if client code raises an exception here? outTbl[m.id].callbacks[m.callback](m.params); } } else if (m.id) { if (!outTbl[m.id]) { - debug('ignoring invalid response: ' + m.id); + debug(`ignoring invalid response: ${m.id}`); } else { // XXX: what if client code raises an exception here? if (m.error) { @@ -636,7 +636,7 @@ var Channel = (function() { // delay posting if we're not ready yet. var verb = (ready ? 'post ' : 'queue '); - debug(verb + ' message: ' + JSON.stringify(msg)); + debug(`${verb} message: ${JSON.stringify(msg)}`); if (!force && !ready) { pendingQueue.push(msg); } else { @@ -644,7 +644,7 @@ var Channel = (function() { try { cfg.postMessageObserver(cfg.origin, msg); } catch (e) { - debug('postMessageObserver() raised an exception: ' + e.toString()); + debug(`postMessageObserver() raised an exception: ${e.toString()}`); } } @@ -683,7 +683,7 @@ var Channel = (function() { // tries to unbind a bound message handler. returns false if not possible unbind: function(method) { if (regTbl[method]) { - if (!(delete regTbl[method])) { throw ("can't delete method: " + method); } + if (!(delete regTbl[method])) { throw (`can't delete method: ${method}`); } return true; } return false; @@ -692,7 +692,7 @@ var Channel = (function() { if (!method || typeof method !== 'string') { throw "'method' argument to bind must be string"; } if (!cb || typeof cb !== 'function') { throw 'callback missing from bind params'; } - if (regTbl[method]) { throw "method '" + method + "' is already bound!"; } + if (regTbl[method]) { throw `method '${method}' is already bound!`; } regTbl[method] = cb; return this; }, diff --git a/common/static/js/capa/symbolic_mathjax_preprocessor.js b/common/static/js/capa/symbolic_mathjax_preprocessor.js index 313cccfee8..0bad708cd7 100644 --- a/common/static/js/capa/symbolic_mathjax_preprocessor.js +++ b/common/static/js/capa/symbolic_mathjax_preprocessor.js @@ -24,7 +24,7 @@ window.SymbolicMathjaxPreprocessor = function() { // a zero width space--this is an invisible character that no one would // use, that gets passed through MathJax and to the server var c = '\u200b'; - eqn = eqn.replace(/__(?:([^\{])|\{([^\}]+)\})/g, '^{' + c + '$1$2}'); + eqn = eqn.replace(/__(?:([^\{])|\{([^\}]+)\})/g, `^{${c}$1$2}`); // NOTE: MathJax supports '\class{name}{mathcode}' but not for asciimath // input, which is too bad. This would be preferable to this char tag diff --git a/common/static/js/spec/logger_spec.js b/common/static/js/spec/logger_spec.js index a293bd8507..919abd10ca 100644 --- a/common/static/js/spec/logger_spec.js +++ b/common/static/js/spec/logger_spec.js @@ -184,7 +184,7 @@ spyOn(jQuery, 'ajax'); window.onunload(); expect(jQuery.ajax).toHaveBeenCalledWith({ - url: this.prefix + '/event', + url: `${this.prefix}/event`, type: 'GET', data: { event_type: 'page_close', diff --git a/common/static/js/spec/string_utils_spec.js b/common/static/js/spec/string_utils_spec.js index 81b4d9fa3a..8d4e7c5181 100644 --- a/common/static/js/spec/string_utils_spec.js +++ b/common/static/js/spec/string_utils_spec.js @@ -1,15 +1,15 @@ describe('interpolate_ntext', function() { it('replaces placeholder values', function() { - expect(interpolate_ntext('contains {count} student', 'contains {count} students', 1, {count: 1})). - toBe('contains 1 student'); - expect(interpolate_ntext('contains {count} student', 'contains {count} students', 5, {count: 2})). - toBe('contains 2 students'); + expect(interpolate_ntext('contains {count} student', 'contains {count} students', 1, {count: 1})) + .toBe('contains 1 student'); + expect(interpolate_ntext('contains {count} student', 'contains {count} students', 5, {count: 2})) + .toBe('contains 2 students'); }); }); describe('interpolate_text', function() { it('replaces placeholder values', function() { - expect(interpolate_text('contains {adjective} students', {adjective: 'awesome'})). - toBe('contains awesome students'); + expect(interpolate_text('contains {adjective} students', {adjective: 'awesome'})) + .toBe('contains awesome students'); }); }); diff --git a/common/static/js/src/accessibility_tools.js b/common/static/js/src/accessibility_tools.js index 54f9997d19..6ced857b32 100644 --- a/common/static/js/src/accessibility_tools.js +++ b/common/static/js/src/accessibility_tools.js @@ -99,7 +99,7 @@ var trapShiftTabFocus = function($last, closeButtonId) { var bindReturnFocusListener = function($previouslyFocusedElement, closeButtonId, modalId, mainPageId) { // Ensures that on modal close, focus is returned to the element // that had focus before the modal was opened. - $('#lean_overlay, ' + closeButtonId).click(function() { + $(`#lean_overlay, ${closeButtonId}`).click(function() { $(mainPageId).attr('aria-hidden', 'false'); $(modalId).attr('aria-hidden', 'true'); $previouslyFocusedElement.focus(); @@ -151,7 +151,7 @@ var accessible_modal = function(trigger, closeButtonId, modalId, mainPageId) { // see http://accessibility.oit.ncsu.edu/blog/2013/09/13/the-incredible-accessible-modal-dialog/ // for more information on managing modals // - var initialFocus + var initialFocus; $(trigger).click(function() { $focusedElementBeforeModal = $(trigger); @@ -206,7 +206,7 @@ $(function() { function SRAlert() { // This initialization sometimes gets done twice, so take to only create a single reader-feedback div. var readerFeedbackID = 'reader-feedback', - $readerFeedbackSelector = $('#' + readerFeedbackID); + $readerFeedbackSelector = $(`#${readerFeedbackID}`); if ($readerFeedbackSelector.length === 0) { edx.HtmlUtils.append( @@ -217,7 +217,7 @@ $(function() { ) ); } - this.el = $('#' + readerFeedbackID); + this.el = $(`#${readerFeedbackID}`); } SRAlert.prototype.clear = function() { diff --git a/common/static/js/src/ie_shim.js b/common/static/js/src/ie_shim.js index 48bcde303e..93afe806ba 100644 --- a/common/static/js/src/ie_shim.js +++ b/common/static/js/src/ie_shim.js @@ -11,6 +11,6 @@ // Internet Explorer does not have built-in property 'window.location.origin', // we need to create one here as some vendor code such as TinyMCE uses this. if (!window.location.origin) { - window.location.origin = window.location.protocol + '//' + window.location.hostname - + (window.location.port ? ':' + window.location.port : ''); + window.location.origin = `${window.location.protocol}//${window.location.hostname + }${window.location.port ? `:${window.location.port}` : ''}`; } diff --git a/common/static/js/src/tooltip_manager.js b/common/static/js/src/tooltip_manager.js index d3fe0d1566..abcdc4e2cc 100644 --- a/common/static/js/src/tooltip_manager.js +++ b/common/static/js/src/tooltip_manager.js @@ -4,7 +4,7 @@ var TooltipManager = function(element) { this.element = $(element); // If tooltip container already exist, use it. - this.tooltip = $('div.' + this.className.split(/\s+/).join('.')); + this.tooltip = $(`div.${this.className.split(/\s+/).join('.')}`); // Otherwise, create new one. if (!this.tooltip.length) { this.tooltip = $('
', { diff --git a/common/static/js/src/utility.js b/common/static/js/src/utility.js index d3124ee26e..396fa9c109 100644 --- a/common/static/js/src/utility.js +++ b/common/static/js/src/utility.js @@ -13,7 +13,7 @@ window.isExternal = function(url) { if (typeof match[2] === 'string' && match[2].length > 0 // this regex removes the port number if it patches the current location's protocol - && match[2].replace(new RegExp(':(' + {'http:': 80, 'https:': 443}[location.protocol] + ')?$'), '') !== location.host) { return true; } + && match[2].replace(new RegExp(`:(${{'http:': 80, 'https:': 443}[location.protocol]})?$`), '') !== location.host) { return true; } return false; }; @@ -34,6 +34,6 @@ window.rewriteStaticLinks = function(content, from, to) { // handle http and https // escape all regex interpretable chars fromRe = from.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); - var regex = new RegExp('(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_\+.~#?&//=]*))?' + fromRe, 'g'); + var regex = new RegExp(`(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_\+.~#?&//=]*))?${fromRe}`, 'g'); return content.replace(regex, replacer); }; diff --git a/common/static/karma_common.conf.js b/common/static/karma_common.conf.js index ef8244ff78..e9085415f0 100644 --- a/common/static/karma_common.conf.js +++ b/common/static/karma_common.conf.js @@ -6,6 +6,7 @@ 'use strict'; var path = require('path'); + var configModule = require(path.join(__dirname, '../../common/static/common/js/karma.common.conf.js')); var options = { @@ -13,7 +14,7 @@ var options = { useRequireJs: false, normalizePathsForCoverageFunc: function(appRoot, pattern) { - return path.join(appRoot, '/common/static/' + pattern); + return path.join(appRoot, `/common/static/${pattern}`); }, // Avoid adding files to this list. Use RequireJS. diff --git a/common/static/karma_common_requirejs.conf.js b/common/static/karma_common_requirejs.conf.js index f407a548d0..2bc0b54b03 100644 --- a/common/static/karma_common_requirejs.conf.js +++ b/common/static/karma_common_requirejs.conf.js @@ -6,6 +6,7 @@ 'use strict'; var path = require('path'); + var configModule = require(path.join(__dirname, '../../common/static/common/js/karma.common.conf.js')); var options = { @@ -13,7 +14,7 @@ var options = { includeCommonFiles: true, normalizePathsForCoverageFunc: function(appRoot, pattern) { - return path.join(appRoot, '/common/static/' + pattern); + return path.join(appRoot, `/common/static/${pattern}`); }, libraryFiles: [ diff --git a/jest.config.js b/jest.config.js index e9e014bd1d..a4e84c2350 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,17 +1,17 @@ module.exports = { - 'globals': { - 'gettext': (t) => { return t; }, + globals: { + gettext: (t) => t, }, - 'modulePaths': [ + modulePaths: [ 'common/static/common/js/components', ], - 'setupFilesAfterEnv': ['/setupTests.js'], - 'testMatch': [ + setupFilesAfterEnv: ['/setupTests.js'], + testMatch: [ '/**/*.test.jsx', 'common/static/common/js/components/**/?(*.)+(spec|test).js?(x)', ], - 'testEnvironment': 'jsdom', - 'transform': { + testEnvironment: 'jsdom', + transform: { '^.+\\.jsx$': 'babel-jest', '^.+\\.js$': 'babel-jest', }, diff --git a/lms/djangoapps/discussion/static/discussion/js/discussion_router.js b/lms/djangoapps/discussion/static/discussion/js/discussion_router.js index 46d2950670..9b97cbdd99 100644 --- a/lms/djangoapps/discussion/static/discussion/js/discussion_router.js +++ b/lms/djangoapps/discussion/static/discussion/js/discussion_router.js @@ -109,7 +109,7 @@ navigateToThread: function(threadId) { var thread = this.discussion.get(threadId); - return this.navigate('' + (thread.get('commentable_id')) + '/threads/' + threadId, { + return this.navigate(`${thread.get('commentable_id')}/threads/${threadId}`, { trigger: true }); }, diff --git a/lms/djangoapps/support/static/support/js/collections/certificate.js b/lms/djangoapps/support/static/support/js/collections/certificate.js index 27595a6b90..e8fd386200 100644 --- a/lms/djangoapps/support/static/support/js/collections/certificate.js +++ b/lms/djangoapps/support/static/support/js/collections/certificate.js @@ -20,9 +20,9 @@ }, url: function() { - var url = '/certificates/search?user=' + this.userFilter; + var url = `/certificates/search?user=${this.userFilter}`; if (this.courseFilter) { - url += '&course_id=' + this.courseFilter; + url += `&course_id=${this.courseFilter}`; } return url; } diff --git a/lms/djangoapps/support/static/support/js/spec/views/certificates_spec.js b/lms/djangoapps/support/static/support/js/spec/views/certificates_spec.js index db0999c8ae..f239a0e1dd 100644 --- a/lms/djangoapps/support/static/support/js/spec/views/certificates_spec.js +++ b/lms/djangoapps/support/static/support/js/spec/views/certificates_spec.js @@ -63,11 +63,11 @@ define([ searchFor = function(user_filter, course_filter, requests, response) { // Enter the search term and submit - var url = '/certificates/search?user=' + user_filter; + var url = `/certificates/search?user=${user_filter}`; view.setUserFilter(user_filter); if (course_filter) { view.setCourseFilter(course_filter); - url += '&course_id=' + course_filter; + url += `&course_id=${course_filter}`; } view.triggerSearch(); @@ -77,12 +77,12 @@ define([ }, regenerateCerts = function(username, courseKey) { - var sel = '.btn-cert-regenerate[data-course-key="' + 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 + '"]'; + var sel = `.btn-cert-generate[data-course-key="${courseKey}"]`; $(sel).click(); }; diff --git a/lms/djangoapps/support/static/support/js/spec/views/enrollment_modal_spec.js b/lms/djangoapps/support/static/support/js/spec/views/enrollment_modal_spec.js index c22b2ac2e5..dd77261883 100644 --- a/lms/djangoapps/support/static/support/js/spec/views/enrollment_modal_spec.js +++ b/lms/djangoapps/support/static/support/js/spec/views/enrollment_modal_spec.js @@ -30,16 +30,16 @@ define([ it('can render itself', function() { expect($('.enrollment-modal h1').text()).toContain( - 'Change enrollment for ' + EnrollmentHelpers.TEST_COURSE + `Change enrollment for ${EnrollmentHelpers.TEST_COURSE}` ); expect($('.enrollment-change-field p').first().text()).toContain('Current enrollment mode: audit'); _.each(['verified', 'audit'], function(mode) { - expect($('.enrollment-new-mode').html()).toContain('') + .append(``) .append(self.schedule_options(chapter.children)); // xss-lint: disable=javascript-jquery-append self.sequential_select.prop('disabled', false); $('#add-unit-button').prop('disabled', false); @@ -83,7 +83,7 @@ var edx = edx || {}; sequential = self.find_unit(self.hidden, chapter, sequential_location); self.vertical_select.html('') // xss-lint: disable=javascript-jquery-append, javascript-concat-html - .append('') + .append(``) .append(self.schedule_options(sequential.children)); // xss-lint: disable=javascript-jquery-append self.vertical_select.prop('disabled', false); self.set_datetime('start', sequential.start); @@ -184,8 +184,8 @@ var edx = edx || {}; $('table.ccx-schedule .date button').each(function() { if ($(this).text().trim() === gettext('Click to change')) { // xss-lint: disable=javascript-jquery-html, javascript-concat-html - $(this).html('Set date ' - + gettext('Click to change') + ''); // xss-lint: disable=javascript-concat-html + $(this).html(`Set date ${ + gettext('Click to change')}`); // xss-lint: disable=javascript-concat-html } }); @@ -222,7 +222,7 @@ var edx = edx || {}; // Populate chapters select, depopulate others this.chapter_select.html('') // xss-lint: disable=javascript-jquery-append, javascript-concat-html - .append('') + .append(``) .append(self.schedule_options(this.hidden)); // xss-lint: disable=javascript-jquery-append this.sequential_select.html('').prop('disabled', true); this.vertical_select.html('').prop('disabled', true); @@ -310,11 +310,11 @@ var edx = edx || {}; }, get_datetime: function(which) { - var date = $('form#add-unit input[name=' + which + '_date]').val(); - var time = $('form#add-unit input[name=' + which + '_time]').val(); + var date = $(`form#add-unit input[name=${which}_date]`).val(); + var time = $(`form#add-unit input[name=${which}_time]`).val(); time = _.isEmpty(time) ? '00:00' : time; if (date && time) { - return date + ' ' + time; + return `${date} ${time}`; } return null; }, @@ -323,8 +323,8 @@ var edx = edx || {}; var parts = value ? value.split(' ') : ['', ''], date = parts[0], time = parts[1]; - $('form#add-unit input[name=' + which + '_date]').val(date); - $('form#add-unit input[name=' + which + '_time]').val(time); + $(`form#add-unit input[name=${which}_date]`).val(date); + $(`form#add-unit input[name=${which}_time]`).val(time); }, schedule_options: function(nodes) { @@ -473,12 +473,12 @@ var edx = edx || {}; return; } if (what === 'start') { - unit.start = date + ' ' + time; + unit.start = `${date} ${time}`; if (unit.category === 'sequential') { self.updateChildrenDates(unit, what, unit.start); } } else { - unit.due = date + ' ' + time; + unit.due = `${date} ${time}`; if (unit.category === 'sequential') { self.updateChildrenDates(unit, what, unit.due); } diff --git a/lms/static/js/certificates/views/certificate_allowlist.js b/lms/static/js/certificates/views/certificate_allowlist.js index 89970dac7b..f0f8619ca7 100644 --- a/lms/static/js/certificates/views/certificate_allowlist.js +++ b/lms/static/js/certificates/views/certificate_allowlist.js @@ -42,7 +42,7 @@ }, loadTemplate: function(name) { - var templateSelector = '#' + name + '-tpl', + var templateSelector = `#${name}-tpl`, templateText = $(templateSelector).text(); return _.template(templateText); }, @@ -79,7 +79,7 @@ }, escapeAndShowMessage: function(message) { - $(this.message_div + '>p').remove(); + $(`${this.message_div}>p`).remove(); // xss-lint: disable=javascript-jquery-append $(this.message_div).removeClass('hidden').append(HtmlUtils.joinHtml( HtmlUtils.HTML('

'), diff --git a/lms/static/js/certificates/views/certificate_allowlist_editor.js b/lms/static/js/certificates/views/certificate_allowlist_editor.js index 136633c8aa..d7c5732d41 100644 --- a/lms/static/js/certificates/views/certificate_allowlist_editor.js +++ b/lms/static/js/certificates/views/certificate_allowlist_editor.js @@ -27,7 +27,7 @@ }, loadTemplate: function(name) { - var templateSelector = '#' + name + '-tpl', + var templateSelector = `#${name}-tpl`, templateText = $(templateSelector).text(); return _.template(templateText); }, @@ -89,7 +89,7 @@ }, escapeAndShowMessage: function(message) { - $(this.message_div + '>p').remove(); + $(`${this.message_div}>p`).remove(); // eslint-disable-next-line max-len this.$(this.message_div).removeClass('hidden').append(HtmlUtils.joinHtml(HtmlUtils.HTML('

'), message, HtmlUtils.HTML('

')).toString()); }, diff --git a/lms/static/js/certificates/views/certificate_bulk_allowlist.js b/lms/static/js/certificates/views/certificate_bulk_allowlist.js index ab93487841..0dcab79552 100644 --- a/lms/static/js/certificates/views/certificate_bulk_allowlist.js +++ b/lms/static/js/certificates/views/certificate_bulk_allowlist.js @@ -48,7 +48,7 @@ }, loadTemplate: function(name) { - var templateSelector = '#' + name + '-tpl', + var templateSelector = `#${name}-tpl`, templateText = $(templateSelector).text(); return _.template(templateText); }, @@ -81,9 +81,9 @@ function generateDiv(group, heading, displayData) { // inner function generate div and display response messages. $('
', { - class: 'message ' + group + class: `message ${group}` }).appendTo('.bulk-exception-results').prepend( // eslint-disable-line max-len, xss-lint: disable=javascript-jquery-insert-into-target,javascript-jquery-prepend - "" + heading) // eslint-disable-line max-len, xss-lint: disable=javascript-concat-html + `${heading}`) // eslint-disable-line max-len, xss-lint: disable=javascript-concat-html .append($('
    ', { class: group })); @@ -91,9 +91,9 @@ for (var i = 0; i < displayData.length; i++) { // eslint-disable-line vars-on-top $('
  • ', { text: displayData[i] - }).appendTo('div.message > .' + group); // eslint-disable-line max-len, xss-lint: disable=javascript-jquery-insert-into-target + }).appendTo(`div.message > .${group}`); // eslint-disable-line max-len, xss-lint: disable=javascript-jquery-insert-into-target } - $('div.message > .' + group).hide(); + $(`div.message > .${group}`).hide(); } function getDisplayText(qty, group) { @@ -103,52 +103,52 @@ switch (group) { case MESSAGE_GROUP.successfully_added: text = qty > 1 - ? gettext(qty + ' learners were successfully added to exception list') - : gettext(qty + ' learner was successfully added to the exception list'); + ? gettext(`${qty} learners were successfully added to exception list`) + : gettext(`${qty} learner was successfully added to the exception list`); break; case MESSAGE_GROUP.data_format_error: text = qty > 1 - ? gettext(qty + ' records are not in the correct format and have not been added to' + ? gettext(`${qty} records are not in the correct format and have not been added to` + ' the exception list') - : gettext(qty + ' record is not in the correct format and has not been added to the' + : gettext(`${qty} record is not in the correct format and has not been added to the` + ' exception list'); break; case MESSAGE_GROUP.user_not_exist: text = qty > 1 - ? gettext(qty + ' learner accounts cannot be found and have not been added to the ' + ? gettext(`${qty} learner accounts cannot be found and have not been added to the ` + 'exception list') - : gettext(qty + ' learner account cannot be found and has not been added to the' + : gettext(`${qty} learner account cannot be found and has not been added to the` + ' exception list'); break; case MESSAGE_GROUP.user_already_allowlisted: text = qty > 1 - ? gettext(qty + ' learners already appear on the exception list in this course') - : gettext(qty + ' learner already appears on the exception list in this course'); + ? gettext(`${qty} learners already appear on the exception list in this course`) + : gettext(`${qty} learner already appears on the exception list in this course`); break; case MESSAGE_GROUP.user_not_enrolled: text = qty > 1 - ? gettext(qty + ' learners are not enrolled in this course and have not added to the' + ? gettext(`${qty} learners are not enrolled in this course and have not added to the` + ' exception list') - : gettext(qty + ' learner is not enrolled in this course and has not been added to the' + : gettext(`${qty} learner is not enrolled in this course and has not been added to the` + ' exception list'); break; case MESSAGE_GROUP.user_on_certificate_invalidation_list: text = qty > 1 - ? gettext(qty + ' learners have an active certificate invalidation in this course and' + ? gettext(`${qty} learners have an active certificate invalidation in this course and` + ' have not been added to the exception list') - : gettext(qty + ' learner has an active certificate invalidation in this course and has' + : gettext(`${qty} learner has an active certificate invalidation in this course and has` + ' not been added to the exception list'); break; default: text = qty > 1 - ? gettext(qty + ' learners encountered unknown errors') - : gettext(qty + ' learner encountered an unknown error'); + ? gettext(`${qty} learners encountered unknown errors`) + : gettext(`${qty} learner encountered an unknown error`); break; } @@ -231,7 +231,7 @@ 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 { diff --git a/lms/static/js/certificates/views/certificate_invalidation_view.js b/lms/static/js/certificates/views/certificate_invalidation_view.js index cb23173a08..d47f31bc47 100644 --- a/lms/static/js/certificates/views/certificate_invalidation_view.js +++ b/lms/static/js/certificates/views/certificate_invalidation_view.js @@ -26,7 +26,7 @@ }, loadTemplate: function(name) { - var templateSelector = '#' + name + '-tpl', + var templateSelector = `#${name}-tpl`, templateText = $(templateSelector).text(); return _.template(templateText); }, @@ -114,8 +114,8 @@ }, escapeAndShowMessage: function(message) { - $(this.messages + '>p').remove(); - this.$(this.messages).removeClass('hidden').append('

    ' + _.escape(message) + '

    '); + $(`${this.messages}>p`).remove(); + this.$(this.messages).removeClass('hidden').append(`

    ${_.escape(message)}

    `); } }); diff --git a/lms/static/js/commerce/credit.js b/lms/static/js/commerce/credit.js index aaedd25014..0b83ebb7b0 100644 --- a/lms/static/js/commerce/credit.js +++ b/lms/static/js/commerce/credit.js @@ -11,7 +11,7 @@ var edx = edx || {}; edx.commerce.credit.createCreditRequest = function(providerId, courseKey, username) { return $.ajax({ - url: '/api/credit/v1/providers/' + providerId + '/request/', + url: `/api/credit/v1/providers/${providerId}/request/`, type: 'POST', headers: { 'X-CSRFToken': $.cookie('csrftoken') diff --git a/lms/static/js/components/card/views/card.js b/lms/static/js/components/card/views/card.js index f5815e90b2..2bf8af402b 100644 --- a/lms/static/js/components/card/views/card.js +++ b/lms/static/js/components/card/views/card.js @@ -65,9 +65,9 @@ }, className: function() { - var result = 'card ' - + this.switchOnConfiguration('square-card', 'list-card') + ' ' - + this.callIfFunction(this.cardClass); + var result = `card ${ + this.switchOnConfiguration('square-card', 'list-card')} ${ + this.callIfFunction(this.cardClass)}`; if (this.callIfFunction(this.pennant)) { result += ' has-pennant'; } @@ -78,7 +78,7 @@ var maxLength = 72, description = this.callIfFunction(this.description); if (description.length > maxLength) { - description = description.substring(0, maxLength).trim() + '...'; + description = `${description.substring(0, maxLength).trim()}...`; } HtmlUtils.setHtml( this.$el, diff --git a/lms/static/js/course_info.js b/lms/static/js/course_info.js index f1c7ffeb2c..c1df47f150 100644 --- a/lms/static/js/course_info.js +++ b/lms/static/js/course_info.js @@ -3,10 +3,10 @@ $(document).ready(function() { $('ul.tabs li').removeClass('enabled'); $(this).addClass('enabled'); - var data_class = '.' + $(this).attr('data-class'); + var data_class = `.${$(this).attr('data-class')}`; $('.tab').slideUp(); - $(data_class + ':hidden').slideDown(); + $(`${data_class}:hidden`).slideDown(); }); var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/); if (isSafari) { diff --git a/lms/static/js/course_sharing/course_sharing_events.js b/lms/static/js/course_sharing/course_sharing_events.js index a38ae16e07..718f0eb353 100644 --- a/lms/static/js/course_sharing/course_sharing_events.js +++ b/lms/static/js/course_sharing/course_sharing_events.js @@ -6,7 +6,7 @@ define(['jquery', 'logger'], function($, Logger) { return function(courseId) { - $(".action-facebook[data-course-id='" + courseId + "']").on('click', function() { + $(`.action-facebook[data-course-id='${courseId}']`).on('click', function() { // Emit an event telling that the Facebook share link was clicked. Logger.log('edx.course.share_clicked', { course_id: courseId, @@ -15,7 +15,7 @@ }); }); - $(".action-twitter[data-course-id='" + courseId + "']").on('click', function() { + $(`.action-twitter[data-course-id='${courseId}']`).on('click', function() { // Emit an event telling that the Twitter share link was clicked. Logger.log('edx.course.share_clicked', { course_id: courseId, diff --git a/lms/static/js/course_survey.js b/lms/static/js/course_survey.js index aca7048d83..4421960863 100644 --- a/lms/static/js/course_survey.js +++ b/lms/static/js/course_survey.js @@ -4,7 +4,7 @@ $(function() { // form field label styling on focus $('form :input').focus(function() { - $("label[for='" + this.id + "']").parent().addClass('is-focused'); + $(`label[for='${this.id}']`).parent().addClass('is-focused'); }).blur(function() { $('label').parent().removeClass('is-focused'); }); @@ -49,9 +49,9 @@ $(function() { }); if (cancel_submit) { - $('.status.message.submission-error'). - removeClass('is-hidden'). - focus(); + $('.status.message.submission-error') + .removeClass('is-hidden') + .focus(); $('html, body').animate({scrollTop: 0}, 'fast'); return false; } @@ -72,10 +72,10 @@ $(function() { toggleSubmitButton(true); json = $.parseJSON(jqXHR.responseText); $('.status.message.submission-error').addClass('is-shown').focus(); - $('.status.message.submission-error .message-copy'). - text(gettext('There has been an error processing your survey.')). - stop(). - css('display', 'block'); + $('.status.message.submission-error .message-copy') + .text(gettext('There has been an error processing your survey.')) + .stop() + .css('display', 'block'); }); }); @@ -83,14 +83,14 @@ function toggleSubmitButton(enable) { var $submitButton = $('form .form-actions #submit'); if (enable) { - $submitButton. - removeClass('is-disabled'). - attr('aria-disabled', false). - removeProp('disabled'); + $submitButton + .removeClass('is-disabled') + .attr('aria-disabled', false) + .removeProp('disabled'); } else { - $submitButton. - addClass('is-disabled'). - attr('aria-disabled', true). - prop('disabled', true); + $submitButton + .addClass('is-disabled') + .attr('aria-disabled', true) + .prop('disabled', true); } } diff --git a/lms/static/js/dashboard/dropdown.js b/lms/static/js/dashboard/dropdown.js index 9c2e0e71fc..3353f31667 100644 --- a/lms/static/js/dashboard/dropdown.js +++ b/lms/static/js/dashboard/dropdown.js @@ -10,8 +10,8 @@ var edx = edx || {}; edx.dashboard.dropdown.toggleCourseActionsDropdownMenu = function(event) { var $target = $(event.currentTarget), dashboardIndex = $target.data().dashboardIndex, - $dropdown = $($target.data('dropdownSelector') || '#actions-dropdown-' + dashboardIndex), - $dropdownButton = $($target.data('dropdownButtonSelector') || '#actions-dropdown-link-' + dashboardIndex), + $dropdown = $($target.data('dropdownSelector') || `#actions-dropdown-${dashboardIndex}`), + $dropdownButton = $($target.data('dropdownButtonSelector') || `#actions-dropdown-link-${dashboardIndex}`), ariaExpandedState = ($dropdownButton.attr('aria-expanded') === 'true'), menuItems = $dropdown.find('a'); diff --git a/lms/static/js/dashboard/legacy.js b/lms/static/js/dashboard/legacy.js index bd36849b25..4cd117a22c 100644 --- a/lms/static/js/dashboard/legacy.js +++ b/lms/static/js/dashboard/legacy.js @@ -272,13 +272,13 @@ var edx = edx || {}; display: 'block', 'z-index': 0 }); - $('#activate-account-modal').focus() + $('#activate-account-modal').focus(); } $('.action-email-settings').each(function(index) { - $(this).attr('id', 'email-settings-' + index); + $(this).attr('id', `email-settings-${index}`); // a bit of a hack, but gets the unique selector for the modal trigger - var trigger = '#' + $(this).attr('id'); + var trigger = `#${$(this).attr('id')}`; accessibleModal( trigger, '#email-settings-modal .close-modal', @@ -288,9 +288,9 @@ var edx = edx || {}; }); $('.action-unenroll').each(function(index) { - $(this).attr('id', 'unenroll-' + index); + $(this).attr('id', `unenroll-${index}`); // a bit of a hack, but gets the unique selector for the modal trigger - var trigger = '#' + $(this).attr('id'); + var trigger = `#${$(this).attr('id')}`; accessibleModal( trigger, '#unenroll-modal .close-modal', diff --git a/lms/static/js/demographics_collection/DemographicsCollectionBanner.jsx b/lms/static/js/demographics_collection/DemographicsCollectionBanner.jsx index 71a221d081..5aeddd5505 100644 --- a/lms/static/js/demographics_collection/DemographicsCollectionBanner.jsx +++ b/lms/static/js/demographics_collection/DemographicsCollectionBanner.jsx @@ -10,7 +10,7 @@ export class DemographicsCollectionBanner extends React.Component { this.state = { modalOpen: false, hideBanner: false - } + }; this.dismissBanner = this.dismissBanner.bind(this); } @@ -88,7 +88,7 @@ export class DemographicsCollectionBanner extends React.Component { }
- ) + ); } else { return null; } diff --git a/lms/static/js/demographics_collection/DemographicsCollectionModal.jsx b/lms/static/js/demographics_collection/DemographicsCollectionModal.jsx index 065cdc7583..1abc81f1f5 100644 --- a/lms/static/js/demographics_collection/DemographicsCollectionModal.jsx +++ b/lms/static/js/demographics_collection/DemographicsCollectionModal.jsx @@ -1,14 +1,14 @@ /* global gettext */ import React from 'react'; import get from 'lodash/get'; -import Wizard from './Wizard'; import Cookies from 'js-cookie'; -import {SelectWithInput} from './SelectWithInput' +import StringUtils from 'edx-ui-toolkit/js/utils/string-utils'; +import FocusLock from 'react-focus-lock'; +import Wizard from './Wizard'; +import {SelectWithInput} from './SelectWithInput'; import {MultiselectDropdown} from './MultiselectDropdown'; import AxiosJwtTokenService from '../jwt_auth/AxiosJwtTokenService'; -import StringUtils from 'edx-ui-toolkit/js/utils/string-utils'; import AxiosCsrfTokenService from '../jwt_auth/AxiosCsrfTokenService'; -import FocusLock from 'react-focus-lock'; const FIELD_NAMES = { CURRENT_WORK: 'current_work_sector', @@ -66,7 +66,7 @@ class DemographicsCollectionModal extends React.Component { accessToken, refreshUrl, ); - this.csrfTokenService = new AxiosCsrfTokenService(this.props.csrfTokenPath) + this.csrfTokenService = new AxiosCsrfTokenService(this.props.csrfTokenPath); } async componentDidMount() { @@ -108,7 +108,7 @@ class DemographicsCollectionModal extends React.Component { }; try { await this.jwtTokenService.getJwtToken(); - await fetch(url, options) + await fetch(url, options); } catch (error) { this.setState({loading: false, fieldError: true, errorMessage: error}); } @@ -129,13 +129,13 @@ class DemographicsCollectionModal extends React.Component { this.setState(({selected}) => { // decline was previously selected if (selected[FIELD_NAMES.ETHNICITY].find(i => i === 'declined')) { - return {selected: {...selected, [FIELD_NAMES.ETHNICITY]: values.filter(value => value !== 'declined')}} + return {selected: {...selected, [FIELD_NAMES.ETHNICITY]: values.filter(value => value !== 'declined')}}; // decline was just selected } else if (decline) { - return {selected: {...selected, [FIELD_NAMES.ETHNICITY]: [decline]}} + return {selected: {...selected, [FIELD_NAMES.ETHNICITY]: [decline]}}; // anything else was selected } else { - return {selected: {...selected, [FIELD_NAMES.ETHNICITY]: values}} + return {selected: {...selected, [FIELD_NAMES.ETHNICITY]: values}}; } }); } @@ -174,7 +174,7 @@ class DemographicsCollectionModal extends React.Component { // We gather the possible answers to any demographics questions from the OPTIONS of the api async getDemographicsQuestionOptions() { try { - const optionsResponse = await fetch(`${this.props.demographicsBaseUrl}/demographics/api/v1/demographics/`, {method: 'OPTIONS'}) + const optionsResponse = await fetch(`${this.props.demographicsBaseUrl}/demographics/api/v1/demographics/`, {method: 'OPTIONS'}); const demographicsOptions = await optionsResponse.json(); return demographicsOptions; } catch (error) { @@ -240,7 +240,7 @@ class DemographicsCollectionModal extends React.Component { render() { if (this.state.loading) { - return
+ return
; } return ( @@ -319,7 +319,7 @@ class DemographicsCollectionModal extends React.Component { name: FIELD_NAMES.ETHNICITY, value: wizardConsumer[FIELD_NAMES.ETHNICITY].map(ethnicity => ({ethnicity, value: ethnicity})), } - } + }; this.handleSelectChange(e); }} /> @@ -366,7 +366,7 @@ class DemographicsCollectionModal extends React.Component { }
-
+
} @@ -411,7 +411,7 @@ class DemographicsCollectionModal extends React.Component { }
- + } @@ -474,7 +474,7 @@ class DemographicsCollectionModal extends React.Component { } - + } @@ -493,7 +493,7 @@ class DemographicsCollectionModal extends React.Component { - ) + ); } } diff --git a/lms/static/js/demographics_collection/MultiselectDropdown.jsx b/lms/static/js/demographics_collection/MultiselectDropdown.jsx index 780ed91929..1dfe965c4a 100644 --- a/lms/static/js/demographics_collection/MultiselectDropdown.jsx +++ b/lms/static/js/demographics_collection/MultiselectDropdown.jsx @@ -13,7 +13,7 @@ class MultiselectDropdown extends React.Component { this.buttonRef = null; this.setButtonRef = (element) => { this.buttonRef = element; - } + }; this.focusButton = this.focusButton.bind(this); this.handleKeydown = this.handleKeydown.bind(this); @@ -87,7 +87,7 @@ class MultiselectDropdown extends React.Component { .map(selected => this.findOption(selected).display_name) .join(', '); if (selectedList.length > 60) { - return selectedList.substring(0, 55) + '...' + return `${selectedList.substring(0, 55)}...`; } return selectedList; } @@ -95,7 +95,7 @@ class MultiselectDropdown extends React.Component { renderUnselect() { return this.props.selected.length > 0 && ( - ) + ); } renderMenu() { @@ -112,15 +112,15 @@ class MultiselectDropdown extends React.Component { {option.display_name} - ) - }) + ); + }); return (
{this.props.label} {options}
- ) + ); } render() { @@ -136,7 +136,7 @@ class MultiselectDropdown extends React.Component { // and close the dropdown. if (!e.currentTarget.contains(e.relatedTarget)) { this.props.onBlur(e); - this.setState({open: false}) + this.setState({open: false}); } }} > @@ -151,7 +151,7 @@ class MultiselectDropdown extends React.Component { {this.renderMenu()} - ) + ); } } diff --git a/lms/static/js/demographics_collection/SelectWithInput.jsx b/lms/static/js/demographics_collection/SelectWithInput.jsx index 794c87e450..237b514ae3 100644 --- a/lms/static/js/demographics_collection/SelectWithInput.jsx +++ b/lms/static/js/demographics_collection/SelectWithInput.jsx @@ -46,5 +46,5 @@ export const SelectWithInput = (props) => { /> } - ) -} + ); +}; diff --git a/lms/static/js/demographics_collection/Wizard.jsx b/lms/static/js/demographics_collection/Wizard.jsx index 42f57d3574..759cc8c2d1 100644 --- a/lms/static/js/demographics_collection/Wizard.jsx +++ b/lms/static/js/demographics_collection/Wizard.jsx @@ -16,7 +16,7 @@ export default class Wizard extends React.Component { totalPages: 0, pages: [], wizardContext: {}, - } + }; this.wizardComplete = this.wizardComplete.bind(this); } @@ -32,18 +32,18 @@ export default class Wizard extends React.Component { handleNext() { if (this.state.currentPage < this.props.children.length) { - this.setState(prevState => ({currentPage: prevState.currentPage + 1})) + this.setState(prevState => ({currentPage: prevState.currentPage + 1})); } } findSubComponentByType(type) { - return React.Children.toArray(this.props.children).filter(child => child.type.name === type) + return React.Children.toArray(this.props.children).filter(child => child.type.name === type); } // this needs to handle the case of no provided header renderHeader() { const header = this.findSubComponentByType(Wizard.Header.name)[0]; - return header.props.children({currentPage: this.state.currentPage, totalPages: this.state.totalPages}) + return header.props.children({currentPage: this.state.currentPage, totalPages: this.state.totalPages}); } renderPage() { @@ -74,7 +74,7 @@ export default class Wizard extends React.Component { - ) + ); } /** diff --git a/lms/static/js/discovery/discovery_factory.js b/lms/static/js/discovery/discovery_factory.js index 662db9c8e1..d12163362a 100644 --- a/lms/static/js/discovery/discovery_factory.js +++ b/lms/static/js/discovery/discovery_factory.js @@ -90,7 +90,7 @@ } function quote(string) { - return '"' + string + '"'; + return `"${string}"`; } }; }); diff --git a/lms/static/js/discussions_management/views/discussions.js b/lms/static/js/discussions_management/views/discussions.js index 54cba38756..1b1330f889 100644 --- a/lms/static/js/discussions_management/views/discussions.js +++ b/lms/static/js/discussions_management/views/discussions.js @@ -222,7 +222,7 @@ }, getSectionCss: function(section) { - return ".instructor-nav .nav-item [data-section='" + section + "']"; + return `.instructor-nav .nav-item [data-section='${section}']`; }, renderTopics: function() { diff --git a/lms/static/js/edxnotes/plugins/store_error_handler.js b/lms/static/js/edxnotes/plugins/store_error_handler.js index 1976293b55..3aafe2dc86 100644 --- a/lms/static/js/edxnotes/plugins/store_error_handler.js +++ b/lms/static/js/edxnotes/plugins/store_error_handler.js @@ -22,7 +22,7 @@ // if response includes an error message it will take precedence if (serverResponse && serverResponse.error_msg) { Annotator.showNotification(serverResponse.error_msg, Annotator.Notification.ERROR); - return console.error(Annotator._t('API request failed:') + (" '" + xhr.status + "'")); + return console.error(`${Annotator._t('API request failed:')} '${xhr.status}'`); } // Delegate to original error handler diff --git a/lms/static/js/edxnotes/utils/notes_collector.js b/lms/static/js/edxnotes/utils/notes_collector.js index b93e792f89..0afefc1ddd 100644 --- a/lms/static/js/edxnotes/utils/notes_collector.js +++ b/lms/static/js/edxnotes/utils/notes_collector.js @@ -53,9 +53,9 @@ dataType: 'json', headers: {'x-annotator-auth-token': searchRequestsData[0].params.token} }; - searchEndpoint = searchRequestsData[0].params.endpoint + 'search/?'; + searchEndpoint = `${searchRequestsData[0].params.endpoint}search/?`; usageIds = _.map(searchRequestsData, function(item) { - return 'usage_id=' + encodeURIComponent(item.params.usageId); + return `usage_id=${encodeURIComponent(item.params.usageId)}`; }); // Search endpoint expects the below format for query params diff --git a/lms/static/js/edxnotes/utils/template.js b/lms/static/js/edxnotes/utils/template.js index 76aca48be5..c67d540fe8 100644 --- a/lms/static/js/edxnotes/utils/template.js +++ b/lms/static/js/edxnotes/utils/template.js @@ -8,10 +8,10 @@ * @return The loaded template. */ var loadTemplate = function(name) { - var templateSelector = '#' + name + '-tpl', + var templateSelector = `#${name}-tpl`, templateText = $(templateSelector).text(); if (!templateText) { - console.error('Failed to load ' + name + ' template'); + console.error(`Failed to load ${name} template`); } return _.template(templateText); }; diff --git a/lms/static/js/edxnotes/utils/utils.js b/lms/static/js/edxnotes/utils/utils.js index 800a26e018..0b64f710bf 100644 --- a/lms/static/js/edxnotes/utils/utils.js +++ b/lms/static/js/edxnotes/utils/utils.js @@ -15,7 +15,7 @@ * string
*/ var nl2br = function(str) { - return (str + '').replace(/(\r\n|\n\r|\r|\n)/g, '
'); + return (`${str}`).replace(/(\r\n|\n\r|\r|\n)/g, '
'); }; return { diff --git a/lms/static/js/edxnotes/views/note_group.js b/lms/static/js/edxnotes/views/note_group.js index c9151f728e..bb92ffa13e 100644 --- a/lms/static/js/edxnotes/views/note_group.js +++ b/lms/static/js/edxnotes/views/note_group.js @@ -9,7 +9,7 @@ GroupView = Backbone.View.extend({ tagName: 'section', id: function() { - return 'note-section-' + _.uniqueId(); + return `note-section-${_.uniqueId()}`; }, initialize: function(options) { @@ -35,7 +35,7 @@ tagName: 'section', className: 'note-group', id: function() { - return 'note-group-' + _.uniqueId(); + return `note-group-${_.uniqueId()}`; }, template: HtmlUtils.template('

<%- chapterName %>

'), diff --git a/lms/static/js/edxnotes/views/note_item.js b/lms/static/js/edxnotes/views/note_item.js index 0b1aedf73b..8aca334a53 100644 --- a/lms/static/js/edxnotes/views/note_item.js +++ b/lms/static/js/edxnotes/views/note_item.js @@ -9,7 +9,7 @@ tagName: 'article', className: 'note', id: function() { - return 'note-' + _.uniqueId(); + return `note-${_.uniqueId()}`; }, events: { 'click .note-excerpt-more-link': 'moreHandler', diff --git a/lms/static/js/edxnotes/views/shim.js b/lms/static/js/edxnotes/views/shim.js index 225ddca625..eefd439828 100644 --- a/lms/static/js/edxnotes/views/shim.js +++ b/lms/static/js/edxnotes/views/shim.js @@ -47,9 +47,9 @@ // Add screen reader label for edit mode. Note that the id of the tags element will not always be "1". // It depends on the number of annotatable components on the page. var tagsField = $('li.annotator-item >input', this.annotator.editor.element).attr('id'); - if ($("label.sr[for='" + tagsField + "']", this.annotator.editor.element).length === 0) { + if ($(`label.sr[for='${tagsField}']`, this.annotator.editor.element).length === 0) { HtmlUtils.prepend( - $('#' + tagsField, this.annotator.editor.element), + $(`#${tagsField}`, this.annotator.editor.element), $(HtmlUtils.joinHtml( HtmlUtils.HTML('
', { 'aria-hidden': 'true', class: 'modal email-modal', - id: 'email_message_' + emailId + id: `email_message_${emailId}` }); $emailWrapper = $('
', { class: 'inner-wrapper email-content-wrapper' @@ -269,7 +269,7 @@ type: 'button', name: 'copy-email-body-text', value: gettext('Copy Email To Editor'), - id: 'copy_email_' + emailId + id: `copy_email_${emailId}` })); $closeButton = $('', { href: '#', @@ -306,16 +306,16 @@ $emailWrapper.append($emailContent); $messageContent.append($emailWrapper); $messagesWrapper.append($messageContent); - $('#email_message_' + emailInfo.email.id + '_trig').leanModal({ + $(`#email_message_${emailInfo.email.id}_trig`).leanModal({ closeButton: '.close-modal', - copyEmailButton: '#copy_email_' + emailId + copyEmailButton: `#copy_email_${emailId}` }); setupCopyEmailButton(emailId, emailInfo.email.html_message, emailInfo.email.subject); } }; setupCopyEmailButton = function(emailId, htmlMessage, subject) { - return $('#copy_email_' + emailId).click(function() { + return $(`#copy_email_${emailId}`).click(function() { var editor; editor = tinyMCE.get('mce_0'); editor.setContent(htmlMessage); diff --git a/lms/static/js/leanModal.js b/lms/static/js/leanModal.js index cd7f490e9d..19ab9636de 100644 --- a/lms/static/js/leanModal.js +++ b/lms/static/js/leanModal.js @@ -1,6 +1,6 @@ (function($) { // eslint-disable-line wrap-iife - -'use strict'; + + 'use strict'; $.fn.extend({ /* @@ -88,22 +88,22 @@ $('iframe', modalId).attr('src', $('iframe', modalId).data('src')); if ($(modalId).hasClass('email-modal')) { $(modalId).css({ - width: 80 + '%', - height: 80 + '%', + width: `${80}%`, + height: `${80}%`, position: o.position, opacity: 0, 'z-index': 11000, - left: 10 + '%', - top: 10 + '%' + left: `${10}%`, + top: `${10}%` }); } else { $(modalId).css({ position: o.position, opacity: 0, 'z-index': 11000, - left: 50 + '%', - 'margin-left': -($(modalId).outerWidth() / 2) + 'px', - top: o.top + 'px' + left: `${50}%`, + 'margin-left': `${-($(modalId).outerWidth() / 2)}px`, + top: `${o.top}px` }); } @@ -139,7 +139,7 @@ embed = $($(this).attr('href')).find('iframe'); if (embed.length > 0 && embed.attr('src')) { sep = (embed.attr('src').indexOf('?') > 0) ? '&' : '?'; - embed.data('src', embed.attr('src') + sep + 'autoplay=1&rel=0'); + embed.data('src', `${embed.attr('src') + sep}autoplay=1&rel=0`); embed.attr('src', ''); } }); diff --git a/lms/static/js/learner_analytics_dashboard/CircleChartLegend.jsx b/lms/static/js/learner_analytics_dashboard/CircleChartLegend.jsx index 7034875197..adf9246073 100644 --- a/lms/static/js/learner_analytics_dashboard/CircleChartLegend.jsx +++ b/lms/static/js/learner_analytics_dashboard/CircleChartLegend.jsx @@ -50,6 +50,6 @@ class CircleChartLegend extends React.Component { CircleChartLegend.propTypes = { data: PropTypes.array.isRequired -} +}; export default CircleChartLegend; diff --git a/lms/static/js/learner_analytics_dashboard/Discussions.jsx b/lms/static/js/learner_analytics_dashboard/Discussions.jsx index d5b48c915a..5b704bfe95 100644 --- a/lms/static/js/learner_analytics_dashboard/Discussions.jsx +++ b/lms/static/js/learner_analytics_dashboard/Discussions.jsx @@ -35,7 +35,7 @@ class Discussions extends React.Component { if (percent === 0) { percentWidth = '2px'; } else { - percentWidth = 'calc((100% - 40px) * ' + percent + ')'; + percentWidth = `calc((100% - 40px) * ${percent})`; } return (
@@ -85,6 +85,6 @@ class Discussions extends React.Component { Discussions.propTypes = { content_authored: PropTypes.number.isRequired, thread_votes: PropTypes.number.isRequired -} +}; export default Discussions; diff --git a/lms/static/js/learner_analytics_dashboard/DueDates.jsx b/lms/static/js/learner_analytics_dashboard/DueDates.jsx index 86be589d0a..bbe85bda2a 100644 --- a/lms/static/js/learner_analytics_dashboard/DueDates.jsx +++ b/lms/static/js/learner_analytics_dashboard/DueDates.jsx @@ -22,11 +22,11 @@ class DueDates extends React.Component { getLabel(type) { const {assignmentCounts} = this.props; - if (assignmentCounts[type] < 2 ) { + if (assignmentCounts[type] < 2) { return type; } else { this.renderLabels[type] += 1; - return type + ' ' + this.renderLabels[type]; + return `${type} ${this.renderLabels[type]}`; } } @@ -35,14 +35,12 @@ class DueDates extends React.Component { this.renderLabels = this.initLabelTracker(assignmentCounts); return dates.sort((a, b) => new Date(a.due) > new Date(b.due)) - .map(({format, due}, index) => { - return ( -
  • -
    {this.getLabel(format)}
    -
    {this.getDate(due)}
    -
  • - ); - }); + .map(({format, due}, index) => ( +
  • +
    {this.getLabel(format)}
    +
    {this.getDate(due)}
    +
  • + )); } initLabelTracker(list) { @@ -51,7 +49,7 @@ class DueDates extends React.Component { return labels.reduce((accumulator, key) => { accumulator[key] = 0; return accumulator; - }, {}) + }, {}); } renderList() { @@ -73,6 +71,6 @@ class DueDates extends React.Component { DueDates.propTypes = { dates: PropTypes.array.isRequired -} +}; export default DueDates; diff --git a/lms/static/js/learner_analytics_dashboard/GradeTable.jsx b/lms/static/js/learner_analytics_dashboard/GradeTable.jsx index 6d5019c27f..c34d02e554 100644 --- a/lms/static/js/learner_analytics_dashboard/GradeTable.jsx +++ b/lms/static/js/learner_analytics_dashboard/GradeTable.jsx @@ -1,20 +1,21 @@ import React from 'react'; import classNames from 'classnames'; import PropTypes from 'prop-types'; + const exGrades = [ { - 'assignment_type':'Exam', - 'total_possible':6.0, - 'total_earned':3.0 + assignment_type: 'Exam', + total_possible: 6.0, + total_earned: 3.0 }, { - 'assignment_type':'Homework', - 'total_possible':5.0, + assignment_type: 'Homework', + total_possible: 5.0, }, { - 'assignment_type':'Homework', - 'total_possible':11.0, - 'total_earned':0.0 + assignment_type: 'Homework', + total_possible: 11.0, + total_earned: 0.0 } ]; @@ -68,7 +69,7 @@ class GradeTable extends React.Component { - ) + ); } }; @@ -77,6 +78,6 @@ GradeTable.propTypes = { grades: PropTypes.array.isRequired, passingGrade: PropTypes.number.isRequired, percentGrade: PropTypes.number.isRequired -} +}; export default GradeTable; diff --git a/lms/static/js/learner_analytics_dashboard/LearnerAnalyticsDashboard.jsx b/lms/static/js/learner_analytics_dashboard/LearnerAnalyticsDashboard.jsx index 24f0593350..817942d17c 100644 --- a/lms/static/js/learner_analytics_dashboard/LearnerAnalyticsDashboard.jsx +++ b/lms/static/js/learner_analytics_dashboard/LearnerAnalyticsDashboard.jsx @@ -15,7 +15,7 @@ function arrayToObject(array) { const key = Object.keys(obj)[0]; accumulator[key] = obj[key]; return accumulator; - }, {}) + }, {}); } function countByType(type, assignments) { @@ -24,7 +24,7 @@ function countByType(type, assignments) { if (format === type) { count += 1; } - }) + }); return count; } @@ -34,11 +34,9 @@ function getActiveUserString(count) { } function getAssignmentCounts(types, assignments) { - const countsArray = types.map((type) => { - return { - [type]: countByType(type, assignments) - } - }); + const countsArray = types.map((type) => ({ + [type]: countByType(type, assignments) + })); return arrayToObject(countsArray); } @@ -56,7 +54,7 @@ function getStreakEncouragement(count) { } function getStreakString(count) { - const unit = (count ===1) ? 'week' : 'weeks'; + const unit = (count === 1) ? 'week' : 'weeks'; return (count > 0) ? `Active ${count} ${unit} in a row` : false; } @@ -64,13 +62,11 @@ export function LearnerAnalyticsDashboard(props) { const { grading_policy, grades, schedule, schedule_raw, week_streak, weekly_active_users, discussion_info, profile_images, passing_grade, percent_grade } = props; - const gradeBreakdown = grading_policy.GRADER.map(({type, weight}, index) => { - return { - value: weight, - label: type, - sliceIndex: index + 1 - } - }); + const gradeBreakdown = grading_policy.GRADER.map(({type, weight}, index) => ({ + value: weight, + label: type, + sliceIndex: index + 1 + })); // Get a list of assignment types minus duplicates const assignments = gradeBreakdown.map(value => value['label']); @@ -101,7 +97,7 @@ export function LearnerAnalyticsDashboard(props) { />
    -
    + }

    Graded Assignments

    diff --git a/lms/static/js/pdf-analytics.js b/lms/static/js/pdf-analytics.js index effbbcdfab..1612fce4e7 100644 --- a/lms/static/js/pdf-analytics.js +++ b/lms/static/js/pdf-analytics.js @@ -1,7 +1,7 @@ function sendLog(name, data, event_type) { var message = data || {}; message.chapter = PDF_URL || ''; - message.name = 'textbook.pdf.' + name; + message.name = `textbook.pdf.${name}`; Logger.log(event_type || message.name, message); } diff --git a/lms/static/js/pending_tasks.js b/lms/static/js/pending_tasks.js index 7796aea5ee..205c420621 100644 --- a/lms/static/js/pending_tasks.js +++ b/lms/static/js/pending_tasks.js @@ -35,7 +35,7 @@ for (task_id in response) { var task_dict = response[task_id]; // find the corresponding entry, and update it: - entry = $(_this.element).find('[data-task-id="' + task_id + '"]'); + entry = $(_this.element).find(`[data-task-id="${task_id}"]`); entry.find('.task-state').text(task_dict.task_state); var duration_value = (task_dict.task_progress && task_dict.task_progress.duration_ms && Math.round(task_dict.task_progress.duration_ms / 1000)) || 'unknown'; diff --git a/lms/static/js/query-params.js b/lms/static/js/query-params.js index 0901d801f1..7d9315aec8 100644 --- a/lms/static/js/query-params.js +++ b/lms/static/js/query-params.js @@ -1,6 +1,6 @@ // http://james.padolsey.com/javascript/bujs-1-getparameterbyname/ function getParameterByName(name) { - var match = RegExp('[?&]' + name + '=([^&]*)') + var match = RegExp(`[?&]${name}=([^&]*)`) .exec(window.location.search); return match diff --git a/lms/static/js/spec/api_admin/catalog_preview_spec.js b/lms/static/js/spec/api_admin/catalog_preview_spec.js index 4e439fa8f0..3226f18057 100644 --- a/lms/static/js/spec/api_admin/catalog_preview_spec.js +++ b/lms/static/js/spec/api_admin/catalog_preview_spec.js @@ -34,7 +34,7 @@ define([ var requests = AjaxHelpers.requests(this); view.$('#id_query').val('*'); view.$('.preview-query').click(); - AjaxHelpers.expectRequest(requests, 'GET', previewUrl + '?q=*'); + AjaxHelpers.expectRequest(requests, 'GET', `${previewUrl}?q=*`); AjaxHelpers.respondWithJson(requests, { results: [{key: 'TestX', title: 'Test Course'}], count: 1, @@ -42,7 +42,7 @@ define([ prev: null }); expect(view.$('.preview-results').text()).toContain('Test Course'); - expect(view.$('.preview-results-list li a').attr('href')).toEqual(catalogApiUrl + 'TestX'); + expect(view.$('.preview-results-list li a').attr('href')).toEqual(`${catalogApiUrl}TestX`); }); it('displays an error when courses cannot be retrieved', function() { diff --git a/lms/static/js/spec/ccx/schedule_spec.js b/lms/static/js/spec/ccx/schedule_spec.js index 5f1a819bcd..db4d26ec2f 100644 --- a/lms/static/js/spec/ccx/schedule_spec.js +++ b/lms/static/js/spec/ccx/schedule_spec.js @@ -9,7 +9,7 @@ define(['edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers', 'js/ccx/schedule'], var scheduleFixture = readFixtures('templates/ccx/schedule.underscore'); appendSetFixtures( - '' + `` ); schedule_template = _.template($('#schedule_template').html()); save_url = 'save_ccx'; diff --git a/lms/static/js/spec/course_sharing/course_sharing_events_spec.js b/lms/static/js/spec/course_sharing/course_sharing_events_spec.js index dc098c1717..8fb3832774 100644 --- a/lms/static/js/spec/course_sharing/course_sharing_events_spec.js +++ b/lms/static/js/spec/course_sharing/course_sharing_events_spec.js @@ -17,7 +17,7 @@ define( }); it('sends an event only for a course whose facebook link is clicked', function() { - $(".action-facebook[data-course-id='" + courseKey1 + "']").click(); + $(`.action-facebook[data-course-id='${courseKey1}']`).click(); expect(Logger.log).toHaveBeenCalledWith('edx.course.share_clicked', { course_id: courseKey1, social_media_site: 'facebook', @@ -26,7 +26,7 @@ define( expect(Logger.log.calls.count()).toEqual(1); Logger.log.calls.reset(); - $(".action-facebook[data-course-id='" + courseKey2 + "']").click(); + $(`.action-facebook[data-course-id='${courseKey2}']`).click(); expect(Logger.log).toHaveBeenCalledWith('edx.course.share_clicked', { course_id: courseKey2, social_media_site: 'facebook', @@ -36,7 +36,7 @@ define( }); it('sends an event only for a course whose twitter link is clicked', function() { - $(".action-twitter[data-course-id='" + courseKey1 + "']").click(); + $(`.action-twitter[data-course-id='${courseKey1}']`).click(); expect(Logger.log).toHaveBeenCalledWith('edx.course.share_clicked', { course_id: courseKey1, social_media_site: 'twitter', @@ -45,7 +45,7 @@ define( expect(Logger.log.calls.count()).toEqual(1); Logger.log.calls.reset(); - $(".action-twitter[data-course-id='" + courseKey2 + "']").click(); + $(`.action-twitter[data-course-id='${courseKey2}']`).click(); expect(Logger.log).toHaveBeenCalledWith('edx.course.share_clicked', { course_id: courseKey2, social_media_site: 'twitter', diff --git a/lms/static/js/spec/courseware/course_info_events_spec.js b/lms/static/js/spec/courseware/course_info_events_spec.js index c53fec57db..0d675915f2 100644 --- a/lms/static/js/spec/courseware/course_info_events_spec.js +++ b/lms/static/js/spec/courseware/course_info_events_spec.js @@ -11,9 +11,9 @@ define(['jquery', 'logger', 'js/courseware/course_info_events'], function($, Log it('sends an event when "Resume Course" is clicked', function() { $('.last-accessed-link').click(); expect(Logger.log).toHaveBeenCalledWith('edx.course.home.resume_course.clicked', { - url: 'http://' - + window.location.host - + '/courses/course-v1:edX+DemoX+Demo_Course/courseware/19a30717eff543078a5d94ae9d6c18a5/' + url: `http://${ + window.location.host + }/courses/course-v1:edX+DemoX+Demo_Course/courseware/19a30717eff543078a5d94ae9d6c18a5/` }); }); diff --git a/lms/static/js/spec/courseware/link_clicked_events_spec.js b/lms/static/js/spec/courseware/link_clicked_events_spec.js index ef9a26815a..23564966c5 100644 --- a/lms/static/js/spec/courseware/link_clicked_events_spec.js +++ b/lms/static/js/spec/courseware/link_clicked_events_spec.js @@ -19,7 +19,7 @@ define(['jquery', 'logger', 'js/courseware/courseware_factory'], function($, Log it('sends an event when an internal link is clicked', function() { $('.internal-link').click(); expect(Logger.log).toHaveBeenCalledWith('edx.ui.lms.link_clicked', { - target_url: 'http://' + window.location.host + '/some/internal/link', + target_url: `http://${window.location.host}/some/internal/link`, current_url: window.location.toString() }); }); diff --git a/lms/static/js/spec/discovery/views/course_card_spec.js b/lms/static/js/spec/discovery/views/course_card_spec.js index e037609901..6413a5155a 100644 --- a/lms/static/js/spec/discovery/views/course_card_spec.js +++ b/lms/static/js/spec/discovery/views/course_card_spec.js @@ -41,8 +41,8 @@ define([ it('renders', function() { var data = this.view.model.attributes; expect(this.view.$el).toContainHtml(data.content.display_name); - expect(this.view.$el).toContainElement('a[href="/courses/' + data.course + '/about"]'); - expect(this.view.$el).toContainElement('img[src="' + data.image_url + '"]'); + expect(this.view.$el).toContainElement(`a[href="/courses/${data.course}/about"]`); + expect(this.view.$el).toContainElement(`img[src="${data.image_url}"]`); expect(this.view.$el.find('.course-name')).toContainHtml(data.org); expect(this.view.$el.find('.course-name')).toContainHtml(data.content.number); expect(this.view.$el.find('.course-name')).toContainHtml(data.content.display_name); diff --git a/lms/static/js/spec/discovery/views/refine_sidebar_spec.js b/lms/static/js/spec/discovery/views/refine_sidebar_spec.js index 8a3fe333ae..744d8331fa 100644 --- a/lms/static/js/spec/discovery/views/refine_sidebar_spec.js +++ b/lms/static/js/spec/discovery/views/refine_sidebar_spec.js @@ -58,7 +58,7 @@ define([ it('expands and collapses facet', function() { var options = _.range(20).map(function(number) { - return {facet: 'org', term: 'test' + number, count: 1}; + return {facet: 'org', term: `test${number}`, count: 1}; }); this.facetOptions.reset(options); this.sidebar.render(); diff --git a/lms/static/js/spec/edxnotes/helpers.js b/lms/static/js/spec/edxnotes/helpers.js index d0d232f0e9..911ebeccd4 100644 --- a/lms/static/js/spec/edxnotes/helpers.js +++ b/lms/static/js/spec/edxnotes/helpers.js @@ -76,15 +76,15 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers' iat: now }; - return 'header.' + base64Encode(JSON.stringify(rawToken)) + '.signature'; + return `header.${base64Encode(JSON.stringify(rawToken))}.signature`; }; getChapter = function(name, location, index, children) { return { display_name: name, - location: 'i4x://chapter/' + location, + location: `i4x://chapter/${location}`, index: index, children: _.map(children, function(i) { - return 'i4x://section/' + i; + return `i4x://section/${i}`; }) }; }; @@ -92,9 +92,9 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers' getSection = function(name, location, children) { return { display_name: name, - location: 'i4x://section/' + location, + location: `i4x://section/${location}`, children: _.map(children, function(i) { - return 'i4x://unit/' + i; + return `i4x://unit/${i}`; }) }; }; @@ -102,7 +102,7 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers' getUnit = function(name, location) { return { display_name: name, - location: 'i4x://unit/' + location, + location: `i4x://unit/${location}`, url: 'http://example.com' }; }; @@ -193,14 +193,14 @@ define(['underscore', 'URI', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers' for (var i = 0; i < options.numNotesToCreate; i++) { var notesInfo = { - chapter: getChapter('First Chapter__' + i, 1, 0, [2]), - section: getSection('First Section__' + i, 2, [3]), - unit: getUnit('First Unit__' + i, 3), + chapter: getChapter(`First Chapter__${i}`, 1, 0, [2]), + section: getSection(`First Section__${i}`, 2, [3]), + unit: getUnit(`First Unit__${i}`, 3), created: new Date().toISOString(), updated: new Date().toISOString(), - text: 'text__' + i, - quote: 'Note__' + i, - tags: ['tag__' + i, 'tag__' + i + 1] + text: `text__${i}`, + quote: `Note__${i}`, + tags: [`tag__${i}`, `tag__${i}${1}`] }; data.results.push(notesInfo); diff --git a/lms/static/js/spec/edxnotes/plugins/events_spec.js b/lms/static/js/spec/edxnotes/plugins/events_spec.js index 304c5746de..702079a569 100644 --- a/lms/static/js/spec/edxnotes/plugins/events_spec.js +++ b/lms/static/js/spec/edxnotes/plugins/events_spec.js @@ -137,8 +137,8 @@ define([ it('should truncate values of some fields', function() { var oldNote = $.extend({}, note, {text: Helpers.LONG_TEXT, tags: ['review', Helpers.LONG_TEXT]}), newNote = $.extend({}, note, { - text: Helpers.LONG_TEXT + '123', - quote: Helpers.LONG_TEXT + '123', + text: `${Helpers.LONG_TEXT}123`, + quote: `${Helpers.LONG_TEXT}123`, tags: ['short', 'tags', 'will', 'stay', Helpers.LONG_TEXT] }); diff --git a/lms/static/js/spec/edxnotes/utils/notes_collector_spec.js b/lms/static/js/spec/edxnotes/utils/notes_collector_spec.js index 1c92151cbf..b6857347a5 100644 --- a/lms/static/js/spec/edxnotes/utils/notes_collector_spec.js +++ b/lms/static/js/spec/edxnotes/utils/notes_collector_spec.js @@ -27,7 +27,7 @@ define([ NotesFactory.factory(wrapper, { endpoint: '/test_endpoint/', user: 'a user', - usageId: 'usage ' + index, + usageId: `usage ${index}`, courseId: 'a course', token: token, tokenUrl: '/test_token_url' diff --git a/lms/static/js/spec/edxnotes/views/shim_spec.js b/lms/static/js/spec/edxnotes/views/shim_spec.js index 871966d20e..772330f937 100644 --- a/lms/static/js/spec/edxnotes/views/shim_spec.js +++ b/lms/static/js/spec/edxnotes/views/shim_spec.js @@ -127,7 +127,7 @@ define([ checkAnnotatorIsFrozen(annotators[0]); // Check that second one doesn't have a bound click.edxnotes:freeze - checkClickEventsNotBound('edxnotes:freeze' + annotators[1].uid); + checkClickEventsNotBound(`edxnotes:freeze${annotators[1].uid}`); }); it('should unbind events on destruction', function() { diff --git a/lms/static/js/spec/financial-assistance/financial_assistance_form_view_spec.js b/lms/static/js/spec/financial-assistance/financial_assistance_form_view_spec.js index 64f94368f7..22decb9943 100644 --- a/lms/static/js/spec/financial-assistance/financial_assistance_form_view_spec.js +++ b/lms/static/js/spec/financial-assistance/financial_assistance_form_view_spec.js @@ -134,23 +134,23 @@ define([ failedSubmission = function() { expect(view.$('.js-success-message').length).toEqual(0); - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(0); validSubmission(); view.model.trigger('error', {status: 500}); expect(view.$('.js-success-message').length).toEqual(0); - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); }; invalidCountry = function() { expect(view.$('.js-success-message').length).toEqual(0); - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); expect(view.$('#user-country-title')).toHaveClass('error'); expect(view.$('.js-submit-form').prop('disabled')).toBeTruthy(); }; validCountry = function() { expect(view.$('.js-success-message').length).toEqual(0); - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(0); expect(view.$('#user-country-title')).not.toHaveClass('error'); expect(view.$('.js-submit-form').prop('disabled')).toBeFalsy(); }; @@ -185,10 +185,10 @@ define([ }); it('should not submit the form if the front end validation fails', function() { - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(0); view.$('.js-submit-form').click(); expect(view.model.save).not.toHaveBeenCalled(); - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); }); it('should submit the form data and additional data if validation passes', function() { diff --git a/lms/static/js/spec/groups/views/cohorts_spec.js b/lms/static/js/spec/groups/views/cohorts_spec.js index a0ae5c7fb4..a6f57e5305 100644 --- a/lms/static/js/spec/groups/views/cohorts_spec.js +++ b/lms/static/js/spec/groups/views/cohorts_spec.js @@ -126,7 +126,7 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollectio }; selectContentGroup = function(groupId, userPartitionId) { - var ids = groupId + ':' + userPartitionId; + var ids = `${groupId}:${userPartitionId}`; cohortsView.$('.radio-yes').prop('checked', true).change(); cohortsView.$('.input-cohort-group-association').val(ids).change(); expect(cohortsView.$('.input-cohort-group-association').prop('disabled')).toBeFalsy(); @@ -140,7 +140,7 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollectio verifyMessage = function(expectedTitle, expectedMessageType, expectedAction, hasDetails) { expect(cohortsView.$('.message-title').text().trim()).toBe(expectedTitle); - expect(cohortsView.$('div.message')).toHaveClass('message-' + expectedMessageType); + expect(cohortsView.$('div.message')).toHaveClass(`message-${expectedMessageType}`); if (expectedAction) { expect(cohortsView.$('.message-actions .action-primary').text().trim()).toBe(expectedAction); } else { @@ -204,15 +204,15 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollectio }; unknownUserMessage = function(name) { - return 'Unknown username: ' + name; + return `Unknown username: ${name}`; }; invalidEmailMessage = function(name) { - return 'Invalid email address: ' + name; + return `Invalid email address: ${name}`; }; notAllowedUserMessage = function(email) { - return 'Cohort assignment not allowed: ' + email; + return `Cohort assignment not allowed: ${email}`; }; beforeEach(function() { @@ -262,8 +262,8 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollectio // But upload form should not be visible until toggle is clicked. expect(cohortsView.$(fileUploadFormCss).length).toBe(0); uploadCsvToggle = cohortsView.$('.toggle-cohort-management-secondary'); - expect(uploadCsvToggle.text()). - toContain('Assign learners to cohorts by uploading a CSV file'); + expect(uploadCsvToggle.text()) + .toContain('Assign learners to cohorts by uploading a CSV file'); uploadCsvToggle.click(); // After toggle is clicked, it should be hidden. expect(uploadCsvToggle).toHaveClass('hidden'); @@ -455,7 +455,7 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollectio {cohorts: createMockCohort(defaultCohortName, 1, 0, null, null, assignmentType)} ); verifyMessage( - 'The ' + defaultCohortName + ' cohort has been created.' + `The ${defaultCohortName} cohort has been created.` + ' You can manually add students to this cohort below.', 'confirmation' ); @@ -704,7 +704,7 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollectio addStudents(sixUsers); AjaxHelpers.expectRequest( requests, 'POST', '/mock_service/cohorts/1/add', - 'users=' + sixUsers.replace(/@/g, '%40').replace(/, /g, '%2C+') + `users=${sixUsers.replace(/@/g, '%40').replace(/, /g, '%2C+')}` ); respondToAdd({ unknown: [ @@ -742,7 +742,7 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, CohortsView, CohortCollectio addStudents(sixUsers); AjaxHelpers.expectRequest(requests, 'POST', '/mock_service/cohorts/1/add', - 'users=' + sixUsers.replace(/@/g, '%40').replace(/, /g, '%2C+') + `users=${sixUsers.replace(/@/g, '%40').replace(/, /g, '%2C+')}` ); respondToAdd({ changed: [ diff --git a/lms/static/js/spec/groups/views/discussions_spec.js b/lms/static/js/spec/groups/views/discussions_spec.js index 378a3c7913..49009ec175 100644 --- a/lms/static/js/spec/groups/views/discussions_spec.js +++ b/lms/static/js/spec/groups/views/discussions_spec.js @@ -92,7 +92,7 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, DiscussionsView, CourseDiscu verifyMessage = function(expectedTitle, expectedMessageType, expectedAction, hasDetails) { expect(discussionsView.$('.message-title').text().trim()).toBe(expectedTitle); - expect(discussionsView.$('div.message')).toHaveClass('message-' + expectedMessageType); + expect(discussionsView.$('div.message')).toHaveClass(`message-${expectedMessageType}`); if (expectedAction) { expect(discussionsView.$('.message-actions .action-primary').text().trim()).toBe(expectedAction); } else { @@ -133,17 +133,17 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, DiscussionsView, CourseDiscu expect($inlineDiscussionsForm.length).toBe(1); expect($courseWideDiscussionsForm.length).toBe(1); - expect($courseWideDiscussionsForm.text()). - toContain('Course-Wide Discussion Topics'); - expect($courseWideDiscussionsForm.text()). - toContain('Select the course-wide discussion topics that you want to divide.'); + expect($courseWideDiscussionsForm.text()) + .toContain('Course-Wide Discussion Topics'); + expect($courseWideDiscussionsForm.text()) + .toContain('Select the course-wide discussion topics that you want to divide.'); // Should see the inline discussions form and its content expect($inlineDiscussionsForm.length).toBe(1); - expect($inlineDiscussionsForm.text()). - toContain('Content-Specific Discussion Topics'); - expect($inlineDiscussionsForm.text()). - toContain('Specify whether content-specific discussion topics are divided.'); + expect($inlineDiscussionsForm.text()) + .toContain('Content-Specific Discussion Topics'); + expect($inlineDiscussionsForm.text()) + .toContain('Specify whether content-specific discussion topics are divided.'); }; beforeEach(function() { @@ -171,8 +171,8 @@ function(Backbone, $, AjaxHelpers, TemplateHelpers, DiscussionsView, CourseDiscu var courseWideView, assertDividedTopics; assertDividedTopics = function(view, type) { - expect($('.check-discussion-subcategory-' + type).length).toBe(2); - expect($('.check-discussion-subcategory-' + type + ':checked').length).toBe(1); + expect($(`.check-discussion-subcategory-${type}`).length).toBe(2); + expect($(`.check-discussion-subcategory-${type}:checked`).length).toBe(1); }; it('renders the view properly', function() { diff --git a/lms/static/js/spec/instructor_dashboard/certificates_bulk_exception_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_bulk_exception_spec.js index 132188280f..de719a243f 100644 --- a/lms/static/js/spec/instructor_dashboard/certificates_bulk_exception_spec.js +++ b/lms/static/js/spec/instructor_dashboard/certificates_bulk_exception_spec.js @@ -19,8 +19,8 @@ function($, CertificateBulkAllowlistView) { ); setFixtures( - "' - + "
    " + `` + + '
    ' ); this.view = new CertificateBulkAllowlistView({ diff --git a/lms/static/js/spec/instructor_dashboard/certificates_exception_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_exception_spec.js index a48fa9f6fa..7006ff1f3d 100644 --- a/lms/static/js/spec/instructor_dashboard/certificates_exception_spec.js +++ b/lms/static/js/spec/instructor_dashboard/certificates_exception_spec.js @@ -194,8 +194,8 @@ function($, sinon, AjaxHelpers, CertificateExceptionModel, CertificateAllowlistV var fixture; setFixtures(); fixture = readFixtures('templates/instructor/instructor_dashboard_2/certificate-allowlist.underscore'); - setFixtures("' - + "
    "); + setFixtures(`` + + '
    '); this.certificate_allowlist = new CertificateAllowlistCollection(certificatesExceptionsJson, { parse: true, @@ -247,9 +247,9 @@ function($, sinon, AjaxHelpers, CertificateExceptionModel, CertificateAllowlistV {user_name: user, notes: notes, user_email: email} ]); - expect(view.$el.find('table tbody tr td:contains("' + user + '")').parent().html()) + expect(view.$el.find(`table tbody tr td:contains("${user}")`).parent().html()) .toMatch(notes); - expect(view.$el.find('table tbody tr td:contains("' + user + '")').parent().html()) + expect(view.$el.find(`table tbody tr td:contains("${user}")`).parent().html()) .toMatch(email); }); @@ -331,10 +331,10 @@ function($, sinon, AjaxHelpers, CertificateExceptionModel, CertificateAllowlistV ); setFixtures( - "' - + "' - + "
    " - + "
    " + `` + + `` + + '
    ' + + '
    ' ); certificateAllowlist = new CertificateAllowlistCollection(certificatesExceptionsJson, { @@ -374,7 +374,7 @@ function($, sinon, AjaxHelpers, CertificateExceptionModel, CertificateAllowlistV var errorMessages = { empty_user_name_email: 'Student username/email field is required and can not be empty. ' + 'Kindly fill in username/email and then press "Add to Exception List" button.', - duplicate_user: '

    ' + (duplicateUser) + ' already in exception list.

    ' + duplicate_user: `

    ${duplicateUser} already in exception list.

    ` }; // click 'Add Exception' button with empty username/email field @@ -416,8 +416,8 @@ function($, sinon, AjaxHelpers, CertificateExceptionModel, CertificateAllowlistV it('verifies certificate exception can be deleted by clicking "delete" ', function() { var username = 'test1', - certificateExceptionSelector = "div.allowlisted-students table tr:contains('" + username + "')", - deleteBtnSelector = certificateExceptionSelector + ' td .delete-exception', + certificateExceptionSelector = `div.allowlisted-students table tr:contains('${username}')`, + deleteBtnSelector = `${certificateExceptionSelector} td .delete-exception`, requests = AjaxHelpers.requests(this); $(deleteBtnSelector).click(); diff --git a/lms/static/js/spec/instructor_dashboard/certificates_invalidation_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_invalidation_spec.js index edd73a4c1a..7267863a89 100644 --- a/lms/static/js/spec/instructor_dashboard/certificates_invalidation_spec.js +++ b/lms/static/js/spec/instructor_dashboard/certificates_invalidation_spec.js @@ -105,13 +105,13 @@ function($, AjaxHelpers, CertificateInvalidationModel, CertificateInvalidationVi error: { empty_user_name_email: 'Student username/email field is required and can not be empty. ' + 'Kindly fill in username/email and then press "Invalidate Certificate" button.', - duplicate_user: 'Certificate of ' + (duplicate_user) + ' has already been invalidated. ' + duplicate_user: `Certificate of ${duplicate_user} has already been invalidated. ` + 'Please check your spelling and retry.', server_error: 'Server Error, Please refresh the page and try again.', from_server: 'Test Message from server' }, success: { - saved: 'Certificate has been successfully invalidated for ' + new_user + '.', + saved: `Certificate has been successfully invalidated for ${new_user}.`, re_validated: 'The certificate for this learner has been re-validated and ' + 'the system is re-running the grade for this learner.' } @@ -141,11 +141,11 @@ function($, AjaxHelpers, CertificateInvalidationModel, CertificateInvalidationVi ); setFixtures( - "
    " + '
    ' + '

    Invalidate Certificates

    ' - + "
    " + + '
    ' + '
    ' - + "' + + `` ); var certificate_invalidations = new CertificateInvalidationCollection(certificate_invalidations_json, { @@ -182,10 +182,10 @@ function($, AjaxHelpers, CertificateInvalidationModel, CertificateInvalidationVi view.collection.add(model); expect(view.$el.find('table tbody tr').length).toBe(3); - expect(view.$el.find('table tbody tr td:contains("' + user + '")').parent().html()). - toMatch(notes); - expect(view.$el.find('table tbody tr td:contains("' + user + '")').parent().html()). - toMatch(user); + expect(view.$el.find(`table tbody tr td:contains("${user}")`).parent().html()) + .toMatch(notes); + expect(view.$el.find(`table tbody tr td:contains("${user}")`).parent().html()) + .toMatch(user); // Remove a model from collection var collection_model = view.collection.get({id: 2}); @@ -240,8 +240,8 @@ function($, AjaxHelpers, CertificateInvalidationModel, CertificateInvalidationVi it('verifies certificate re-validation request and success message.', function() { var user = 'test1', - re_validate_certificate = "div.certificate-invalidation-container table tr:contains('" - + user + "') td .re-validate-certificate"; + re_validate_certificate = `div.certificate-invalidation-container table tr:contains('${ + user}') td .re-validate-certificate`; $(re_validate_certificate).click(); AjaxHelpers.respondWithJson(requests, {}); @@ -251,8 +251,8 @@ function($, AjaxHelpers, CertificateInvalidationModel, CertificateInvalidationVi it('verifies error message from server is displayed.', function() { var user = 'test1', - re_validate_certificate = "div.certificate-invalidation-container table tr:contains('" - + user + "') td .re-validate-certificate"; + re_validate_certificate = `div.certificate-invalidation-container table tr:contains('${ + user}') td .re-validate-certificate`; $(re_validate_certificate).click(); AjaxHelpers.respondWithError(requests, 400, { diff --git a/lms/static/js/spec/instructor_dashboard/certificates_spec.js b/lms/static/js/spec/instructor_dashboard/certificates_spec.js index e0558d5583..597a206b67 100644 --- a/lms/static/js/spec/instructor_dashboard/certificates_spec.js +++ b/lms/static/js/spec/instructor_dashboard/certificates_spec.js @@ -26,13 +26,13 @@ function($, AjaxHelpers) { var select_options = function(option_values) { $.each(option_values, function(index, element) { - $('#certificate-regenerating-form input[value=' + element + ']').click(); + $(`#certificate-regenerating-form input[value=${element}]`).click(); }); }; beforeEach(function() { var fixture = '
    ' - + '
    ' + + `` + '

    To regenerate certificates for your course, ' + ' chose the learners who will receive regenerated certificates and click
    ' + ' Regenerate Certificates.' @@ -53,7 +53,7 @@ function($, AjaxHelpers) { + ' Regenerate for learners in an error state. (0)' + '
    ' + '' + + ` value="Regenerate Certificates" data-endpoint="${expected.url}">` + '

    ' + '
    ' + '
    '; diff --git a/lms/static/js/spec/instructor_dashboard/membership_auth_spec.js b/lms/static/js/spec/instructor_dashboard/membership_auth_spec.js index 0d4ba1bb27..ed03491cc0 100644 --- a/lms/static/js/spec/instructor_dashboard/membership_auth_spec.js +++ b/lms/static/js/spec/instructor_dashboard/membership_auth_spec.js @@ -28,8 +28,8 @@ function($, AjaxHelpers) { 'templates/instructor/instructor_dashboard_2/membership-list-widget.underscore' ); appendSetFixtures( - "' - + membershipMain + `${ + membershipMain}` ); membership = new window.InstructorDashboard.sections.Membership($('#membership')); }); diff --git a/lms/static/js/spec/instructor_dashboard/student_admin_spec.js b/lms/static/js/spec/instructor_dashboard/student_admin_spec.js index 97d5cd0407..2abbd4d429 100644 --- a/lms/static/js/spec/instructor_dashboard/student_admin_spec.js +++ b/lms/static/js/spec/instructor_dashboard/student_admin_spec.js @@ -2,8 +2,8 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/utils/spec-helpers/ajax-helpers'], function($, StudentAdmin, AjaxHelpers) { // 'js/instructor_dashboard/student_admin' - -'use strict'; + + 'use strict'; describe('edx.instructor_dashboard.student_admin.StudentAdmin', function() { var studentadmin, dashboardApiUrl, uniqStudentIdentifier, alertMsg; @@ -30,7 +30,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut var fullSuccessMessage = interpolate_text(successMessage, { student_id: uniqStudentIdentifier }); - var url = dashboardApiUrl + '/reset_student_attempts_for_entrance_exam'; + var url = `${dashboardApiUrl}/reset_student_attempts_for_entrance_exam`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); @@ -60,7 +60,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut }); it('shows an error when resetting of entrance exam fails', function() { - var url = dashboardApiUrl + '/reset_student_attempts_for_entrance_exam'; + var url = `${dashboardApiUrl}/reset_student_attempts_for_entrance_exam`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); // Verify that the client contacts the server to start instructor task @@ -90,7 +90,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut var fullSuccessMessage = interpolate_text(successMessage, { student_id: uniqStudentIdentifier }); - var url = dashboardApiUrl + '/rescore_entrance_exam'; + var url = `${dashboardApiUrl}/rescore_entrance_exam`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); @@ -119,7 +119,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut }); it('shows an error when entrance exam rescoring fails', function() { - var url = dashboardApiUrl + '/rescore_entrance_exam'; + var url = `${dashboardApiUrl}/rescore_entrance_exam`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); // Verify that the client contacts the server to start instructor task @@ -151,7 +151,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut var fullSuccessMessage = interpolate_text(successMessage, { student_id: uniqStudentIdentifier }); - var url = dashboardApiUrl + '/mark_student_can_skip_entrance_exam'; + var url = `${dashboardApiUrl}/mark_student_can_skip_entrance_exam`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); @@ -179,7 +179,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut it('shows an error when skip entrance exam fails', function() { // Spy on AJAX requests var requests = AjaxHelpers.requests(this); - var url = dashboardApiUrl + '/mark_student_can_skip_entrance_exam'; + var url = `${dashboardApiUrl}/mark_student_can_skip_entrance_exam`; var errorMessage = "An error occurred. Make sure that the student's username or email address is correct and try again."; // eslint-disable-line max-len studentadmin.$field_exam_grade.val(uniqStudentIdentifier); studentadmin.$btn_skip_entrance_exam.click(); @@ -199,7 +199,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut var fullSuccessMessage = interpolate_text(successMessage, { student_id: uniqStudentIdentifier }); - var url = dashboardApiUrl + '/reset_student_attempts_for_entrance_exam'; + var url = `${dashboardApiUrl}/reset_student_attempts_for_entrance_exam`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); @@ -227,7 +227,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut }); it('shows an error when delete student state for entrance exam fails', function() { - var url = dashboardApiUrl + '/reset_student_attempts_for_entrance_exam'; + var url = `${dashboardApiUrl}/reset_student_attempts_for_entrance_exam`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); var params = $.param({ @@ -251,7 +251,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut }); it('initiates listing of entrance exam task history when button is clicked', function() { - var url = dashboardApiUrl + '/list_entrance_exam_instructor_tasks'; + var url = `${dashboardApiUrl}/list_entrance_exam_instructor_tasks`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); @@ -289,7 +289,7 @@ define(['jquery', 'js/instructor_dashboard/student_admin', 'edx-ui-toolkit/js/ut }); it('shows an error when listing entrance exam task history fails', function() { - var url = dashboardApiUrl + '/list_entrance_exam_instructor_tasks'; + var url = `${dashboardApiUrl}/list_entrance_exam_instructor_tasks`; // Spy on AJAX requests var requests = AjaxHelpers.requests(this); var params = $.param({ diff --git a/lms/static/js/spec/staff_debug_actions_spec.js b/lms/static/js/spec/staff_debug_actions_spec.js index dc605d75f9..cc117b920a 100644 --- a/lms/static/js/spec/staff_debug_actions_spec.js +++ b/lms/static/js/spec/staff_debug_actions_spec.js @@ -13,15 +13,15 @@ function(Backbone, $, tmp, AjaxHelpers) { var courseId = 'course-v1:edX+DemoX+1'; var location = 'block-v1:edX+DemoX+1+type@problem+block@9518dd51055b40cd82feb01502644c89'; var locationName = 'test_loc'; - var usernameFixtureID = 'sd_fu_' + locationName; + var usernameFixtureID = `sd_fu_${locationName}`; var $usernameFixture = $('', {id: usernameFixtureID, placeholder: 'userman'}); - var scoreFixtureID = 'sd_fs_' + locationName; + var scoreFixtureID = `sd_fs_${locationName}`; var $scoreFixture = $('', {id: scoreFixtureID, placeholder: '0'}); var escapableLocationName = 'test\.\*\+\?\^\:\$\{\}\(\)\|\]\[loc'; - var escapableFixtureID = 'sd_fu_' + escapableLocationName; + var escapableFixtureID = `sd_fu_${escapableLocationName}`; var $escapableFixture = $('', {id: escapableFixtureID, placeholder: 'userman'}); var esclocationName = 'P2:problem_1'; - var escapableId = 'result_' + esclocationName; + var escapableId = `result_${esclocationName}`; var $escapableResultArea = $('
    ', {id: escapableId}); describe('getURL ', function() { @@ -49,15 +49,15 @@ function(Backbone, $, tmp, AjaxHelpers) { it('gets the placeholder username if input field is empty', function() { $('body').append($usernameFixture); expect(StaffDebug.getUser(locationName)).toBe('userman'); - $('#' + usernameFixtureID).remove(); + $(`#${usernameFixtureID}`).remove(); }); it('gets a filled in name if there is one', function() { $('body').append($usernameFixture); - $('#' + usernameFixtureID).val('notuserman'); + $(`#${usernameFixtureID}`).val('notuserman'); expect(StaffDebug.getUser(locationName)).toBe('notuserman'); - $('#' + usernameFixtureID).val(''); - $('#' + usernameFixtureID).remove(); + $(`#${usernameFixtureID}`).val(''); + $(`#${usernameFixtureID}`).remove(); }); it('gets the placeholder name if the id has escapable characters', function() { $('body').append($escapableFixture); @@ -69,15 +69,15 @@ function(Backbone, $, tmp, AjaxHelpers) { it('gets the placeholder score if input field is empty', function() { $('body').append($scoreFixture); expect(StaffDebug.getScore(locationName)).toBe('0'); - $('#' + scoreFixtureID).remove(); + $(`#${scoreFixtureID}`).remove(); }); it('gets a filled in score if there is one', function() { $('body').append($scoreFixture); - $('#' + scoreFixtureID).val('1'); + $(`#${scoreFixtureID}`).val('1'); expect(StaffDebug.getScore(locationName)).toBe('1'); - $('#' + scoreFixtureID).val(''); - $('#' + scoreFixtureID).remove(); + $(`#${scoreFixtureID}`).val(''); + $(`#${scoreFixtureID}`).remove(); }); }); describe('doInstructorDashAction success', function() { @@ -92,7 +92,7 @@ function(Backbone, $, tmp, AjaxHelpers) { StaffDebug.doInstructorDashAction(action); AjaxHelpers.respondWithJson(requests, action); expect($('#idash_msg').text()).toBe('Successfully reset the attempts for user userman'); - $('#result_' + locationName).remove(); + $(`#result_${locationName}`).remove(); }); }); describe('doInstructorDashAction error', function() { @@ -107,7 +107,7 @@ function(Backbone, $, tmp, AjaxHelpers) { StaffDebug.doInstructorDashAction(action); AjaxHelpers.respondWithTextError(requests); expect($('#idash_msg').text()).toBe('Failed to reset attempts for user. Unknown Error Occurred.'); - $('#result_' + locationName).remove(); + $(`#result_${locationName}`).remove(); }); }); describe('reset', function() { @@ -128,7 +128,7 @@ function(Backbone, $, tmp, AjaxHelpers) { expect($.ajax.calls.mostRecent().args[0].url).toEqual( '/courses/course-v1:edX+DemoX+1/instructor/api/reset_student_attempts' ); - $('#' + usernameFixtureID).remove(); + $(`#${usernameFixtureID}`).remove(); }); }); describe('deleteStudentState', function() { @@ -150,7 +150,7 @@ function(Backbone, $, tmp, AjaxHelpers) { '/courses/course-v1:edX+DemoX+1/instructor/api/reset_student_attempts' ); - $('#' + usernameFixtureID).remove(); + $(`#${usernameFixtureID}`).remove(); }); }); describe('rescore', function() { @@ -171,7 +171,7 @@ function(Backbone, $, tmp, AjaxHelpers) { expect($.ajax.calls.mostRecent().args[0].url).toEqual( '/courses/course-v1:edX+DemoX+1/instructor/api/rescore_problem' ); - $('#' + usernameFixtureID).remove(); + $(`#${usernameFixtureID}`).remove(); }); }); describe('rescoreIfHigher', function() { @@ -192,14 +192,14 @@ function(Backbone, $, tmp, AjaxHelpers) { expect($.ajax.calls.mostRecent().args[0].url).toEqual( '/courses/course-v1:edX+DemoX+1/instructor/api/rescore_problem' ); - $('#' + usernameFixtureID).remove(); + $(`#${usernameFixtureID}`).remove(); }); }); describe('overrideScore', function() { it('makes an ajax call with the expected parameters', function() { $('body').append($usernameFixture); $('body').append($scoreFixture); - $('#' + scoreFixtureID).val('1'); + $(`#${scoreFixtureID}`).val('1'); spyOn($, 'ajax'); StaffDebug.overrideScore(courseId, locationName, location); @@ -214,7 +214,7 @@ function(Backbone, $, tmp, AjaxHelpers) { expect($.ajax.calls.mostRecent().args[0].url).toEqual( '/courses/course-v1:edX+DemoX+1/instructor/api/override_problem_score' ); - $('#' + usernameFixtureID).remove(); + $(`#${usernameFixtureID}`).remove(); }); }); }); diff --git a/lms/static/js/spec/student_account/access_spec.js b/lms/static/js/spec/student_account/access_spec.js index 142fa1fb4a..d35a5ff907 100644 --- a/lms/static/js/spec/student_account/access_spec.js +++ b/lms/static/js/spec/student_account/access_spec.js @@ -95,7 +95,7 @@ var selectForm = function(type) { // Create a fake change event to control form toggling var changeEvent = $.Event('change'); - changeEvent.currentTarget = $('.form-toggle[data-type="' + type + '"]'); + changeEvent.currentTarget = $(`.form-toggle[data-type="${type}"]`); // Load form corresponding to the change event view.toggleForm(changeEvent); diff --git a/lms/static/js/spec/student_account/finish_auth_spec.js b/lms/static/js/spec/student_account/finish_auth_spec.js index b440ca4e45..80ddf37f23 100644 --- a/lms/static/js/spec/student_account/finish_auth_spec.js +++ b/lms/static/js/spec/student_account/finish_auth_spec.js @@ -75,7 +75,7 @@ // Expect that the view tried to enroll the student expect(EnrollmentInterface.enroll).toHaveBeenCalledWith( COURSE_KEY, - '/course_modes/choose/' + COURSE_KEY + '/' + `/course_modes/choose/${COURSE_KEY}/` ); }); @@ -91,7 +91,7 @@ // Expect that the view tried to enroll the student expect(EnrollmentInterface.enroll).toHaveBeenCalledWith( COURSE_KEY, - '/course_modes/choose/' + COURSE_KEY + '/' + `/course_modes/choose/${COURSE_KEY}/` ); }); @@ -109,7 +109,7 @@ // mode select flow with the purchase_workflow parameter expect(EnrollmentInterface.enroll).toHaveBeenCalledWith( COURSE_KEY, - '/course_modes/choose/' + COURSE_KEY + '/?purchase_workflow=bulk' + `/course_modes/choose/${COURSE_KEY}/?purchase_workflow=bulk` ); }); @@ -128,7 +128,7 @@ // with a redirect into the payment flow. expect(EnrollmentInterface.enroll).toHaveBeenCalledWith( COURSE_KEY, - '/verify_student/start-flow/' + COURSE_KEY + '/' + `/verify_student/start-flow/${COURSE_KEY}/` ); }); @@ -150,7 +150,7 @@ // purchase_workflow parameter. expect(EnrollmentInterface.enroll).toHaveBeenCalledWith( COURSE_KEY, - '/verify_student/start-flow/' + COURSE_KEY + '/?purchase_workflow=bulk' + `/verify_student/start-flow/${COURSE_KEY}/?purchase_workflow=bulk` ); }); diff --git a/lms/static/js/spec/student_account/helpers.js b/lms/static/js/spec/student_account/helpers.js index 9215bd4edc..c208117b55 100644 --- a/lms/static/js/spec/student_account/helpers.js +++ b/lms/static/js/spec/student_account/helpers.js @@ -158,7 +158,7 @@ define(['underscore'], function(_) { } else if (view.fieldType === 'button') { expect($(element).find('button').length).toBe(1); } else { - throw new Error('Unexpected field type: ' + view.fieldType); + throw new Error(`Unexpected field type: ${view.fieldType}`); } }; diff --git a/lms/static/js/spec/student_account/login_spec.js b/lms/static/js/spec/student_account/login_spec.js index 2d1c481fb2..364f1a1feb 100644 --- a/lms/static/js/spec/student_account/login_spec.js +++ b/lms/static/js/spec/student_account/login_spec.js @@ -243,7 +243,7 @@ createLoginView(this); // Verify that the success message is not visible - expect(view.$formFeedback.find('.' + view.passwordResetSuccessJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.passwordResetSuccessJsHook}`).length).toEqual(0); /* After a successful password reset request, the resetModel will trigger a 'sync' * event, which lets the LoginView know to render the password reset success message. @@ -251,7 +251,7 @@ view.resetModel.trigger('sync'); // Verify that the success message is visible - expect(view.$formFeedback.find('.' + view.passwordResetSuccessJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.passwordResetSuccessJsHook}`).length).toEqual(1); }); it('validates login form fields', function() { @@ -271,7 +271,7 @@ submitForm(false); // Verify that submission errors are visible - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); // Expect auth complete NOT to have been triggered expect(authComplete).toBe(false); @@ -290,7 +290,7 @@ AjaxHelpers.respondWithError(requests); // Expect that an error is displayed and that auth complete is not triggered - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); expect(authComplete).toBe(false); @@ -307,7 +307,7 @@ AjaxHelpers.respondWithJson(requests, {}); // Expect that the error is hidden and auth complete is triggered - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(0); expect(authComplete).toBe(true); }); @@ -334,7 +334,7 @@ clock.tick(timeout + 1); // Expect that an error is displayed and that auth complete is not triggered - $error = view.$formFeedback.find('.' + view.formErrorsJsHook); + $error = view.$formFeedback.find(`.${view.formErrorsJsHook}`); expect($error.length).toEqual(1); expect($error.text()).toContain( 'An error has occurred. Check your Internet connection and try again.' @@ -357,7 +357,7 @@ AjaxHelpers.respondWithError(requests, 500); // Expect that an error is displayed and that auth complete is not triggered - $error = view.$formFeedback.find('.' + view.formErrorsJsHook); + $error = view.$formFeedback.find(`.${view.formErrorsJsHook}`); expect($error.length).toEqual(1); expect($error.text()).toContain( 'An error has occurred. Try refreshing the page, or check your Internet connection.' diff --git a/lms/static/js/spec/student_account/password_reset_spec.js b/lms/static/js/spec/student_account/password_reset_spec.js index 68d6172f5c..cb1a524339 100644 --- a/lms/static/js/spec/student_account/password_reset_spec.js +++ b/lms/static/js/spec/student_account/password_reset_spec.js @@ -123,7 +123,7 @@ expect(view.validate).toHaveBeenCalledWith($('#password-reset-email')[0]); // Verify that no submission errors are visible - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(0); }); it('displays password reset validation errors', function() { @@ -133,7 +133,7 @@ submitEmail(false); // Verify that submission errors are visible - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); }); it('displays an error if the server returns an error while sending a password reset email', function() { @@ -144,7 +144,7 @@ AjaxHelpers.respondWithError(requests); // Expect that an error is displayed - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); // If we try again and succeed, the error should go away submitEmail(); @@ -153,7 +153,7 @@ AjaxHelpers.respondWithJson(requests, {}); // Expect that the error is hidden - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(0); }); }); }); diff --git a/lms/static/js/spec/student_account/register_spec.js b/lms/static/js/spec/student_account/register_spec.js index 8b3fcce0e0..46283bb2f8 100644 --- a/lms/static/js/spec/student_account/register_spec.js +++ b/lms/static/js/spec/student_account/register_spec.js @@ -410,7 +410,7 @@ expect(view.validate).toHaveBeenCalledWith($password[0]); // Verify that no submission errors are visible - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(0); // Form button should be disabled on success. expect(view.$submitButton).toHaveAttr('disabled'); @@ -450,7 +450,7 @@ submitForm(false); // Verify that submission errors are visible - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); // Expect that auth complete is NOT triggered expect(authComplete).toBe(false); @@ -496,7 +496,7 @@ AjaxHelpers.respondWithError(requests); // Expect that an error is displayed and that auth complete is NOT triggered - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(1); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(1); expect(authComplete).toBe(false); // If we try again and succeed, the error should go away @@ -506,7 +506,7 @@ AjaxHelpers.respondWithJson(requests, {}); // Expect that the error is hidden and that auth complete is triggered - expect(view.$formFeedback.find('.' + view.formErrorsJsHook).length).toEqual(0); + expect(view.$formFeedback.find(`.${view.formErrorsJsHook}`).length).toEqual(0); expect(authComplete).toBe(true); // Form button should be disabled on success. @@ -514,7 +514,7 @@ }); it('shows optional exposed fields', function() { - var formFields = FORM_DESCRIPTION.fields + var formFields = FORM_DESCRIPTION.fields; formFields.push({ placeholder: '', name: 'exposed_custom_optional_field', @@ -525,15 +525,15 @@ exposed: true, instructions: 'Check this field if you would like to.', restrictions: {} - }) + }); createRegisterView(this, formFields); var elementClasses = view.$('.exposed-optional-fields').attr('class'); - var elementChildren = view.$('.exposed-optional-fields .form-field') + var elementChildren = view.$('.exposed-optional-fields .form-field'); // Expect the exposed optional fields container does not have other // classes assigned, like .hidden expect(elementClasses).toEqual('exposed-optional-fields'); - expect(elementChildren.length).toEqual(1) + expect(elementChildren.length).toEqual(1); }); it('hides optional fields by default', function() { diff --git a/lms/static/js/spec/student_account/utils_spec.js b/lms/static/js/spec/student_account/utils_spec.js index 6103252b02..db3d64c820 100644 --- a/lms/static/js/spec/student_account/utils_spec.js +++ b/lms/static/js/spec/student_account/utils_spec.js @@ -11,7 +11,7 @@ define(['jquery', 'js/student_account/utils'], }; beforeEach(function() { - document.cookie = edxUserInfoCookieName + '="' + document.cookie = `${edxUserInfoCookieName}="` + '{\"version\": 1, \"username\": \"local-test-user\"}";'; // eslint-disable-line no-useless-escape }); diff --git a/lms/static/js/spec/verify_student/image_input_spec.js b/lms/static/js/spec/verify_student/image_input_spec.js index a3e25faa83..3e59b70ee7 100644 --- a/lms/static/js/spec/verify_student/image_input_spec.js +++ b/lms/static/js/spec/verify_student/image_input_spec.js @@ -36,7 +36,7 @@ define([ if (fileType !== null) { fakeFile = new Blob( [IMAGE_DATA], - {type: 'image/' + fileType} + {type: `image/${fileType}`} ); fakeEvent.target.files = [fakeFile]; } @@ -61,7 +61,7 @@ define([ var expectPreview = function(view, fileType) { var previewImage = view.$preview.attr('src'); if (fileType) { - expect(previewImage).toContain('data:image/' + fileType); + expect(previewImage).toContain(`data:image/${fileType}`); } else { expect(previewImage).toEqual(''); } @@ -78,7 +78,7 @@ define([ var expectImageData = function(view, fileType) { var imageData = view.model.get(view.modelAttribute); if (fileType) { - expect(imageData).toContain('data:image/' + fileType); + expect(imageData).toContain(`data:image/${fileType}`); } else { expect(imageData).toEqual(''); } diff --git a/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js b/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js index 31aa924130..55a96e895d 100644 --- a/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js +++ b/lms/static/js/spec/verify_student/make_payment_step_view_ab_testing_spec.js @@ -106,7 +106,7 @@ function($, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView) { var $el = $('.payment-button'); expect($el.length).toEqual(_.size(buttons)); _.each(buttons, function(expectedText, expectedId) { - var $buttonEl = $('#' + expectedId), + var $buttonEl = $(`#${expectedId}`), request; $buttonEl.removeAttr('disabled'); @@ -119,7 +119,7 @@ function($, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView) { expect($buttonEl[0]).toHaveClass('is-selected'); expectPaymentButtonEnabled(false); request = AjaxHelpers.currentRequest(requests); - expect(request.requestBody.split('&')).toContain('processor=' + expectedId); + expect(request.requestBody.split('&')).toContain(`processor=${expectedId}`); AjaxHelpers.respondWithJson(requests, {}); }); }; diff --git a/lms/static/js/spec/verify_student/make_payment_step_view_spec.js b/lms/static/js/spec/verify_student/make_payment_step_view_spec.js index fa24a757d5..72963c24e0 100644 --- a/lms/static/js/spec/verify_student/make_payment_step_view_spec.js +++ b/lms/static/js/spec/verify_student/make_payment_step_view_spec.js @@ -101,7 +101,7 @@ function($, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView) { var $el = $('.payment-button'); expect($el.length).toEqual(_.size(buttons)); _.each(buttons, function(expectedText, expectedId) { - var $buttonEl = $('#' + expectedId), + var $buttonEl = $(`#${expectedId}`), request; $buttonEl.removeAttr('disabled'); @@ -114,7 +114,7 @@ function($, _, Backbone, AjaxHelpers, TemplateHelpers, MakePaymentStepView) { expect($buttonEl[0]).toHaveClass('is-selected'); expectPaymentButtonEnabled(false); request = AjaxHelpers.currentRequest(requests); - expect(request.requestBody.split('&')).toContain('processor=' + expectedId); + expect(request.requestBody.split('&')).toContain(`processor=${expectedId}`); AjaxHelpers.respondWithJson(requests, {}); }); }; diff --git a/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js b/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js index 4e537625f5..d907cb9143 100644 --- a/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js +++ b/lms/static/js/spec/verify_student/pay_and_verify_view_spec.js @@ -56,7 +56,7 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/ var expectStepRendered = function(stepName) { // Expect that the step container div rendered - expect($('.' + stepName).length > 0).toBe(true); + expect($(`.${stepName}`).length > 0).toBe(true); }; beforeEach(function() { @@ -65,7 +65,7 @@ define(['jquery', 'common/js/spec_helpers/template_helpers', 'js/verify_student/ setFixtures('
    '); $.each(TEMPLATES, function(index, templateName) { - TemplateHelpers.installTemplate('templates/verify_student/' + templateName); + TemplateHelpers.installTemplate(`templates/verify_student/${templateName}`); }); }); diff --git a/lms/static/js/spec/verify_student/reverify_view_spec.js b/lms/static/js/spec/verify_student/reverify_view_spec.js index 1af070fff2..30039b571d 100644 --- a/lms/static/js/spec/verify_student/reverify_view_spec.js +++ b/lms/static/js/spec/verify_student/reverify_view_spec.js @@ -39,7 +39,7 @@ function($, TemplateHelpers, ReviewPhotosStepView, ReverifyView) { var expectStepRendered = function(stepName) { // Expect that the step container div rendered - expect($('.' + stepName).length > 0).toBe(true); + expect($(`.${stepName}`).length > 0).toBe(true); }; beforeEach(function() { @@ -48,7 +48,7 @@ function($, TemplateHelpers, ReviewPhotosStepView, ReverifyView) { setFixtures('
    '); $.each(TEMPLATES, function(index, templateName) { - TemplateHelpers.installTemplate('templates/verify_student/' + templateName); + TemplateHelpers.installTemplate(`templates/verify_student/${templateName}`); }); }); diff --git a/lms/static/js/spec/views/fields_spec.js b/lms/static/js/spec/views/fields_spec.js index 4137dd0123..43d36afbc5 100644 --- a/lms/static/js/spec/views/fields_spec.js +++ b/lms/static/js/spec/views/fields_spec.js @@ -323,7 +323,7 @@ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews, FieldViewsSpe var view = new FieldViews.LinkFieldView(fieldData).render(); FieldViewsSpecHelpers.expectTitleAndMessageToContain(view, fieldData.title, fieldData.helpMessage); - expect(view.$('.u-field-value > a .u-field-link-title-' + view.options.valueAttribute).text().trim()).toBe(fieldData.linkTitle); + expect(view.$(`.u-field-value > a .u-field-link-title-${view.options.valueAttribute}`).text().trim()).toBe(fieldData.linkTitle); }); it("can't persist changes if persistChanges is off", function() { diff --git a/lms/static/js/spec/views/file_uploader_spec.js b/lms/static/js/spec/views/file_uploader_spec.js index f74cb1f3be..98acee00f8 100644 --- a/lms/static/js/spec/views/file_uploader_spec.js +++ b/lms/static/js/spec/views/file_uploader_spec.js @@ -42,7 +42,7 @@ function(Backbone, $, FileUploaderView, TemplateHelpers, AjaxHelpers, Notificati }; verifyNotificationMessage = function(expectedMessage, type) { - verifyText('.file-upload-form-result .message-' + type + ' .message-title', expectedMessage); + verifyText(`.file-upload-form-result .message-${type} .message-title`, expectedMessage); }; mimicUpload = function(test) { diff --git a/lms/static/js/split.js b/lms/static/js/split.js index 3d6cdf1391..d526307352 100644 --- a/lms/static/js/split.js +++ b/lms/static/js/split.js @@ -50,12 +50,12 @@ _split = _split || (function(undef) { + (separator.sticky ? 'y' : ''), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy - separator = new RegExp(separator.source, flags + 'g'), + separator = new RegExp(separator.source, `${flags}g`), separator2, match, lastIndex, lastLength; str += ''; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt - separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags); + separator2 = new RegExp(`^${separator.source}$(?!\\s)`, flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 diff --git a/lms/static/js/staff_debug_actions.js b/lms/static/js/staff_debug_actions.js index ae2f38e02a..459f7dad72 100644 --- a/lms/static/js/staff_debug_actions.js +++ b/lms/static/js/staff_debug_actions.js @@ -2,7 +2,7 @@ // Build StaffDebug object var StaffDebug = (function() { var getURL = function(courseId, action) { - return '/courses/' + courseId + '/instructor/api/' + action; + return `/courses/${courseId}/instructor/api/${action}`; }; var sanitizeString = function(string) { @@ -11,18 +11,18 @@ var StaffDebug = (function() { var getUser = function(locationName) { var sanitizedLocationName = sanitizeString(locationName); - var uname = $('#sd_fu_' + sanitizedLocationName).val(); + var uname = $(`#sd_fu_${sanitizedLocationName}`).val(); if (uname === '') { - uname = $('#sd_fu_' + sanitizedLocationName).attr('placeholder'); + uname = $(`#sd_fu_${sanitizedLocationName}`).attr('placeholder'); } return uname; }; var getScore = function(locationName) { var sanitizedLocationName = sanitizeString(locationName); - var score = $('#sd_fs_' + sanitizedLocationName).val(); + var score = $(`#sd_fs_${sanitizedLocationName}`).val(); if (score === '') { - score = $('#sd_fs_' + sanitizedLocationName).attr('placeholder'); + score = $(`#sd_fs_${sanitizedLocationName}`).attr('placeholder'); } return score; }; @@ -48,7 +48,7 @@ var StaffDebug = (function() { {text: text} ); edx.HtmlUtils.setHtml( - $('#result_' + sanitizeString(action.locationName)), + $(`#result_${sanitizeString(action.locationName)}`), edx.HtmlUtils.HTML(html) ); }, @@ -72,7 +72,7 @@ var StaffDebug = (function() { {text: text} ); edx.HtmlUtils.setHtml( - $('#result_' + sanitizeString(action.locationName)), + $(`#result_${sanitizeString(action.locationName)}`), edx.HtmlUtils.HTML(html) ); }, diff --git a/lms/static/js/student_account/models/user_account_model.js b/lms/static/js/student_account/models/user_account_model.js index 842bf780f4..77f288a3db 100644 --- a/lms/static/js/student_account/models/user_account_model.js +++ b/lms/static/js/student_account/models/user_account_model.js @@ -62,7 +62,7 @@ minimumAllowedAge = this.get('parental_consent_age_limit'), enableCoppaCompliance = this.get('enable_coppa_compliance'); - if(enableCoppaCompliance){ + if (enableCoppaCompliance) { var currentYear = new Date().getFullYear(), isOlderThanMinimum = (currentYear - yearOfBirth) >= minimumAllowedAge; return isBirthDefined && isOlderThanMinimum && !(this.get('requires_parental_consent')); diff --git a/lms/static/js/student_account/multiple_enterprise.js b/lms/static/js/student_account/multiple_enterprise.js index a0c3604b6f..3e04128bb6 100644 --- a/lms/static/js/student_account/multiple_enterprise.js +++ b/lms/static/js/student_account/multiple_enterprise.js @@ -29,7 +29,7 @@ var userInEnterprise = false; var userWithMultipleEnterprises = false; $.ajax({ - url: this.urls.learners + '?username=' + username, + url: `${this.urls.learners}?username=${username}`, type: 'GET', contentType: 'application/json; charset=utf-8', headers: this.headers, diff --git a/lms/static/js/student_account/shoppingcart.js b/lms/static/js/student_account/shoppingcart.js index f61a4d5d9c..30f54ed571 100644 --- a/lms/static/js/student_account/shoppingcart.js +++ b/lms/static/js/student_account/shoppingcart.js @@ -21,7 +21,7 @@ */ addCourseToCart: function(courseId) { $.ajax({ - url: this.urls.addCourse + courseId + '/', + url: `${this.urls.addCourse + courseId}/`, type: 'POST', data: {}, headers: this.headers, diff --git a/lms/static/js/student_account/tos_modal.js b/lms/static/js/student_account/tos_modal.js index b1c9ad0571..b2ef185fe7 100644 --- a/lms/static/js/student_account/tos_modal.js +++ b/lms/static/js/student_account/tos_modal.js @@ -130,11 +130,11 @@ $(document).ready(function() { var tosLinkSelector = '.checkbox-honor_code .supplemental-link a', closeButtonClass = 'modal-close-button', - closeButtonSelector = '.' + closeButtonClass, + closeButtonSelector = `.${closeButtonClass}`, contentClass = 'modal-content', - contentSelector = '.' + contentClass, + contentSelector = `.${contentClass}`, modalClass = 'tos-modal', - modalSelector = '.' + modalClass; + modalSelector = `.${modalClass}`; $('body').on('click', tosLinkSelector, function(event) { var link = event.target, diff --git a/lms/static/js/student_account/utils.js b/lms/static/js/student_account/utils.js index 0d55d97a22..9823eae382 100644 --- a/lms/static/js/student_account/utils.js +++ b/lms/static/js/student_account/utils.js @@ -6,7 +6,7 @@ userFromEdxUserCookie: function(edxUserInfoCookieName) { var cookie, user, userCookie; - cookie = document.cookie.match('(^|;)\\s*' + edxUserInfoCookieName + '\\s*=\\s*([^;]+)'); + cookie = document.cookie.match(`(^|;)\\s*${edxUserInfoCookieName}\\s*=\\s*([^;]+)`); userCookie = cookie ? cookie.pop() : $.cookie(edxUserInfoCookieName); if (!userCookie) { diff --git a/lms/static/js/student_account/views/AccessView.js b/lms/static/js/student_account/views/AccessView.js index 3886a8272b..9d48ebc945 100644 --- a/lms/static/js/student_account/views/AccessView.js +++ b/lms/static/js/student_account/views/AccessView.js @@ -117,7 +117,7 @@ mode: this.activeForm }) ) - ) + ); this.postRender(); return this; @@ -258,15 +258,15 @@ toggleForm: function(e) { var type = $(e.currentTarget).data('type'), - $form = $('#' + type + '-form'), + $form = $(`#${type}-form`), scrollX = window.scrollX, scrollY = window.scrollY, queryParams = url('?'), - queryStr = queryParams.length > 0 ? '?' + queryParams : ''; + queryStr = queryParams.length > 0 ? `?${queryParams}` : ''; e.preventDefault(); - window.analytics.track('edx.bi.' + type + '_form.toggled', { + window.analytics.track(`edx.bi.${type}_form.toggled`, { category: 'user-engagement' }); @@ -288,12 +288,12 @@ // Update url without reloading page if (type != 'institution_login' && type != 'reset') { - History.pushState(null, document.title, '/' + type + queryStr); + History.pushState(null, document.title, `/${type}${queryStr}`); } analytics.page('login_and_registration', type); // Focus on the form - $('#' + type).focus(); + $(`#${type}`).focus(); // Maintain original scroll position window.scrollTo(scrollX, scrollY); diff --git a/lms/static/js/student_account/views/FinishAuthView.js b/lms/static/js/student_account/views/FinishAuthView.js index f863881880..3253d1051b 100644 --- a/lms/static/js/student_account/views/FinishAuthView.js +++ b/lms/static/js/student_account/views/FinishAuthView.js @@ -78,7 +78,7 @@ var next = _.bind(this.enrollment, this); this.checkEmailOptIn(next); } catch (err) { - this.updateTaskDescription(gettext('Error') + ': ' + err.message); + this.updateTaskDescription(`${gettext('Error')}: ${err.message}`); this.redirect(this.nextUrl); } }, @@ -93,7 +93,7 @@ if (this.purchaseWorkflow) { // Append the purchase_workflow parameter to indicate // whether this is a bulk purchase or a single seat purchase - redirectUrl += '?purchase_workflow=' + this.purchaseWorkflow; + redirectUrl += `?purchase_workflow=${this.purchaseWorkflow}`; } return redirectUrl; }, @@ -134,7 +134,7 @@ The track selection page would allow the user to select the course mode ("verified", "honor", etc.) -- or, if the only course mode was "honor", it would redirect the user to the dashboard. */ - redirectUrl = this.appendPurchaseWorkflow(this.urls.trackSelection + courseId + '/'); + redirectUrl = this.appendPurchaseWorkflow(`${this.urls.trackSelection + courseId}/`); } else if (this.courseMode === 'honor' || this.courseMode === 'audit') { /* The newer version of the course details page allows the user to specify which course mode to enroll as. If the student has @@ -144,7 +144,7 @@ } else { /* If the user selected any other kind of course mode, send them to the payment/verification flow. */ - redirectUrl = this.appendPurchaseWorkflow(this.urls.payment + courseId + '/'); + redirectUrl = this.appendPurchaseWorkflow(`${this.urls.payment + courseId}/`); } /* Attempt to auto-enroll the user in a free mode of the course, diff --git a/lms/static/js/student_account/views/FormView.js b/lms/static/js/student_account/views/FormView.js index b04427df7d..faff008c57 100644 --- a/lms/static/js/student_account/views/FormView.js +++ b/lms/static/js/student_account/views/FormView.js @@ -65,7 +65,7 @@ HtmlUtils: HtmlUtils }) ) - ) + ); this.postRender(); return this; @@ -161,7 +161,7 @@ for (i = 0; i < len; i++) { $el = $(elements[i]); - $label = $form.find('label[for=' + $el.attr('id') + ']'); + $label = $form.find(`label[for=${$el.attr('id')}]`); key = $el.attr('name') || false; // Due to a bug in firefox, whitespaces in email type field are not removed. @@ -190,7 +190,7 @@ HtmlUtils.append($validationNode, HtmlUtils.HTML($n)); } - $desc = $form.find('#' + $el.attr('id') + '-desc'); + $desc = $form.find(`#${$el.attr('id')}-desc`); $desc.remove(); } @@ -213,7 +213,7 @@ }, get_error_validation_node: function($el, $form) { - var $node = $form.find('#' + $el.attr('id') + '-validation-error-msg'); + var $node = $form.find(`#${$el.attr('id')}-validation-error-msg`); return $node.find('ul'); }, @@ -306,7 +306,7 @@ }, clearFormErrors: function() { - var query = '.' + this.formErrorsJsHook; + var query = `.${this.formErrorsJsHook}`; this.clearFormFeedbackItems(query); }, diff --git a/lms/static/js/student_account/views/LoginView.js b/lms/static/js/student_account/views/LoginView.js index 818c63144a..0ff526e0ac 100644 --- a/lms/static/js/student_account/views/LoginView.js +++ b/lms/static/js/student_account/views/LoginView.js @@ -285,12 +285,12 @@ }, clearPasswordResetSuccess: function() { - var query = '.' + this.passwordResetSuccessJsHook; + var query = `.${this.passwordResetSuccessJsHook}`; this.clearFormFeedbackItems(query); }, clearAuthWarning: function() { - var query = '.' + this.authWarningJsHook; + var query = `.${this.authWarningJsHook}`; this.clearFormFeedbackItems(query); } }); diff --git a/lms/static/js/student_account/views/RegisterView.js b/lms/static/js/student_account/views/RegisterView.js index 3bbb89f5f7..07cd064f03 100644 --- a/lms/static/js/student_account/views/RegisterView.js +++ b/lms/static/js/student_account/views/RegisterView.js @@ -338,7 +338,7 @@ }, getRequiredTextLabel: function($el) { - return $('#' + $el.attr('id') + '-required-label'); + return $(`#${$el.attr('id')}-required-label`); }, renderLiveValidations: function($el, decisions) { @@ -362,29 +362,29 @@ }, getLabel: function($el) { - return this.$form.find('label[for=' + $el.attr('id') + ']'); + return this.$form.find(`label[for=${$el.attr('id')}]`); }, getIcon: function($el) { - return $('#' + $el.attr('id') + '-validation-icon'); + return $(`#${$el.attr('id')}-validation-icon`); }, addValidationErrorMsgForScreenReader: function($el) { - var $validation_node = this.$form.find('#' + $el.attr('id') + '-validation-error'); + var $validation_node = this.$form.find(`#${$el.attr('id')}-validation-error`); $validation_node.find('.sr-only').text('ERROR:'); }, removeValidationErrorMsgForScreenReader: function($el) { - var $validation_node = this.$form.find('#' + $el.attr('id') + '-validation-error'); + var $validation_node = this.$form.find(`#${$el.attr('id')}-validation-error`); $validation_node.find('.sr-only').text(''); }, getErrorTip: function($el) { - return $('#' + $el.attr('id') + '-validation-error-msg'); + return $(`#${$el.attr('id')}-validation-error-msg`); }, getFieldTimeout: function($el) { - return $('#' + $el.attr('id')).attr('timeout-id') || null; + return $(`#${$el.attr('id')}`).attr('timeout-id') || null; }, setFieldTimeout: function($el, time, action) { @@ -439,7 +439,7 @@ $el.addClass(indicator); $label.addClass(indicator); $req.addClass(indicator); - $icon.addClass(indicator + ' ' + icon); + $icon.addClass(`${indicator} ${icon}`); if (['username', 'email'].indexOf($el.attr('name')) > -1) { $tip.addClass(' data-hj-suppress'); } @@ -450,7 +450,7 @@ $el.removeClass(indicator); $label.removeClass(indicator); $req.removeClass(indicator); - $icon.removeClass(indicator + ' ' + icon); + $icon.removeClass(`${indicator} ${icon}`); }, thirdPartyAuth: function(event) { @@ -515,7 +515,7 @@ 'We just need a little more information before you start learning with %(platformName)s.' ), fullMsg = _.sprintf( - msgPart1 + ' ' + msgPart2, + `${msgPart1} ${msgPart2}`, {currentProvider: this.currentProvider, platformName: this.platformName} ); @@ -586,7 +586,7 @@ i; for (i = 0; i < this.liveValidationFields.length; ++i) { field = this.liveValidationFields[i]; - data[field] = $('#register-' + field).val(); + data[field] = $(`#register-${field}`).val(); } FormView.prototype.liveValidate( $el, this.validationUrl, 'json', data, 'POST', this.model diff --git a/lms/static/js/toggle_login_modal.js b/lms/static/js/toggle_login_modal.js index a8dc9db043..e9773cabdc 100644 --- a/lms/static/js/toggle_login_modal.js +++ b/lms/static/js/toggle_login_modal.js @@ -65,22 +65,22 @@ $('iframe', modal_id).attr('src', $('iframe', modal_id).data('src')); if ($(modal_id).hasClass('email-modal')) { $(modal_id).css({ - width: 80 + '%', - height: 80 + '%', + width: `${80}%`, + height: `${80}%`, position: o.position, opacity: 0, 'z-index': 11000, - left: 10 + '%', - top: 10 + '%' + left: `${10}%`, + top: `${10}%` }); } else { $(modal_id).css({ position: o.position, opacity: 0, 'z-index': 11000, - left: 50 + '%', - 'margin-left': -(modal_width / 2) + 'px', - top: o.top + 'px' + left: `${50}%`, + 'margin-left': `${-(modal_width / 2)}px`, + top: `${o.top}px` }); } @@ -115,7 +115,7 @@ embed = $($link.attr('href')).find('iframe'); if (embed.length > 0 && embed.attr('src')) { var sep = (embed.attr('src').indexOf('?') > 0) ? '&' : '?'; - embed.data('src', embed.attr('src') + sep + 'autoplay=1&rel=0'); + embed.data('src', `${embed.attr('src') + sep}autoplay=1&rel=0`); embed.attr('src', ''); } }); diff --git a/lms/static/js/utils/navigation.js b/lms/static/js/utils/navigation.js index ed219cac3c..f6f0829cca 100644 --- a/lms/static/js/utils/navigation.js +++ b/lms/static/js/utils/navigation.js @@ -20,7 +20,7 @@ var edx = edx || {}, button = null; if (index > -1) { - button = $('.accordion .button-chapter:eq(' + index + ')'); + button = $(`.accordion .button-chapter:eq(${index})`); } return button; diff --git a/lms/static/js/verify_student/views/step_view.js b/lms/static/js/verify_student/views/step_view.js index 09e09fbeee..8e9f4b24f6 100644 --- a/lms/static/js/verify_student/views/step_view.js +++ b/lms/static/js/verify_student/views/step_view.js @@ -28,7 +28,7 @@ var edx = edx || {}; }, render: function() { - var templateHtml = $('#' + this.templateName + '-tpl').html(); + var templateHtml = $(`#${this.templateName}-tpl`).html(); // Allow subclasses to add additional information // to the template context, perhaps asynchronously. diff --git a/lms/static/js/verify_student/views/webcam_photo_view.js b/lms/static/js/verify_student/views/webcam_photo_view.js index 35b644879c..6531a76672 100644 --- a/lms/static/js/verify_student/views/webcam_photo_view.js +++ b/lms/static/js/verify_student/views/webcam_photo_view.js @@ -185,8 +185,8 @@ var edx = edx || {}, this.trigger( 'error', gettext('No Webcam Detected'), - gettext("You don't seem to have a webcam connected.") + ' ' - + gettext('Double-check that your webcam is connected and working to continue.') + `${gettext("You don't seem to have a webcam connected.")} ${ + gettext('Double-check that your webcam is connected and working to continue.')}` ); // eslint-disable-next-line brace-style } diff --git a/lms/static/js/views/fields.js b/lms/static/js/views/fields.js index f34b8a189e..85dd82a682 100644 --- a/lms/static/js/views/fields.js +++ b/lms/static/js/views/fields.js @@ -27,7 +27,7 @@ fieldType: 'generic', className: function() { - return 'u-field u-field-' + this.fieldType + ' u-field-' + this.options.valueAttribute; + return `u-field u-field-${this.fieldType} u-field-${this.options.valueAttribute}`; }, tagName: 'div', @@ -103,8 +103,8 @@ }, getMessage: function(messageStatus) { - if ((messageStatus + 'Message') in this) { - return this[messageStatus + 'Message'].call(this); + if ((`${messageStatus}Message`) in this) { + return this[`${messageStatus}Message`].call(this); } else if (this.showMessages) { return HtmlUtils.joinHtml(this.indicators[messageStatus], this.messages[messageStatus]); } @@ -198,7 +198,7 @@ this._super(options); this.editable = _.isUndefined(this.options.editable) ? 'always' : this.options.editable; - this.$el.addClass('editable-' + this.editable); + this.$el.addClass(`editable-${this.editable}`); if (this.editable === 'always') { this.showEditMode(false); @@ -299,7 +299,7 @@ initialize: function(options) { this._super(options); _.bindAll(this, 'render', 'fieldValue', 'updateValueInField'); - this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField); + this.listenTo(this.model, `change:${this.options.valueAttribute}`, this.updateValueInField); }, render: function() { @@ -368,7 +368,7 @@ initialize: function(options) { this._super(options); _.bindAll(this, 'render', 'fieldValue', 'updateValueInField', 'saveValue'); - this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField); + this.listenTo(this.model, `change:${this.options.valueAttribute}`, this.updateValueInField); }, render: function() { @@ -420,7 +420,7 @@ 'saveValue', 'createGroupOptions'); this._super(options); - this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateValueInField); + this.listenTo(this.model, `change:${this.options.valueAttribute}`, this.updateValueInField); }, render: function() { @@ -582,7 +582,7 @@ _.bindAll(this, 'render', 'onKeyDown', 'adjustTextareaHeight', 'manageTextareaContentChange', 'fieldValue', 'saveValue', 'updateView'); this._super(options); - this.listenTo(this.model, 'change:' + this.options.valueAttribute, this.updateView); + this.listenTo(this.model, `change:${this.options.valueAttribute}`, this.updateView); }, render: function() { @@ -626,7 +626,7 @@ var $charCount = $('.u-field-footer .current-char-count'); // Update character count for textarea if (this.options.maxCharacters) { - curCharCount = $('#u-field-textarea-' + this.options.valueAttribute).val().length; + curCharCount = $(`#u-field-textarea-${this.options.valueAttribute}`).val().length; remainingCharCount = this.options.maxCharacters - curCharCount; if (remainingCharCount < 20) { $charCount.attr({ diff --git a/lms/static/js/views/image_field.js b/lms/static/js/views/image_field.js index 90427d38cd..c05d1cd00f 100644 --- a/lms/static/js/views/image_field.js +++ b/lms/static/js/views/image_field.js @@ -225,7 +225,7 @@ size /= 1024; ++i; } - return size.toFixed(1) * 1 + ' ' + units[i]; + return `${size.toFixed(1) * 1} ${units[i]}`; } }); diff --git a/lms/static/karma_lms.conf.js b/lms/static/karma_lms.conf.js index a9827dbd80..0119d4d18c 100644 --- a/lms/static/karma_lms.conf.js +++ b/lms/static/karma_lms.conf.js @@ -6,6 +6,7 @@ 'use strict'; var path = require('path'); + var configModule = require(path.join(__dirname, '../../common/static/common/js/karma.common.conf.js')); var options = { diff --git a/lms/static/lms/js/preview/preview_factory.js b/lms/static/lms/js/preview/preview_factory.js index 862f65e861..6e818c8bca 100644 --- a/lms/static/lms/js/preview/preview_factory.js +++ b/lms/static/lms/js/preview/preview_factory.js @@ -55,7 +55,7 @@ user_name: selectedOption.val() === 'specific student' ? $userNameElement.val() : null }; $.ajax({ - url: '/courses/' + options.courseId + '/masquerade', + url: `/courses/${options.courseId}/masquerade`, type: 'POST', dataType: 'json', contentType: 'application/json', diff --git a/lms/static/lms/js/require-config.js b/lms/static/lms/js/require-config.js index c385d2cba3..1ace39213a 100644 --- a/lms/static/lms/js/require-config.js +++ b/lms/static/lms/js/require-config.js @@ -28,7 +28,7 @@ define(name, [], function() { return globalValue; }); } } else { - console.error('Expected library to be included on page, but not found on window object: ' + name); + console.error(`Expected library to be included on page, but not found on window object: ${name}`); } }; diff --git a/lms/static/lms/js/spec/main.js b/lms/static/lms/js/spec/main.js index 795782948f..2be855a50b 100644 --- a/lms/static/lms/js/spec/main.js +++ b/lms/static/lms/js/spec/main.js @@ -819,7 +819,7 @@ ]; for (i = 0; i < testFiles.length; i++) { - testFiles[i] = '/base/' + testFiles[i]; + testFiles[i] = `/base/${testFiles[i]}`; } specHelpers = [ diff --git a/lms/static/lms/js/spec/main_requirejs_coffee.js b/lms/static/lms/js/spec/main_requirejs_coffee.js index 3a83c6b80a..c726d5030e 100644 --- a/lms/static/lms/js/spec/main_requirejs_coffee.js +++ b/lms/static/lms/js/spec/main_requirejs_coffee.js @@ -23,7 +23,7 @@ define(name, [], function() { return globalValue; }); } } else { - console.error('Expected library to be included on page, but not found on window object: ' + name); + console.error(`Expected library to be included on page, but not found on window object: ${name}`); } }; defineDependency('jQuery', 'jquery'); diff --git a/openedx/features/announcements/static/announcements/jsx/Announcements.jsx b/openedx/features/announcements/static/announcements/jsx/Announcements.jsx index 162a09aec8..7b58f04e36 100644 --- a/openedx/features/announcements/static/announcements/jsx/Announcements.jsx +++ b/openedx/features/announcements/static/announcements/jsx/Announcements.jsx @@ -15,11 +15,11 @@ class AnnouncementSkipLink extends React.Component { this.setState({ count: data.count }); - }) + }); } render() { - return (
    {'Skip to list of ' + this.state.count + ' announcements'}
    ) + return (
    {`Skip to list of ${this.state.count} announcements`}
    ); } } @@ -54,7 +54,7 @@ class AnnouncementList extends React.Component { } retrievePage(page) { - $.get('/announcements/page/' + page) + $.get(`/announcements/page/${page}`) .then(data => { this.setState({ announcements: data.announcements, @@ -66,7 +66,7 @@ class AnnouncementList extends React.Component { end_index: data.end_index, page: page }); - }) + }); } renderPrevPage() { @@ -93,7 +93,7 @@ class AnnouncementList extends React.Component { onClick={() => this.renderPrevPage()} label="← previous" /> - {this.state.start_index + ' - ' + this.state.end_index + ') of ' + this.state.count} + {`${this.state.start_index} - ${this.state.end_index}) of ${this.state.count}`}
    ); } @@ -105,7 +105,7 @@ class AnnouncementList extends React.Component { onClick={() => this.renderNextPage()} label="next →" /> - {this.state.start_index + ' - ' + this.state.end_index + ') of ' + this.state.count} + {`${this.state.start_index} - ${this.state.end_index}) of ${this.state.count}`}
    ); } @@ -132,4 +132,4 @@ export default class AnnouncementsView { } } -export {AnnouncementsView, AnnouncementList, AnnouncementSkipLink} +export {AnnouncementsView, AnnouncementList, AnnouncementSkipLink}; diff --git a/openedx/features/announcements/static/announcements/jsx/Announcements.test.jsx b/openedx/features/announcements/static/announcements/jsx/Announcements.test.jsx index 4b3b6a251e..afcec6882b 100644 --- a/openedx/features/announcements/static/announcements/jsx/Announcements.test.jsx +++ b/openedx/features/announcements/static/announcements/jsx/Announcements.test.jsx @@ -1,15 +1,15 @@ import React from 'react'; import renderer from 'react-test-renderer'; -import testAnnouncements from './test-announcements.json' +import testAnnouncements from './test-announcements.json'; -import {AnnouncementSkipLink, AnnouncementList} from './Announcements' +import {AnnouncementSkipLink, AnnouncementList} from './Announcements'; describe('Announcements component', () => { test('render skip link', () => { const component = renderer.create( , ); - component.root.instance.setState({'count': 10}) + component.root.instance.setState({count: 10}); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); diff --git a/openedx/features/course_bookmarks/static/course_bookmarks/js/models/bookmark.js b/openedx/features/course_bookmarks/static/course_bookmarks/js/models/bookmark.js index 13671bddf5..f1eddf32cd 100644 --- a/openedx/features/course_bookmarks/static/course_bookmarks/js/models/bookmark.js +++ b/openedx/features/course_bookmarks/static/course_bookmarks/js/models/bookmark.js @@ -13,7 +13,7 @@ }, blockUrl: function() { - return '/courses/' + this.get('course_id') + '/jump_to/' + this.get('usage_id'); + return `/courses/${this.get('course_id')}/jump_to/${this.get('usage_id')}`; } }); }); diff --git a/openedx/features/course_bookmarks/static/course_bookmarks/js/spec/bookmark_button_view_spec.js b/openedx/features/course_bookmarks/static/course_bookmarks/js/spec/bookmark_button_view_spec.js index b3722dedd6..14bacbb063 100644 --- a/openedx/features/course_bookmarks/static/course_bookmarks/js/spec/bookmark_button_view_spec.js +++ b/openedx/features/course_bookmarks/static/course_bookmarks/js/spec/bookmark_button_view_spec.js @@ -62,7 +62,7 @@ function(Backbone, $, _, AjaxHelpers, TemplateHelpers, BookmarkButtonView) { handler: 'removeBookmark', event: 'bookmark:remove', method: 'DELETE', - url: API_URL + 'bilbo,usage_1/', + url: `${API_URL}bilbo,usage_1/`, body: null }; var removeBookmarkData = { diff --git a/openedx/features/course_bookmarks/static/course_bookmarks/js/spec_helpers/bookmark_helpers.js b/openedx/features/course_bookmarks/static/course_bookmarks/js/spec_helpers/bookmark_helpers.js index 094bd1ee9f..014e6b44fe 100644 --- a/openedx/features/course_bookmarks/static/course_bookmarks/js/spec_helpers/bookmark_helpers.js +++ b/openedx/features/course_bookmarks/static/course_bookmarks/js/spec_helpers/bookmark_helpers.js @@ -21,10 +21,10 @@ define( for (i = 0; i < options.numBookmarksToCreate; i++) { bookmarkInfo = { id: i, - display_name: 'UNIT_DISPLAY_NAME_' + i, + display_name: `UNIT_DISPLAY_NAME_${i}`, created: new Date().toISOString(), course_id: 'COURSE_ID', - usage_id: 'UNIT_USAGE_ID_' + i, + usage_id: `UNIT_USAGE_ID_${i}`, block_type: 'vertical', path: [ {display_name: 'SECTION_DISPLAY_NAME', usage_id: 'SECTION_USAGE_ID'}, @@ -39,13 +39,13 @@ define( }; var createBookmarkUrl = function(courseId, usageId) { - return '/courses/' + courseId + '/jump_to/' + usageId; + return `/courses/${courseId}/jump_to/${usageId}`; }; var breadcrumbTrail = function(path, unitDisplayName) { - return _.pluck(path, 'display_name'). - concat([unitDisplayName]). - join(' - '); + return _.pluck(path, 'display_name') + .concat([unitDisplayName]) + .join(' - '); }; var verifyBookmarkedData = function(view, expectedData) { @@ -71,7 +71,7 @@ define( .toBe(breadcrumbTrail(results[i].path, results[i].display_name)); expect($bookmark.find('.list-item-date').text().trim()) - .toBe('Bookmarked on ' + view.humanFriendlyDate(results[i].created)); + .toBe(`Bookmarked on ${view.humanFriendlyDate(results[i].created)}`); } }; diff --git a/openedx/features/course_bookmarks/static/course_bookmarks/js/views/bookmark_button.js b/openedx/features/course_bookmarks/static/course_bookmarks/js/views/bookmark_button.js index 838f631868..10ef2eaa04 100644 --- a/openedx/features/course_bookmarks/static/course_bookmarks/js/views/bookmark_button.js +++ b/openedx/features/course_bookmarks/static/course_bookmarks/js/views/bookmark_button.js @@ -65,7 +65,7 @@ removeBookmark: function() { var view = this; - var deleteUrl = view.apiUrl + view.bookmarkId + '/'; + var deleteUrl = `${view.apiUrl + view.bookmarkId}/`; $.ajax({ type: 'DELETE', diff --git a/openedx/features/course_search/static/course_search/js/course_search_factory.js b/openedx/features/course_search/static/course_search/js/course_search_factory.js index e7fb824a6b..5a88e35153 100644 --- a/openedx/features/course_search/static/course_search/js/course_search_factory.js +++ b/openedx/features/course_search/static/course_search/js/course_search_factory.js @@ -26,7 +26,7 @@ dispatcher.listenTo(form, 'search', function(query) { results.showLoadingMessage(); collection.performSearch(query); - router.navigate('search/' + query, {replace: true}); + router.navigate(`search/${query}`, {replace: true}); }); dispatcher.listenTo(form, 'clear', function() { diff --git a/openedx/features/course_search/static/course_search/js/dashboard_search_factory.js b/openedx/features/course_search/static/course_search/js/dashboard_search_factory.js index 3697ce381a..79a2adc00c 100644 --- a/openedx/features/course_search/static/course_search/js/dashboard_search_factory.js +++ b/openedx/features/course_search/static/course_search/js/dashboard_search_factory.js @@ -22,7 +22,7 @@ dispatcher.listenTo(form, 'search', function(query) { results.showLoadingMessage(); collection.performSearch(query); - router.navigate('search/' + query, {replace: true}); + router.navigate(`search/${query}`, {replace: true}); }); dispatcher.listenTo(form, 'clear', function() { diff --git a/openedx/features/course_search/static/course_search/js/spec/course_search_spec.js b/openedx/features/course_search/static/course_search/js/spec/course_search_spec.js index 281369f94d..4651c03fea 100644 --- a/openedx/features/course_search/static/course_search/js/spec/course_search_spec.js +++ b/openedx/features/course_search/static/course_search/js/spec/course_search_spec.js @@ -248,8 +248,8 @@ define([ it('rendersItem', function() { expect(this.item.$el).toHaveAttr('role', 'region'); expect(this.item.$el).toHaveAttr('aria-label', 'search result'); - expect(this.item.$el).toContainElement('a[href="' + this.model.get('url') + '"]'); - expect(this.item.$el.find('.result-type i')).toHaveClass('fa-' + this.item.unitIcon()); + expect(this.item.$el).toContainElement(`a[href="${this.model.get('url')}"]`); + expect(this.item.$el.find('.result-type i')).toHaveClass(`fa-${this.item.unitIcon()}`); expect(this.item.$el.find('.result-excerpt')).toContainHtml(this.model.get('excerpt')); expect(this.item.$el.find('.result-link')).toContainHtml('section / subsection / unit'); }); @@ -257,8 +257,8 @@ define([ it('rendersSequentialItem', function() { expect(this.seqItem.$el).toHaveAttr('role', 'region'); expect(this.seqItem.$el).toHaveAttr('aria-label', 'search result'); - expect(this.seqItem.$el).toContainElement('a[href="' + this.seqModel.get('url') + '"]'); - expect(this.seqItem.$el.find('.result-type i')).toHaveClass('fa-' + this.seqItem.unitIcon()); + expect(this.seqItem.$el).toContainElement(`a[href="${this.seqModel.get('url')}"]`); + expect(this.seqItem.$el.find('.result-type i')).toHaveClass(`fa-${this.seqItem.unitIcon()}`); expect(this.seqItem.$el.find('.result-excerpt')).toBeEmpty(); expect(this.seqItem.$el.find('.result-link')).toContainHtml('section / subsection'); }); @@ -385,9 +385,9 @@ define([ expect(this.resultsView.$el.find('ol')[0]).toExist(); expect(this.resultsView.$el.find('li').length).toEqual(1); expect(this.resultsView.$el).toContainHtml( - this.collection.totalCount - + ' result found for "' - + this.collection.searchTerm + '"' + `${this.collection.totalCount + } result found for "${ + this.collection.searchTerm}"` ); expect(this.resultsView.$el).toContainHtml('this is a short excerpt'); diff --git a/scripts/delete-mongo-test-dbs.js b/scripts/delete-mongo-test-dbs.js index 8a33944289..fb1890ad6c 100644 --- a/scripts/delete-mongo-test-dbs.js +++ b/scripts/delete-mongo-test-dbs.js @@ -17,7 +17,7 @@ var dbNameList = db.getMongo().getDBNames(); for (var i in dbNameList) { if (dbNameList[i].startsWith('test_') || dbNameList[i].startsWith('acceptance_')) { dbToDrop = db.getMongo().getDB(dbNameList[i]); - print('Dropping test db ' + dbNameList[i]); + print(`Dropping test db ${dbNameList[i]}`); dbToDrop.dropDatabase(); } } diff --git a/scripts/xsslint/tests/templates/test.js b/scripts/xsslint/tests/templates/test.js index 6cc29a89e5..ca39db942d 100644 --- a/scripts/xsslint/tests/templates/test.js +++ b/scripts/xsslint/tests/templates/test.js @@ -1,5 +1,5 @@ var message = 'Rock & Roll'; -var x = '' + message + ''; +var x = `${message}`; var template = '<%= invalid %>'; // quiet the linter alert(x); diff --git a/webpack.common.config.js b/webpack.common.config.js index bebd07cbb5..f8aba71095 100644 --- a/webpack.common.config.js +++ b/webpack.common.config.js @@ -22,9 +22,9 @@ var defineHeader = /\(function ?\(((define|require|requirejs|\$)(, )?)+\) ?\{/; var defineCallFooter = /\}\)\.call\(this, ((define|require)( \|\| RequireJS\.(define|require))?(, )?)+?\);/; var defineDirectFooter = /\}\(((window\.)?(RequireJS\.)?(requirejs|define|require|jQuery)(, )?)+\)\);/; var defineFancyFooter = /\}\).call\(\s*this(\s|.)*define(\s|.)*\);/; -var defineFooter = new RegExp('(' + defineCallFooter.source + ')|(' - + defineDirectFooter.source + ')|(' - + defineFancyFooter.source + ')', 'm'); +var defineFooter = new RegExp(`(${defineCallFooter.source})|(${ + defineDirectFooter.source})|(${ + defineFancyFooter.source})`, 'm'); var workerConfig = function() { try { @@ -200,7 +200,7 @@ module.exports = Merge.smart({ }, { pattern: /\/\* Webpack/g, - replacement: function(match) { return match + ' */'; } + replacement: function(match) { return `${match} */`; } }, { pattern: /text!(.*?\.underscore)/g, @@ -387,7 +387,7 @@ module.exports = Merge.smart({ // https://github.com/webpack/webpack/issues/304#issuecomment-272150177 // (I've tried every other suggestion solution on that page, this // was the only one that worked.) - sinon: __dirname + '/node_modules/sinon/pkg/sinon.js', + sinon: `${__dirname}/node_modules/sinon/pkg/sinon.js`, hls: 'hls.js/dist/hls.js' }, modules: [ diff --git a/xmodule/assets/library_source_block/LibrarySourcedBlockPicker.jsx b/xmodule/assets/library_source_block/LibrarySourcedBlockPicker.jsx index d491939c94..b1cd8e3906 100644 --- a/xmodule/assets/library_source_block/LibrarySourcedBlockPicker.jsx +++ b/xmodule/assets/library_source_block/LibrarySourcedBlockPicker.jsx @@ -29,7 +29,7 @@ class LibrarySourcedBlockPicker extends React.Component { this.fetchLibraries(); } - fetchLibraries(textSearch='', page=1, append=false) { + fetchLibraries(textSearch = '', page = 1, append = false) { this.setState({ libraries: append ? this.state.libraries : [], libraryLoading: true, @@ -42,7 +42,7 @@ class LibrarySourcedBlockPicker extends React.Component { libraryLoading: false, }, () => { if (res.next) { - this.fetchLibraries(textSearch, page+1, true); + this.fetchLibraries(textSearch, page + 1, true); } }); } catch (error) { @@ -58,7 +58,7 @@ class LibrarySourcedBlockPicker extends React.Component { }); } - fetchXblocks(library, textSearch='', page=1, append=false) { + fetchXblocks(library, textSearch = '', page = 1, append = false) { this.setState({ xblocks: append ? this.state.xblocks : [], xblocksLoading: true, @@ -71,7 +71,7 @@ class LibrarySourcedBlockPicker extends React.Component { xblocksLoading: false, }, () => { if (res.next) { - this.fetchXblocks(library, textSearch, page+1, true); + this.fetchXblocks(library, textSearch, page + 1, true); } }); } catch (error) { @@ -88,7 +88,7 @@ class LibrarySourcedBlockPicker extends React.Component { } onLibrarySearchInput(event) { - event.persist() + event.persist(); this.setState({ searchedLibrary: event.target.value, }); @@ -101,7 +101,7 @@ class LibrarySourcedBlockPicker extends React.Component { } onXBlockSearchInput(event) { - event.persist() + event.persist(); if (!this.debouncedFetchXblocks) { this.debouncedFetchXblocks = _.debounce(value => { this.fetchXblocks(this.state.selectedLibrary, value); diff --git a/xmodule/js/karma_runner_webpack.js b/xmodule/js/karma_runner_webpack.js index c5c4290d60..64cd930666 100644 --- a/xmodule/js/karma_runner_webpack.js +++ b/xmodule/js/karma_runner_webpack.js @@ -32,9 +32,9 @@ import '../../common/static/common/js/vendor/sinon.js'; import 'jquery.ui'; // These -import './src/video/10_main.js' -import './spec/helper.js' -import './spec/video_helper.js' +import './src/video/10_main.js'; +import './spec/helper.js'; +import './spec/video_helper.js'; // These are the tests that will be run import './spec/video/async_process_spec.js'; @@ -74,8 +74,8 @@ import './spec/video/social_share_spec.js'; // Somehow the code initialized in jQuery's onready doesn't get called before karma auto starts 'use strict'; -window.__karma__.loaded = function () { - setTimeout(function () { +window.__karma__.loaded = function() { + setTimeout(function() { window.__karma__.start(); }, 1000); }; diff --git a/xmodule/js/karma_xmodule.conf.js b/xmodule/js/karma_xmodule.conf.js index 7d62917118..185e1e6688 100644 --- a/xmodule/js/karma_xmodule.conf.js +++ b/xmodule/js/karma_xmodule.conf.js @@ -6,6 +6,7 @@ 'use strict'; var path = require('path'); + var configModule = require(path.join(__dirname, 'common_static/common/js/karma.common.conf.js')); var options = { diff --git a/xmodule/js/karma_xmodule_webpack.conf.js b/xmodule/js/karma_xmodule_webpack.conf.js index c1a1e63830..e0abad75a8 100644 --- a/xmodule/js/karma_xmodule_webpack.conf.js +++ b/xmodule/js/karma_xmodule_webpack.conf.js @@ -6,6 +6,7 @@ 'use strict'; var path = require('path'); + var configModule = require(path.join(__dirname, 'common_static/common/js/karma.common.conf.js')); var options = { diff --git a/xmodule/js/spec/capa/imageinput_spec.js b/xmodule/js/spec/capa/imageinput_spec.js index 18b724a796..5dd2cc0441 100644 --- a/xmodule/js/spec/capa/imageinput_spec.js +++ b/xmodule/js/spec/capa/imageinput_spec.js @@ -67,7 +67,7 @@ expect(cssLeft).toBeCloseTo(posX - 15, 1); expect(cssTop).toBeCloseTo(posY - 15, 1); expect(state.inputEl.val()).toBe( - '[' + Math.round(posX) + ',' + Math.round(posY) + ']' + `[${Math.round(posX)},${Math.round(posY)}]` ); }); @@ -101,7 +101,7 @@ expect(cssLeft).toBeCloseTo(posX - 15, 1); expect(cssTop).toBeCloseTo(posY - 15, 1); expect(state.inputEl.val()).toBe( - '[' + Math.round(posX) + ',' + Math.round(posY) + ']' + `[${Math.round(posX)},${Math.round(posY)}]` ); }); }); diff --git a/xmodule/js/spec/collapsible_spec.js b/xmodule/js/spec/collapsible_spec.js index f5cef2e5ab..c98fd55b76 100644 --- a/xmodule/js/spec/collapsible_spec.js +++ b/xmodule/js/spec/collapsible_spec.js @@ -64,7 +64,7 @@ state = 'closed'; } - anchors = $el.find('.' + anchorsElClass); + anchors = $el.find(`.${anchorsElClass}`); if (state === 'closed') { expect($el.find('.longform')).toBeHidden(); diff --git a/xmodule/js/spec/helper.js b/xmodule/js/spec/helper.js index 978de6785e..d26a71fc61 100644 --- a/xmodule/js/spec/helper.js +++ b/xmodule/js/spec/helper.js @@ -120,7 +120,7 @@ if (document.createEvent) { el.dispatchEvent(event); } else { - el.fireEvent('on' + event.eventType, event); + el.fireEvent(`on${event.eventType}`, event); } }; @@ -180,7 +180,7 @@ return {}; } else if (settings.url === '/save_user_state') { return {success: true}; - } else if (settings.url.match(new RegExp(jasmine.getFixtures().fixturesPath + '.+', 'g'))) { + } else if (settings.url.match(new RegExp(`${jasmine.getFixtures().fixturesPath}.+`, 'g'))) { return origAjax(settings); } else { return $.ajax.and.callThrough(); diff --git a/xmodule/js/spec/main_requirejs.js b/xmodule/js/spec/main_requirejs.js index b9e38a13f5..a4f0c54f67 100644 --- a/xmodule/js/spec/main_requirejs.js +++ b/xmodule/js/spec/main_requirejs.js @@ -23,7 +23,7 @@ define(name, [], function() { return globalValue; }); } } else { - console.error('Expected library to be included on page, but not found on window object: ' + name); + console.error(`Expected library to be included on page, but not found on window object: ${name}`); } }; defineDependency('jQuery', 'jquery'); diff --git a/xmodule/js/spec/video/video_events_plugin_spec.js b/xmodule/js/spec/video/video_events_plugin_spec.js index 54ed189207..d6840e3941 100644 --- a/xmodule/js/spec/video/video_events_plugin_spec.js +++ b/xmodule/js/spec/video/video_events_plugin_spec.js @@ -1,4 +1,4 @@ -import '../helper.js' +import '../helper.js'; (function(undefined) { 'use strict'; diff --git a/xmodule/js/spec/video/video_play_placeholder_spec.js b/xmodule/js/spec/video/video_play_placeholder_spec.js index f43280ec39..97905bd9ee 100644 --- a/xmodule/js/spec/video/video_play_placeholder_spec.js +++ b/xmodule/js/spec/video/video_play_placeholder_spec.js @@ -92,8 +92,8 @@ $.each(['iPad', 'Android'], function(index, device) { it( - 'is shown on paused video on ' + device - + ' in HTML5 player', + `is shown on paused video on ${device + } in HTML5 player`, function() { var btnPlay; @@ -107,8 +107,8 @@ }); it( - 'is hidden on playing video on ' + device - + ' in HTML5 player', + `is hidden on playing video on ${device + } in HTML5 player`, function() { var btnPlay; @@ -121,8 +121,8 @@ }); it( - 'is hidden on paused video on ' + device - + ' in YouTube player', + `is hidden on paused video on ${device + } in YouTube player`, function() { var btnPlay; diff --git a/xmodule/js/spec/video/video_player_spec.js b/xmodule/js/spec/video/video_player_spec.js index 13f3821be4..348cf64427 100644 --- a/xmodule/js/spec/video/video_player_spec.js +++ b/xmodule/js/spec/video/video_player_spec.js @@ -145,7 +145,7 @@ describe('when on a touch based device', function() { $.each(['iPad', 'Android'], function(index, device) { - it('create video volume control on' + device, function() { + it(`create video volume control on${device}`, function() { window.onTouchBasedDevice.and.returnValue([device]); state = jasmine.initializePlayer(); @@ -847,7 +847,7 @@ $.each(['iPad', 'Android'], function(index, device) { var message = 'controls become visible after playing starts ' - + 'on ' + device; + + `on ${device}`; it(message, function(done) { var controls; diff --git a/xmodule/js/spec/video/video_progress_slider_spec.js b/xmodule/js/spec/video/video_progress_slider_spec.js index 0bf6ae39b1..01947fee54 100644 --- a/xmodule/js/spec/video/video_progress_slider_spec.js +++ b/xmodule/js/spec/video/video_progress_slider_spec.js @@ -65,7 +65,7 @@ // because sliders are used in other parts of Video. }); $.each(['iPad', 'Android'], function(index, device) { - it('build the slider on ' + device, function() { + it(`build the slider on ${device}`, function() { window.onTouchBasedDevice.and.returnValue([device]); state = jasmine.initializePlayer(); @@ -240,8 +240,8 @@ left = testCase.startTime * step, width = testCase.endTime * step - left, expectedParams = { - left: left + '%', - width: width + '%' + left: `${left}%`, + width: `${width}%` }, params = state.videoProgressSlider.getRangeParams( testCase.startTime, testCase.endTime, testCase.duration diff --git a/xmodule/js/spec/video/video_save_state_plugin_spec.js b/xmodule/js/spec/video/video_save_state_plugin_spec.js index 556a6c6a1d..04206ae9ad 100644 --- a/xmodule/js/spec/video/video_save_state_plugin_spec.js +++ b/xmodule/js/spec/video/video_save_state_plugin_spec.js @@ -183,7 +183,7 @@ import * as Time from 'time.js'; state.videoSaveStatePlugin.onUnload(); expect($.ajax).not.toHaveBeenCalledWith({ url: state.config.saveStateUrl - }) + }); state.config.saveStateEnabled = true; $.ajax.calls.reset(); state.videoSaveStatePlugin.onUnload(); @@ -200,7 +200,7 @@ import * as Time from 'time.js'; state.el.trigger('pause'); expect($.ajax).not.toHaveBeenCalledWith({ url: state.config.saveStateUrl - }) + }); state.config.saveStateEnabled = true; state.el.trigger('pause'); expect($.ajax).toHaveBeenCalledWith({ @@ -233,7 +233,7 @@ import * as Time from 'time.js'; state.config.saveStateEnabled = false; state.config.recordedYoutubeIsAvailable = false; state.el.trigger('youtube_availability', [true]); - expect($.ajax).not.toHaveBeenCalled() + expect($.ajax).not.toHaveBeenCalled(); state.config.saveStateEnabled = true; state.config.recordedYoutubeIsAvailable = false; state.el.trigger('youtube_availability', [true]); diff --git a/xmodule/js/spec/video/video_speed_control_spec.js b/xmodule/js/spec/video/video_speed_control_spec.js index 97d69643f8..875b49733c 100644 --- a/xmodule/js/spec/video/video_speed_control_spec.js +++ b/xmodule/js/spec/video/video_speed_control_spec.js @@ -39,7 +39,7 @@ $.each(li.toArray().reverse(), function(index, link) { expect($(link).attr('data-speed')).toEqual(state.speeds[index]); expect($(link).find('.speed-option').text()).toBe( - state.speeds[index] + 'x' + `${state.speeds[index]}x` ); }); }); @@ -47,7 +47,7 @@ describe('when running on touch based device', function() { $.each(['iPad', 'Android'], function(index, device) { - it('is not rendered on' + device, function() { + it(`is not rendered on${device}`, function() { window.onTouchBasedDevice.and.returnValue([device]); state = jasmine.initializePlayer(); diff --git a/xmodule/js/spec/video/video_volume_control_spec.js b/xmodule/js/spec/video/video_volume_control_spec.js index c869316031..85c5d43b65 100644 --- a/xmodule/js/spec/video/video_volume_control_spec.js +++ b/xmodule/js/spec/video/video_volume_control_spec.js @@ -102,7 +102,7 @@ var $region = $('.video-live-region'); var getExpectedText = function(text) { - return text + ' Volume.'; + return `${text} Volume.`; }; actual.setVolume(volume, true, true); diff --git a/xmodule/js/src/capa/display.js b/xmodule/js/src/capa/display.js index 8afe368d42..fa9c594022 100644 --- a/xmodule/js/src/capa/display.js +++ b/xmodule/js/src/capa/display.js @@ -160,7 +160,7 @@ window.update_schematics(); } problemPrefix = this.element_id.replace(/problem_/, ''); - this.inputs = this.$('[id^="input_' + problemPrefix + '_"]'); + this.inputs = this.$(`[id^="input_${problemPrefix}_"]`); this.$('div.action button').click(this.refreshAnswers); this.reviewButton = this.$('.notification-btn.review-btn'); this.reviewButton.click(this.scroll_to_problem_meta); @@ -322,7 +322,7 @@ Problem.prototype.poll = function(previousTimeout, focusCallback) { var that = this; - return $.postWithPrefix('' + this.url + '/problem_get', function(response) { + return $.postWithPrefix(`${this.url}/problem_get`, function(response) { var newTimeout; // If queueing status changed, then render that.new_queued_items = $(response.html).find('.xqueue'); @@ -374,7 +374,7 @@ Problem.inputAjax = function(url, inputId, dispatch, data, callback) { data.dispatch = dispatch; // eslint-disable-line no-param-reassign data.input_id = inputId; // eslint-disable-line no-param-reassign - return $.postWithPrefix('' + url + '/input_ajax', data, callback); + return $.postWithPrefix(`${url}/input_ajax`, data, callback); }; Problem.prototype.render = function(content, focusCallback) { @@ -389,7 +389,7 @@ return typeof focusCallback === 'function' ? focusCallback() : void 0; }); } else { - return $.postWithPrefix('' + this.url + '/problem_get', function(response) { + return $.postWithPrefix(`${this.url}/problem_get`, function(response) { edx.HtmlUtils.setHtml(that.el, edx.HtmlUtils.HTML(response.html)); return JavascriptLoader.executeModuleScripts(that.el, function() { that.setupInputTypes(); @@ -479,7 +479,7 @@ Problem.prototype.focus_on_notification = function(type) { var notification; - notification = this.$('.notification-' + type); + notification = this.$(`.notification-${type}`); if (notification.length > 0) { notification.focus(); } @@ -490,7 +490,7 @@ }; Problem.prototype.focus_on_hint_notification = function(hintIndex) { - this.$('.notification-hint .notification-message > ol > li.hint-index-' + hintIndex).focus(); + this.$(`.notification-hint .notification-message > ol > li.hint-index-${hintIndex}`).focus(); }; Problem.prototype.focus_on_save_notification = function() { @@ -621,7 +621,7 @@ that.gentle_alert(response.responseJSON.success); } }; - $.ajaxWithPrefix('' + this.url + '/problem_check', settings); + $.ajaxWithPrefix(`${this.url}/problem_check`, settings); } }; @@ -634,7 +634,7 @@ Problem.prototype.submit_internal = function() { var that = this; Logger.log('problem_check', this.answers); - return $.postWithPrefix('' + this.url + '/problem_check', this.answers, function(response) { + return $.postWithPrefix(`${this.url}/problem_check`, this.answers, function(response) { switch (response.success) { case 'submitted': case 'incorrect': @@ -699,7 +699,7 @@ Problem.prototype.reset_internal = function() { var that = this; Logger.log('problem_reset', this.answers); - return $.postWithPrefix('' + this.url + '/problem_reset', { + return $.postWithPrefix(`${this.url}/problem_reset`, { id: this.id }, function(response) { if (response.success) { @@ -721,14 +721,14 @@ Logger.log('problem_show', { problem: this.id }); - return $.postWithPrefix('' + this.url + '/problem_show', function(response) { + return $.postWithPrefix(`${this.url}/problem_show`, function(response) { var answers; answers = response.answers; $.each(answers, function(key, value) { var safeKey = key.replace(':', '\\:'); // fix for courses which use url_names with colons, e.g. problem:question1 var answer; if (!$.isArray(value)) { - answer = that.$('#answer_' + safeKey + ', #solution_' + safeKey); + answer = that.$(`#answer_${safeKey}, #solution_${safeKey}`); edx.HtmlUtils.setHtml(answer, edx.HtmlUtils.HTML(value)); Collapsible.setCollapsibles(answer); @@ -804,7 +804,7 @@ Problem.prototype.save_internal = function() { var that = this; Logger.log('problem_save', this.answers); - return $.postWithPrefix('' + this.url + '/problem_save', this.answers, function(response) { + return $.postWithPrefix(`${this.url}/problem_save`, this.answers, function(response) { var saveMessage; saveMessage = response.msg; if (response.success) { @@ -829,10 +829,10 @@ element = event.target; // eslint-disable-line no-param-reassign } elid = element.id.replace(/^input_/, ''); - target = 'display_' + elid; + target = `display_${elid}`; // MathJax preprocessor is loaded by 'setupInputTypes' - preprocessorTag = 'inputtype_' + elid; + preprocessorTag = `inputtype_${elid}`; mathjaxPreprocessor = this.inputtypeDisplays[preprocessorTag]; if (typeof MathJax !== 'undefined' && MathJax !== null && MathJax.Hub.getAllJax(target)[0]) { jax = MathJax.Hub.getAllJax(target)[0]; @@ -846,7 +846,7 @@ Problem.prototype.updateMathML = function(jax, element) { try { - $('#' + element.id + '_dynamath').val(jax.root.toMathML('')); + $(`#${element.id}_dynamath`).val(jax.root.toMathML('')); } catch (exception) { if (!exception.restart) { throw exception; @@ -907,8 +907,8 @@ this.el.find('.choicegroup').each(function(i, choicegroupBlock) { var checked; checked = false; - $(choicegroupBlock).find('input[type=checkbox], input[type=radio]'). - each(function(j, checkboxOrRadio) { + $(choicegroupBlock).find('input[type=checkbox], input[type=radio]') + .each(function(j, checkboxOrRadio) { if ($(checkboxOrRadio).is(':checked')) { checked = true; } @@ -988,14 +988,14 @@ id = ($element.attr('id').match(/^inputtype_(.*)$/))[1]; return $element.find('input').on('change', function() { var $status; - $status = $('#status_' + id); + $status = $(`#status_${id}`); if ($status[0]) { $status.removeAttr('class').addClass('status unanswered'); } else { $('', { class: 'status unanswered', style: 'display: inline-block;', - id: 'status_' + id + id: `status_${id}` }); } $element.find('label').find('span.status.correct').remove(); @@ -1007,7 +1007,7 @@ $select = $(element).find('select'); id = ($select.attr('id').match(/^input_(.*)$/))[1]; return $select.on('change', function() { - return $('#status_' + id).removeAttr('class').addClass('unanswered') + return $(`#status_${id}`).removeAttr('class').addClass('unanswered') .find('.sr') .text(gettext('unsubmitted')); }); @@ -1068,8 +1068,8 @@ }); id = element.attr('id').replace(/^input_/, ''); CodeMirrorTextArea = CodeMirrorEditor.getInputField(); - CodeMirrorTextArea.setAttribute('id', 'cm-textarea-' + id); - CodeMirrorTextArea.setAttribute('aria-describedby', 'cm-editor-exit-message-' + id + ' status_' + id); + CodeMirrorTextArea.setAttribute('id', `cm-textarea-${id}`); + CodeMirrorTextArea.setAttribute('aria-describedby', `cm-editor-exit-message-${id} status_${id}`); return CodeMirrorEditor; } }; @@ -1084,8 +1084,8 @@ results = []; for (i = 0, len = answer.length; i < len; i++) { choice = answer[i]; - $inputLabel = $element.find('#input_' + inputId + '_' + choice + ' + label'); - $inputStatus = $element.find('#status_' + inputId); + $inputLabel = $element.find(`#input_${inputId}_${choice} + label`); + $inputStatus = $element.find(`#status_${inputId}`); // If the correct answer was already Submitted before "Show Answer" was selected, // the status HTML will already be present. Otherwise, inject the status HTML. @@ -1113,7 +1113,7 @@ results = []; for (i = 0, len = answer.length; i < len; i++) { choice = answer[i]; - results.push($element.find('section#forinput' + choice).addClass('choicetextgroup_show_correct')); + results.push($element.find(`section#forinput${choice}`).addClass('choicetextgroup_show_correct')); } return results; }, @@ -1180,7 +1180,7 @@ }; $element = $(element); id = $element.attr('id').replace(/inputtype_/, ''); - container = $element.find('#answer_' + id); + container = $element.find(`#answer_${id}`); canvas = document.createElement('canvas'); canvas.width = container.data('width'); canvas.height = container.data('height'); @@ -1200,7 +1200,7 @@ }); edx.HtmlUtils.setHtml(container, edx.HtmlUtils.HTML(canvas)); } else { - console.log('Answer is absent for image input with id=' + id); // eslint-disable-line no-console + console.log(`Answer is absent for image input with id=${id}`); // eslint-disable-line no-console } } }; @@ -1315,7 +1315,7 @@ } else { nextIndex = parseInt(hintIndex, 10) + 1; } - return $.postWithPrefix('' + this.url + '/hint_button', { + return $.postWithPrefix(`${this.url}/hint_button`, { hint_index: nextIndex, input_id: this.id }, function(response) { diff --git a/xmodule/js/src/capa/imageinput.js b/xmodule/js/src/capa/imageinput.js index e62daa7933..0904ad208b 100644 --- a/xmodule/js/src/capa/imageinput.js +++ b/xmodule/js/src/capa/imageinput.js @@ -24,9 +24,9 @@ window.ImageInput = (function($, undefined) { return ImageInput; function ImageInputConstructor(elementId) { - this.el = $('#imageinput_' + elementId); - this.crossEl = $('#cross_' + elementId); - this.inputEl = $('#input_' + elementId); + this.el = $(`#imageinput_${elementId}`); + this.crossEl = $(`#cross_${elementId}`); + this.inputEl = $(`#input_${elementId}`); this.el.on('click', this.clickHandler.bind(this)); } @@ -43,7 +43,7 @@ window.ImageInput = (function($, undefined) { // // IE10: `posX` and `posY` - float. // Chrome, FF: `posX` and `posY` - integers. - result = '[' + Math.round(posX) + ',' + Math.round(posY) + ']'; + result = `[${Math.round(posX)},${Math.round(posY)}]`; this.crossEl.css({ left: posX - 15, diff --git a/xmodule/js/src/poll/poll_main.js b/xmodule/js/src/poll/poll_main.js index dd1e91c607..8722820a17 100644 --- a/xmodule/js/src/poll/poll_main.js +++ b/xmodule/js/src/poll/poll_main.js @@ -24,9 +24,9 @@ _this.answersObj[index].statsEl.show(); // eslint-disable-next-line max-len - _this.answersObj[index].numberEl.html(HtmlUtils.HTML('' + value + ' (' + percentValue.toFixed(1) + '%)').toString()); + _this.answersObj[index].numberEl.html(HtmlUtils.HTML(`${value} (${percentValue.toFixed(1)}%)`).toString()); _this.answersObj[index].percentEl.css({ - width: '' + percentValue.toFixed(1) + '%' + width: `${percentValue.toFixed(1)}%` }); }); }, @@ -49,7 +49,7 @@ // Send the data to the server as an AJAX request. Attach a callback that will // be fired on server's response. $.postWithPrefix( - _this.ajax_url + '/' + answer, {}, + `${_this.ajax_url}/${answer}`, {}, function(response) { console.log('success! response = '); console.log(response); @@ -81,7 +81,7 @@ // Send the data to the server as an AJAX request. Attach a callback that will // be fired on server's response. $.postWithPrefix( - this.ajax_url + '/' + 'reset_poll', + `${this.ajax_url}/` + 'reset_poll', {}, function(response) { console.log('success! response = '); @@ -293,7 +293,7 @@ this.jsonConfig = JSON.parse(this.questionEl.children('.poll_question_div').html()); $.postWithPrefix( - '' + this.questionEl.data('ajax-url') + '/' + 'get_state', {}, + `${this.questionEl.data('ajax-url')}/` + 'get_state', {}, function(response) { _this.jsonConfig.poll_answer = response.poll_answer; _this.jsonConfig.total = response.total; @@ -312,8 +312,8 @@ return; } catch (err) { console.log( - 'ERROR: Invalid JSON config for poll ID "' + this.id + '".', - 'Error messsage: "' + err.message + '".' + `ERROR: Invalid JSON config for poll ID "${this.id}".`, + `Error messsage: "${err.message}".` ); return; diff --git a/xmodule/js/src/problem/edit.js b/xmodule/js/src/problem/edit.js index c5595f000c..f979a2ffa9 100644 --- a/xmodule/js/src/problem/edit.js +++ b/xmodule/js/src/problem/edit.js @@ -31,26 +31,26 @@ // the eslint warnings are being suppressed. extendsHelper(MarkdownEditingDescriptor, _super); // eslint-disable-line no-use-before-define - MarkdownEditingDescriptor.multipleChoiceTemplate = '( ) ' // eslint-disable-line no-use-before-define - + (gettext('incorrect')) + '\n( ) ' + (gettext('incorrect')) + '\n(x) ' + (gettext('correct')) + '\n'; + MarkdownEditingDescriptor.multipleChoiceTemplate = `( ) ${// eslint-disable-line no-use-before-define + gettext('incorrect')}\n( ) ${gettext('incorrect')}\n(x) ${gettext('correct')}\n`; - MarkdownEditingDescriptor.checkboxChoiceTemplate = '[x] ' // eslint-disable-line no-use-before-define - + (gettext('correct')) + '\n[ ] incorrect\n[x] correct\n'; + MarkdownEditingDescriptor.checkboxChoiceTemplate = `[x] ${// eslint-disable-line no-use-before-define + gettext('correct')}\n[ ] incorrect\n[x] correct\n`; - MarkdownEditingDescriptor.stringInputTemplate = '= ' // eslint-disable-line no-use-before-define - + (gettext('answer')) + '\n'; + MarkdownEditingDescriptor.stringInputTemplate = `= ${// eslint-disable-line no-use-before-define + gettext('answer')}\n`; - MarkdownEditingDescriptor.numberInputTemplate = '= ' // eslint-disable-line no-use-before-define - + (gettext('answer')) + ' +- 0.001%\n'; + MarkdownEditingDescriptor.numberInputTemplate = `= ${// eslint-disable-line no-use-before-define + gettext('answer')} +- 0.001%\n`; - MarkdownEditingDescriptor.selectTemplate = '[[' // eslint-disable-line no-use-before-define - + (gettext('incorrect')) + ', (' + (gettext('correct')) + '), ' + (gettext('incorrect')) + ']]\n'; + MarkdownEditingDescriptor.selectTemplate = `[[${// eslint-disable-line no-use-before-define + gettext('incorrect')}, (${gettext('correct')}), ${gettext('incorrect')}]]\n`; - MarkdownEditingDescriptor.headerTemplate = '' // eslint-disable-line no-use-before-define - + (gettext('Header')) + '\n=====\n'; + MarkdownEditingDescriptor.headerTemplate = `${// eslint-disable-line no-use-before-define + gettext('Header')}\n=====\n`; - MarkdownEditingDescriptor.explanationTemplate = '[explanation]\n' // eslint-disable-line no-use-before-define - + (gettext('Short explanation')) + '\n[explanation]\n'; + MarkdownEditingDescriptor.explanationTemplate = `[explanation]\n${// eslint-disable-line no-use-before-define + gettext('Short explanation')}\n[explanation]\n`; function MarkdownEditingDescriptor(element) { var that = this; @@ -224,7 +224,7 @@ } else { revisedLines += ' '; } - revisedLines += choiceEnd + ' ' + line + '\n'; + revisedLines += `${choiceEnd} ${line}\n`; } return revisedLines; } else { @@ -293,14 +293,14 @@ // description xml = xml.replace(/>>([^]+?)<\n'; // xss-lint: disable=javascript-concat-html + label = `\n`; // xss-lint: disable=javascript-concat-html // don't add empty tag if (result.length === 1 || !result[1]) { return label; } // xss-lint: disable=javascript-concat-html - return label + '' + result[1] + '\n'; + return `${label}${result[1]}\n`; }); // Pull out demand hints, || a hint || @@ -312,7 +312,7 @@ inner = /\s*\|\|(.*?)\|\|/.exec(options[i]); if (inner) { // xss-lint: disable=javascript-concat-html - demandhints += ' ' + inner[1].trim() + '\n'; + demandhints += ` ${inner[1].trim()}\n`; } } return ''; @@ -344,7 +344,7 @@ if (labelmatch) { hint = hint.replace(labelmatch[0], '').trim(); label = labelmatch[1].trim(); - labelassign = ' label="' + label + '"'; + labelassign = ` label="${label}"`; } } if (detectParens) { @@ -382,8 +382,8 @@ options = group1.split(/\,\s*/g); optiontag = ' \n' + optiontag + '\n\n\n'; + return `\n\n${optiontag}\n\n\n`; } // new style [[ many-lines ]] @@ -405,22 +405,22 @@ if (!textHint.nothint) { throw new Error(gettext('An answer option has been left blank. Please review and edit the component.')); } - correctstr = ' correct="' + (textHint.parens ? 'True' : 'False') + '"'; + correctstr = ` correct="${textHint.parens ? 'True' : 'False'}"`; hintstr = ''; if (textHint.hint) { label = textHint.label; if (label) { - label = ' label="' + label + '"'; + label = ` label="${label}"`; } // xss-lint: disable=javascript-concat-html - hintstr = ' ' + textHint.hint + ''; + hintstr = ` ${textHint.hint}`; } // xss-lint: disable=javascript-concat-html - optionlines += ' ' + textHint.nothint + hintstr + '\n'; + optionlines += ` ${textHint.nothint}${hintstr}\n`; } } // xss-lint: disable=javascript-concat-html - return '\n\n \n' + optionlines + ' \n\n\n'; + return `\n\n \n${optionlines} \n\n\n`; }); // multiple choice questions @@ -452,10 +452,10 @@ if (hint.hint) { value = hint.nothint; // xss-lint: disable=javascript-concat-html - value = value + ' ' + hint.hint + ''; + value = `${value} ${hint.hint}`; } // xss-lint: disable=javascript-concat-html - choices += ' ' + value + '\n'; + choices += ` ${value}\n`; } } result = '\n'; @@ -492,7 +492,7 @@ hintbody = abhint[2]; hintbody = hintbody.replace('&lf;', '\n').trim(); // xss-lint: disable=javascript-concat-html - endHints += ' ' + hintbody + '\n'; + endHints += ` ${hintbody}\n`; continue; // bail } @@ -506,7 +506,7 @@ // {unselected: Remember that apple is also a fruit.}} hint = extractHint(value); if (hint.hint) { - inner = '{' + hint.hint + '}'; // parsing is easier if we put outer { } back + inner = `{${hint.hint}}`; // parsing is easier if we put outer { } back // include \n since we are downstream of extractHint() select = /{\s*(s|selected):((.|\n)*?)}/i.exec(inner); @@ -514,12 +514,12 @@ // You’re right that apple is a fruit. if (select) { // xss-lint: disable=javascript-concat-html - hints += '\n ' + select[2].trim() + ''; + hints += `\n ${select[2].trim()}`; } select = /{\s*(u|unselected):((.|\n)*?)}/i.exec(inner); if (select) { // xss-lint: disable=javascript-concat-html - hints += '\n ' + select[2].trim() + ''; + hints += `\n ${select[2].trim()}`; } // Blank out the original text only if the specific "selected" syntax is found @@ -529,7 +529,7 @@ } } // xss-lint: disable=javascript-concat-html - groupString += ' ' + value + hints + '\n'; + groupString += ` ${value}${hints}\n`; } } @@ -593,7 +593,7 @@ if (textHint.hint) { firstAnswer = textHint.nothint; // xss-lint: disable=javascript-concat-html - hintLine = ' ' + textHint.hint + '\n'; + hintLine = ` ${textHint.hint}\n`; } // Range case @@ -601,14 +601,14 @@ // [5, 7) or (5, 7), or (1.2345 * (2+3), 7*4 ] - range tolerance case // = (5*2)*3 should not be used as range tolerance // xss-lint: disable=javascript-concat-html - numericalResponseString = '\n'; + numericalResponseString = `\n`; } else { answerData = getAnswerData(firstAnswer); // xss-lint: disable=javascript-concat-html - numericalResponseString = '\n'; + numericalResponseString = `\n`; if (answerData.default) { // xss-lint: disable=javascript-concat-html - numericalResponseString += ' \n'; + numericalResponseString += ` \n`; } } @@ -632,11 +632,11 @@ if (additionalTextHint.hint) { // xss-lint: disable=javascript-concat-html - additionalHintLine = '' + additionalTextHint.hint + ''; + additionalHintLine = `${additionalTextHint.hint}`; } // xss-lint: disable=javascript-concat-html - additionalAnswerString += ' '; + additionalAnswerString += ` `; additionalAnswerString += additionalHintLine; additionalAnswerString += '\n'; } @@ -667,11 +667,11 @@ firstAnswer = firstAnswer.slice(1).trim(); } // xss-lint: disable=javascript-concat-html - string = '\n'; + string = `\n`; if (textHint.hint) { // xss-lint: disable=javascript-concat-html - string += ' ' - + textHint.hint + '\n'; // xss-lint: disable=javascript-concat-html + string += ` ${ + textHint.hint}\n`; // xss-lint: disable=javascript-concat-html } // Subsequent cases are not= or or= @@ -680,7 +680,7 @@ notMatch = /^not\=\s*(.*)/.exec(textHint.nothint); if (notMatch) { // xss-lint: disable=javascript-concat-html - string += ' ' + textHint.hint + '\n'; + string += ` ${textHint.hint}\n`; continue; } @@ -688,10 +688,10 @@ if (orMatch) { // additional_answer with answer= attribute // xss-lint: disable=javascript-concat-html - string += ' '; + string += ` `; if (textHint.hint) { // xss-lint: disable=javascript-concat-html - string += '' + textHint.hint + ''; + string += `${textHint.hint}`; } string += '\n'; } @@ -708,13 +708,13 @@ // replace explanations xml = xml.replace(/\[explanation\]\n?([^\]]*)\[\/?explanation\]/gmi, function(match, p1) { // xss-lint: disable=javascript-concat-html - return '\n
    \n' + gettext('Explanation') + '\n\n' + p1 + '\n
    \n
    '; + return `\n
    \n${gettext('Explanation')}\n\n${p1}\n
    \n
    `; }); // replace code blocks xml = xml.replace(/\[code\]\n?([^\]]*)\[\/?code\]/gmi, function(match, p1) { // xss-lint: disable=javascript-concat-html - return '
    ' + p1 + '
    '; + return `
    ${p1}
    `; }); // split scripts and preformatted sections, and wrap paragraphs @@ -753,7 +753,7 @@ // make temporary xml // xss-lint: disable=javascript-concat-html - $xml = $($.parseXML('' + xml + '')); + $xml = $($.parseXML(`${xml}`)); responseType = $xml.find(responseTypesSelector); // convert if there is only one responsetype @@ -802,11 +802,11 @@ finalDemandHints = ''; if (demandHintTags.length) { // xss-lint: disable=javascript-concat-html - finalDemandHints = '\n\n' + demandHintTags.join('') + ''; + finalDemandHints = `\n\n${demandHintTags.join('')}`; } // make all responsetypes descendants of a single problem element // xss-lint: disable=javascript-concat-html - finalXml = '\n' + responseTypesXML.join('\n\n') + finalDemandHints + '\n'; + finalXml = `\n${responseTypesXML.join('\n\n')}${finalDemandHints}\n`; return finalXml; }; diff --git a/xmodule/js/src/sequence/display.js b/xmodule/js/src/sequence/display.js index 0c136a5b58..bf511b24c2 100644 --- a/xmodule/js/src/sequence/display.js +++ b/xmodule/js/src/sequence/display.js @@ -85,7 +85,7 @@ if (index === 0) { $navItemList = $sequenceList.find('li').last(); } else { - $navItemList = $sequenceList.find('li:eq(' + index + ')').prev(); + $navItemList = $sequenceList.find(`li:eq(${index})`).prev(); } $sequenceList.find('.tab').removeClass('visited').removeClass('focused'); $navItemList.find('.tab').addClass('focused').focus(); @@ -97,7 +97,7 @@ if (index === total) { $navItemList = $sequenceList.find('li').first(); } else { - $navItemList = $sequenceList.find('li:eq(' + index + ')').next(); + $navItemList = $sequenceList.find(`li:eq(${index})`).next(); } $sequenceList.find('.tab').removeClass('visited').removeClass('focused'); $navItemList.find('.tab').addClass('focused').focus(); @@ -145,7 +145,7 @@ if (positionLink && positionLink.data('page-title')) { currentUnitTitle = positionLink.data('page-title'); - newPageTitle = currentUnitTitle + ' | ' + this.base_page_title; + newPageTitle = `${currentUnitTitle} | ${this.base_page_title}`; if (newPageTitle !== document.title) { document.title = newPageTitle; @@ -262,7 +262,7 @@ latestContent = latestData[0]; latestResponse = latestData[1]; self.content_container - .find("[data-problem-id='" + problemId + "']") + .find(`[data-problem-id='${problemId}']`) .data('content', latestContent) .data('problem-score', latestResponse.current_score) .data('problem-total-possible', latestResponse.total_possible) @@ -352,7 +352,7 @@ return; } event.preventDefault(); - analyticsEventName = 'edx.ui.lms.sequence.' + direction + '_selected'; + analyticsEventName = `edx.ui.lms.sequence.${direction}_selected`; isBottomNav = $(event.target).closest('nav[class="sequence-bottom"]').length > 0; if (isBottomNav) { @@ -398,7 +398,7 @@ }; Sequence.prototype.link_for = function(position) { - return this.$('#sequence-list .nav-item[data-element=' + position + ']'); + return this.$(`#sequence-list .nav-item[data-element=${position}]`); }; Sequence.prototype.mark_visited = function(position) { diff --git a/xmodule/js/src/time.js b/xmodule/js/src/time.js index 7fecbebc9a..7ff83438dd 100644 --- a/xmodule/js/src/time.js +++ b/xmodule/js/src/time.js @@ -8,15 +8,15 @@ function format(time, formatFull) { seconds = Math.floor(time); minutes = Math.floor(seconds / 60); hours = Math.floor(minutes / 60); - seconds = seconds % 60; - minutes = minutes % 60; + seconds %= 60; + minutes %= 60; if (formatFull) { - return '' + _pad(hours) + ':' + _pad(minutes) + ':' + _pad(seconds % 60); + return `${_pad(hours)}:${_pad(minutes)}:${_pad(seconds % 60)}`; } else if (hours) { - return '' + hours + ':' + _pad(minutes) + ':' + _pad(seconds % 60); + return `${hours}:${_pad(minutes)}:${_pad(seconds % 60)}`; } else { - return '' + minutes + ':' + _pad(seconds % 60); + return `${minutes}:${_pad(seconds % 60)}`; } } @@ -32,10 +32,10 @@ function convert(time, oldSpeed, newSpeed) { function _pad(number) { if (number < 10) { - return '0' + number; + return `0${number}`; } else { - return '' + number; + return `${number}`; } } -export {format, formatFull, convert} +export {format, formatFull, convert}; diff --git a/xmodule/js/src/video/01_initialize.js b/xmodule/js/src/video/01_initialize.js index d4ceab9288..0aa3aa7e24 100644 --- a/xmodule/js/src/video/01_initialize.js +++ b/xmodule/js/src/video/01_initialize.js @@ -427,7 +427,7 @@ if (_.isFunction(conversions[option])) { value = conversions[option].call(this, value); } else { - throw new TypeError(option + ' is not a function.'); + throw new TypeError(`${option} is not a function.`); } } config[option] = value; @@ -582,7 +582,7 @@ $(scriptTag).on('error', function() { console.log( '[Video info]: YouTube returned an error for ' - + 'video with id "' + self.id + '".' + + `video with id "${self.id}".` ); // If the video is already loaded in `_waitForYoutubeApi` by the // time we get here, then we shouldn't load it again. diff --git a/xmodule/js/src/video/02_html5_hls_video.js b/xmodule/js/src/video/02_html5_hls_video.js index cb6a1a2fda..af585f4227 100644 --- a/xmodule/js/src/video/02_html5_hls_video.js +++ b/xmodule/js/src/video/02_html5_hls_video.js @@ -60,7 +60,7 @@ data.levels.map(function(level) { return { bitrate: level.bitrate, - resolution: level.width + 'x' + level.height + resolution: `${level.width}x${level.height}` }; }) ); @@ -72,7 +72,7 @@ '[HLS Video]: LEVEL_SWITCHED, qualityLevelInfo: ', { bitrate: level.bitrate, - resolution: level.width + 'x' + level.height + resolution: `${level.width}x${level.height}` } ); }); diff --git a/xmodule/js/src/video/02_html5_video.js b/xmodule/js/src/video/02_html5_video.js index 12f19ee50d..34e8d67558 100644 --- a/xmodule/js/src/video/02_html5_video.js +++ b/xmodule/js/src/video/02_html5_video.js @@ -342,7 +342,7 @@ ); } - el.trigger('html5:' + eventName, arguments); + el.trigger(`html5:${eventName}`, arguments); }); }); diff --git a/xmodule/js/src/video/04_video_control.js b/xmodule/js/src/video/04_video_control.js index b8cec53cae..5f1c37b09f 100644 --- a/xmodule/js/src/video/04_video_control.js +++ b/xmodule/js/src/video/04_video_control.js @@ -155,7 +155,7 @@ var endTime = (this.config.endTime !== null) ? this.config.endTime : params.duration; // in case endTime is accidentally specified as being greater than the video endTime = Math.min(endTime, params.duration); - this.videoControl.vidTimeEl.text(Time.format(params.time) + ' / ' + Time.format(endTime)); + this.videoControl.vidTimeEl.text(`${Time.format(params.time)} / ${Time.format(endTime)}`); } } ); diff --git a/xmodule/js/src/video/05_video_quality_control.js b/xmodule/js/src/video/05_video_quality_control.js index ad19aa3132..aa97119d3a 100644 --- a/xmodule/js/src/video/05_video_quality_control.js +++ b/xmodule/js/src/video/05_video_quality_control.js @@ -1,7 +1,7 @@ (function(requirejs, require, define) { // VideoQualityControl module. - -'use strict'; + + 'use strict'; define( 'video/05_video_quality_control.js', diff --git a/xmodule/js/src/video/06_video_progress_slider.js b/xmodule/js/src/video/06_video_progress_slider.js index aba6a89bcb..64e3f0a045 100644 --- a/xmodule/js/src/video/06_video_progress_slider.js +++ b/xmodule/js/src/video/06_video_progress_slider.js @@ -190,8 +190,8 @@ mind, or whether to act, and in acting, to live." width = endTime * step - left; return { - left: left + '%', - width: width + '%' + left: `${left}%`, + width: `${width}%` }; } @@ -332,16 +332,16 @@ mind, or whether to act, and in acting, to live." return interpolate(msg, {value: value}, true); }; - seconds = seconds % 60; - minutes = minutes % 60; + seconds %= 60; + minutes %= 60; if (hours) { - return i18n(hours, 'hour') + ' ' - + i18n(minutes, 'minute') + ' ' - + i18n(seconds, 'second'); + return `${i18n(hours, 'hour')} ${ + i18n(minutes, 'minute')} ${ + i18n(seconds, 'second')}`; } else if (minutes) { - return i18n(minutes, 'minute') + ' ' - + i18n(seconds, 'second'); + return `${i18n(minutes, 'minute')} ${ + i18n(seconds, 'second')}`; } return i18n(seconds, 'second'); diff --git a/xmodule/js/src/video/07_video_volume_control.js b/xmodule/js/src/video/07_video_volume_control.js index 3ab5126329..471a96aad9 100644 --- a/xmodule/js/src/video/07_video_volume_control.js +++ b/xmodule/js/src/video/07_video_volume_control.js @@ -133,7 +133,7 @@ */ render: function() { var container = this.el.find('.volume-slider'), - instructionsId = 'volume-instructions-' + this.state.id; + instructionsId = `volume-instructions-${this.state.id}`; HtmlUtils.append(container, HtmlUtils.HTML('
    ')); @@ -473,7 +473,7 @@ update: function(volume) { this.liveRegion.text([ this.getVolumeDescription(volume), - this.i18n.Volume + '.' + `${this.i18n.Volume}.` ].join(' ')); $(this.button).parent().find('.volume-slider') diff --git a/xmodule/js/src/video/08_video_speed_control.js b/xmodule/js/src/video/08_video_speed_control.js index 47cbe0ce5b..3dbf064422 100644 --- a/xmodule/js/src/video/08_video_speed_control.js +++ b/xmodule/js/src/video/08_video_speed_control.js @@ -99,7 +99,7 @@ render: function(speeds, currentSpeed) { var speedsContainer = this.speedsContainer, reversedSpeeds = speeds.concat().reverse(), - instructionsId = 'speed-instructions-' + this.state.id, + instructionsId = `speed-instructions-${this.state.id}`, speedsList = $.map(reversedSpeeds, function(speed) { return HtmlUtils.interpolateHtml( HtmlUtils.HTML( @@ -236,9 +236,9 @@ if (newSpeed !== this.currentSpeed || forceUpdate) { this.speedsContainer .find('li') - .siblings("li[data-speed='" + newSpeed + "']"); + .siblings(`li[data-speed='${newSpeed}']`); - this.speedButton.find('.value').text(newSpeed + 'x'); + this.speedButton.find('.value').text(`${newSpeed}x`); this.currentSpeed = newSpeed; if (!silent) { @@ -261,13 +261,13 @@ }, setActiveSpeed: function(speed) { - var speedOption = this.speedsContainer.find('li[data-speed="' + this.state.speedToString(speed) + '"]'); + var speedOption = this.speedsContainer.find(`li[data-speed="${this.state.speedToString(speed)}"]`); speedOption.addClass('is-active') .find('.speed-option') .attr('aria-pressed', 'true'); - this.speedButton.attr('title', gettext('Video speed: ') + this.state.speedToString(speed) + 'x'); + this.speedButton.attr('title', `${gettext('Video speed: ') + this.state.speedToString(speed)}x`); }, /** diff --git a/xmodule/js/src/video/095_video_context_menu.js b/xmodule/js/src/video/095_video_context_menu.js index de7c0b70e5..adf65d5c5c 100644 --- a/xmodule/js/src/video/095_video_context_menu.js +++ b/xmodule/js/src/video/095_video_context_menu.js @@ -119,11 +119,11 @@ keyDownHandler: function() { }, delegateEvents: function() { }, undelegateEvents: function() { - this.getElement().off('.' + this.id); + this.getElement().off(`.${this.id}`); }, addNamespace: function(events) { return _.map(events.split(/\s+/), function(event) { - return event + '.' + this.id; + return `${event}.${this.id}`; }, this).join(' '); } }); @@ -190,7 +190,7 @@ createElement: function() { return $('
      ', { - class: ['contextmenu', this.options.prefix + 'contextmenu'].join(' '), + class: ['contextmenu', `${this.options.prefix}contextmenu`].join(' '), role: 'menu', tabindex: -1 }); @@ -366,13 +366,13 @@ delegateEvents: function() { var self = this; $(document) - .on('click' + this.ns, function() { + .on(`click${this.ns}`, function() { if (_.isFunction(self.clickHandler)) { self.clickHandler.apply(this, arguments); } self.hide(); }) - .on('contextmenu' + this.ns, function() { + .on(`contextmenu${this.ns}`, function() { if (_.isFunction(self.contextmenuHandler)) { self.contextmenuHandler.apply(this, arguments); } @@ -396,22 +396,22 @@ var $spanElem, $listElem, $element = $('
    1. ', { - class: ['submenu-item', 'menu-item', this.options.prefix + 'submenu-item'].join(' '), + class: ['submenu-item', 'menu-item', `${this.options.prefix}submenu-item`].join(' '), 'aria-expanded': 'false', 'aria-haspopup': 'true', - 'aria-labelledby': 'submenu-item-label-' + this.id, + 'aria-labelledby': `submenu-item-label-${this.id}`, role: 'menuitem', tabindex: -1 }); $spanElem = $('', { - id: 'submenu-item-label-' + this.id, + id: `submenu-item-label-${this.id}`, text: this.options.label }); this.label = $spanElem.appendTo($element); $listElem = $('
        ', { - class: ['submenu', this.options.prefix + 'submenu'].join(' '), + class: ['submenu', `${this.options.prefix}submenu`].join(' '), role: 'menu' }); @@ -499,7 +499,7 @@ MenuItem = AbstractItem.extend({ createElement: function() { var classNames = [ - 'menu-item', this.options.prefix + 'menu-item', + 'menu-item', `${this.options.prefix}menu-item`, this.options.isSelected ? 'is-selected' : '' ].join(' '); @@ -639,7 +639,7 @@ items: _.map(state.speeds, function(speed) { var isSelected = parseFloat(speed) === state.speed; return { - label: speed + 'x', callback: speedCallback, speed: speed, isSelected: isSelected + label: `${speed}x`, callback: speedCallback, speed: speed, isSelected: isSelected }; }), initialize: function(menuitem) { diff --git a/xmodule/js/src/video/09_completion.js b/xmodule/js/src/video/09_completion.js index 1ce09b9b31..8cd59686db 100644 --- a/xmodule/js/src/video/09_completion.js +++ b/xmodule/js/src/video/09_completion.js @@ -172,7 +172,7 @@ self.complete = false; errmsg = 'Failed to submit completion'; if (xhr.responseJSON !== undefined) { - errmsg += ': ' + xhr.responseJSON.error; + errmsg += `: ${xhr.responseJSON.error}`; } console.warn(errmsg); /* eslint-enable no-console */ diff --git a/xmodule/js/src/video/09_events_bumper_plugin.js b/xmodule/js/src/video/09_events_bumper_plugin.js index 725cf29936..80a4810a34 100644 --- a/xmodule/js/src/video/09_events_bumper_plugin.js +++ b/xmodule/js/src/video/09_events_bumper_plugin.js @@ -67,7 +67,7 @@ onSkip: function(event, doNotShowAgain) { var info = {currentTime: this.getCurrentTime()}, - eventName = 'edx.video.bumper.' + (doNotShowAgain ? 'dismissed' : 'skipped'); + eventName = `edx.video.bumper.${doNotShowAgain ? 'dismissed' : 'skipped'}`; this.log(eventName, info); }, diff --git a/xmodule/js/src/video/09_video_caption.js b/xmodule/js/src/video/09_video_caption.js index 1d602bb933..46f969b134 100644 --- a/xmodule/js/src/video/09_video_caption.js +++ b/xmodule/js/src/video/09_video_caption.js @@ -1,7 +1,7 @@ (function(define) { // VideoCaption module. - -'use strict'; + + 'use strict'; define('video/09_video_caption.js', [ 'video/00_sjson.js', @@ -299,7 +299,7 @@ .focus(); } else { this.languageChooserEl - .find('li:eq(' + index + ')') + .find(`li:eq(${index})`) .next() .find('.control-lang') .focus(); @@ -321,7 +321,7 @@ .focus(); } else { this.languageChooserEl - .find('li:eq(' + index + ')') + .find(`li:eq(${index})`) .prev() .find('.control-lang') .focus(); @@ -582,8 +582,8 @@ var canFetchWithYoutubeId; console.log('[Video info]: ERROR while fetching captions.'); console.log( - '[Video info]: STATUS:', textStatus - + ', MESSAGE:', '' + errorThrown + '[Video info]: STATUS:', `${textStatus + }, MESSAGE:`, `${errorThrown}` ); // If initial list of languages has more than 1 item, check // for availability other transcripts. @@ -1070,12 +1070,12 @@ } this.subtitlesEl - .find("span[data-index='" + newIndex + "']") + .find(`span[data-index='${newIndex}']`) .parent() .addClass('current'); this.currentIndex = newIndex; - this.captionDisplayEl.text(this.subtitlesEl.find("span[data-index='" + newIndex + "']").text()); + this.captionDisplayEl.text(this.subtitlesEl.find(`span[data-index='${newIndex}']`).text()); this.scrollCaption(); } } diff --git a/xmodule/js/src/video/10_commands.js b/xmodule/js/src/video/10_commands.js index 066fe73479..33183616fb 100644 --- a/xmodule/js/src/video/10_commands.js +++ b/xmodule/js/src/video/10_commands.js @@ -45,7 +45,7 @@ if (_.has(this.commands, command)) { this.commands[command].execute.apply(this, [this.state].concat(args)); } else { - console.log('Command "' + command + '" is not available.'); + console.log(`Command "${command}" is not available.`); } }, diff --git a/xmodule/js/src/xmodule.js b/xmodule/js/src/xmodule.js index 3dd386dfe9..899a938227 100644 --- a/xmodule/js/src/xmodule.js +++ b/xmodule/js/src/xmodule.js @@ -90,7 +90,7 @@ return module; } catch (error) { - console.error('Unable to load ' + moduleType + ': ' + error.message); + console.error(`Unable to load ${moduleType}: ${error.message}`); } };