diff options
author | John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> | 2019-09-25 18:19:42 +0200 |
---|---|---|
committer | John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> | 2019-10-01 17:16:09 +0200 |
commit | b9bc2417e7a8dc81feb0abe20359bedaf864f790 (patch) | |
tree | 61b47fbf37c1d168da8625224debde9e6a985348 /core/src | |
parent | 7fb651235128dcbca8a6683b5cdafdf835f46300 (diff) | |
download | nextcloud-server-b9bc2417e7a8dc81feb0abe20359bedaf864f790.tar.gz nextcloud-server-b9bc2417e7a8dc81feb0abe20359bedaf864f790.zip |
Comply to eslint
Signed-off-by: John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
Diffstat (limited to 'core/src')
74 files changed, 2772 insertions, 2747 deletions
diff --git a/core/src/OC/admin.js b/core/src/OC/admin.js index 565af9946f7..008016645d9 100644 --- a/core/src/OC/admin.js +++ b/core/src/OC/admin.js @@ -24,7 +24,7 @@ const isAdmin = !!window._oc_isadmin /** * Returns whether the current user is an administrator * - * @return {bool} true if the user is an admin, false otherwise + * @returns {bool} true if the user is an admin, false otherwise * @since 9.0.0 */ export const isUserAdmin = () => isAdmin diff --git a/core/src/OC/appconfig.js b/core/src/OC/appconfig.js index 1248475ce77..37fc3ca420d 100644 --- a/core/src/OC/appconfig.js +++ b/core/src/OC/appconfig.js @@ -1,3 +1,4 @@ +/* eslint-disable */ /** * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com> * @@ -18,7 +19,7 @@ * */ -import {getValue, setValue, getApps, getKeys, deleteKey} from '../OCP/appconfig' + import { getValue, setValue, getApps, getKeys, deleteKey } from '../OCP/appconfig' export const appConfig = window.oc_appconfig || {} @@ -30,42 +31,42 @@ export const AppConfig = { /** * @deprecated Use OCP.AppConfig.getValue() instead */ - getValue: function (app, key, defaultValue, callback) { + getValue: function(app, key, defaultValue, callback) { getValue(app, key, defaultValue, { success: callback - }); + }) }, /** * @deprecated Use OCP.AppConfig.setValue() instead */ - setValue: function (app, key, value) { - setValue(app, key, value); + setValue: function(app, key, value) { + setValue(app, key, value) }, /** * @deprecated Use OCP.AppConfig.getApps() instead */ - getApps: function (callback) { + getApps: function(callback) { getApps({ success: callback - }); + }) }, /** * @deprecated Use OCP.AppConfig.getKeys() instead */ - getKeys: function (app, callback) { + getKeys: function(app, callback) { getKeys(app, { success: callback - }); + }) }, /** * @deprecated Use OCP.AppConfig.deleteKey() instead */ - deleteKey: function (app, key) { - deleteKey(app, key); + deleteKey: function(app, key) { + deleteKey(app, key) } -}; +} diff --git a/core/src/OC/apps.js b/core/src/OC/apps.js index d476e74c811..f94059a4212 100644 --- a/core/src/OC/apps.js +++ b/core/src/OC/apps.js @@ -8,26 +8,26 @@ * @copyright Bernhard Posselt 2014 */ -import $ from 'jquery'; +import $ from 'jquery' -var dynamicSlideToggleEnabled = false; +var dynamicSlideToggleEnabled = false const Apps = { - enableDynamicSlideToggle: function () { - dynamicSlideToggleEnabled = true; + enableDynamicSlideToggle: function() { + dynamicSlideToggleEnabled = true } -}; +} /** * Shows the #app-sidebar and add .with-app-sidebar to subsequent siblings * * @param {Object} [$el] sidebar element to show, defaults to $('#app-sidebar') */ -Apps.showAppSidebar = function ($el) { - var $appSidebar = $el || $('#app-sidebar'); - $appSidebar.removeClass('disappear').show(); - $('#app-content').trigger(new $.Event('appresized')); -}; +Apps.showAppSidebar = function($el) { + var $appSidebar = $el || $('#app-sidebar') + $appSidebar.removeClass('disappear').show() + $('#app-content').trigger(new $.Event('appresized')) +} /** * Shows the #app-sidebar and removes .with-app-sidebar from subsequent @@ -35,11 +35,11 @@ Apps.showAppSidebar = function ($el) { * * @param {Object} [$el] sidebar element to hide, defaults to $('#app-sidebar') */ -Apps.hideAppSidebar = function ($el) { - var $appSidebar = $el || $('#app-sidebar'); - $appSidebar.hide().addClass('disappear'); - $('#app-content').trigger(new $.Event('appresized')); -}; +Apps.hideAppSidebar = function($el) { + var $appSidebar = $el || $('#app-sidebar') + $appSidebar.hide().addClass('disappear') + $('#app-content').trigger(new $.Event('appresized')) +} /** * Provides a way to slide down a target area through a button and slide it @@ -51,40 +51,40 @@ Apps.hideAppSidebar = function ($el) { * <div class=".slide-area" class="hidden">I'm sliding up</div> */ export const registerAppsSlideToggle = () => { - var buttons = $('[data-apps-slide-toggle]'); + var buttons = $('[data-apps-slide-toggle]') if (buttons.length === 0) { - $('#app-navigation').addClass('without-app-settings'); + $('#app-navigation').addClass('without-app-settings') } - $(document).click(function (event) { + $(document).click(function(event) { if (dynamicSlideToggleEnabled) { - buttons = $('[data-apps-slide-toggle]'); + buttons = $('[data-apps-slide-toggle]') } - buttons.each(function (index, button) { + buttons.each(function(index, button) { - var areaSelector = $(button).data('apps-slide-toggle'); - var area = $(areaSelector); + var areaSelector = $(button).data('apps-slide-toggle') + var area = $(areaSelector) - function hideArea () { - area.slideUp(OC.menuSpeed * 4, function () { - area.trigger(new $.Event('hide')); - }); - area.removeClass('opened'); - $(button).removeClass('opened'); + function hideArea() { + area.slideUp(OC.menuSpeed * 4, function() { + area.trigger(new $.Event('hide')) + }) + area.removeClass('opened') + $(button).removeClass('opened') } - function showArea () { - area.slideDown(OC.menuSpeed * 4, function () { - area.trigger(new $.Event('show')); - }); - area.addClass('opened'); - $(button).addClass('opened'); - var input = $(areaSelector + ' [autofocus]'); + function showArea() { + area.slideDown(OC.menuSpeed * 4, function() { + area.trigger(new $.Event('show')) + }) + area.addClass('opened') + $(button).addClass('opened') + var input = $(areaSelector + ' [autofocus]') if (input.length === 1) { - input.focus(); + input.focus() } } @@ -94,23 +94,23 @@ export const registerAppsSlideToggle = () => { // button toggles the area if ($(button).is($(event.target).closest('[data-apps-slide-toggle]'))) { if (area.is(':visible')) { - hideArea(); + hideArea() } else { - showArea(); + showArea() } // all other areas that have not been clicked but are open // should be slid up } else { - var closest = $(event.target).closest(areaSelector); + var closest = $(event.target).closest(areaSelector) if (area.is(':visible') && closest[0] !== area[0]) { - hideArea(); + hideArea() } } } - }); + }) - }); -}; + }) +} -export default Apps; +export default Apps diff --git a/core/src/OC/appsettings.js b/core/src/OC/appsettings.js index b62af5c592a..7665d93fb7c 100644 --- a/core/src/OC/appsettings.js +++ b/core/src/OC/appsettings.js @@ -1,4 +1,5 @@ -/* +/* eslint-disable */ +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -18,9 +19,8 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ - import $ from 'jquery' -import {filePath} from './routing' +import { filePath } from './routing' /** * Opens a popup with the setting for an app. @@ -42,7 +42,7 @@ export const appSettings = args => { message: 'The parameter appid is missing' } } - var props = {scriptName: 'settings.php', cache: true} + var props = { scriptName: 'settings.php', cache: true } $.extend(props, args) var settings = $('#appsettings') if (settings.length === 0) { @@ -61,10 +61,10 @@ export const appSettings = args => { popup.hide().remove() } else { const arrowclass = settings.hasClass('topright') ? 'up' : 'left' - $.get(filePath(props.appid, '', props.scriptName), function (data) { - popup.html(data).ready(function () { + $.get(filePath(props.appid, '', props.scriptName), function(data) { + popup.html(data).ready(function() { popup.prepend('<span class="arrow ' + arrowclass + '"></span><h2>' + t('core', 'Settings') + '</h2><a class="close"></a>').show() - popup.find('.close').bind('click', function () { + popup.find('.close').bind('click', function() { popup.remove() }) if (typeof props.loadJS !== 'undefined') { @@ -80,10 +80,10 @@ export const appSettings = args => { } } if (props.cache) { - $.ajaxSetup({cache: true}) + $.ajaxSetup({ cache: true }) } $.getScript(filePath(props.appid, 'js', scriptname)) - .fail(function (jqxhr, settings, e) { + .fail(function(jqxhr, settings, e) { throw e }) } diff --git a/core/src/OC/backbone-webdav.js b/core/src/OC/backbone-webdav.js index d007054630f..b27d117e568 100644 --- a/core/src/OC/backbone-webdav.js +++ b/core/src/OC/backbone-webdav.js @@ -1,3 +1,4 @@ +/* eslint-disable */ /* * Copyright (c) 2015 * @@ -53,8 +54,8 @@ * }); */ -import _ from 'underscore'; -import dav from 'davclient.js'; +import _ from 'underscore' +import dav from 'davclient.js' const methodMap = { create: 'POST', @@ -62,11 +63,11 @@ const methodMap = { patch: 'PROPPATCH', delete: 'DELETE', read: 'PROPFIND' -}; +} // Throw an error when a URL is needed, and none is supplied. -function urlError () { - throw new Error('A "url" property or function must be specified'); +function urlError() { + throw new Error('A "url" property or function must be specified') } /** @@ -75,184 +76,184 @@ function urlError () { * @param {Object} result * @param {Object} davProperties properties mapping */ -function parsePropFindResult (result, davProperties) { +function parsePropFindResult(result, davProperties) { if (_.isArray(result)) { - return _.map(result, function (subResult) { - return parsePropFindResult(subResult, davProperties); - }); + return _.map(result, function(subResult) { + return parsePropFindResult(subResult, davProperties) + }) } var props = { href: result.href - }; + } - _.each(result.propStat, function (propStat) { + _.each(result.propStat, function(propStat) { if (propStat.status !== 'HTTP/1.1 200 OK') { - return; + return } for (var key in propStat.properties) { - var propKey = key; + var propKey = key if (key in davProperties) { - propKey = davProperties[key]; + propKey = davProperties[key] } - props[propKey] = propStat.properties[key]; + props[propKey] = propStat.properties[key] } - }); + }) if (!props.id) { // parse id from href - props.id = parseIdFromLocation(props.href); + props.id = parseIdFromLocation(props.href) } - return props; + return props } /** * Parse ID from location * * @param {string} url url - * @return {string} id + * @returns {string} id */ -function parseIdFromLocation (url) { - var queryPos = url.indexOf('?'); +function parseIdFromLocation(url) { + var queryPos = url.indexOf('?') if (queryPos > 0) { - url = url.substr(0, queryPos); + url = url.substr(0, queryPos) } - var parts = url.split('/'); - var result; + var parts = url.split('/') + var result do { - result = parts[parts.length - 1]; - parts.pop(); + result = parts[parts.length - 1] + parts.pop() // note: first result can be empty when there is a trailing slash, // so we take the part before that - } while (!result && parts.length > 0); + } while (!result && parts.length > 0) - return result; + return result } -function isSuccessStatus (status) { - return status >= 200 && status <= 299; +function isSuccessStatus(status) { + return status >= 200 && status <= 299 } -function convertModelAttributesToDavProperties (attrs, davProperties) { - var props = {}; - var key; +function convertModelAttributesToDavProperties(attrs, davProperties) { + var props = {} + var key for (key in attrs) { - var changedProp = davProperties[key]; - var value = attrs[key]; + var changedProp = davProperties[key] + var value = attrs[key] if (!changedProp) { - console.warn('No matching DAV property for property "' + key); - changedProp = key; + console.warn('No matching DAV property for property "' + key) + changedProp = key } if (_.isBoolean(value) || _.isNumber(value)) { // convert to string - value = '' + value; + value = '' + value } - props[changedProp] = value; + props[changedProp] = value } - return props; + return props } -function callPropFind (client, options, model, headers) { +function callPropFind(client, options, model, headers) { return client.propFind( options.url, _.values(options.davProperties) || [], options.depth, headers - ).then(function (response) { + ).then(function(response) { if (isSuccessStatus(response.status)) { if (_.isFunction(options.success)) { - var propsMapping = _.invert(options.davProperties); - var results = parsePropFindResult(response.body, propsMapping); + var propsMapping = _.invert(options.davProperties) + var results = parsePropFindResult(response.body, propsMapping) if (options.depth > 0) { // discard root entry - results.shift(); + results.shift() } - options.success(results); - return; + options.success(results) + } } else if (_.isFunction(options.error)) { - options.error(response); + options.error(response) } - }); + }) } -function callPropPatch (client, options, model, headers) { +function callPropPatch(client, options, model, headers) { return client.propPatch( options.url, convertModelAttributesToDavProperties(model.changed, options.davProperties), headers - ).then(function (result) { + ).then(function(result) { if (isSuccessStatus(result.status)) { if (_.isFunction(options.success)) { // pass the object's own values because the server // does not return the updated model - options.success(model.toJSON()); + options.success(model.toJSON()) } } else if (_.isFunction(options.error)) { - options.error(result); + options.error(result) } - }); + }) } -function callMkCol (client, options, model, headers) { +function callMkCol(client, options, model, headers) { // call MKCOL without data, followed by PROPPATCH return client.request( options.type, options.url, headers, null - ).then(function (result) { + ).then(function(result) { if (!isSuccessStatus(result.status)) { if (_.isFunction(options.error)) { - options.error(result); + options.error(result) } - return; + return } - callPropPatch(client, options, model, headers); - }); + callPropPatch(client, options, model, headers) + }) } -function callMethod (client, options, model, headers) { - headers['Content-Type'] = 'application/json'; +function callMethod(client, options, model, headers) { + headers['Content-Type'] = 'application/json' return client.request( options.type, options.url, headers, options.data - ).then(function (result) { + ).then(function(result) { if (!isSuccessStatus(result.status)) { if (_.isFunction(options.error)) { - options.error(result); + options.error(result) } - return; + return } if (_.isFunction(options.success)) { if (options.type === 'PUT' || options.type === 'POST' || options.type === 'MKCOL') { // pass the object's own values because the server // does not return anything - var responseJson = result.body || model.toJSON(); - var locationHeader = result.xhr.getResponseHeader('Content-Location'); + var responseJson = result.body || model.toJSON() + var locationHeader = result.xhr.getResponseHeader('Content-Location') if (options.type === 'POST' && locationHeader) { - responseJson.id = parseIdFromLocation(locationHeader); + responseJson.id = parseIdFromLocation(locationHeader) } - options.success(responseJson); - return; + options.success(responseJson) + return } // if multi-status, parse if (result.status === 207) { - var propsMapping = _.invert(options.davProperties); - options.success(parsePropFindResult(result.body, propsMapping)); + var propsMapping = _.invert(options.davProperties) + options.success(parsePropFindResult(result.body, propsMapping)) } else { - options.success(result.body); + options.success(result.body) } } - }); + }) } export const davCall = (options, model) => { @@ -262,22 +263,22 @@ export const davCall = (options, model) => { 'DAV:': 'd', 'http://owncloud.org/ns': 'oc' }, options.xmlNamespaces || {}) - }); - client.resolveUrl = function () { - return options.url; - }; + }) + client.resolveUrl = function() { + return options.url + } var headers = _.extend({ 'X-Requested-With': 'XMLHttpRequest', 'requesttoken': OC.requestToken - }, options.headers); + }, options.headers) if (options.type === 'PROPFIND') { - return callPropFind(client, options, model, headers); + return callPropFind(client, options, model, headers) } else if (options.type === 'PROPPATCH') { - return callPropPatch(client, options, model, headers); + return callPropPatch(client, options, model, headers) } else if (options.type === 'MKCOL') { - return callMkCol(client, options, model, headers); + return callMkCol(client, options, model, headers) } else { - return callMethod(client, options, model, headers); + return callMethod(client, options, model, headers) } } @@ -285,73 +286,73 @@ export const davCall = (options, model) => { * DAV transport */ export const davSync = Backbone => (method, model, options) => { - var params = {type: methodMap[method] || method}; - var isCollection = (model instanceof Backbone.Collection); + var params = { type: methodMap[method] || method } + var isCollection = (model instanceof Backbone.Collection) if (method === 'update') { // if a model has an inner collection, it must define an // attribute "hasInnerCollection" that evaluates to true if (model.hasInnerCollection) { // if the model itself is a Webdav collection, use MKCOL - params.type = 'MKCOL'; + params.type = 'MKCOL' } else if (model.usePUT || (model.collection && model.collection.usePUT)) { // use PUT instead of PROPPATCH - params.type = 'PUT'; + params.type = 'PUT' } } // Ensure that we have a URL. if (!options.url) { - params.url = _.result(model, 'url') || urlError(); + params.url = _.result(model, 'url') || urlError() } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { - params.data = JSON.stringify(options.attrs || model.toJSON(options)); + params.data = JSON.stringify(options.attrs || model.toJSON(options)) } // Don't process data on a non-GET request. if (params.type !== 'PROPFIND') { - params.processData = false; + params.processData = false } if (params.type === 'PROPFIND' || params.type === 'PROPPATCH') { - var davProperties = model.davProperties; + var davProperties = model.davProperties if (!davProperties && model.model) { // use dav properties from model in case of collection - davProperties = model.model.prototype.davProperties; + davProperties = model.model.prototype.davProperties } if (davProperties) { if (_.isFunction(davProperties)) { - params.davProperties = davProperties.call(model); + params.davProperties = davProperties.call(model) } else { - params.davProperties = davProperties; + params.davProperties = davProperties } } - params.davProperties = _.extend(params.davProperties || {}, options.davProperties); + params.davProperties = _.extend(params.davProperties || {}, options.davProperties) if (_.isUndefined(options.depth)) { if (isCollection) { - options.depth = 1; + options.depth = 1 } else { - options.depth = 0; + options.depth = 0 } } } // Pass along `textStatus` and `errorThrown` from jQuery. - var error = options.error; - options.error = function (xhr, textStatus, errorThrown) { - options.textStatus = textStatus; - options.errorThrown = errorThrown; + var error = options.error + options.error = function(xhr, textStatus, errorThrown) { + options.textStatus = textStatus + options.errorThrown = errorThrown if (error) { - error.call(options.context, xhr, textStatus, errorThrown); + error.call(options.context, xhr, textStatus, errorThrown) } - }; + } // Make the request, allowing the user to override any Ajax options. - var xhr = options.xhr = Backbone.davCall(_.extend(params, options), model); - model.trigger('request', model, xhr, options); - return xhr; + var xhr = options.xhr = Backbone.davCall(_.extend(params, options), model) + model.trigger('request', model, xhr, options) + return xhr } diff --git a/core/src/OC/backbone.js b/core/src/OC/backbone.js index 07b5593eff9..38bfc046501 100644 --- a/core/src/OC/backbone.js +++ b/core/src/OC/backbone.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -19,15 +19,15 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -import VendorBackbone from 'backbone'; -import {davCall, davSync} from './backbone-webdav'; +import VendorBackbone from 'backbone' +import { davCall, davSync } from './backbone-webdav' -const Backbone = VendorBackbone.noConflict(); +const Backbone = VendorBackbone.noConflict() // Patch Backbone for DAV Object.assign(Backbone, { davCall, - davSync: davSync(Backbone), -}); + davSync: davSync(Backbone) +}) -export default Backbone; +export default Backbone diff --git a/core/src/OC/capabilities.js b/core/src/OC/capabilities.js index 1adfe80d288..2e0a8da3995 100644 --- a/core/src/OC/capabilities.js +++ b/core/src/OC/capabilities.js @@ -24,7 +24,7 @@ const capabilities = window._oc_capabilities || {} /** * Returns the capabilities * - * @return {Array} capabilities + * @returns {Array} capabilities * * @since 14.0 */ diff --git a/core/src/OC/constants.js b/core/src/OC/constants.js index d77a2d28c70..972848997ae 100644 --- a/core/src/OC/constants.js +++ b/core/src/OC/constants.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -19,7 +19,7 @@ * along with this program. If not see <http://www.gnu.org/licenses/>. */ -export const coreApps = ['', 'admin','log','core/search','core','3rdparty'] +export const coreApps = ['', 'admin', 'log', 'core/search', 'core', '3rdparty'] export const menuSpeed = 50 export const PERMISSION_NONE = 0 export const PERMISSION_CREATE = 4 diff --git a/core/src/OC/contactsmenu.js b/core/src/OC/contactsmenu.js index 0af4bad412d..e986c46ec20 100644 --- a/core/src/OC/contactsmenu.js +++ b/core/src/OC/contactsmenu.js @@ -1,4 +1,4 @@ -/* global Backbone, Handlebars, Promise, _ */ +/* eslint-disable */ /** * @copyright 2017 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -22,10 +22,10 @@ * */ -import $ from 'jquery'; -import {Collection, Model, View} from 'backbone'; +import $ from 'jquery' +import { Collection, Model, View } from 'backbone' -import OC from './index'; +import OC from './index' /** * @class Contact @@ -43,18 +43,18 @@ const Contact = Model.extend({ /** * @returns {undefined} */ - initialize: function () { + initialize: function() { // Add needed property for easier template rendering if (this.get('actions').length === 0) { - this.set('hasOneAction', true); + this.set('hasOneAction', true) } else if (this.get('actions').length === 1) { - this.set('hasTwoActions', true); - this.set('secondAction', this.get('actions')[0]); + this.set('hasTwoActions', true) + this.set('secondAction', this.get('actions')[0]) } else { - this.set('hasManyActions', true); + this.set('hasManyActions', true) } } -}); +}) /** * @class ContactCollection @@ -62,7 +62,7 @@ const Contact = Model.extend({ */ const ContactCollection = Collection.extend({ model: Contact -}); +}) /** * @class ContactsListView @@ -80,29 +80,29 @@ const ContactsListView = View.extend({ * @param {object} options * @returns {undefined} */ - initialize: function (options) { - this._collection = options.collection; + initialize: function(options) { + this._collection = options.collection }, /** * @returns {self} */ - render: function () { - var self = this; - self.$el.html(''); - self._subViews = []; + render: function() { + var self = this + self.$el.html('') + self._subViews = [] - self._collection.forEach(function (contact) { + self._collection.forEach(function(contact) { var item = new ContactsListItemView({ model: contact - }); - item.render(); - self.$el.append(item.$el); - item.on('toggle:actionmenu', self._onChildActionMenuToggle, self); - self._subViews.push(item); - }); - - return self; + }) + item.render() + self.$el.append(item.$el) + item.on('toggle:actionmenu', self._onChildActionMenuToggle, self) + self._subViews.push(item) + }) + + return self }, /** @@ -111,12 +111,12 @@ const ContactsListView = View.extend({ * @param {type} $src * @returns {undefined} */ - _onChildActionMenuToggle: function ($src) { - this._subViews.forEach(function (view) { - view.trigger('parent:toggle:actionmenu', $src); - }); + _onChildActionMenuToggle: function($src) { + this._subViews.forEach(function(view) { + view.trigger('parent:toggle:actionmenu', $src) + }) } -}); +}) /** * @class ContactsListItemView @@ -146,37 +146,37 @@ const ContactsListItemView = View.extend({ * @param {object} data * @returns {undefined} */ - template: function (data) { - return this.contactTemplate(data); + template: function(data) { + return this.contactTemplate(data) }, /** * @param {object} options * @returns {undefined} */ - initialize: function (options) { - this._model = options.model; - this.on('parent:toggle:actionmenu', this._onOtherActionMenuOpened, this); + initialize: function(options) { + this._model = options.model + this.on('parent:toggle:actionmenu', this._onOtherActionMenuOpened, this) }, /** * @returns {self} */ - render: function () { + render: function() { this.$el.html(this.template({ contact: this._model.toJSON() - })); - this.delegateEvents(); + })) + this.delegateEvents() // Show placeholder if no avatar is available (avatar is rendered as img, not div) - this.$('div.avatar').imageplaceholder(this._model.get('fullName')); + this.$('div.avatar').imageplaceholder(this._model.get('fullName')) // Show tooltip for top action - this.$('.top-action').tooltip({placement: 'left'}); + this.$('.top-action').tooltip({ placement: 'left' }) // Show tooltip for second action - this.$('.second-action').tooltip({placement: 'left'}); + this.$('.second-action').tooltip({ placement: 'left' }) - return this; + return this }, /** @@ -185,14 +185,14 @@ const ContactsListItemView = View.extend({ * @private * @returns {undefined} */ - _onToggleActionsMenu: function () { - this._actionMenuShown = !this._actionMenuShown; + _onToggleActionsMenu: function() { + this._actionMenuShown = !this._actionMenuShown if (this._actionMenuShown) { - this.$('.menu').show(); + this.$('.menu').show() } else { - this.$('.menu').hide(); + this.$('.menu').hide() } - this.trigger('toggle:actionmenu', this.$el); + this.trigger('toggle:actionmenu', this.$el) }, /** @@ -200,15 +200,15 @@ const ContactsListItemView = View.extend({ * @argument {jQuery} $src * @returns {undefined} */ - _onOtherActionMenuOpened: function ($src) { + _onOtherActionMenuOpened: function($src) { if (this.$el.is($src)) { // Ignore - return; + return } - this._actionMenuShown = false; - this.$('.menu').hide(); + this._actionMenuShown = false + this.$('.menu').hide() } -}); +}) /** * @class ContactsMenuView @@ -248,15 +248,15 @@ const ContactsMenuView = View.extend({ /** * @returns {undefined} */ - _onSearch: _.debounce(function (e) { - var searchTerm = this.$('#contactsmenu-search').val(); + _onSearch: _.debounce(function(e) { + var searchTerm = this.$('#contactsmenu-search').val() // IE11 triggers an 'input' event after the view has been rendered // resulting in an endless loading loop. To prevent this, we remember // the last search term to savely ignore some events // See https://github.com/nextcloud/server/issues/5281 if (searchTerm !== this._searchTerm) { - this.trigger('search', this.$('#contactsmenu-search').val()); - this._searchTerm = searchTerm; + this.trigger('search', this.$('#contactsmenu-search').val()) + this._searchTerm = searchTerm } }, 700), @@ -264,75 +264,75 @@ const ContactsMenuView = View.extend({ * @param {object} data * @returns {string} */ - loadingTemplate: function (data) { - return this.templates.loading(data); + loadingTemplate: function(data) { + return this.templates.loading(data) }, /** * @param {object} data * @returns {string} */ - errorTemplate: function (data) { + errorTemplate: function(data) { return this.templates.error( _.extend({ couldNotLoadText: t('core', 'Could not load your contacts') }, data) - ); + ) }, /** * @param {object} data * @returns {string} */ - contentTemplate: function (data) { + contentTemplate: function(data) { return this.templates.menu( _.extend({ searchContactsText: t('core', 'Search contacts …') }, data) - ); + ) }, /** * @param {object} data * @returns {string} */ - contactsTemplate: function (data) { + contactsTemplate: function(data) { return this.templates.list( _.extend({ noContactsFoundText: t('core', 'No contacts found'), showAllContactsText: t('core', 'Show all contacts …'), contactsAppMgmtText: t('core', 'Install the Contacts app') }, data) - ); + ) }, /** * @param {object} options * @returns {undefined} */ - initialize: function (options) { - this.options = options; + initialize: function(options) { + this.options = options }, /** * @param {string} text * @returns {undefined} */ - showLoading: function (text) { - this.render(); - this._contacts = undefined; + showLoading: function(text) { + this.render() + this._contacts = undefined this.$('.content').html(this.loadingTemplate({ loadingText: text - })); + })) }, /** * @returns {undefined} */ - showError: function () { - this.render(); - this._contacts = undefined; - this.$('.content').html(this.errorTemplate()); + showError: function() { + this.render() + this._contacts = undefined + this.$('.content').html(this.errorTemplate()) }, /** @@ -340,16 +340,16 @@ const ContactsMenuView = View.extend({ * @param {string} searchTerm * @returns {undefined} */ - showContacts: function (viewData, searchTerm) { - this._contacts = viewData.contacts; + showContacts: function(viewData, searchTerm) { + this._contacts = viewData.contacts this.render({ contacts: viewData.contacts - }); + }) var list = new ContactsListView({ collection: viewData.contacts - }); - list.render(); + }) + list.render() this.$('.content').html(this.contactsTemplate({ contacts: viewData.contacts, searchTerm: searchTerm, @@ -357,25 +357,25 @@ const ContactsMenuView = View.extend({ contactsAppURL: OC.generateUrl('/apps/contacts'), canInstallApp: OC.isUserAdmin(), contactsAppMgmtURL: OC.generateUrl('/settings/apps/social/contacts') - })); - this.$('#contactsmenu-contacts').html(list.$el); + })) + this.$('#contactsmenu-contacts').html(list.$el) }, /** * @param {object} data * @returns {self} */ - render: function (data) { - var searchVal = this.$('#contactsmenu-search').val(); - this.$el.html(this.contentTemplate(data)); + render: function(data) { + var searchVal = this.$('#contactsmenu-search').val() + this.$el.html(this.contentTemplate(data)) // Focus search - this.$('#contactsmenu-search').val(searchVal); - this.$('#contactsmenu-search').focus(); - return this; + this.$('#contactsmenu-search').val(searchVal) + this.$('#contactsmenu-search').focus() + return this } -}); +}) /** * @param {Object} options @@ -384,9 +384,9 @@ const ContactsMenuView = View.extend({ * @class ContactsMenu * @memberOf OC */ -const ContactsMenu = function (options) { - this.initialize(options); -}; +const ContactsMenu = function(options) { + this.initialize(options) +} ContactsMenu.prototype = { /** @type {jQuery} */ @@ -407,23 +407,23 @@ ContactsMenu.prototype = { * @param {jQuery} options.trigger - the element to click on to open the menu * @returns {undefined} */ - initialize: function (options) { - this.$el = options.el; - this._$trigger = options.trigger; + initialize: function(options) { + this.$el = options.el + this._$trigger = options.trigger this._view = new ContactsMenuView({ el: this.$el - }); - this._view.on('search', function (searchTerm) { - this._loadContacts(searchTerm); - }, this); - - OC.registerMenu(this._$trigger, this.$el, function () { - this._toggleVisibility(true); - }.bind(this), true); - this.$el.on('beforeHide', function () { - this._toggleVisibility(false); - }.bind(this)); + }) + this._view.on('search', function(searchTerm) { + this._loadContacts(searchTerm) + }, this) + + OC.registerMenu(this._$trigger, this.$el, function() { + this._toggleVisibility(true) + }.bind(this), true) + this.$el.on('beforeHide', function() { + this._toggleVisibility(false) + }.bind(this)) }, /** @@ -431,12 +431,12 @@ ContactsMenu.prototype = { * @param {boolean} show * @returns {Promise} */ - _toggleVisibility: function (show) { + _toggleVisibility: function(show) { if (show) { - return this._loadContacts(); + return this._loadContacts() } else { - this.$el.html(''); - return Promise.resolve(); + this.$el.html('') + return Promise.resolve() } }, @@ -445,48 +445,48 @@ ContactsMenu.prototype = { * @param {string|undefined} searchTerm * @returns {Promise} */ - _getContacts: function (searchTerm) { - var url = OC.generateUrl('/contactsmenu/contacts'); + _getContacts: function(searchTerm) { + var url = OC.generateUrl('/contactsmenu/contacts') return Promise.resolve($.ajax(url, { method: 'POST', data: { filter: searchTerm } - })); + })) }, /** * @param {string|undefined} searchTerm * @returns {undefined} */ - _loadContacts: function (searchTerm) { - var self = this; + _loadContacts: function(searchTerm) { + var self = this if (!self._contactsPromise) { - self._contactsPromise = self._getContacts(searchTerm); + self._contactsPromise = self._getContacts(searchTerm) } if (_.isUndefined(searchTerm) || searchTerm === '') { - self._view.showLoading(t('core', 'Loading your contacts …')); + self._view.showLoading(t('core', 'Loading your contacts …')) } else { self._view.showLoading(t('core', 'Looking for {term} …', { term: searchTerm - })); + })) } - return self._contactsPromise.then(function (data) { + return self._contactsPromise.then(function(data) { // Convert contact entries to Backbone collection - data.contacts = new ContactCollection(data.contacts); + data.contacts = new ContactCollection(data.contacts) - self._view.showContacts(data, searchTerm); - }, function (e) { - self._view.showError(); - console.error('There was an error loading your contacts', e); - }).then(function () { + self._view.showContacts(data, searchTerm) + }, function(e) { + self._view.showError() + console.error('There was an error loading your contacts', e) + }).then(function() { // Delete promise, so that contacts are fetched again when the // menu is opened the next time. - delete self._contactsPromise; - }).catch(console.error.bind(this)); + delete self._contactsPromise + }).catch(console.error.bind(this)) } -}; +} -export default ContactsMenu; +export default ContactsMenu diff --git a/core/src/OC/currentuser.js b/core/src/OC/currentuser.js index 061abba89d6..c8f9d59c1eb 100644 --- a/core/src/OC/currentuser.js +++ b/core/src/OC/currentuser.js @@ -31,6 +31,6 @@ export const currentUser = rawUid !== undefined ? rawUid : false export const getCurrentUser = () => { return { uid: currentUser, - displayName, + displayName } } diff --git a/core/src/OC/dialogs.js b/core/src/OC/dialogs.js index b5a2c2c01b3..abc5b3e1c3a 100644 --- a/core/src/OC/dialogs.js +++ b/core/src/OC/dialogs.js @@ -1,5 +1,5 @@ /* global alert */ - +/* eslint-disable */ /* * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * @@ -42,14 +42,15 @@ const Dialogs = { // used to name each dialog dialogsCounter: 0, + /** * displays alert dialog - * @param text content of dialog - * @param title dialog title - * @param callback which will be triggered when user presses OK - * @param modal make the dialog modal + * @param {string} text content of dialog + * @param {string} title dialog title + * @param {function} callback which will be triggered when user presses OK + * @param {boolean} [modal] make the dialog modal */ - alert: function (text, title, callback, modal) { + alert: function(text, title, callback, modal) { this.message( text, title, @@ -57,27 +58,28 @@ const Dialogs = { Dialogs.OK_BUTTON, callback, modal - ); + ) }, /** * displays info dialog - * @param text content of dialog - * @param title dialog title - * @param callback which will be triggered when user presses OK - * @param modal make the dialog modal + * @param {string} text content of dialog + * @param {string} title dialog title + * @param {function} callback which will be triggered when user presses OK + * @param {boolean} [modal] make the dialog modal */ - info: function (text, title, callback, modal) { - this.message(text, title, 'info', Dialogs.OK_BUTTON, callback, modal); + info: function(text, title, callback, modal) { + this.message(text, title, 'info', Dialogs.OK_BUTTON, callback, modal) }, + /** * displays confirmation dialog - * @param text content of dialog - * @param title dialog title - * @param callback which will be triggered when user presses YES or NO - * (true or false would be passed to callback respectively) - * @param modal make the dialog modal + * @param {string} text content of dialog + * @param {string} title dialog title + * @param {function} callback which will be triggered when user presses OK (true or false would be passed to callback respectively) + * @param {boolean} [modal] make the dialog modal + * @returns {Promise} */ - confirm: function (text, title, callback, modal) { + confirm: function(text, title, callback, modal) { return this.message( text, title, @@ -85,17 +87,17 @@ const Dialogs = { Dialogs.YES_NO_BUTTONS, callback, modal - ); + ) }, /** * displays confirmation dialog - * @param text content of dialog - * @param title dialog title - * @param callback which will be triggered when user presses YES or NO - * (true or false would be passed to callback respectively) - * @param modal make the dialog modal + * @param {string} text content of dialog + * @param {string} title dialog title + * @param {function} callback which will be triggered when user presses OK (true or false would be passed to callback respectively) + * @param {boolean} [modal] make the dialog modal + * @returns {Promise} */ - confirmHtml: function (text, title, callback, modal) { + confirmHtml: function(text, title, callback, modal) { return this.message( text, title, @@ -104,79 +106,81 @@ const Dialogs = { callback, modal, true - ); + ) }, /** * displays prompt dialog - * @param text content of dialog - * @param title dialog title - * @param callback which will be triggered when user presses YES or NO - * (true or false would be passed to callback respectively) - * @param modal make the dialog modal - * @param name name of the input field - * @param password whether the input should be a password input + * @param {string} text content of dialog + * @param {string} title dialog title + * @param {function} callback which will be triggered when user presses OK (true or false would be passed to callback respectively) + * @param {boolean} [modal] make the dialog modal + * @param {string} name name of the input field + * @param {boolean} password whether the input should be a password input + * @returns {Promise} */ - prompt: function (text, title, callback, modal, name, password) { - return $.when(this._getMessageTemplate()).then(function ($tmpl) { - var dialogName = 'oc-dialog-' + Dialogs.dialogsCounter + '-content'; - var dialogId = '#' + dialogName; + prompt: function(text, title, callback, modal, name, password) { + return $.when(this._getMessageTemplate()).then(function($tmpl) { + var dialogName = 'oc-dialog-' + Dialogs.dialogsCounter + '-content' + var dialogId = '#' + dialogName var $dlg = $tmpl.octemplate({ dialog_name: dialogName, title: title, message: text, type: 'notice' - }); - var input = $('<input/>'); - input.attr('type', password ? 'password' : 'text').attr('id', dialogName + '-input').attr('placeholder', name); - var label = $('<label/>').attr('for', dialogName + '-input').text(name + ': '); - $dlg.append(label); - $dlg.append(input); + }) + var input = $('<input/>') + input.attr('type', password ? 'password' : 'text').attr('id', dialogName + '-input').attr('placeholder', name) + var label = $('<label/>').attr('for', dialogName + '-input').text(name + ': ') + $dlg.append(label) + $dlg.append(input) if (modal === undefined) { - modal = false; + modal = false } - $('body').append($dlg); + $('body').append($dlg) // wrap callback in _.once(): // only call callback once and not twice (button handler and close // event) but call it for the close event, if ESC or the x is hit if (callback !== undefined) { - callback = _.once(callback); + callback = _.once(callback) } var buttonlist = [{ text: t('core', 'No'), - click: function () { + click: function() { if (callback !== undefined) { - callback(false, input.val()); + // eslint-disable-next-line standard/no-callback-literal + callback(false, input.val()) } - $(dialogId).ocdialog('close'); + $(dialogId).ocdialog('close') } }, { text: t('core', 'Yes'), - click: function () { + click: function() { if (callback !== undefined) { - callback(true, input.val()); + // eslint-disable-next-line standard/no-callback-literal + callback(true, input.val()) } - $(dialogId).ocdialog('close'); + $(dialogId).ocdialog('close') }, defaultButton: true - } - ]; + }] $(dialogId).ocdialog({ closeOnEscape: true, modal: modal, buttons: buttonlist, - close: function () { + close: function() { // callback is already fired if Yes/No is clicked directly if (callback !== undefined) { - callback(false, input.val()); + // eslint-disable-next-line standard/no-callback-literal + callback(false, input.val()) } } - }); - input.focus(); - Dialogs.dialogsCounter++; - }); + }) + input.focus() + Dialogs.dialogsCounter++ + }) }, /** * show a file picker to pick a file from @@ -188,56 +192,56 @@ const Dialogs = { * be able to select both files and folders "['*', 'httpd/unix-directory']" * should be used instead. * - * @param title dialog title - * @param callback which will be triggered when user presses Choose - * @param multiselect whether it should be possible to select multiple files - * @param mimetypeFilter mimetype to filter by - directories will always be included - * @param modal make the dialog modal - * @param type Type of file picker : Choose, copy, move, copy and move - * @param path path to the folder that the the file can be picket from - * @param options additonal options that need to be set + * @param {string} title dialog title + * @param {function} callback which will be triggered when user presses Choose + * @param {boolean} [multiselect] whether it should be possible to select multiple files + * @param {string[]} [mimetypeFilter] mimetype to filter by - directories will always be included + * @param {boolean} [modal] make the dialog modal + * @param {string} [type] Type of file picker : Choose, copy, move, copy and move + * @param {string} [path] path to the folder that the the file can be picket from + * @param {Object} [options] additonal options that need to be set */ - filepicker: function (title, callback, multiselect, mimetypeFilter, modal, type, path, options) { - var self = this; + filepicker: function(title, callback, multiselect, mimetypeFilter, modal, type, path, options) { + var self = this - this.filepicker.sortField = 'name'; - this.filepicker.sortOrder = 'asc'; + this.filepicker.sortField = 'name' + this.filepicker.sortOrder = 'asc' // avoid opening the picker twice if (this.filepicker.loading) { - return; + return } if (type === undefined) { - type = this.FILEPICKER_TYPE_CHOOSE; + type = this.FILEPICKER_TYPE_CHOOSE } - var emptyText = t('core', 'No files in here'); - var newText = t('files', 'New folder'); + var emptyText = t('core', 'No files in here') + var newText = t('files', 'New folder') if (type === this.FILEPICKER_TYPE_COPY || type === this.FILEPICKER_TYPE_MOVE || type === this.FILEPICKER_TYPE_COPY_MOVE) { - emptyText = t('core', 'No more subfolders in here'); + emptyText = t('core', 'No more subfolders in here') } - this.filepicker.loading = true; - this.filepicker.filesClient = (OCA.Sharing && OCA.Sharing.PublicApp && OCA.Sharing.PublicApp.fileList) ? OCA.Sharing.PublicApp.fileList.filesClient : OC.Files.getClient(); + this.filepicker.loading = true + this.filepicker.filesClient = (OCA.Sharing && OCA.Sharing.PublicApp && OCA.Sharing.PublicApp.fileList) ? OCA.Sharing.PublicApp.fileList.filesClient : OC.Files.getClient() - this.filelist = null; - path = path || ''; + this.filelist = null + path = path || '' options = Object.assign({ allowDirectoryChooser: false }, options) - $.when(this._getFilePickerTemplate()).then(function ($tmpl) { - self.filepicker.loading = false; - var dialogName = 'oc-dialog-filepicker-content'; + $.when(this._getFilePickerTemplate()).then(function($tmpl) { + self.filepicker.loading = false + var dialogName = 'oc-dialog-filepicker-content' if (self.$filePicker) { - self.$filePicker.ocdialog('close'); + self.$filePicker.ocdialog('close') } if (mimetypeFilter === undefined || mimetypeFilter === null) { - mimetypeFilter = []; + mimetypeFilter = [] } - if (typeof (mimetypeFilter) === "string") { - mimetypeFilter = [mimetypeFilter]; + if (typeof (mimetypeFilter) === 'string') { + mimetypeFilter = [mimetypeFilter] } self.$filePicker = $tmpl.octemplate({ @@ -251,190 +255,190 @@ const Dialogs = { }).data('path', path).data('multiselect', multiselect).data('mimetype', mimetypeFilter).data('allowDirectoryChooser', options.allowDirectoryChooser) if (modal === undefined) { - modal = false; + modal = false } if (multiselect === undefined) { - multiselect = false; + multiselect = false } // No grid for IE! if (OC.Util.isIE()) { - self.$filePicker.find('#picker-view-toggle').remove(); - self.$filePicker.find('#picker-filestable').removeClass('view-grid'); + self.$filePicker.find('#picker-view-toggle').remove() + self.$filePicker.find('#picker-filestable').removeClass('view-grid') } - $('body').append(self.$filePicker); + $('body').append(self.$filePicker) - self.$showGridView = $('input#picker-showgridview'); - self.$showGridView.on('change', _.bind(self._onGridviewChange, self)); + self.$showGridView = $('input#picker-showgridview') + self.$showGridView.on('change', _.bind(self._onGridviewChange, self)) if (!OC.Util.isIE()) { - self._getGridSettings(); + self._getGridSettings() } - var newButton = self.$filePicker.find('.actions.creatable .button-add'); + var newButton = self.$filePicker.find('.actions.creatable .button-add') if (type === self.FILEPICKER_TYPE_CHOOSE) { - newButton.hide(); + newButton.hide() } - newButton.on('focus', function () { - self.$filePicker.ocdialog('setEnterCallback', function () { - event.stopImmediatePropagation(); - event.preventDefault(); - newButton.click(); - }); - }); - newButton.on('blur', function () { - self.$filePicker.ocdialog('unsetEnterCallback'); - }); - - OC.registerMenu(newButton, self.$filePicker.find('.menu'), function () { - $input.focus(); - self.$filePicker.ocdialog('setEnterCallback', function () { - event.stopImmediatePropagation(); - event.preventDefault(); - self.$form.submit(); - }); - var newName = $input.val(); - var lastPos = newName.lastIndexOf('.'); + newButton.on('focus', function() { + self.$filePicker.ocdialog('setEnterCallback', function() { + event.stopImmediatePropagation() + event.preventDefault() + newButton.click() + }) + }) + newButton.on('blur', function() { + self.$filePicker.ocdialog('unsetEnterCallback') + }) + + OC.registerMenu(newButton, self.$filePicker.find('.menu'), function() { + $input.focus() + self.$filePicker.ocdialog('setEnterCallback', function() { + event.stopImmediatePropagation() + event.preventDefault() + self.$form.submit() + }) + var newName = $input.val() + var lastPos = newName.lastIndexOf('.') if (lastPos === -1) { - lastPos = newName.length; + lastPos = newName.length } - $input.selectRange(0, lastPos); - }); - var $form = self.$filePicker.find('.filenameform'); - var $input = $form.find('input[type=\'text\']'); - var $submit = $form.find('input[type=\'submit\']'); - $submit.on('click', function (event) { - event.stopImmediatePropagation(); - event.preventDefault(); - $form.submit(); - }); - - var checkInput = function () { - var filename = $input.val(); + $input.selectRange(0, lastPos) + }) + var $form = self.$filePicker.find('.filenameform') + var $input = $form.find('input[type=\'text\']') + var $submit = $form.find('input[type=\'submit\']') + $submit.on('click', function(event) { + event.stopImmediatePropagation() + event.preventDefault() + $form.submit() + }) + + var checkInput = function() { + var filename = $input.val() try { if (!Files.isFileNameValid(filename)) { // Files.isFileNameValid(filename) throws an exception itself - } else if (self.filelist.find(function (file) { - return file.name === this; + } else if (self.filelist.find(function(file) { + return file.name === this }, filename)) { - throw t('files', '{newName} already exists', {newName: filename}, undefined, { + throw t('files', '{newName} already exists', { newName: filename }, undefined, { escape: false - }); + }) } else { - return true; + return true } } catch (error) { - $input.attr('title', error); + $input.attr('title', error) $input.tooltip({ placement: 'right', trigger: 'manual', 'container': '.newFolderMenu' - }); - $input.tooltip('fixTitle'); - $input.tooltip('show'); - $input.addClass('error'); + }) + $input.tooltip('fixTitle') + $input.tooltip('show') + $input.addClass('error') } - return false; - }; + return false + } - $form.on('submit', function (event) { - event.stopPropagation(); - event.preventDefault(); + $form.on('submit', function(event) { + event.stopPropagation() + event.preventDefault() if (checkInput()) { - var newname = $input.val(); + var newname = $input.val() self.filepicker.filesClient.createDirectory(self.$filePicker.data('path') + "/" + newname).always(function (status) { - self._fillFilePicker(self.$filePicker.data('path') + "/" + newname); - }); - OC.hideMenus(); - self.$filePicker.ocdialog('unsetEnterCallback'); - self.$filePicker.click(); - $input.val(newText); + self._fillFilePicker(self.$filePicker.data('path') + "/" + newname) + }) + OC.hideMenus() + self.$filePicker.ocdialog('unsetEnterCallback') + self.$filePicker.click() + $input.val(newText) } - }); - $input.keypress(function (event) { + }) + $input.keypress(function(event) { if (event.keyCode === 13 || event.which === 13) { - event.stopImmediatePropagation(); - event.preventDefault(); - $form.submit(); + event.stopImmediatePropagation() + event.preventDefault() + $form.submit() } - }); - - self.$filePicker.ready(function () { - self.$fileListHeader = self.$filePicker.find('.filelist thead tr'); - self.$filelist = self.$filePicker.find('.filelist tbody'); - self.$filelistContainer = self.$filePicker.find('.filelist-container'); - self.$dirTree = self.$filePicker.find('.dirtree'); - self.$dirTree.on('click', 'div:not(:last-child)', self, function (event) { - self._handleTreeListSelect(event, type); - }); - self.$filelist.on('click', 'tr', function (event) { - self._handlePickerClick(event, $(this), type); - }); - self.$fileListHeader.on('click', 'a', function (event) { - var dir = self.$filePicker.data('path'); - self.filepicker.sortField = $(event.currentTarget).data('sort'); - self.filepicker.sortOrder = self.filepicker.sortOrder === 'asc' ? 'desc' : 'asc'; - self._fillFilePicker(dir); - }); - self._fillFilePicker(path); - }); + }) + + self.$filePicker.ready(function() { + self.$fileListHeader = self.$filePicker.find('.filelist thead tr') + self.$filelist = self.$filePicker.find('.filelist tbody') + self.$filelistContainer = self.$filePicker.find('.filelist-container') + self.$dirTree = self.$filePicker.find('.dirtree') + self.$dirTree.on('click', 'div:not(:last-child)', self, function(event) { + self._handleTreeListSelect(event, type) + }) + self.$filelist.on('click', 'tr', function(event) { + self._handlePickerClick(event, $(this), type) + }) + self.$fileListHeader.on('click', 'a', function(event) { + var dir = self.$filePicker.data('path') + self.filepicker.sortField = $(event.currentTarget).data('sort') + self.filepicker.sortOrder = self.filepicker.sortOrder === 'asc' ? 'desc' : 'asc' + self._fillFilePicker(dir) + }) + self._fillFilePicker(path) + }) // build buttons - var functionToCall = function (returnType) { + var functionToCall = function(returnType) { if (callback !== undefined) { - var datapath; + var datapath if (multiselect === true) { - datapath = []; - self.$filelist.find('tr.filepicker_element_selected').each(function (index, element) { - datapath.push(self.$filePicker.data('path') + '/' + $(element).data('entryname')); - }); + datapath = [] + self.$filelist.find('tr.filepicker_element_selected').each(function(index, element) { + datapath.push(self.$filePicker.data('path') + '/' + $(element).data('entryname')) + }) } else { - datapath = self.$filePicker.data('path'); - var selectedName = self.$filelist.find('tr.filepicker_element_selected').data('entryname'); + datapath = self.$filePicker.data('path') + var selectedName = self.$filelist.find('tr.filepicker_element_selected').data('entryname') if (selectedName) { - datapath += '/' + selectedName; + datapath += '/' + selectedName } } - callback(datapath, returnType); - self.$filePicker.ocdialog('close'); + callback(datapath, returnType) + self.$filePicker.ocdialog('close') } - }; + } - var chooseCallback = function () { - functionToCall(Dialogs.FILEPICKER_TYPE_CHOOSE); - }; + var chooseCallback = function() { + functionToCall(Dialogs.FILEPICKER_TYPE_CHOOSE) + } - var copyCallback = function () { - functionToCall(Dialogs.FILEPICKER_TYPE_COPY); - }; + var copyCallback = function() { + functionToCall(Dialogs.FILEPICKER_TYPE_COPY) + } - var moveCallback = function () { - functionToCall(Dialogs.FILEPICKER_TYPE_MOVE); - }; + var moveCallback = function() { + functionToCall(Dialogs.FILEPICKER_TYPE_MOVE) + } - var buttonlist = []; + var buttonlist = [] if (type === Dialogs.FILEPICKER_TYPE_CHOOSE) { buttonlist.push({ text: t('core', 'Choose'), click: chooseCallback, defaultButton: true - }); + }) } else { if (type === Dialogs.FILEPICKER_TYPE_COPY || type === Dialogs.FILEPICKER_TYPE_COPY_MOVE) { buttonlist.push({ text: t('core', 'Copy'), click: copyCallback, defaultButton: false - }); + }) } if (type === Dialogs.FILEPICKER_TYPE_MOVE || type === Dialogs.FILEPICKER_TYPE_COPY_MOVE) { buttonlist.push({ text: t('core', 'Move'), click: moveCallback, defaultButton: true - }); + }) } } @@ -446,108 +450,108 @@ const Dialogs = { modal: modal, buttons: buttonlist, style: { - buttons: 'aside', + buttons: 'aside' }, - close: function () { + close: function() { try { - $(this).ocdialog('destroy').remove(); + $(this).ocdialog('destroy').remove() } catch (e) { } - self.$filePicker = null; + self.$filePicker = null } - }); + }) // We can access primary class only from oc-dialog. // Hence this is one of the approach to get the choose button. - var getOcDialog = self.$filePicker.closest('.oc-dialog'); - var buttonEnableDisable = getOcDialog.find('.primary'); - if (self.$filePicker.data('mimetype').indexOf("httpd/unix-directory") !== -1 && !self.$filePicker.data('.allowDirectoryChooser')) { - buttonEnableDisable.prop("disabled", false); + var getOcDialog = self.$filePicker.closest('.oc-dialog') + var buttonEnableDisable = getOcDialog.find('.primary') + if (self.$filePicker.data('mimetype').indexOf('httpd/unix-directory') !== -1 && !self.$filePicker.data('.allowDirectoryChooser')) { + buttonEnableDisable.prop('disabled', false) } else { - buttonEnableDisable.prop("disabled", true); + buttonEnableDisable.prop('disabled', true) } }) - .fail(function (status, error) { + .fail(function(status, error) { // If the method is called while navigating away // from the page, it is probably not needed ;) - self.filepicker.loading = false; + self.filepicker.loading = false if (status !== 0) { - alert(t('core', 'Error loading file picker template: {error}', {error: error})); + alert(t('core', 'Error loading file picker template: {error}', { error: error })) } - }); + }) }, /** * Displays raw dialog * You better use a wrapper instead ... */ - message: function (content, title, dialogType, buttons, callback, modal, allowHtml) { - return $.when(this._getMessageTemplate()).then(function ($tmpl) { - var dialogName = 'oc-dialog-' + Dialogs.dialogsCounter + '-content'; - var dialogId = '#' + dialogName; + message: function(content, title, dialogType, buttons, callback, modal, allowHtml) { + return $.when(this._getMessageTemplate()).then(function($tmpl) { + var dialogName = 'oc-dialog-' + Dialogs.dialogsCounter + '-content' + var dialogId = '#' + dialogName var $dlg = $tmpl.octemplate({ dialog_name: dialogName, title: title, message: content, type: dialogType - }, allowHtml ? {escapeFunction: ''} : {}); + }, allowHtml ? { escapeFunction: '' } : {}) if (modal === undefined) { - modal = false; + modal = false } - $('body').append($dlg); - var buttonlist = []; + $('body').append($dlg) + var buttonlist = [] switch (buttons) { - case Dialogs.YES_NO_BUTTONS: - buttonlist = [{ - text: t('core', 'No'), - click: function () { - if (callback !== undefined) { - callback(false); - } - $(dialogId).ocdialog('close'); + case Dialogs.YES_NO_BUTTONS: + buttonlist = [{ + text: t('core', 'No'), + click: function() { + if (callback !== undefined) { + callback(false) } - }, - { - text: t('core', 'Yes'), - click: function () { - if (callback !== undefined) { - callback(true); - } - $(dialogId).ocdialog('close'); - }, - defaultButton: true - }]; - break; - case Dialogs.OK_BUTTON: - var functionToCall = function () { - $(dialogId).ocdialog('close'); + $(dialogId).ocdialog('close') + } + }, + { + text: t('core', 'Yes'), + click: function() { if (callback !== undefined) { - callback(); + callback(true) } - }; - buttonlist[0] = { - text: t('core', 'OK'), - click: functionToCall, - defaultButton: true - }; - break; + $(dialogId).ocdialog('close') + }, + defaultButton: true + }] + break + case Dialogs.OK_BUTTON: + var functionToCall = function() { + $(dialogId).ocdialog('close') + if (callback !== undefined) { + callback() + } + } + buttonlist[0] = { + text: t('core', 'OK'), + click: functionToCall, + defaultButton: true + } + break } $(dialogId).ocdialog({ closeOnEscape: true, modal: modal, buttons: buttonlist - }); - Dialogs.dialogsCounter++; + }) + Dialogs.dialogsCounter++ }) - .fail(function (status, error) { + .fail(function(status, error) { // If the method is called while navigating away from // the page, we still want to deliver the message. if (status === 0) { - alert(title + ': ' + content); + alert(title + ': ' + content) } else { - alert(t('core', 'Error loading message template: {error}', {error: error})); + alert(t('core', 'Error loading message template: {error}', { error: error })) } - }); + }) }, _fileexistsshown: false, /** @@ -556,64 +560,64 @@ const Dialogs = { * @param {object} original file with name, size and mtime * @param {object} replacement file with name, size and mtime * @param {object} controller with onCancel, onSkip, onReplace and onRename methods - * @return {Promise} jquery promise that resolves after the dialog template was loaded + * @returns {Promise} jquery promise that resolves after the dialog template was loaded */ - fileexists: function (data, original, replacement, controller) { - var self = this; - var dialogDeferred = new $.Deferred(); + fileexists: function(data, original, replacement, controller) { + var self = this + var dialogDeferred = new $.Deferred() - var getCroppedPreview = function (file) { - var deferred = new $.Deferred(); + var getCroppedPreview = function(file) { + var deferred = new $.Deferred() // Only process image files. - var type = file.type && file.type.split('/').shift(); + var type = file.type && file.type.split('/').shift() if (window.FileReader && type === 'image') { - var reader = new FileReader(); - reader.onload = function (e) { - var blob = new Blob([e.target.result]); - window.URL = window.URL || window.webkitURL; - var originalUrl = window.URL.createObjectURL(blob); - var image = new Image(); - image.src = originalUrl; - image.onload = function () { - var url = crop(image); - deferred.resolve(url); - }; - }; - reader.readAsArrayBuffer(file); + var reader = new FileReader() + reader.onload = function(e) { + var blob = new Blob([e.target.result]) + window.URL = window.URL || window.webkitURL + var originalUrl = window.URL.createObjectURL(blob) + var image = new Image() + image.src = originalUrl + image.onload = function() { + var url = crop(image) + deferred.resolve(url) + } + } + reader.readAsArrayBuffer(file) } else { - deferred.reject(); + deferred.reject() } - return deferred; - }; + return deferred + } - var crop = function (img) { - var canvas = document.createElement('canvas'), - targetSize = 96, - width = img.width, - height = img.height, - x, y, size; + var crop = function(img) { + var canvas = document.createElement('canvas') + var targetSize = 96 + var width = img.width + var height = img.height + var x; var y; var size // Calculate the width and height, constraining the proportions if (width > height) { - y = 0; - x = (width - height) / 2; + y = 0 + x = (width - height) / 2 } else { - y = (height - width) / 2; - x = 0; + y = (height - width) / 2 + x = 0 } - size = Math.min(width, height); + size = Math.min(width, height) // Set canvas size to the cropped area - canvas.width = size; - canvas.height = size; - var ctx = canvas.getContext("2d"); - ctx.drawImage(img, x, y, size, size, 0, 0, size, size); + canvas.width = size + canvas.height = size + var ctx = canvas.getContext('2d') + ctx.drawImage(img, x, y, size, size, 0, 0, size, size) // Resize the canvas to match the destination (right size uses 96px) - resampleHermite(canvas, size, size, targetSize, targetSize); + resampleHermite(canvas, size, size, targetSize, targetSize) - return canvas.toDataURL("image/png", 0.7); - }; + return canvas.toDataURL('image/png', 0.7) + } /** * Fast image resize/resample using Hermite filter with JavaScript. @@ -626,130 +630,129 @@ const Dialogs = { * @param {number} W2 * @param {number} H2 */ - var resampleHermite = function (canvas, W, H, W2, H2) { - W2 = Math.round(W2); - H2 = Math.round(H2); - var img = canvas.getContext("2d").getImageData(0, 0, W, H); - var img2 = canvas.getContext("2d").getImageData(0, 0, W2, H2); - var data = img.data; - var data2 = img2.data; - var ratio_w = W / W2; - var ratio_h = H / H2; - var ratio_w_half = Math.ceil(ratio_w / 2); - var ratio_h_half = Math.ceil(ratio_h / 2); + var resampleHermite = function(canvas, W, H, W2, H2) { + W2 = Math.round(W2) + H2 = Math.round(H2) + var img = canvas.getContext('2d').getImageData(0, 0, W, H) + var img2 = canvas.getContext('2d').getImageData(0, 0, W2, H2) + var data = img.data + var data2 = img2.data + var ratio_w = W / W2 + var ratio_h = H / H2 + var ratio_w_half = Math.ceil(ratio_w / 2) + var ratio_h_half = Math.ceil(ratio_h / 2) for (var j = 0; j < H2; j++) { for (var i = 0; i < W2; i++) { - var x2 = (i + j * W2) * 4; - var weight = 0; - var weights = 0; - var weights_alpha = 0; - var gx_r = 0; - var gx_g = 0; - var gx_b = 0; - var gx_a = 0; - var center_y = (j + 0.5) * ratio_h; + var x2 = (i + j * W2) * 4 + var weight = 0 + var weights = 0 + var weights_alpha = 0 + var gx_r = 0 + var gx_g = 0 + var gx_b = 0 + var gx_a = 0 + var center_y = (j + 0.5) * ratio_h for (var yy = Math.floor(j * ratio_h); yy < (j + 1) * ratio_h; yy++) { - var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half; - var center_x = (i + 0.5) * ratio_w; - var w0 = dy * dy; //pre-calc part of w + var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half + var center_x = (i + 0.5) * ratio_w + var w0 = dy * dy // pre-calc part of w for (var xx = Math.floor(i * ratio_w); xx < (i + 1) * ratio_w; xx++) { - var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half; - var w = Math.sqrt(w0 + dx * dx); + var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half + var w = Math.sqrt(w0 + dx * dx) if (w >= -1 && w <= 1) { - //hermite filter - weight = 2 * w * w * w - 3 * w * w + 1; + // hermite filter + weight = 2 * w * w * w - 3 * w * w + 1 if (weight > 0) { - dx = 4 * (xx + yy * W); - //alpha - gx_a += weight * data[dx + 3]; - weights_alpha += weight; - //colors - if (data[dx + 3] < 255) - weight = weight * data[dx + 3] / 250; - gx_r += weight * data[dx]; - gx_g += weight * data[dx + 1]; - gx_b += weight * data[dx + 2]; - weights += weight; + dx = 4 * (xx + yy * W) + // alpha + gx_a += weight * data[dx + 3] + weights_alpha += weight + // colors + if (data[dx + 3] < 255) { weight = weight * data[dx + 3] / 250 } + gx_r += weight * data[dx] + gx_g += weight * data[dx + 1] + gx_b += weight * data[dx + 2] + weights += weight } } } } - data2[x2] = gx_r / weights; - data2[x2 + 1] = gx_g / weights; - data2[x2 + 2] = gx_b / weights; - data2[x2 + 3] = gx_a / weights_alpha; + data2[x2] = gx_r / weights + data2[x2 + 1] = gx_g / weights + data2[x2 + 2] = gx_b / weights + data2[x2 + 3] = gx_a / weights_alpha } } - canvas.getContext("2d").clearRect(0, 0, Math.max(W, W2), Math.max(H, H2)); - canvas.width = W2; - canvas.height = H2; - canvas.getContext("2d").putImageData(img2, 0, 0); - }; + canvas.getContext('2d').clearRect(0, 0, Math.max(W, W2), Math.max(H, H2)) + canvas.width = W2 + canvas.height = H2 + canvas.getContext('2d').putImageData(img2, 0, 0) + } - var addConflict = function ($conflicts, original, replacement) { + var addConflict = function($conflicts, original, replacement) { - var $conflict = $conflicts.find('.template').clone().removeClass('template').addClass('conflict'); - var $originalDiv = $conflict.find('.original'); - var $replacementDiv = $conflict.find('.replacement'); + var $conflict = $conflicts.find('.template').clone().removeClass('template').addClass('conflict') + var $originalDiv = $conflict.find('.original') + var $replacementDiv = $conflict.find('.replacement') - $conflict.data('data', data); + $conflict.data('data', data) - $conflict.find('.filename').text(original.name); - $originalDiv.find('.size').text(humanFileSize(original.size)); - $originalDiv.find('.mtime').text(formatDate(original.mtime)); + $conflict.find('.filename').text(original.name) + $originalDiv.find('.size').text(humanFileSize(original.size)) + $originalDiv.find('.mtime').text(formatDate(original.mtime)) // ie sucks if (replacement.size && replacement.lastModifiedDate) { - $replacementDiv.find('.size').text(humanFileSize(replacement.size)); - $replacementDiv.find('.mtime').text(formatDate(replacement.lastModifiedDate)); + $replacementDiv.find('.size').text(humanFileSize(replacement.size)) + $replacementDiv.find('.mtime').text(formatDate(replacement.lastModifiedDate)) } - var path = original.directory + '/' + original.name; + var path = original.directory + '/' + original.name var urlSpec = { file: path, x: 96, y: 96, c: original.etag, forceIcon: 0 - }; - var previewpath = Files.generatePreviewUrl(urlSpec); + } + var previewpath = Files.generatePreviewUrl(urlSpec) // Escaping single quotes - previewpath = previewpath.replace(/'/g, "%27"); - $originalDiv.find('.icon').css({"background-image": "url('" + previewpath + "')"}); + previewpath = previewpath.replace(/'/g, '%27') + $originalDiv.find('.icon').css({ 'background-image': "url('" + previewpath + "')" }) getCroppedPreview(replacement).then( - function (path) { - $replacementDiv.find('.icon').css('background-image', 'url(' + path + ')'); - }, function () { - path = OC.MimeType.getIconUrl(replacement.type); - $replacementDiv.find('.icon').css('background-image', 'url(' + path + ')'); + function(path) { + $replacementDiv.find('.icon').css('background-image', 'url(' + path + ')') + }, function() { + path = OC.MimeType.getIconUrl(replacement.type) + $replacementDiv.find('.icon').css('background-image', 'url(' + path + ')') } - ); + ) // connect checkboxes with labels - var checkboxId = $conflicts.find('.conflict').length; - $originalDiv.find('input:checkbox').attr('id', 'checkbox_original_' + checkboxId); - $replacementDiv.find('input:checkbox').attr('id', 'checkbox_replacement_' + checkboxId); + var checkboxId = $conflicts.find('.conflict').length + $originalDiv.find('input:checkbox').attr('id', 'checkbox_original_' + checkboxId) + $replacementDiv.find('input:checkbox').attr('id', 'checkbox_replacement_' + checkboxId) - $conflicts.append($conflict); + $conflicts.append($conflict) - //set more recent mtime bold + // set more recent mtime bold // ie sucks if (replacement.lastModifiedDate && replacement.lastModifiedDate.getTime() > original.mtime) { - $replacementDiv.find('.mtime').css('font-weight', 'bold'); + $replacementDiv.find('.mtime').css('font-weight', 'bold') } else if (replacement.lastModifiedDate && replacement.lastModifiedDate.getTime() < original.mtime) { - $originalDiv.find('.mtime').css('font-weight', 'bold'); + $originalDiv.find('.mtime').css('font-weight', 'bold') } else { - //TODO add to same mtime collection? + // TODO add to same mtime collection? } // set bigger size bold if (replacement.size && replacement.size > original.size) { - $replacementDiv.find('.size').css('font-weight', 'bold'); + $replacementDiv.find('.size').css('font-weight', 'bold') } else if (replacement.size && replacement.size < original.size) { - $originalDiv.find('.size').css('font-weight', 'bold'); + $originalDiv.find('.size').css('font-weight', 'bold') } else { - //TODO add to same size collection? + // TODO add to same size collection? } - //TODO show skip action for files with same size and mtime in bottom row + // TODO show skip action for files with same size and mtime in bottom row // always keep readonly files @@ -758,40 +761,40 @@ const Dialogs = { .addClass('readonly') .find('input[type="checkbox"]') .prop('checked', true) - .prop('disabled', true); + .prop('disabled', true) $originalDiv.find('.message') - .text(t('core', 'read-only')); + .text(t('core', 'read-only')) } - }; - //var selection = controller.getSelection(data.originalFiles); - //if (selection.defaultAction) { + } + // var selection = controller.getSelection(data.originalFiles); + // if (selection.defaultAction) { // controller[selection.defaultAction](data); - //} else { - var dialogName = 'oc-dialog-fileexists-content'; - var dialogId = '#' + dialogName; + // } else { + var dialogName = 'oc-dialog-fileexists-content' + var dialogId = '#' + dialogName if (this._fileexistsshown) { // add conflict - var $conflicts = $(dialogId + ' .conflicts'); - addConflict($conflicts, original, replacement); + var $conflicts = $(dialogId + ' .conflicts') + addConflict($conflicts, original, replacement) - var count = $(dialogId + ' .conflict').length; + var count = $(dialogId + ' .conflict').length var title = n('core', '{count} file conflict', '{count} file conflicts', count, - {count: count} - ); - $(dialogId).parent().children('.oc-dialog-title').text(title); + { count: count } + ) + $(dialogId).parent().children('.oc-dialog-title').text(title) - //recalculate dimensions - $(window).trigger('resize'); - dialogDeferred.resolve(); + // recalculate dimensions + $(window).trigger('resize') + dialogDeferred.resolve() } else { - //create dialog - this._fileexistsshown = true; - $.when(this._getFileExistsTemplate()).then(function ($tmpl) { - var title = t('core', 'One file conflict'); + // create dialog + this._fileexistsshown = true + $.when(this._getFileExistsTemplate()).then(function($tmpl) { + var title = t('core', 'One file conflict') var $dlg = $tmpl.octemplate({ dialog_name: dialogName, title: title, @@ -802,34 +805,34 @@ const Dialogs = { why: t('core', 'Which files do you want to keep?'), what: t('core', 'If you select both versions, the copied file will have a number added to its name.') - }); - $('body').append($dlg); + }) + $('body').append($dlg) if (original && replacement) { - var $conflicts = $dlg.find('.conflicts'); - addConflict($conflicts, original, replacement); + var $conflicts = $dlg.find('.conflicts') + addConflict($conflicts, original, replacement) } var buttonlist = [{ text: t('core', 'Cancel'), classes: 'cancel', - click: function () { + click: function() { if (typeof controller.onCancel !== 'undefined') { - controller.onCancel(data); + controller.onCancel(data) } - $(dialogId).ocdialog('close'); + $(dialogId).ocdialog('close') } }, - { - text: t('core', 'Continue'), - classes: 'continue', - click: function () { - if (typeof controller.onContinue !== 'undefined') { - controller.onContinue($(dialogId + ' .conflict')); - } - $(dialogId).ocdialog('close'); + { + text: t('core', 'Continue'), + classes: 'continue', + click: function() { + if (typeof controller.onContinue !== 'undefined') { + controller.onContinue($(dialogId + ' .conflict')) } - }]; + $(dialogId).ocdialog('close') + } + }] $(dialogId).ocdialog({ width: 500, @@ -837,157 +840,157 @@ const Dialogs = { modal: true, buttons: buttonlist, closeButton: null, - close: function () { - self._fileexistsshown = false; - $(this).ocdialog('destroy').remove(); + close: function() { + self._fileexistsshown = false + $(this).ocdialog('destroy').remove() } - }); + }) - $(dialogId).css('height', 'auto'); + $(dialogId).css('height', 'auto') - var $primaryButton = $dlg.closest('.oc-dialog').find('button.continue'); - $primaryButton.prop('disabled', true); + var $primaryButton = $dlg.closest('.oc-dialog').find('button.continue') + $primaryButton.prop('disabled', true) - function updatePrimaryButton () { - var checkedCount = $dlg.find('.conflicts .checkbox:checked').length; - $primaryButton.prop('disabled', checkedCount === 0); + function updatePrimaryButton() { + var checkedCount = $dlg.find('.conflicts .checkbox:checked').length + $primaryButton.prop('disabled', checkedCount === 0) } - //add checkbox toggling actions - $(dialogId).find('.allnewfiles').on('click', function () { - var $checkboxes = $(dialogId).find('.conflict .replacement input[type="checkbox"]'); - $checkboxes.prop('checked', $(this).prop('checked')); - }); - $(dialogId).find('.allexistingfiles').on('click', function () { - var $checkboxes = $(dialogId).find('.conflict .original:not(.readonly) input[type="checkbox"]'); - $checkboxes.prop('checked', $(this).prop('checked')); - }); - $(dialogId).find('.conflicts').on('click', '.replacement,.original:not(.readonly)', function () { - var $checkbox = $(this).find('input[type="checkbox"]'); - $checkbox.prop('checked', !$checkbox.prop('checked')); - }); - $(dialogId).find('.conflicts').on('click', '.replacement input[type="checkbox"],.original:not(.readonly) input[type="checkbox"]', function () { - var $checkbox = $(this); - $checkbox.prop('checked', !$checkbox.prop('checked')); - }); - - //update counters - $(dialogId).on('click', '.replacement,.allnewfiles', function () { - var count = $(dialogId).find('.conflict .replacement input[type="checkbox"]:checked').length; + // add checkbox toggling actions + $(dialogId).find('.allnewfiles').on('click', function() { + var $checkboxes = $(dialogId).find('.conflict .replacement input[type="checkbox"]') + $checkboxes.prop('checked', $(this).prop('checked')) + }) + $(dialogId).find('.allexistingfiles').on('click', function() { + var $checkboxes = $(dialogId).find('.conflict .original:not(.readonly) input[type="checkbox"]') + $checkboxes.prop('checked', $(this).prop('checked')) + }) + $(dialogId).find('.conflicts').on('click', '.replacement,.original:not(.readonly)', function() { + var $checkbox = $(this).find('input[type="checkbox"]') + $checkbox.prop('checked', !$checkbox.prop('checked')) + }) + $(dialogId).find('.conflicts').on('click', '.replacement input[type="checkbox"],.original:not(.readonly) input[type="checkbox"]', function() { + var $checkbox = $(this) + $checkbox.prop('checked', !$checkbox.prop('checked')) + }) + + // update counters + $(dialogId).on('click', '.replacement,.allnewfiles', function() { + var count = $(dialogId).find('.conflict .replacement input[type="checkbox"]:checked').length if (count === $(dialogId + ' .conflict').length) { - $(dialogId).find('.allnewfiles').prop('checked', true); - $(dialogId).find('.allnewfiles + .count').text(t('core', '(all selected)')); + $(dialogId).find('.allnewfiles').prop('checked', true) + $(dialogId).find('.allnewfiles + .count').text(t('core', '(all selected)')) } else if (count > 0) { - $(dialogId).find('.allnewfiles').prop('checked', false); - $(dialogId).find('.allnewfiles + .count').text(t('core', '({count} selected)', {count: count})); + $(dialogId).find('.allnewfiles').prop('checked', false) + $(dialogId).find('.allnewfiles + .count').text(t('core', '({count} selected)', { count: count })) } else { - $(dialogId).find('.allnewfiles').prop('checked', false); - $(dialogId).find('.allnewfiles + .count').text(''); + $(dialogId).find('.allnewfiles').prop('checked', false) + $(dialogId).find('.allnewfiles + .count').text('') } - updatePrimaryButton(); - }); - $(dialogId).on('click', '.original,.allexistingfiles', function () { - var count = $(dialogId).find('.conflict .original input[type="checkbox"]:checked').length; + updatePrimaryButton() + }) + $(dialogId).on('click', '.original,.allexistingfiles', function() { + var count = $(dialogId).find('.conflict .original input[type="checkbox"]:checked').length if (count === $(dialogId + ' .conflict').length) { - $(dialogId).find('.allexistingfiles').prop('checked', true); - $(dialogId).find('.allexistingfiles + .count').text(t('core', '(all selected)')); + $(dialogId).find('.allexistingfiles').prop('checked', true) + $(dialogId).find('.allexistingfiles + .count').text(t('core', '(all selected)')) } else if (count > 0) { - $(dialogId).find('.allexistingfiles').prop('checked', false); + $(dialogId).find('.allexistingfiles').prop('checked', false) $(dialogId).find('.allexistingfiles + .count') - .text(t('core', '({count} selected)', {count: count})); + .text(t('core', '({count} selected)', { count: count })) } else { - $(dialogId).find('.allexistingfiles').prop('checked', false); - $(dialogId).find('.allexistingfiles + .count').text(''); + $(dialogId).find('.allexistingfiles').prop('checked', false) + $(dialogId).find('.allexistingfiles + .count').text('') } - updatePrimaryButton(); - }); + updatePrimaryButton() + }) - dialogDeferred.resolve(); + dialogDeferred.resolve() }) - .fail(function () { - dialogDeferred.reject(); - alert(t('core', 'Error loading file exists template')); - }); + .fail(function() { + dialogDeferred.reject() + alert(t('core', 'Error loading file exists template')) + }) } - //} - return dialogDeferred.promise(); + // } + return dialogDeferred.promise() }, // get the gridview setting and set the input accordingly - _getGridSettings: function () { - var self = this; - $.get(OC.generateUrl('/apps/files/api/v1/showgridview'), function (response) { - self.$showGridView.get(0).checked = response.gridview; + _getGridSettings: function() { + var self = this + $.get(OC.generateUrl('/apps/files/api/v1/showgridview'), function(response) { + self.$showGridView.get(0).checked = response.gridview self.$showGridView.next('#picker-view-toggle') .removeClass('icon-toggle-filelist icon-toggle-pictures') .addClass(response.gridview ? 'icon-toggle-filelist' : 'icon-toggle-pictures') - $('.list-container').toggleClass('view-grid', response.gridview); - }); + $('.list-container').toggleClass('view-grid', response.gridview) + }) }, - _onGridviewChange: function () { - var show = this.$showGridView.is(':checked'); + _onGridviewChange: function() { + var show = this.$showGridView.is(':checked') // only save state if user is logged in if (OC.currentUser) { $.post(OC.generateUrl('/apps/files/api/v1/showgridview'), { show: show - }); + }) } this.$showGridView.next('#picker-view-toggle') .removeClass('icon-toggle-filelist icon-toggle-pictures') .addClass(show ? 'icon-toggle-filelist' : 'icon-toggle-pictures') - $('.list-container').toggleClass('view-grid', show); + $('.list-container').toggleClass('view-grid', show) }, - _getFilePickerTemplate: function () { - var defer = $.Deferred(); + _getFilePickerTemplate: function() { + var defer = $.Deferred() if (!this.$filePickerTemplate) { - var self = this; - $.get(OC.filePath('core', 'templates', 'filepicker.html'), function (tmpl) { - self.$filePickerTemplate = $(tmpl); - self.$listTmpl = self.$filePickerTemplate.find('.filelist tbody tr:first-child').detach(); - defer.resolve(self.$filePickerTemplate); + var self = this + $.get(OC.filePath('core', 'templates', 'filepicker.html'), function(tmpl) { + self.$filePickerTemplate = $(tmpl) + self.$listTmpl = self.$filePickerTemplate.find('.filelist tbody tr:first-child').detach() + defer.resolve(self.$filePickerTemplate) }) - .fail(function (jqXHR, textStatus, errorThrown) { - defer.reject(jqXHR.status, errorThrown); - }); + .fail(function(jqXHR, textStatus, errorThrown) { + defer.reject(jqXHR.status, errorThrown) + }) } else { - defer.resolve(this.$filePickerTemplate); + defer.resolve(this.$filePickerTemplate) } - return defer.promise(); + return defer.promise() }, - _getMessageTemplate: function () { - var defer = $.Deferred(); + _getMessageTemplate: function() { + var defer = $.Deferred() if (!this.$messageTemplate) { - var self = this; - $.get(OC.filePath('core', 'templates', 'message.html'), function (tmpl) { - self.$messageTemplate = $(tmpl); - defer.resolve(self.$messageTemplate); + var self = this + $.get(OC.filePath('core', 'templates', 'message.html'), function(tmpl) { + self.$messageTemplate = $(tmpl) + defer.resolve(self.$messageTemplate) }) - .fail(function (jqXHR, textStatus, errorThrown) { - defer.reject(jqXHR.status, errorThrown); - }); + .fail(function(jqXHR, textStatus, errorThrown) { + defer.reject(jqXHR.status, errorThrown) + }) } else { - defer.resolve(this.$messageTemplate); + defer.resolve(this.$messageTemplate) } - return defer.promise(); + return defer.promise() }, - _getFileExistsTemplate: function () { - var defer = $.Deferred(); + _getFileExistsTemplate: function() { + var defer = $.Deferred() if (!this.$fileexistsTemplate) { - var self = this; - $.get(OC.filePath('files', 'templates', 'fileexists.html'), function (tmpl) { - self.$fileexistsTemplate = $(tmpl); - defer.resolve(self.$fileexistsTemplate); + var self = this + $.get(OC.filePath('files', 'templates', 'fileexists.html'), function(tmpl) { + self.$fileexistsTemplate = $(tmpl) + defer.resolve(self.$fileexistsTemplate) }) - .fail(function () { - defer.reject(); - }); + .fail(function() { + defer.reject() + }) } else { - defer.resolve(this.$fileexistsTemplate); + defer.resolve(this.$fileexistsTemplate) } - return defer.promise(); + return defer.promise() }, - _getFileList: function (dir, mimeType) { //this is only used by the spreedme app atm - if (typeof (mimeType) === "string") { - mimeType = [mimeType]; + _getFileList: function(dir, mimeType) { // this is only used by the spreedme app atm + if (typeof (mimeType) === 'string') { + mimeType = [mimeType] } return $.getJSON( @@ -996,88 +999,88 @@ const Dialogs = { dir: dir, mimetypes: JSON.stringify(mimeType) } - ); + ) }, /** * fills the filepicker with files */ - _fillFilePicker: function (dir) { - var self = this; - this.$filelist.empty(); - this.$filePicker.find('.emptycontent').hide(); - this.$filelistContainer.addClass('icon-loading'); - this.$filePicker.data('path', dir); - var filter = this.$filePicker.data('mimetype'); - if (typeof (filter) === "string") { - filter = [filter]; + _fillFilePicker: function(dir) { + var self = this + this.$filelist.empty() + this.$filePicker.find('.emptycontent').hide() + this.$filelistContainer.addClass('icon-loading') + this.$filePicker.data('path', dir) + var filter = this.$filePicker.data('mimetype') + if (typeof (filter) === 'string') { + filter = [filter] } - self.$fileListHeader.find('.sort-indicator').addClass('hidden').removeClass('icon-triangle-n').removeClass('icon-triangle-s'); - self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').removeClass('hidden'); + self.$fileListHeader.find('.sort-indicator').addClass('hidden').removeClass('icon-triangle-n').removeClass('icon-triangle-s') + self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').removeClass('hidden') if (self.filepicker.sortOrder === 'asc') { - self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').addClass('icon-triangle-n'); + self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').addClass('icon-triangle-n') } else { - self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').addClass('icon-triangle-s'); + self.$fileListHeader.find('[data-sort=' + self.filepicker.sortField + '] .sort-indicator').addClass('icon-triangle-s') } - self.filepicker.filesClient.getFolderContents(dir).then(function (status, files) { - self.filelist = files; + self.filepicker.filesClient.getFolderContents(dir).then(function(status, files) { + self.filelist = files if (filter && filter.length > 0 && filter.indexOf('*') === -1) { - files = files.filter(function (file) { - return file.type === 'dir' || filter.indexOf(file.mimetype) !== -1; - }); + files = files.filter(function(file) { + return file.type === 'dir' || filter.indexOf(file.mimetype) !== -1 + }) } var Comparators = { - name: function (fileInfo1, fileInfo2) { + name: function(fileInfo1, fileInfo2) { if (fileInfo1.type === 'dir' && fileInfo2.type !== 'dir') { - return -1; + return -1 } if (fileInfo1.type !== 'dir' && fileInfo2.type === 'dir') { - return 1; + return 1 } - return OC.Util.naturalSortCompare(fileInfo1.name, fileInfo2.name); + return OC.Util.naturalSortCompare(fileInfo1.name, fileInfo2.name) }, - size: function (fileInfo1, fileInfo2) { - return fileInfo1.size - fileInfo2.size; + size: function(fileInfo1, fileInfo2) { + return fileInfo1.size - fileInfo2.size }, - mtime: function (fileInfo1, fileInfo2) { - return fileInfo1.mtime - fileInfo2.mtime; + mtime: function(fileInfo1, fileInfo2) { + return fileInfo1.mtime - fileInfo2.mtime + } + } + var comparator = Comparators[self.filepicker.sortField] || Comparators.name + files = files.sort(function(file1, file2) { + var isFavorite = function(fileInfo) { + return fileInfo.tags && fileInfo.tags.indexOf(OC.TAG_FAVORITE) >= 0 } - }; - var comparator = Comparators[self.filepicker.sortField] || Comparators.name; - files = files.sort(function (file1, file2) { - var isFavorite = function (fileInfo) { - return fileInfo.tags && fileInfo.tags.indexOf(OC.TAG_FAVORITE) >= 0; - }; if (isFavorite(file1) && !isFavorite(file2)) { - return -1; + return -1 } else if (!isFavorite(file1) && isFavorite(file2)) { - return 1; + return 1 } - return self.filepicker.sortOrder === 'asc' ? comparator(file1, file2) : -comparator(file1, file2); - }); + return self.filepicker.sortOrder === 'asc' ? comparator(file1, file2) : -comparator(file1, file2) + }) - self._fillSlug(); + self._fillSlug() if (files.length === 0) { - self.$filePicker.find('.emptycontent').show(); - self.$fileListHeader.hide(); + self.$filePicker.find('.emptycontent').show() + self.$fileListHeader.hide() } else { - self.$filePicker.find('.emptycontent').hide(); - self.$fileListHeader.show(); + self.$filePicker.find('.emptycontent').hide() + self.$fileListHeader.show() } - $.each(files, function (idx, entry) { - entry.icon = OC.MimeType.getIconUrl(entry.mimetype); - var simpleSize, sizeColor; + $.each(files, function(idx, entry) { + entry.icon = OC.MimeType.getIconUrl(entry.mimetype) + var simpleSize, sizeColor if (typeof (entry.size) !== 'undefined' && entry.size >= 0) { - simpleSize = humanFileSize(parseInt(entry.size, 10), true); - sizeColor = Math.round(160 - Math.pow((entry.size / (1024 * 1024)), 2)); + simpleSize = humanFileSize(parseInt(entry.size, 10), true) + sizeColor = Math.round(160 - Math.pow((entry.size / (1024 * 1024)), 2)) } else { - simpleSize = t('files', 'Pending'); - sizeColor = 80; + simpleSize = t('files', 'Pending') + sizeColor = 80 } // split the filename in half if the size is bigger than 20 char @@ -1102,90 +1105,90 @@ const Dialogs = { size: simpleSize, sizeColor: sizeColor, icon: entry.icon - }); + }) if (entry.type === 'file') { var urlSpec = { file: dir + '/' + entry.name, x: 100, y: 100 - }; - var img = new Image(); - var previewUrl = OC.generateUrl('/core/preview.png?') + $.param(urlSpec); - img.onload = function () { + } + var img = new Image() + var previewUrl = OC.generateUrl('/core/preview.png?') + $.param(urlSpec) + img.onload = function() { if (img.width > 5) { - $row.find('td.filename').attr('style', 'background-image:url(' + previewUrl + ')'); + $row.find('td.filename').attr('style', 'background-image:url(' + previewUrl + ')') } - }; - img.src = previewUrl; + } + img.src = previewUrl } - self.$filelist.append($row); - }); + self.$filelist.append($row) + }) - self.$filelistContainer.removeClass('icon-loading'); - }); + self.$filelistContainer.removeClass('icon-loading') + }) }, /** * fills the tree list with directories */ - _fillSlug: function () { - this.$dirTree.empty(); - var self = this; - var dir; - var path = this.$filePicker.data('path'); - var $template = $('<div data-dir="{dir}"><a>{name}</a></div>').addClass('crumb'); + _fillSlug: function() { + this.$dirTree.empty() + var self = this + var dir + var path = this.$filePicker.data('path') + var $template = $('<div data-dir="{dir}"><a>{name}</a></div>').addClass('crumb') if (path) { - var paths = path.split('/'); - $.each(paths, function (index, dir) { - dir = paths.pop(); + var paths = path.split('/') + $.each(paths, function(index, dir) { + dir = paths.pop() if (dir === '') { - return false; + return false } self.$dirTree.prepend($template.octemplate({ dir: paths.join('/') + '/' + dir, name: dir - })); - }); + })) + }) } $template.octemplate({ dir: '', name: '' // Ugly but works ;) - }, {escapeFunction: null}).prependTo(this.$dirTree); + }, { escapeFunction: null }).prependTo(this.$dirTree) }, /** * handle selection made in the tree list */ - _handleTreeListSelect: function (event, type) { - var self = event.data; - var dir = $(event.target).closest('.crumb').data('dir'); - self._fillFilePicker(dir); - var getOcDialog = (event.target).closest('.oc-dialog'); - var buttonEnableDisable = $('.primary', getOcDialog); - this._changeButtonsText(type, dir.split(/[/]+/).pop()); - if (this.$filePicker.data('mimetype').indexOf("httpd/unix-directory") !== -1) { - buttonEnableDisable.prop("disabled", false); + _handleTreeListSelect: function(event, type) { + var self = event.data + var dir = $(event.target).closest('.crumb').data('dir') + self._fillFilePicker(dir) + var getOcDialog = (event.target).closest('.oc-dialog') + var buttonEnableDisable = $('.primary', getOcDialog) + this._changeButtonsText(type, dir.split(/[/]+/).pop()) + if (this.$filePicker.data('mimetype').indexOf('httpd/unix-directory') !== -1) { + buttonEnableDisable.prop('disabled', false) } else { - buttonEnableDisable.prop("disabled", true); + buttonEnableDisable.prop('disabled', true) } }, /** * handle clicks made in the filepicker */ - _handlePickerClick: function (event, $element, type) { - var getOcDialog = this.$filePicker.closest('.oc-dialog'); - var buttonEnableDisable = getOcDialog.find('.primary'); + _handlePickerClick: function(event, $element, type) { + var getOcDialog = this.$filePicker.closest('.oc-dialog') + var buttonEnableDisable = getOcDialog.find('.primary') if ($element.data('type') === 'file') { if (this.$filePicker.data('multiselect') !== true || !event.ctrlKey) { - this.$filelist.find('.filepicker_element_selected').removeClass('filepicker_element_selected'); + this.$filelist.find('.filepicker_element_selected').removeClass('filepicker_element_selected') } - $element.toggleClass('filepicker_element_selected'); - buttonEnableDisable.prop("disabled", false); + $element.toggleClass('filepicker_element_selected') + buttonEnableDisable.prop('disabled', false) } else if ($element.data('type') === 'dir') { - this._fillFilePicker(this.$filePicker.data('path') + '/' + $element.data('entryname')); - this._changeButtonsText(type, $element.data('entryname')); - if (this.$filePicker.data('mimetype').indexOf("httpd/unix-directory") !== -1 || this.$filePicker.data('allowDirectoryChooser')) { - buttonEnableDisable.prop("disabled", false); + this._fillFilePicker(this.$filePicker.data('path') + '/' + $element.data('entryname')) + this._changeButtonsText(type, $element.data('entryname')) + if (this.$filePicker.data('mimetype').indexOf('httpd/unix-directory') !== -1 || this.$filePicker.data('allowDirectoryChooser')) { + buttonEnableDisable.prop('disabled', false) } else { - buttonEnableDisable.prop("disabled", true); + buttonEnableDisable.prop('disabled', true) } } }, @@ -1196,23 +1199,23 @@ const Dialogs = { * @param dir on which to change buttons text * @private */ - _changeButtonsText: function (type, dir) { - var copyText = dir === '' ? t('core', 'Copy') : t('core', 'Copy to {folder}', {folder: dir}); - var moveText = dir === '' ? t('core', 'Move') : t('core', 'Move to {folder}', {folder: dir}); - var buttons = $('.oc-dialog-buttonrow button'); + _changeButtonsText: function(type, dir) { + var copyText = dir === '' ? t('core', 'Copy') : t('core', 'Copy to {folder}', { folder: dir }) + var moveText = dir === '' ? t('core', 'Move') : t('core', 'Move to {folder}', { folder: dir }) + var buttons = $('.oc-dialog-buttonrow button') switch (type) { - case this.FILEPICKER_TYPE_CHOOSE: - break; - case this.FILEPICKER_TYPE_COPY: - buttons.text(copyText); - break; - case this.FILEPICKER_TYPE_MOVE: - buttons.text(moveText); - break; - case this.FILEPICKER_TYPE_COPY_MOVE: - buttons.eq(0).text(copyText); - buttons.eq(1).text(moveText); - break; + case this.FILEPICKER_TYPE_CHOOSE: + break + case this.FILEPICKER_TYPE_COPY: + buttons.text(copyText) + break + case this.FILEPICKER_TYPE_MOVE: + buttons.text(moveText) + break + case this.FILEPICKER_TYPE_COPY_MOVE: + buttons.eq(0).text(copyText) + buttons.eq(1).text(moveText) + break } } } diff --git a/core/src/OC/eventsource.js b/core/src/OC/eventsource.js index ec70e665014..cc576d8655a 100644 --- a/core/src/OC/eventsource.js +++ b/core/src/OC/eventsource.js @@ -1,3 +1,4 @@ +/* eslint-disable */ /** * ownCloud * @@ -32,7 +33,7 @@ import $ from 'jquery' -import {getToken} from './requesttoken' +import { getToken } from './requesttoken' /** * Create a new event source @@ -41,62 +42,62 @@ import {getToken} from './requesttoken' * * @constructs OCEventSource */ -const OCEventSource = function (src, data) { - var dataStr = ''; - var name; - var joinChar; - this.typelessListeners = []; - this.closed = false; - this.listeners = {}; +const OCEventSource = function(src, data) { + var dataStr = '' + var name + var joinChar + this.typelessListeners = [] + this.closed = false + this.listeners = {} if (data) { for (name in data) { - dataStr += name + '=' + encodeURIComponent(data[name]) + '&'; + dataStr += name + '=' + encodeURIComponent(data[name]) + '&' } } - dataStr += 'requesttoken=' + encodeURIComponent(getToken()); + dataStr += 'requesttoken=' + encodeURIComponent(getToken()) if (!this.useFallBack && typeof EventSource !== 'undefined') { - joinChar = '&'; + joinChar = '&' if (src.indexOf('?') === -1) { - joinChar = '?'; + joinChar = '?' } - this.source = new EventSource(src + joinChar + dataStr); - this.source.onmessage = function (e) { + this.source = new EventSource(src + joinChar + dataStr) + this.source.onmessage = function(e) { for (var i = 0; i < this.typelessListeners.length; i++) { - this.typelessListeners[i](JSON.parse(e.data)); + this.typelessListeners[i](JSON.parse(e.data)) } - }.bind(this); + }.bind(this) } else { - var iframeId = 'oc_eventsource_iframe_' + OCEventSource.iframeCount; - OCEventSource.fallBackSources[OCEventSource.iframeCount] = this; - this.iframe = $('<iframe/>'); - this.iframe.attr('id', iframeId); - this.iframe.hide(); + var iframeId = 'oc_eventsource_iframe_' + OCEventSource.iframeCount + OCEventSource.fallBackSources[OCEventSource.iframeCount] = this + this.iframe = $('<iframe/>') + this.iframe.attr('id', iframeId) + this.iframe.hide() - joinChar = '&'; + joinChar = '&' if (src.indexOf('?') === -1) { - joinChar = '?'; + joinChar = '?' } - this.iframe.attr('src', src + joinChar + 'fallback=true&fallback_id=' + OCEventSource.iframeCount + '&' + dataStr); - $('body').append(this.iframe); - this.useFallBack = true; - OCEventSource.iframeCount++; + this.iframe.attr('src', src + joinChar + 'fallback=true&fallback_id=' + OCEventSource.iframeCount + '&' + dataStr) + $('body').append(this.iframe) + this.useFallBack = true + OCEventSource.iframeCount++ } - //add close listener - this.listen('__internal__', function (data) { + // add close listener + this.listen('__internal__', function(data) { if (data === 'close') { - this.close(); + this.close() } - }.bind(this)); -}; -OCEventSource.fallBackSources = []; -OCEventSource.iframeCount = 0;//number of fallback iframes -OCEventSource.fallBackCallBack = function (id, type, data) { - OCEventSource.fallBackSources[id].fallBackCallBack(type, data); -}; + }.bind(this)) +} +OCEventSource.fallBackSources = [] +OCEventSource.iframeCount = 0// number of fallback iframes +OCEventSource.fallBackCallBack = function(id, type, data) { + OCEventSource.fallBackSources[id].fallBackCallBack(type, data) +} OCEventSource.prototype = { typelessListeners: [], iframe: null, - listeners: {},//only for fallback + listeners: {}, // only for fallback useFallBack: false, /** * Fallback callback for browsers that don't have the @@ -108,63 +109,63 @@ OCEventSource.prototype = { * @param {String} type event type * @param {Object} data received data */ - fallBackCallBack: function (type, data) { - var i; + fallBackCallBack: function(type, data) { + var i // ignore messages that might appear after closing if (this.closed) { - return; + return } if (type) { if (typeof this.listeners.done !== 'undefined') { for (i = 0; i < this.listeners[type].length; i++) { - this.listeners[type][i](data); + this.listeners[type][i](data) } } } else { for (i = 0; i < this.typelessListeners.length; i++) { - this.typelessListeners[i](data); + this.typelessListeners[i](data) } } }, - lastLength: 0,//for fallback + lastLength: 0, // for fallback /** * Listen to a given type of events. * * @param {String} type event type * @param {Function} callback event callback */ - listen: function (type, callback) { + listen: function(type, callback) { if (callback && callback.call) { if (type) { if (this.useFallBack) { if (!this.listeners[type]) { - this.listeners[type] = []; + this.listeners[type] = [] } - this.listeners[type].push(callback); + this.listeners[type].push(callback) } else { - this.source.addEventListener(type, function (e) { + this.source.addEventListener(type, function(e) { if (typeof e.data !== 'undefined') { - callback(JSON.parse(e.data)); + callback(JSON.parse(e.data)) } else { - callback(''); + callback('') } - }, false); + }, false) } } else { - this.typelessListeners.push(callback); + this.typelessListeners.push(callback) } } }, /** * Closes this event source. */ - close: function () { - this.closed = true; + close: function() { + this.closed = true if (typeof this.source !== 'undefined') { - this.source.close(); + this.source.close() } } -}; +} -export default OCEventSource; +export default OCEventSource diff --git a/core/src/OC/get_set.js b/core/src/OC/get_set.js index 9fafe121387..bf45ce85fc7 100644 --- a/core/src/OC/get_set.js +++ b/core/src/OC/get_set.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -21,8 +21,8 @@ /** * Get a variable by name - * @param {string} name - * @return {*} + * @param {string} context context + * @returns {Function} getter */ export const get = context => name => { const namespaces = name.split('.') @@ -39,11 +39,11 @@ export const get = context => name => { /** * Set a variable by name - * @param {string} name - * @param {*} value + * @param {string} context context + * @returns {Function} setter */ export const set = context => (name, value) => { - const namespaces = name.split(".") + const namespaces = name.split('.') const tail = namespaces.pop() for (let i = 0; i < namespaces.length; i++) { @@ -53,4 +53,5 @@ export const set = context => (name, value) => { context = context[namespaces[i]] } context[tail] = value + return value } diff --git a/core/src/OC/host.js b/core/src/OC/host.js index ac02c63a72a..f90ca65b4da 100644 --- a/core/src/OC/host.js +++ b/core/src/OC/host.js @@ -21,7 +21,7 @@ /** * Protocol that is used to access this Nextcloud instance - * @return {string} Used protocol + * @returns {string} Used protocol * @deprecated 17.0.0 use window.location.protocol directly */ export const getProtocol = () => window.location.protocol.split(':')[0] @@ -35,7 +35,7 @@ export const getProtocol = () => window.location.protocol.split(':')[0] * https://example.com => example.com * http://example.com:8080 => example.com:8080 * - * @return {string} host + * @returns {string} host * * @since 8.2 * @deprecated 17.0.0 use window.location.host directly @@ -46,7 +46,7 @@ export const getHost = () => window.location.host * Returns the hostname used to access this Nextcloud instance * The hostname is always stripped of the port * - * @return {string} hostname + * @returns {string} hostname * @since 9.0 * @deprecated 17.0.0 use window.location.hostname directly */ @@ -55,7 +55,7 @@ export const getHostName = () => window.location.hostname /** * Returns the port number used to access this Nextcloud instance * - * @return {int} port number + * @returns {int} port number * * @since 8.2 * @deprecated 17.0.0 use window.location.port directly diff --git a/core/src/OC/index.js b/core/src/OC/index.js index 461e0160526..0c95fe3e95f 100644 --- a/core/src/OC/index.js +++ b/core/src/OC/index.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -19,15 +19,15 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -import {addScript, addStyle} from './legacy-loader' +import { addScript, addStyle } from './legacy-loader' import { ajaxConnectionLostHandler, processAjaxError, - registerXHRForErrorProcessing, + registerXHRForErrorProcessing } from './xhr-error' import Apps from './apps' -import {AppConfig, appConfig} from './appconfig' -import {appSettings} from './appsettings' +import { AppConfig, appConfig } from './appconfig' +import { appSettings } from './appsettings' import appswebroots from './appswebroots' import Backbone from './backbone' import { @@ -35,11 +35,11 @@ import { dirname, encodePath, isSamePath, - joinPaths, + joinPaths } from './path' import { build as buildQueryString, - parse as parseQueryString, + parse as parseQueryString } from './query-string' import Config from './config' import { @@ -52,37 +52,37 @@ import { PERMISSION_READ, PERMISSION_SHARE, PERMISSION_UPDATE, - TAG_FAVORITE, + TAG_FAVORITE } from './constants' import ContactsMenu from './contactsmenu' -import {currentUser, getCurrentUser} from './currentuser' +import { currentUser, getCurrentUser } from './currentuser' import Dialogs from './dialogs' import EventSource from './eventsource' -import {get, set} from './get_set' -import {getCapabilities} from './capabilities' +import { get, set } from './get_set' +import { getCapabilities } from './capabilities' import { getHost, getHostName, getPort, - getProtocol, + getProtocol } from './host' import { getToken as getRequestToken, - subscribe as subscribeToRequestTokenChange, + subscribe as subscribeToRequestTokenChange } from './requesttoken' import { hideMenus, registerMenu, showMenu, - unregisterMenu, + unregisterMenu } from './menu' -import {isUserAdmin} from './admin' -import L10N from './l10n' -import { +import { isUserAdmin } from './admin' +import L10N, { getCanonicalLocale, getLanguage, - getLocale, + getLocale } from './l10n' + import { filePath, generateUrl, @@ -91,17 +91,17 @@ import { linkTo, linkToOCS, linkToRemote, - linkToRemoteBase, + linkToRemoteBase } from './routing' import msg from './msg' import Notification from './notification' import PasswordConfirmation from './password-confirmation' import Plugins from './plugins' import search from './search' -import {theme} from './theme' +import { theme } from './theme' import Util from './util' -import {debug} from './debug' -import {redirect, reload} from './navigation' +import { debug } from './debug' +import { redirect, reload } from './navigation' import webroot from './webroot' /** @namespace OC */ @@ -126,6 +126,7 @@ export default { /** * Check if a user file is allowed to be handled. * @param {string} file to check + * @returns {Boolean} * @deprecated 17.0.0 */ fileIsBlacklisted: file => !!(file.match(Config.blacklist_files_regex)), @@ -253,8 +254,8 @@ export default { * @deprecated since 8.2, use OC.getRootPath() instead * @see OC#getRootPath */ - webroot, + webroot } // Keep the request token prop in sync -subscribeToRequestTokenChange(token => OC.requestToken = token) +subscribeToRequestTokenChange(token => { OC.requestToken = token }) diff --git a/core/src/OC/l10n-registry.js b/core/src/OC/l10n-registry.js index 6f537c86c00..44dc6f91be5 100644 --- a/core/src/OC/l10n-registry.js +++ b/core/src/OC/l10n-registry.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -24,9 +24,9 @@ window._oc_l10n_registry_translations = window._oc_l10n_registry_translations || window._oc_l10n_registry_plural_functions = window._oc_l10n_registry_plural_functions || {} /** - * @param {String} appId - * @param {Object} translations - * @param {Function} pluralFunction + * @param {String} appId the app id + * @param {Object} translations the translations list + * @param {Function} pluralFunction the translations list */ const register = (appId, translations, pluralFunction) => { window._oc_l10n_registry_translations[appId] = translations @@ -34,9 +34,9 @@ const register = (appId, translations, pluralFunction) => { } /** - * @param {String} appId - * @param {Object} translations - * @param {Function} pluralFunction + * @param {String} appId the app id + * @param {Object} translations the translations list + * @param {Function} pluralFunction the translations list */ const extend = (appId, translations, pluralFunction) => { window._oc_l10n_registry_translations[appId] = Object.assign( @@ -47,9 +47,9 @@ const extend = (appId, translations, pluralFunction) => { } /** - * @param {String} appId - * @param {Object} translations - * @param {Function} pluralFunction + * @param {String} appId the app id + * @param {Object} translations the translations list + * @param {Function} pluralFunction the translations list */ export const registerAppTranslations = (appId, translations, pluralFunction) => { if (!hasAppTranslations(appId)) { @@ -60,7 +60,7 @@ export const registerAppTranslations = (appId, translations, pluralFunction) => } /** - * @param {String} appId + * @param {String} appId the app id */ export const unregisterAppTranslations = appId => { delete window._oc_l10n_registry_translations[appId] @@ -68,8 +68,8 @@ export const unregisterAppTranslations = appId => { } /** - * @param {String} appId - * @return {Boolean} + * @param {String} appId the app id + * @returns {Boolean} */ export const hasAppTranslations = appId => { return window._oc_l10n_registry_translations[appId] !== undefined @@ -77,12 +77,12 @@ export const hasAppTranslations = appId => { } /** - * @param {String} appId - * @return {Object} + * @param {String} appId the app id + * @returns {Object} */ export const getAppTranslations = appId => { return { translations: window._oc_l10n_registry_translations[appId] || {}, - pluralFunction: window._oc_l10n_registry_plural_functions[appId], + pluralFunction: window._oc_l10n_registry_plural_functions[appId] } } diff --git a/core/src/OC/l10n.js b/core/src/OC/l10n.js index 769d55326ba..fd81d3282d7 100644 --- a/core/src/OC/l10n.js +++ b/core/src/OC/l10n.js @@ -34,39 +34,39 @@ const L10n = { * @param {String} appName name of the app * @param {Function} callback callback to be called when * the translations are loaded - * @return {Promise} promise + * @returns {Promise} promise */ load: function(appName, callback) { // already available ? if (hasAppTranslations(appName) || OC.getLocale() === 'en') { - var deferred = $.Deferred(); - var promise = deferred.promise(); - promise.then(callback); - deferred.resolve(); - return promise; + var deferred = $.Deferred() + var promise = deferred.promise() + promise.then(callback) + deferred.resolve() + return promise } - var self = this; - var url = OC.filePath(appName, 'l10n', OC.getLocale() + '.json'); + var self = this + var url = OC.filePath(appName, 'l10n', OC.getLocale() + '.json') // load JSON translation bundle per AJAX return $.get(url) .then( function(result) { if (result.translations) { - self.register(appName, result.translations, result.pluralForm); + self.register(appName, result.translations, result.pluralForm) } }) - .then(callback); + .then(callback) }, /** * Register an app's translation bundle. * * @param {String} appName name of the app - * @param {Object<String,String>} bundle + * @param {Object<String,String>} bundle bundle */ - register: function(appName, bundle, pluralForm) { + register: function(appName, bundle) { registerAppTranslations(appName, bundle, this._getPlural) }, @@ -79,49 +79,49 @@ const L10n = { * Translate a string * @param {string} app the id of the app for which to translate the string * @param {string} text the string to translate - * @param [vars] map of placeholder key to value + * @param {Object} [vars] map of placeholder key to value * @param {number} [count] number to replace %n with * @param {array} [options] options array * @param {bool} [options.escape=true] enable/disable auto escape of placeholders (by default enabled) - * @return {string} + * @returns {string} */ translate: function(app, text, vars, count, options) { var defaultOptions = { - escape: true - }, - allOptions = options || {}; - _.defaults(allOptions, defaultOptions); + escape: true + } + var allOptions = options || {} + _.defaults(allOptions, defaultOptions) // TODO: cache this function to avoid inline recreation // of the same function over and over again in case // translate() is used in a loop - var _build = function (text, vars, count) { + var _build = function(text, vars, count) { return text.replace(/%n/g, count).replace(/{([^{}]*)}/g, - function (a, b) { - var r = vars[b]; - if(typeof r === 'string' || typeof r === 'number') { - if(allOptions.escape) { - return DOMPurify.sanitize(escapeHTML(r)); + function(a, b) { + var r = vars[b] + if (typeof r === 'string' || typeof r === 'number') { + if (allOptions.escape) { + return DOMPurify.sanitize(escapeHTML(r)) } else { - return DOMPurify.sanitize(r); + return DOMPurify.sanitize(r) } } else { - return DOMPurify.sanitize(a); + return DOMPurify.sanitize(a) } } - ); - }; - var translation = text; - var bundle = getAppTranslations(app); - var value = bundle.translations[text]; - if( typeof(value) !== 'undefined' ){ - translation = value; + ) + } + var translation = text + var bundle = getAppTranslations(app) + var value = bundle.translations[text] + if (typeof (value) !== 'undefined') { + translation = value } - if(typeof vars === 'object' || count !== undefined ) { - return DOMPurify.sanitize(_build(translation, vars, count)); + if (typeof vars === 'object' || count !== undefined) { + return DOMPurify.sanitize(_build(translation, vars, count)) } else { - return DOMPurify.sanitize(translation); + return DOMPurify.sanitize(translation) } }, @@ -131,50 +131,50 @@ const L10n = { * @param {string} textSingular the string to translate for exactly one object * @param {string} textPlural the string to translate for n objects * @param {number} count number to determine whether to use singular or plural - * @param [vars] map of placeholder key to value + * @param {Object} [vars] map of placeholder key to value * @param {array} [options] options array * @param {bool} [options.escape=true] enable/disable auto escape of placeholders (by default enabled) - * @return {string} Translated string + * @returns {string} Translated string */ translatePlural: function(app, textSingular, textPlural, count, vars, options) { - const identifier = '_' + textSingular + '_::_' + textPlural + '_'; - const bundle = getAppTranslations(app); - const value = bundle.translations[identifier]; - if( typeof(value) !== 'undefined' ){ - var translation = value; + const identifier = '_' + textSingular + '_::_' + textPlural + '_' + const bundle = getAppTranslations(app) + const value = bundle.translations[identifier] + if (typeof (value) !== 'undefined') { + var translation = value if ($.isArray(translation)) { - var plural = bundle.pluralFunction(count); - return this.translate(app, translation[plural], vars, count, options); + var plural = bundle.pluralFunction(count) + return this.translate(app, translation[plural], vars, count, options) } } if (count === 1) { - return this.translate(app, textSingular, vars, count, options); + return this.translate(app, textSingular, vars, count, options) } else { - return this.translate(app, textPlural, vars, count, options); + return this.translate(app, textPlural, vars, count, options) } }, /** * The plural function taken from symfony * - * @param {number} number + * @param {number} number the number of elements * @returns {number} * @private */ _getPlural: function(number) { - var language = OC.getLanguage(); - if ('pt_BR' === language) { + var language = OC.getLanguage() + if (language === 'pt_BR') { // temporary set a locale for brazilian - language = 'xbr'; + language = 'xbr' } if (typeof language === 'undefined' || language === '') { - return (1 == number) ? 0 : 1; + return (number === 1) ? 0 : 1 } if (language.length > 3) { - language = language.substring(0, language.lastIndexOf('_')); + language = language.substring(0, language.lastIndexOf('_')) } /* @@ -183,146 +183,146 @@ const L10n = { * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) */ switch (language) { - case 'az': - case 'bo': - case 'dz': - case 'id': - case 'ja': - case 'jv': - case 'ka': - case 'km': - case 'kn': - case 'ko': - case 'ms': - case 'th': - case 'tr': - case 'vi': - case 'zh': - return 0; - - case 'af': - case 'bn': - case 'bg': - case 'ca': - case 'da': - case 'de': - case 'el': - case 'en': - case 'eo': - case 'es': - case 'et': - case 'eu': - case 'fa': - case 'fi': - case 'fo': - case 'fur': - case 'fy': - case 'gl': - case 'gu': - case 'ha': - case 'he': - case 'hu': - case 'is': - case 'it': - case 'ku': - case 'lb': - case 'ml': - case 'mn': - case 'mr': - case 'nah': - case 'nb': - case 'ne': - case 'nl': - case 'nn': - case 'no': - case 'oc': - case 'om': - case 'or': - case 'pa': - case 'pap': - case 'ps': - case 'pt': - case 'so': - case 'sq': - case 'sv': - case 'sw': - case 'ta': - case 'te': - case 'tk': - case 'ur': - case 'zu': - return (1 == number) ? 0 : 1; - - case 'am': - case 'bh': - case 'fil': - case 'fr': - case 'gun': - case 'hi': - case 'hy': - case 'ln': - case 'mg': - case 'nso': - case 'xbr': - case 'ti': - case 'wa': - return ((0 == number) || (1 == number)) ? 0 : 1; - - case 'be': - case 'bs': - case 'hr': - case 'ru': - case 'sh': - case 'sr': - case 'uk': - return ((1 == number % 10) && (11 != number % 100)) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2); - - case 'cs': - case 'sk': - return (1 == number) ? 0 : (((number >= 2) && (number <= 4)) ? 1 : 2); - - case 'ga': - return (1 == number) ? 0 : ((2 == number) ? 1 : 2); - - case 'lt': - return ((1 == number % 10) && (11 != number % 100)) ? 0 : (((number % 10 >= 2) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2); - - case 'sl': - return (1 == number % 100) ? 0 : ((2 == number % 100) ? 1 : (((3 == number % 100) || (4 == number % 100)) ? 2 : 3)); - - case 'mk': - return (1 == number % 10) ? 0 : 1; - - case 'mt': - return (1 == number) ? 0 : (((0 == number) || ((number % 100 > 1) && (number % 100 < 11))) ? 1 : (((number % 100 > 10) && (number % 100 < 20)) ? 2 : 3)); - - case 'lv': - return (0 == number) ? 0 : (((1 == number % 10) && (11 != number % 100)) ? 1 : 2); - - case 'pl': - return (1 == number) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 12) || (number % 100 > 14))) ? 1 : 2); - - case 'cy': - return (1 == number) ? 0 : ((2 == number) ? 1 : (((8 == number) || (11 == number)) ? 2 : 3)); - - case 'ro': - return (1 == number) ? 0 : (((0 == number) || ((number % 100 > 0) && (number % 100 < 20))) ? 1 : 2); - - case 'ar': - return (0 == number) ? 0 : ((1 == number) ? 1 : ((2 == number) ? 2 : (((number % 100 >= 3) && (number % 100 <= 10)) ? 3 : (((number % 100 >= 11) && (number % 100 <= 99)) ? 4 : 5)))); - - default: - return 0; + case 'az': + case 'bo': + case 'dz': + case 'id': + case 'ja': + case 'jv': + case 'ka': + case 'km': + case 'kn': + case 'ko': + case 'ms': + case 'th': + case 'tr': + case 'vi': + case 'zh': + return 0 + + case 'af': + case 'bn': + case 'bg': + case 'ca': + case 'da': + case 'de': + case 'el': + case 'en': + case 'eo': + case 'es': + case 'et': + case 'eu': + case 'fa': + case 'fi': + case 'fo': + case 'fur': + case 'fy': + case 'gl': + case 'gu': + case 'ha': + case 'he': + case 'hu': + case 'is': + case 'it': + case 'ku': + case 'lb': + case 'ml': + case 'mn': + case 'mr': + case 'nah': + case 'nb': + case 'ne': + case 'nl': + case 'nn': + case 'no': + case 'oc': + case 'om': + case 'or': + case 'pa': + case 'pap': + case 'ps': + case 'pt': + case 'so': + case 'sq': + case 'sv': + case 'sw': + case 'ta': + case 'te': + case 'tk': + case 'ur': + case 'zu': + return (number === 1) ? 0 : 1 + + case 'am': + case 'bh': + case 'fil': + case 'fr': + case 'gun': + case 'hi': + case 'hy': + case 'ln': + case 'mg': + case 'nso': + case 'xbr': + case 'ti': + case 'wa': + return ((number === 0) || (number === 1)) ? 0 : 1 + + case 'be': + case 'bs': + case 'hr': + case 'ru': + case 'sh': + case 'sr': + case 'uk': + return ((number % 10 === 1) && (number % 100 !== 11)) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2) + + case 'cs': + case 'sk': + return (number === 1) ? 0 : (((number >= 2) && (number <= 4)) ? 1 : 2) + + case 'ga': + return (number === 1) ? 0 : ((number === 2) ? 1 : 2) + + case 'lt': + return ((number % 10 === 1) && (number % 100 !== 11)) ? 0 : (((number % 10 >= 2) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2) + + case 'sl': + return (number % 100 === 1) ? 0 : ((number % 100 === 2) ? 1 : (((number % 100 === 3) || (number % 100 === 4)) ? 2 : 3)) + + case 'mk': + return (number % 10 === 1) ? 0 : 1 + + case 'mt': + return (number === 1) ? 0 : (((number === 0) || ((number % 100 > 1) && (number % 100 < 11))) ? 1 : (((number % 100 > 10) && (number % 100 < 20)) ? 2 : 3)) + + case 'lv': + return (number === 0) ? 0 : (((number % 10 === 1) && (number % 100 !== 11)) ? 1 : 2) + + case 'pl': + return (number === 1) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 12) || (number % 100 > 14))) ? 1 : 2) + + case 'cy': + return (number === 1) ? 0 : ((number === 2) ? 1 : (((number === 8) || (number === 11)) ? 2 : 3)) + + case 'ro': + return (number === 1) ? 0 : (((number === 0) || ((number % 100 > 0) && (number % 100 < 20))) ? 1 : 2) + + case 'ar': + return (number === 0) ? 0 : ((number === 1) ? 1 : ((number === 2) ? 2 : (((number % 100 >= 3) && (number % 100 <= 10)) ? 3 : (((number % 100 >= 11) && (number % 100 <= 99)) ? 4 : 5)))) + + default: + return 0 } } -}; +} -export default L10n; +export default L10n /** * Returns the user's locale as a BCP 47 compliant language tag * - * @return {String} locale string + * @returns {String} locale string */ export const getCanonicalLocale = () => { const locale = getLocale() @@ -332,7 +332,7 @@ export const getCanonicalLocale = () => { /** * Returns the user's locale * - * @return {String} locale string + * @returns {String} locale string */ export const getLocale = () => $('html').data('locale') @@ -344,6 +344,5 @@ export const getLocale = () => $('html').data('locale') export const getLanguage = () => $('html').prop('lang') Handlebars.registerHelper('t', function(app, text) { - return L10n.translate(app, text); -}); - + return L10n.translate(app, text) +}) diff --git a/core/src/OC/legacy-loader.js b/core/src/OC/legacy-loader.js index a2c76c2e3ab..ece9f3c3fc1 100644 --- a/core/src/OC/legacy-loader.js +++ b/core/src/OC/legacy-loader.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -29,7 +29,8 @@ const loadedStyles = [] * the event handler will be called directly * @param {string} app the app id to which the script belongs * @param {string} script the filename of the script - * @param ready event handler to be called when the script is loaded + * @param {Function} ready event handler to be called when the script is loaded + * @returns {jQuery.Deferred} * @deprecated 16.0.0 Use OCP.Loader.loadScript */ export const addScript = (app, script, ready) => { diff --git a/core/src/OC/menu.js b/core/src/OC/menu.js index 04d0e078b9a..82cde9e862d 100644 --- a/core/src/OC/menu.js +++ b/core/src/OC/menu.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -22,33 +22,32 @@ import _ from 'underscore' import $ from 'jquery' -import {menuSpeed} from './constants' +import { menuSpeed } from './constants' -let currentMenu = null -let currentMenuToggle = null +export let currentMenu = null +export let currentMenuToggle = null /** * For menu toggling * - * @param {jQuery} $toggle - * @param {jQuery} $menuEl + * @param {jQuery} $toggle the toggle element + * @param {jQuery} $menuEl the menu container element * @param {function|undefined} toggle callback invoked everytime the menu is opened * @param {boolean} headerMenu is this a top right header menu? * @returns {undefined} */ -export const registerMenu = ($toggle, $menuEl, toggle, headerMenu) => { +export const registerMenu = function($toggle, $menuEl, toggle, headerMenu) { $menuEl.addClass('menu') + const isClickableElement = $toggle.prop('tagName') === 'A' || $toggle.prop('tagName') === 'BUTTON' // On link and button, the enter key trigger a click event // Only use the click to avoid two fired events - $toggle.on(($toggle.prop('tagName') === 'A' || $toggle.prop('tagName') === 'BUTTON') - ? 'click.menu' - : 'click.menu keyup.menu', function (event) { + $toggle.on(isClickableElement ? 'click.menu' : 'click.menu keyup.menu', function(event) { // prevent the link event (append anchor to URL) event.preventDefault() // allow enter key as a trigger - if (event.key && event.key !== "Enter") { + if (event.key && event.key !== 'Enter') { return } @@ -75,7 +74,10 @@ export const registerMenu = ($toggle, $menuEl, toggle, headerMenu) => { } /** - * @todo Write documentation + * Unregister a previously registered menu + * + * @param {jQuery} $toggle the toggle element + * @param {jQuery} $menuEl the menu container element */ export const unregisterMenu = ($toggle, $menuEl) => { // close menu if opened @@ -95,7 +97,7 @@ export const hideMenus = function(complete) { if (currentMenu) { const lastMenu = currentMenu currentMenu.trigger(new $.Event('beforeHide')) - currentMenu.slideUp(menuSpeed, function () { + currentMenu.slideUp(menuSpeed, function() { lastMenu.trigger(new $.Event('afterHide')) if (complete) { complete.apply(this, arguments) diff --git a/core/src/OC/msg.js b/core/src/OC/msg.js index 1d43b4375e7..e210f32bb14 100644 --- a/core/src/OC/msg.js +++ b/core/src/OC/msg.js @@ -21,7 +21,7 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -import $ from 'jquery'; +import $ from 'jquery' /** * A little class to manage a status field for a "saving" process. @@ -36,8 +36,8 @@ export default { * * @param {Object} selector Placeholder to display the message in */ - startSaving: function (selector) { - this.startAction(selector, t('core', 'Saving...')); + startSaving: function(selector) { + this.startAction(selector, t('core', 'Saving...')) }, /** @@ -46,12 +46,12 @@ export default { * @param {Object} selector Placeholder to display the message in * @param {string} message Plain text message to display (no HTML allowed) */ - startAction: function (selector, message) { + startAction: function(selector, message) { $(selector).text(message) .removeClass('success') .removeClass('error') .stop(true, true) - .show(); + .show() }, /** @@ -64,8 +64,8 @@ export default { * @param {string} response.status is being used to decide whether the message * is displayed as an error/success */ - finishedSaving: function (selector, response) { - this.finishedAction(selector, response); + finishedSaving: function(selector, response) { + this.finishedAction(selector, response) }, /** @@ -78,11 +78,11 @@ export default { * @param {string} response.status is being used to decide whether the message * is displayed as an error/success */ - finishedAction: function (selector, response) { - if (response.status === "success") { - this.finishedSuccess(selector, response.data.message); + finishedAction: function(selector, response) { + if (response.status === 'success') { + this.finishedSuccess(selector, response.data.message) } else { - this.finishedError(selector, response.data.message); + this.finishedError(selector, response.data.message) } }, @@ -92,14 +92,14 @@ export default { * @param {Object} selector Placeholder to display the message in * @param {string} message Plain text success message to display (no HTML allowed) */ - finishedSuccess: function (selector, message) { + finishedSuccess: function(selector, message) { $(selector).text(message) .addClass('success') .removeClass('error') .stop(true, true) .delay(3000) .fadeOut(900) - .show(); + .show() }, /** @@ -108,10 +108,10 @@ export default { * @param {Object} selector Placeholder to display the message in * @param {string} message Plain text error message to display (no HTML allowed) */ - finishedError: function (selector, message) { + finishedError: function(selector, message) { $(selector).text(message) .addClass('error') .removeClass('success') - .show(); + .show() } } diff --git a/core/src/OC/navigation.js b/core/src/OC/navigation.js index b37d339b41b..f9e6789950a 100644 --- a/core/src/OC/navigation.js +++ b/core/src/OC/navigation.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -24,10 +24,10 @@ * @param {string} targetURL URL to redirect to * @deprecated 17.0.0 use window.location directly */ -export const redirect = targetURL => window.location = targetURL +export const redirect = targetURL => { window.location = targetURL } /** * Reloads the current page * @deprecated 17.0.0 use window.location.reload directly */ -export const reload = () => window.location.reload() +export const reload = () => { window.location.reload() } diff --git a/core/src/OC/notification.js b/core/src/OC/notification.js index f31b37e4ba4..b56fb6b14de 100644 --- a/core/src/OC/notification.js +++ b/core/src/OC/notification.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -21,7 +21,6 @@ import _ from 'underscore' import $ from 'jquery' -import Toastify from 'toastify-js' /** * @todo Write documentation @@ -35,11 +34,11 @@ export default { getDefaultNotificationFunction: null, /** - * @param callback + * @param {Function} callback callback function * @deprecated 17.0.0 use OCP.Toast */ - setDefault: function (callback) { - this.getDefaultNotificationFunction = callback; + setDefault: function(callback) { + this.getDefaultNotificationFunction = callback }, /** @@ -52,23 +51,20 @@ export default { * @param {Function} [callback] callback * @deprecated 17.0.0 use OCP.Toast */ - hide: function ($row, callback) { - var self = this; - var $notification = $('#content'); - + hide: function($row, callback) { if (_.isFunction($row)) { // first arg is the callback - callback = $row; - $row = undefined; + callback = $row + $row = undefined } if (!$row) { - console.error('Missing argument $row in OC.Notification.hide() call, caller needs to be adjusted to only dismiss its own notification'); - return; + console.error('Missing argument $row in OC.Notification.hide() call, caller needs to be adjusted to only dismiss its own notification') + return } // remove the row directly - $row.each(function () { + $row.each(function() { $(this)[0].toastify.hideToast() if (this === this.updatableNotification) { this.updatableNotification = null @@ -91,10 +87,10 @@ export default { * @param {Object} [options] options * @param {string} [options.type] notification type * @param {int} [options.timeout=0] timeout value, defaults to 0 (permanent) - * @return {jQuery} jQuery element for notification row + * @returns {jQuery} jQuery element for notification row * @deprecated 17.0.0 use OCP.Toast */ - showHtml: function (html, options) { + showHtml: function(html, options) { options = options || {} options.isHTML = true options.timeout = (!options.timeout) ? -1 : options.timeout @@ -109,29 +105,29 @@ export default { * @param {Object} [options] options * @param {string} [options.type] notification type * @param {int} [options.timeout=0] timeout value, defaults to 0 (permanent) - * @return {jQuery} jQuery element for notification row + * @returns {jQuery} jQuery element for notification row * @deprecated 17.0.0 use OCP.Toast */ - show: function (text, options) { - options = options || {}; - options.timeout = (!options.timeout) ? -1 : options.timeout; - const toast = window.OCP.Toast.message(text, options); - return $(toast.toastElement); + show: function(text, options) { + options = options || {} + options.timeout = (!options.timeout) ? -1 : options.timeout + const toast = window.OCP.Toast.message(text, options) + return $(toast.toastElement) }, /** * Updates (replaces) a sanitized notification. * * @param {string} text Message to display - * @return {jQuery} JQuery element for notificaiton row + * @returns {jQuery} JQuery element for notificaiton row * @deprecated 17.0.0 use OCP.Toast */ - showUpdate: function (text) { + showUpdate: function(text) { if (this.updatableNotification) { - this.updatableNotification.hideToast(); + this.updatableNotification.hideToast() } - this.updatableNotification = OCP.Toast.message(text, {timeout: -1}) - return $(this.updatableNotification.toastElement); + this.updatableNotification = OCP.Toast.message(text, { timeout: -1 }) + return $(this.updatableNotification.toastElement) }, /** @@ -143,21 +139,22 @@ export default { * @param {int} [options.timeout=7] timeout in seconds, if this is 0 it will show the message permanently * @param {boolean} [options.isHTML=false] an indicator for HTML notifications (true) or text (false) * @param {string} [options.type] notification type + * @returns {JQuery<any>} the toast element * @deprecated 17.0.0 use OCP.Toast */ - showTemporary: function (text, options) { + showTemporary: function(text, options) { options = options || {} - options.timeout = options.timeout || 7; - const toast = window.OCP.Toast.message(text, options); - return $(toast.toastElement); + options.timeout = options.timeout || 7 + const toast = window.OCP.Toast.message(text, options) + return $(toast.toastElement) }, /** * Returns whether a notification is hidden. - * @return {boolean} + * @returns {boolean} * @deprecated 17.0.0 use OCP.Toast */ - isHidden: function () { - return !$('#content').find('.toastify').length; + isHidden: function() { + return !$('#content').find('.toastify').length } } diff --git a/core/src/OC/password-confirmation.js b/core/src/OC/password-confirmation.js index a38f32b4b5e..e303d70bf5d 100644 --- a/core/src/OC/password-confirmation.js +++ b/core/src/OC/password-confirmation.js @@ -1,6 +1,4 @@ -/* global nc_pageLoad */ - -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -35,24 +33,26 @@ export default { pageLoadTime: null, - init: function () { - $('.password-confirm-required').on('click', _.bind(this.requirePasswordConfirmation, this)); - this.pageLoadTime = moment.now(); + init: function() { + $('.password-confirm-required').on('click', _.bind(this.requirePasswordConfirmation, this)) + this.pageLoadTime = moment.now() }, - requiresPasswordConfirmation: function () { - var serverTimeDiff = this.pageLoadTime - (nc_pageLoad * 1000); - var timeSinceLogin = moment.now() - (serverTimeDiff + (nc_lastLogin * 1000)); + requiresPasswordConfirmation: function() { + var serverTimeDiff = this.pageLoadTime - (window.nc_pageLoad * 1000) + var timeSinceLogin = moment.now() - (serverTimeDiff + (window.nc_lastLogin * 1000)) // if timeSinceLogin > 30 minutes and user backend allows password confirmation - return (backendAllowsPasswordConfirmation && timeSinceLogin > 30 * 60 * 1000); + return (window.backendAllowsPasswordConfirmation && timeSinceLogin > 30 * 60 * 1000) }, /** - * @param {function} callback + * @param {Function} callback success callback function + * @param {Object} options options + * @param {Function} rejectCallback error callback function */ - requirePasswordConfirmation: function (callback, options, rejectCallback) { - options = typeof options !== 'undefined' ? options : {}; + requirePasswordConfirmation: function(callback, options, rejectCallback) { + options = typeof options !== 'undefined' ? options : {} var defaults = { title: t('core', 'Authentication required'), text: t( @@ -61,20 +61,20 @@ export default { ), confirm: t('core', 'Confirm'), label: t('core', 'Password'), - error: '', - }; + error: '' + } - var config = _.extend(defaults, options); + var config = _.extend(defaults, options) - var self = this; + var self = this if (this.requiresPasswordConfirmation()) { OC.dialogs.prompt( config.text, config.title, - function (result, password) { + function(result, password) { if (result && password !== '') { - self._confirmPassword(password, config); + self._confirmPassword(password, config) } else if (_.isFunction(rejectCallback)) { rejectCallback() } @@ -82,27 +82,27 @@ export default { true, config.label, true - ).then(function () { - var $dialog = $('.oc-dialog:visible'); - $dialog.find('.ui-icon').remove(); - $dialog.addClass('password-confirmation'); + ).then(function() { + var $dialog = $('.oc-dialog:visible') + $dialog.find('.ui-icon').remove() + $dialog.addClass('password-confirmation') if (config.error !== '') { - var $error = $('<p></p>').addClass('msg warning').text(config.error); + var $error = $('<p></p>').addClass('msg warning').text(config.error) } - $dialog.find('.oc-dialog-content').append($error); - $dialog.find('.oc-dialog-buttonrow').addClass('aside'); + $dialog.find('.oc-dialog-content').append($error) + $dialog.find('.oc-dialog-buttonrow').addClass('aside') - var $buttons = $dialog.find('button'); - $buttons.eq(0).hide(); - $buttons.eq(1).text(config.confirm); - }); + var $buttons = $dialog.find('button') + $buttons.eq(0).hide() + $buttons.eq(1).text(config.confirm) + }) } - this.callback = callback; + this.callback = callback }, - _confirmPassword: function (password, config) { - var self = this; + _confirmPassword: function(password, config) { + var self = this $.ajax({ url: OC.generateUrl('/login/confirm'), @@ -110,17 +110,17 @@ export default { password: password }, type: 'POST', - success: function (response) { - nc_lastLogin = response.lastLogin; + success: function(response) { + window.nc_lastLogin = response.lastLogin if (_.isFunction(self.callback)) { - self.callback(); + self.callback() } }, - error: function () { - config.error = t('core', 'Failed to authenticate, try again'); - OC.PasswordConfirmation.requirePasswordConfirmation(self.callback, config); + error: function() { + config.error = t('core', 'Failed to authenticate, try again') + OC.PasswordConfirmation.requirePasswordConfirmation(self.callback, config) } - }); + }) } -}; +} diff --git a/core/src/OC/path.js b/core/src/OC/path.js index ef58caf4850..145c90d1e5e 100644 --- a/core/src/OC/path.js +++ b/core/src/OC/path.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -22,8 +22,8 @@ /** * URI-Encodes a file path but keep the path slashes. * - * @param {String} path - * @return {String} encoded path + * @param {String} path path + * @returns {String} encoded path */ export const encodePath = path => { if (!path) { @@ -41,8 +41,8 @@ export const encodePath = path => { * Returns the base name of the given path. * For example for "/abc/somefile.txt" it will return "somefile.txt" * - * @param {String} path - * @return {String} base name + * @param {String} path path + * @returns {String} base name */ export const basename = path => path.replace(/\\/g, '/').replace(/.*\//, '') @@ -50,10 +50,10 @@ export const basename = path => path.replace(/\\/g, '/').replace(/.*\//, '') * Returns the dir name of the given path. * For example for "/abc/somefile.txt" it will return "/abc" * - * @param {String} path - * @return {String} dir name + * @param {String} path path + * @returns {String} dir name */ -export const dirname = path => path.replace(/\\/g, '/').replace(/\/[^\/]*$/, '') +export const dirname = path => path.replace(/\\/g, '/').replace(/\/[^/]*$/, '') /** * Returns whether the given paths are the same, without @@ -62,7 +62,7 @@ export const dirname = path => path.replace(/\\/g, '/').replace(/\/[^\/]*$/, '') * * @param {String} path1 first path * @param {String} path2 second path - * @return {bool} true if the paths are the same + * @returns {bool} true if the paths are the same * * @since 9.0 */ @@ -80,13 +80,13 @@ export const isSamePath = (path1, path2) => { * * @param {...String} path sections * - * @return {String} joined path, any leading or trailing slash + * @returns {String} joined path, any leading or trailing slash * will be kept * * @since 8.2 */ export const joinPaths = (...args) => { - if (arguments.length < 1) { + if (args.length < 1) { return '' } @@ -98,7 +98,7 @@ export const joinPaths = (...args) => { const lastArg = nonEmptyArgs[nonEmptyArgs.length - 1] const leadingSlash = nonEmptyArgs[0].charAt(0) === '/' - const trailingSlash = lastArg.charAt(lastArg.length - 1) === '/'; + const trailingSlash = lastArg.charAt(lastArg.length - 1) === '/' const sections = nonEmptyArgs.reduce((acc, section) => acc.concat(section.split('/')), []) let first = !leadingSlash diff --git a/core/src/OC/plugins.js b/core/src/OC/plugins.js index dd25610c2db..124116b9a59 100644 --- a/core/src/OC/plugins.js +++ b/core/src/OC/plugins.js @@ -33,14 +33,14 @@ export default { * Register plugin * * @param {String} targetName app name / class name to hook into - * @param {OC.Plugin} plugin + * @param {OC.Plugin} plugin plugin */ - register: function (targetName, plugin) { - var plugins = this._plugins[targetName]; + register: function(targetName, plugin) { + var plugins = this._plugins[targetName] if (!plugins) { - plugins = this._plugins[targetName] = []; + plugins = this._plugins[targetName] = [] } - plugins.push(plugin); + plugins.push(plugin) }, /** @@ -48,24 +48,24 @@ export default { * name / app name / class name. * * @param {String} targetName app name / class name to hook into - * @return {Array.<OC.Plugin>} array of plugins + * @returns {Array.<OC.Plugin>} array of plugins */ - getPlugins: function (targetName) { - return this._plugins[targetName] || []; + getPlugins: function(targetName) { + return this._plugins[targetName] || [] }, /** * Call attach() on all plugins registered to the given target name. * * @param {String} targetName app name / class name - * @param {Object} object to be extended + * @param {Object} targetObject to be extended * @param {Object} [options] options */ - attach: function (targetName, targetObject, options) { - var plugins = this.getPlugins(targetName); + attach: function(targetName, targetObject, options) { + var plugins = this.getPlugins(targetName) for (var i = 0; i < plugins.length; i++) { if (plugins[i].attach) { - plugins[i].attach(targetObject, options); + plugins[i].attach(targetObject, options) } } }, @@ -74,16 +74,16 @@ export default { * Call detach() on all plugins registered to the given target name. * * @param {String} targetName app name / class name - * @param {Object} object to be extended + * @param {Object} targetObject to be extended * @param {Object} [options] options */ - detach: function (targetName, targetObject, options) { - var plugins = this.getPlugins(targetName); + detach: function(targetName, targetObject, options) { + var plugins = this.getPlugins(targetName) for (var i = 0; i < plugins.length; i++) { if (plugins[i].detach) { - plugins[i].detach(targetObject, options); + plugins[i].detach(targetObject, options) } } } -}
\ No newline at end of file +} diff --git a/core/src/OC/query-string.js b/core/src/OC/query-string.js index 973412de579..a8141777905 100644 --- a/core/src/OC/query-string.js +++ b/core/src/OC/query-string.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -22,15 +22,14 @@ /** * Parses a URL query string into a JS map * @param {string} queryString query string in the format param1=1234¶m2=abcde¶m3=xyz - * @return {Object.<string, string>} map containing key/values matching the URL parameters + * @returns {Object.<string, string>} map containing key/values matching the URL parameters */ export const parse = queryString => { - let parts, - pos, - components, - result = {}, - key, - value + let parts + let pos + let components + let result = {} + let key if (!queryString) { return null } @@ -73,13 +72,13 @@ export const parse = queryString => { /** * Builds a URL query from a JS map. * @param {Object.<string, string>} params map containing key/values matching the URL parameters - * @return {string} String containing a URL query (without question) mark + * @returns {string} String containing a URL query (without question) mark */ export const build = params => { if (!params) { return '' } - return $.map(params, function (value, key) { + return $.map(params, function(value, key) { var s = encodeURIComponent(key) if (value !== null && typeof (value) !== 'undefined') { s += '=' + encodeURIComponent(value) diff --git a/core/src/OC/requesttoken.js b/core/src/OC/requesttoken.js index 3c4a185f1c0..a92eb169577 100644 --- a/core/src/OC/requesttoken.js +++ b/core/src/OC/requesttoken.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -19,25 +19,24 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -let token = document.getElementsByTagName('head')[0].getAttribute('data-requesttoken'); +let token = document.getElementsByTagName('head')[0].getAttribute('data-requesttoken') const observers = [] /** - * @return {string} + * @returns {string} */ export const getToken = () => token /** - * @param {Function} observer - * @return {number} + * @param {Function} observer observer + * @returns {number} */ export const subscribe = observer => observers.push(observer) /** - * @param {String} newToken + * @param {String} newToken new token */ export const setToken = newToken => { token = newToken - observers.forEach(o => o(token)) } diff --git a/core/src/OC/routing.js b/core/src/OC/routing.js index 0223a6cfd1e..36fd0009032 100644 --- a/core/src/OC/routing.js +++ b/core/src/OC/routing.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -22,27 +22,27 @@ import _ from 'underscore' import OC from './index' -import {coreApps} from './constants' +import { coreApps } from './constants' /** * Get an absolute url to a file in an app * @param {string} app the id of the app the file belongs to * @param {string} file the file path relative to the app folder - * @return {string} Absolute URL to a file + * @returns {string} Absolute URL to a file */ export const linkTo = (app, file) => filePath(app, '', file) /** * Creates a relative url for remote use * @param {string} service id - * @return {string} the url + * @returns {string} the url */ export const linkToRemoteBase = service => getRootPath() + '/remote.php/' + service /** * @brief Creates an absolute url for remote use * @param {string} service id - * @return {string} the url + * @returns {string} the url */ export const linkToRemote = service => window.location.protocol + '//' + window.location.host + linkToRemoteBase(service) @@ -50,7 +50,7 @@ export const linkToRemote = service => window.location.protocol + '//' + window. * Gets the base path for the given OCS API service. * @param {string} service name * @param {int} version OCS API version - * @return {string} OCS API base path + * @returns {string} OCS API base path */ export const linkToOCS = (service, version) => { version = (version !== 2) ? 1 : 2 @@ -60,42 +60,42 @@ export const linkToOCS = (service, version) => { /** * Generates the absolute url for the given relative url, which can contain parameters. * Parameters will be URL encoded automatically. - * @param {string} url - * @param [params] params - * @param [options] options + * @param {string} url the url + * @param {Object} [params] params + * @param {Object} [options] destructuring object * @param {bool} [options.escape=true] enable/disable auto escape of placeholders (by default enabled) - * @return {string} Absolute URL for the given relative URL + * @returns {string} Absolute URL for the given relative URL */ export const generateUrl = (url, params, options) => { const defaultOptions = { - escape: true - }, - allOptions = options || {}; - _.defaults(allOptions, defaultOptions); + escape: true + } + const allOptions = options || {} + _.defaults(allOptions, defaultOptions) - const _build = function (text, vars) { - vars = vars || []; + const _build = function(text, vars) { + vars = vars || [] return text.replace(/{([^{}]*)}/g, - function (a, b) { - var r = (vars[b]); + function(a, b) { + var r = (vars[b]) if (allOptions.escape) { - return (typeof r === 'string' || typeof r === 'number') ? encodeURIComponent(r) : encodeURIComponent(a); + return (typeof r === 'string' || typeof r === 'number') ? encodeURIComponent(r) : encodeURIComponent(a) } else { - return (typeof r === 'string' || typeof r === 'number') ? r : a; + return (typeof r === 'string' || typeof r === 'number') ? r : a } } - ); - }; + ) + } if (url.charAt(0) !== '/') { - url = '/' + url; + url = '/' + url } if (OC.config.modRewriteWorking === true) { - return getRootPath() + _build(url, params); + return getRootPath() + _build(url, params) } - return getRootPath() + '/index.php' + _build(url, params); + return getRootPath() + '/index.php' + _build(url, params) } /** @@ -105,11 +105,11 @@ export const generateUrl = (url, params, options) => { * * @param {string} app the app id to which the image belongs * @param {string} file the name of the image file - * @return {string} + * @returns {string} */ export const imagePath = (app, file) => { if (file.indexOf('.') === -1) { - //if no extension is given, use svg + // if no extension is given, use svg return filePath(app, 'img', file + '.svg') } @@ -121,13 +121,13 @@ export const imagePath = (app, file) => { * @param {string} app the id of the app * @param {string} type the type of the file to link to (e.g. css,img,ajax.template) * @param {string} file the filename - * @return {string} Absolute URL for a file in an app + * @returns {string} Absolute URL for a file in an app */ export const filePath = (app, type, file) => { const isCore = coreApps.indexOf(app) !== -1 let link = getRootPath() if (file.substring(file.length - 3) === 'php' && !isCore) { - link += '/index.php/apps/' + app; + link += '/index.php/apps/' + app if (file !== 'index.php') { link += '/' if (type) { @@ -136,7 +136,7 @@ export const filePath = (app, type, file) => { link += file } } else if (file.substring(file.length - 3) !== 'php' && !isCore) { - link = OC.appswebroots[app]; + link = OC.appswebroots[app] if (type) { link += '/' + type + '/' } @@ -170,7 +170,7 @@ export const filePath = (app, type, file) => { * is accessible, with a leading slash. * For example "/nextcloud". * - * @return {string} web root path + * @returns {string} web root path * * @since 8.2 */ diff --git a/core/src/OC/search.js b/core/src/OC/search.js index 31f8df7ecf1..281907a06a7 100644 --- a/core/src/OC/search.js +++ b/core/src/OC/search.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -25,17 +25,17 @@ import OC from './index' * Do a search query and display the results * @param {string} query the search query */ -const search = function (query) { - OC.Search.search(query, null, 0, 30); -}; +const search = function(query) { + OC.Search.search(query, null, 0, 30) +} /** * @namespace OC.search */ -search.customResults = {}; +search.customResults = {} /** * @deprecated use get/setFormatter() instead */ -search.resultTypes = {}; +search.resultTypes = {} -export default search; +export default search diff --git a/core/src/OC/util-history.js b/core/src/OC/util-history.js index 3dd1a104ef8..77607b64022 100644 --- a/core/src/OC/util-history.js +++ b/core/src/OC/util-history.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -20,7 +20,6 @@ */ import _ from 'underscore' - import OC from './index' /** @@ -46,40 +45,41 @@ export default { * using the params as query string * @param {boolean} [replace=false] whether to replace instead of pushing */ - _pushState: function (params, url, replace) { - var strParams; + _pushState: function(params, url, replace) { + var strParams if (typeof (params) === 'string') { - strParams = params; + strParams = params } else { - strParams = OC.buildQueryString(params); + strParams = OC.buildQueryString(params) } + if (window.history.pushState) { - url = url || location.pathname + '?' + strParams; + url = url || location.pathname + '?' + strParams // Workaround for bug with SVG and window.history.pushState on Firefox < 51 // https://bugzilla.mozilla.org/show_bug.cgi?id=652991 - var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; + var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1 if (isFirefox && parseInt(navigator.userAgent.split('/').pop()) < 51) { - var patterns = document.querySelectorAll('[fill^="url(#"], [stroke^="url(#"], [filter^="url(#invert"]'); + var patterns = document.querySelectorAll('[fill^="url(#"], [stroke^="url(#"], [filter^="url(#invert"]') for (var i = 0, ii = patterns.length, pattern; i < ii; i++) { - pattern = patterns[i]; - pattern.style.fill = pattern.style.fill; - pattern.style.stroke = pattern.style.stroke; - pattern.removeAttribute("filter"); - pattern.setAttribute("filter", "url(#invert)"); + const { fill, stroke } = pattern.style + pattern = patterns[i] + pattern.style.fill = fill + pattern.style.stroke = stroke + pattern.removeAttribute('filter') + pattern.setAttribute('filter', 'url(#invert)') } } if (replace) { - window.history.replaceState(params, '', url); + window.history.replaceState(params, '', url) } else { - window.history.pushState(params, '', url); + window.history.pushState(params, '', url) } - } - // use URL hash for IE8 - else { - window.location.hash = '?' + strParams; + } else { + // use URL hash for IE8 + window.location.hash = '?' + strParams // inhibit next onhashchange that just added itself // to the event queue - this._cancelPop = true; + this._cancelPop = true } }, @@ -89,13 +89,11 @@ export default { * Note: this includes a workaround for IE8/IE9 that uses * the hash part instead of the search part. * - * @param {Object|string} params to append to the URL, can be either a string - * or a map - * @param {string} [url] URL to be used, otherwise the current URL will be used, - * using the params as query string + * @param {Object|string} params to append to the URL, can be either a string or a map + * @param {string} [url] URL to be used, otherwise the current URL will be used, using the params as query string */ - pushState: function (params, url) { - return this._pushState(params, url, false); + pushState: function(params, url) { + this._pushState(params, url, false) }, /** @@ -109,75 +107,76 @@ export default { * @param {string} [url] URL to be used, otherwise the current URL will be used, * using the params as query string */ - replaceState: function (params, url) { - return this._pushState(params, url, true); + replaceState: function(params, url) { + this._pushState(params, url, true) }, /** * Add a popstate handler * - * @param handler function + * @param {Function} handler handler */ - addOnPopStateHandler: function (handler) { - this._handlers.push(handler); + addOnPopStateHandler: function(handler) { + this._handlers.push(handler) }, /** * Parse a query string from the hash part of the URL. * (workaround for IE8 / IE9) + * @returns {string} */ - _parseHashQuery: function () { - var hash = window.location.hash, - pos = hash.indexOf('?'); + _parseHashQuery: function() { + var hash = window.location.hash + var pos = hash.indexOf('?') if (pos >= 0) { - return hash.substr(pos + 1); + return hash.substr(pos + 1) } if (hash.length) { // remove hash sign - return hash.substr(1); + return hash.substr(1) } - return ''; + return '' }, - _decodeQuery: function (query) { - return query.replace(/\+/g, ' '); + _decodeQuery: function(query) { + return query.replace(/\+/g, ' ') }, /** * Parse the query/search part of the URL. * Also try and parse it from the URL hash (for IE8) * - * @return map of parameters + * @returns {Object} map of parameters */ - parseUrlQuery: function () { - var query = this._parseHashQuery(), - params; + parseUrlQuery: function() { + var query = this._parseHashQuery() + var params // try and parse from URL hash first if (query) { - params = OC.parseQueryString(this._decodeQuery(query)); + params = OC.parseQueryString(this._decodeQuery(query)) } // else read from query attributes - params = _.extend(params || {}, OC.parseQueryString(this._decodeQuery(location.search))); - return params || {}; + params = _.extend(params || {}, OC.parseQueryString(this._decodeQuery(location.search))) + return params || {} }, - _onPopState: function (e) { + _onPopState: function(e) { if (this._cancelPop) { - this._cancelPop = false; - return; + this._cancelPop = false + return } - var params; + var params if (!this._handlers.length) { - return; + return } - params = (e && e.state); + params = (e && e.state) if (_.isString(params)) { - params = OC.parseQueryString(params); + params = OC.parseQueryString(params) } else if (!params) { - params = this.parseUrlQuery() || {}; + params = this.parseUrlQuery() || {} } for (var i = 0; i < this._handlers.length; i++) { - this._handlers[i](params); + this._handlers[i](params) } } } diff --git a/core/src/OC/util.js b/core/src/OC/util.js index dd66f4b2954..7c4a44b77d9 100644 --- a/core/src/OC/util.js +++ b/core/src/OC/util.js @@ -1,6 +1,4 @@ -/* global t */ - -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -30,22 +28,26 @@ import humanFileSize from '../Util/human-file-size' function chunkify(t) { // Adapted from http://my.opera.com/GreyWyvern/blog/show.dml/1671288 - let tz = [], x = 0, y = -1, n = 0, code, c; + let tz = [] + let x = 0 + let y = -1 + let n = 0 + let c while (x < t.length) { - c = t.charAt(x); + c = t.charAt(x) // only include the dot in strings - var m = ((!n && c === '.') || (c >= '0' && c <= '9')); + var m = ((!n && c === '.') || (c >= '0' && c <= '9')) if (m !== n) { // next chunk - y++; - tz[y] = ''; - n = m; + y++ + tz[y] = '' + n = m } - tz[y] += c; - x++; + tz[y] += c + x++ } - return tz; + return tz } /** @@ -64,17 +66,17 @@ export default { * Makes 2kB to 2048. * Inspired by computerFileSize in helper.php * @param {string} string file size in human readable format - * @return {number} or null if string could not be parsed + * @returns {number} or null if string could not be parsed * * */ - computerFileSize: function (string) { + computerFileSize: function(string) { if (typeof string !== 'string') { - return null; + return null } - var s = string.toLowerCase().trim(); - var bytes = null; + var s = string.toLowerCase().trim() + var bytes = null var bytesArray = { 'b': 1, @@ -88,164 +90,165 @@ export default { 't': 1024 * 1024 * 1024 * 1024, 'pb': 1024 * 1024 * 1024 * 1024 * 1024, 'p': 1024 * 1024 * 1024 * 1024 * 1024 - }; + } - var matches = s.match(/^[\s+]?([0-9]*)(\.([0-9]+))?( +)?([kmgtp]?b?)$/i); + var matches = s.match(/^[\s+]?([0-9]*)(\.([0-9]+))?( +)?([kmgtp]?b?)$/i) if (matches !== null) { - bytes = parseFloat(s); + bytes = parseFloat(s) if (!isFinite(bytes)) { - return null; + return null } } else { - return null; + return null } if (matches[5]) { - bytes = bytes * bytesArray[matches[5]]; + bytes = bytes * bytesArray[matches[5]] } - bytes = Math.round(bytes); - return bytes; + bytes = Math.round(bytes) + return bytes }, /** - * @param timestamp - * @param format + * @param {string|number} timestamp timestamp + * @param {string} format date format, see momentjs docs * @returns {string} timestamp formatted as requested */ - formatDate: function (timestamp, format) { - format = format || "LLL"; - return moment(timestamp).format(format); + formatDate: function(timestamp, format) { + format = format || 'LLL' + return moment(timestamp).format(format) }, /** - * @param timestamp + * @param {string|number} timestamp timestamp * @returns {string} human readable difference from now */ - relativeModifiedDate: function (timestamp) { - var diff = moment().diff(moment(timestamp)); + relativeModifiedDate: function(timestamp) { + var diff = moment().diff(moment(timestamp)) if (diff >= 0 && diff < 45000) { - return t('core', 'seconds ago'); + return t('core', 'seconds ago') } - return moment(timestamp).fromNow(); + return moment(timestamp).fromNow() }, /** * Returns whether this is IE * - * @return {bool} true if this is IE, false otherwise + * @returns {bool} true if this is IE, false otherwise */ - isIE: function () { - return $('html').hasClass('ie'); + isIE: function() { + return $('html').hasClass('ie') }, /** * Returns the width of a generic browser scrollbar * - * @return {int} width of scrollbar + * @returns {int} width of scrollbar */ - getScrollBarWidth: function () { + getScrollBarWidth: function() { if (this._scrollBarWidth) { - return this._scrollBarWidth; + return this._scrollBarWidth } - var inner = document.createElement('p'); - inner.style.width = "100%"; - inner.style.height = "200px"; - - var outer = document.createElement('div'); - outer.style.position = "absolute"; - outer.style.top = "0px"; - outer.style.left = "0px"; - outer.style.visibility = "hidden"; - outer.style.width = "200px"; - outer.style.height = "150px"; - outer.style.overflow = "hidden"; - outer.appendChild(inner); - - document.body.appendChild(outer); - var w1 = inner.offsetWidth; - outer.style.overflow = 'scroll'; - var w2 = inner.offsetWidth; + var inner = document.createElement('p') + inner.style.width = '100%' + inner.style.height = '200px' + + var outer = document.createElement('div') + outer.style.position = 'absolute' + outer.style.top = '0px' + outer.style.left = '0px' + outer.style.visibility = 'hidden' + outer.style.width = '200px' + outer.style.height = '150px' + outer.style.overflow = 'hidden' + outer.appendChild(inner) + + document.body.appendChild(outer) + var w1 = inner.offsetWidth + outer.style.overflow = 'scroll' + var w2 = inner.offsetWidth if (w1 === w2) { - w2 = outer.clientWidth; + w2 = outer.clientWidth } - document.body.removeChild(outer); + document.body.removeChild(outer) - this._scrollBarWidth = (w1 - w2); + this._scrollBarWidth = (w1 - w2) - return this._scrollBarWidth; + return this._scrollBarWidth }, /** * Remove the time component from a given date * * @param {Date} date date - * @return {Date} date with stripped time + * @returns {Date} date with stripped time */ - stripTime: function (date) { + stripTime: function(date) { // FIXME: likely to break when crossing DST // would be better to use a library like momentJS - return new Date(date.getFullYear(), date.getMonth(), date.getDate()); + return new Date(date.getFullYear(), date.getMonth(), date.getDate()) }, /** * Compare two strings to provide a natural sort - * @param a first string to compare - * @param b second string to compare - * @return -1 if b comes before a, 1 if a comes before b + * @param {string} a first string to compare + * @param {string} b second string to compare + * @returns {number} -1 if b comes before a, 1 if a comes before b * or 0 if the strings are identical */ - naturalSortCompare: function (a, b) { - var x; - var aa = chunkify(a); - var bb = chunkify(b); + naturalSortCompare: function(a, b) { + var x + var aa = chunkify(a) + var bb = chunkify(b) for (x = 0; aa[x] && bb[x]; x++) { if (aa[x] !== bb[x]) { - var aNum = Number(aa[x]), bNum = Number(bb[x]); + var aNum = Number(aa[x]); var bNum = Number(bb[x]) // note: == is correct here + /* eslint-disable-next-line */ if (aNum == aa[x] && bNum == bb[x]) { - return aNum - bNum; + return aNum - bNum } else { // Note: This locale setting isn't supported by all browsers but for the ones // that do there will be more consistency between client-server sorting - return aa[x].localeCompare(bb[x], OC.getLanguage()); + return aa[x].localeCompare(bb[x], OC.getLanguage()) } } } - return aa.length - bb.length; + return aa.length - bb.length }, /** * Calls the callback in a given interval until it returns true - * @param {function} callback + * @param {function} callback function to call on success * @param {integer} interval in milliseconds */ - waitFor: function (callback, interval) { - var internalCallback = function () { + waitFor: function(callback, interval) { + var internalCallback = function() { if (callback() !== true) { - setTimeout(internalCallback, interval); + setTimeout(internalCallback, interval) } - }; + } - internalCallback(); + internalCallback() }, /** * Checks if a cookie with the given name is present and is set to the provided value. * @param {string} name name of the cookie * @param {string} value value of the cookie - * @return {boolean} true if the cookie with the given name has the given value + * @returns {boolean} true if the cookie with the given name has the given value */ - isCookieSetToValue: function (name, value) { - var cookies = document.cookie.split(';'); + isCookieSetToValue: function(name, value) { + var cookies = document.cookie.split(';') for (var i = 0; i < cookies.length; i++) { - var cookie = cookies[i].split('='); + var cookie = cookies[i].split('=') if (cookie[0].trim() === name && cookie[1].trim() === value) { - return true; + return true } } - return false; + return false } } diff --git a/core/src/OC/xhr-error.js b/core/src/OC/xhr-error.js index 43b2eba7229..8d2ad115336 100644 --- a/core/src/OC/xhr-error.js +++ b/core/src/OC/xhr-error.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -34,11 +34,12 @@ import Notification from './notification' */ export const ajaxConnectionLostHandler = _.throttle(() => { Notification.showTemporary(t('core', 'Connection to server lost')) -}, 7 * 1000, {trailing: false}) +}, 7 * 1000, { trailing: false }) /** * Process ajax error, redirects to main page * if an error/auth error status was returned. + * @param {XMLHttpRequest} xhr xhr request */ export const processAjaxError = xhr => { // purposefully aborted request ? @@ -50,18 +51,18 @@ export const processAjaxError = xhr => { if (_.contains([302, 303, 307, 401], xhr.status) && OC.currentUser) { // sometimes "beforeunload" happens later, so need to defer the reload a bit - setTimeout(function () { + setTimeout(function() { if (!OC._userIsNavigatingAway && !OC._reloadCalled) { let timer = 0 const seconds = 5 - const interval = setInterval(function () { - Notification.showUpdate(n('core', 'Problem loading page, reloading in %n second', 'Problem loading page, reloading in %n seconds', seconds - timer)) - if (timer >= seconds) { - clearInterval(interval) - OC.reload() - } - timer++ - }, 1000 // 1 second interval + const interval = setInterval(function() { + Notification.showUpdate(n('core', 'Problem loading page, reloading in %n second', 'Problem loading page, reloading in %n seconds', seconds - timer)) + if (timer >= seconds) { + clearInterval(interval) + OC.reload() + } + timer++ + }, 1000 // 1 second interval ) // only call reload once @@ -70,7 +71,7 @@ export const processAjaxError = xhr => { }, 100) } else if (xhr.status === 0) { // Connection lost (e.g. WiFi disconnected or server is down) - setTimeout(function () { + setTimeout(function() { if (!OC._userIsNavigatingAway && !OC._reloadCalled) { // TODO: call method above directly OC._ajaxConnectionLostHandler() @@ -85,7 +86,7 @@ export const processAjaxError = xhr => { * This means that if this XHR object returns 401 or session timeout errors, * the current page will automatically be reloaded. * - * @param {XMLHttpRequest} xhr + * @param {XMLHttpRequest} xhr xhr request */ export const registerXHRForErrorProcessing = xhr => { const loadCallback = () => { @@ -93,7 +94,7 @@ export const registerXHRForErrorProcessing = xhr => { return } - if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { + if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { return } diff --git a/core/src/OCA/index.js b/core/src/OCA/index.js index fa354456c91..4b87d325a55 100644 --- a/core/src/OCA/index.js +++ b/core/src/OCA/index.js @@ -23,4 +23,4 @@ * Namespace for apps * @namespace OCA */ -export default {}; +export default {} diff --git a/core/src/OCP/appconfig.js b/core/src/OCP/appconfig.js index 9c5b063566f..f4213419aab 100644 --- a/core/src/OCP/appconfig.js +++ b/core/src/OCP/appconfig.js @@ -23,94 +23,94 @@ import $ from 'jquery' import OC from '../OC/index' /** - * @param {string} method - * @param {string} endpoint - * @param {Object} [options] - * @param {Object} [options.data] - * @param {function} [options.success] - * @param {function} [options.error] + * @param {string} method 'post' or 'delete' + * @param {string} endpoint endpoint + * @param {Object} [options] destructuring object + * @param {Object} [options.data] option data + * @param {function} [options.success] success callback + * @param {function} [options.error] error callback * @internal */ -function call (method, endpoint, options) { +function call(method, endpoint, options) { if ((method === 'post' || method === 'delete') && OC.PasswordConfirmation.requiresPasswordConfirmation()) { - OC.PasswordConfirmation.requirePasswordConfirmation(_.bind(call, this, method, endpoint, options)); - return; + OC.PasswordConfirmation.requirePasswordConfirmation(_.bind(call, this, method, endpoint, options)) + return } - options = options || {}; + options = options || {} $.ajax({ type: method.toUpperCase(), url: OC.linkToOCS('apps/provisioning_api/api/v1', 2) + 'config/apps' + endpoint, data: options.data || {}, success: options.success, error: options.error - }); + }) } /** - * @param {Object} [options] - * @param {function} [options.success] + * @param {Object} [options] destructuring object + * @param {function} [options.success] success callback * @since 11.0.0 */ -export function getApps (options) { - call('get', '', options); +export function getApps(options) { + call('get', '', options) } /** - * @param {string} app - * @param {Object} [options] - * @param {function} [options.success] - * @param {function} [options.error] + * @param {string} app app id + * @param {Object} [options] destructuring object + * @param {function} [options.success] success callback + * @param {function} [options.error] error callback * @since 11.0.0 */ -export function getKeys (app, options) { - call('get', '/' + app, options); +export function getKeys(app, options) { + call('get', '/' + app, options) } /** - * @param {string} app - * @param {string} key - * @param {string|function} defaultValue - * @param {Object} [options] - * @param {function} [options.success] - * @param {function} [options.error] + * @param {string} app app id + * @param {string} key key + * @param {string|function} defaultValue default value + * @param {Object} [options] destructuring object + * @param {function} [options.success] success callback + * @param {function} [options.error] error callback * @since 11.0.0 */ -export function getValue (app, key, defaultValue, options) { - options = options || {}; +export function getValue(app, key, defaultValue, options) { + options = options || {} options.data = { defaultValue: defaultValue - }; + } - call('get', '/' + app + '/' + key, options); + call('get', '/' + app + '/' + key, options) } /** - * @param {string} app - * @param {string} key - * @param {string} value - * @param {Object} [options] - * @param {function} [options.success] - * @param {function} [options.error] + * @param {string} app app id + * @param {string} key key + * @param {string} value value + * @param {Object} [options] destructuring object + * @param {function} [options.success] success callback + * @param {function} [options.error] error callback * @since 11.0.0 */ -export function setValue (app, key, value, options) { - options = options || {}; +export function setValue(app, key, value, options) { + options = options || {} options.data = { value: value - }; + } - call('post', '/' + app + '/' + key, options); + call('post', '/' + app + '/' + key, options) } /** - * @param {string} app - * @param {string} key - * @param {Object} [options] - * @param {function} [options.success] - * @param {function} [options.error] + * @param {string} app app id + * @param {string} key key + * @param {Object} [options] destructuring object + * @param {function} [options.success] success callback + * @param {function} [options.error] error callback * @since 11.0.0 */ -export function deleteKey (app, key, options) { - call('delete', '/' + app + '/' + key, options); +export function deleteKey(app, key, options) { + call('delete', '/' + app + '/' + key, options) } diff --git a/core/src/OCP/collaboration.js b/core/src/OCP/collaboration.js index 162fe8e2a75..4eea517f3aa 100644 --- a/core/src/OCP/collaboration.js +++ b/core/src/OCP/collaboration.js @@ -1,4 +1,4 @@ -/* +/** * @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net> * * @author Julius Härtl <jus@bitgrid.net> @@ -30,13 +30,14 @@ /** * @type {TypeDefinition[]} **/ -let types = {}; +let types = {} /** * Those translations will be used by the vue component but they should be shipped with the server * FIXME: Those translations should be added to the library + * @returns {Array} */ -const l10nProjects = () => { +export const l10nProjects = () => { return [ t('core', 'Add to a project'), t('core', 'Show details'), @@ -47,32 +48,32 @@ const l10nProjects = () => { t('core', 'Failed to add the item to the project'), t('core', 'Connect items to a project to make them easier to find'), t('core', 'Type to search for existing projects') - ]; + ] } export default { /** * - * @param type - * @param {TypeDefinition} typeDefinition + * @param {string} type type + * @param {TypeDefinition} typeDefinition typeDefinition */ registerType(type, typeDefinition) { - types[type] = typeDefinition; + types[type] = typeDefinition }, trigger(type) { return types[type].action() }, getTypes() { - return Object.keys(types); + return Object.keys(types) }, getIcon(type) { - return types[type].typeIconClass || ''; + return types[type].typeIconClass || '' }, getLabel(type) { return escapeHTML(types[type].typeString || type) }, getLink(type, id) { /* TODO: Allow action to be executed instead of href as well */ - return typeof types[type] !== 'undefined' ? types[type].link(id) : ''; + return typeof types[type] !== 'undefined' ? types[type].link(id) : '' } -}; +} diff --git a/core/src/OCP/comments.js b/core/src/OCP/comments.js index 1500e1937c3..2e12accddce 100644 --- a/core/src/OCP/comments.js +++ b/core/src/OCP/comments.js @@ -18,34 +18,34 @@ import $ from 'jquery' * The downside: anything not ascii is excluded. Not sure how common it is in areas using different * alphabets… the upside: fake domains with similar looking characters won't be formatted as links */ -const urlRegex = /(\s|^)(https?:\/\/)?((?:[-A-Z0-9+_]+\.)+[-A-Z]+(?:\/[-A-Z0-9+&@#%?=~_|!:,.;()]*)*)(\s|$)/ig; +const urlRegex = /(\s|^)(https?:\/\/)?((?:[-A-Z0-9+_]+\.)+[-A-Z]+(?:\/[-A-Z0-9+&@#%?=~_|!:,.;()]*)*)(\s|$)/ig -export function plainToRich (content) { - return this.formatLinksRich(content); +export function plainToRich(content) { + return this.formatLinksRich(content) } -export function richToPlain (content) { - return this.formatLinksPlain(content); +export function richToPlain(content) { + return this.formatLinksPlain(content) } -export function formatLinksRich (content) { - return content.replace(urlRegex, function (_, leadingSpace, protocol, url, trailingSpace) { - let linkText = url; +export function formatLinksRich(content) { + return content.replace(urlRegex, function(_, leadingSpace, protocol, url, trailingSpace) { + let linkText = url if (!protocol) { - protocol = 'https://'; + protocol = 'https://' } else if (protocol === 'http://') { - linkText = protocol + url; + linkText = protocol + url } - return leadingSpace + '<a class="external" target="_blank" rel="noopener noreferrer" href="' + protocol + url + '">' + linkText + '</a>' + trailingSpace; - }); + return leadingSpace + '<a class="external" target="_blank" rel="noopener noreferrer" href="' + protocol + url + '">' + linkText + '</a>' + trailingSpace + }) } -export function formatLinksPlain (content) { - const $content = $('<div></div>').html(content); - $content.find('a').each(function () { - const $this = $(this); - $this.html($this.attr('href')); - }); - return $content.html(); +export function formatLinksPlain(content) { + const $content = $('<div></div>').html(content) + $content.find('a').each(function() { + const $this = $(this) + $this.html($this.attr('href')) + }) + return $content.html() } diff --git a/core/src/OCP/index.js b/core/src/OCP/index.js index a4d8f46b88d..7d5edd5a9d0 100644 --- a/core/src/OCP/index.js +++ b/core/src/OCP/index.js @@ -18,4 +18,4 @@ export default { Loader, Toast, WhatsNew -}; +} diff --git a/core/src/OCP/initialstate.js b/core/src/OCP/initialstate.js index af5dd91e3f9..0a6f364ed00 100644 --- a/core/src/OCP/initialstate.js +++ b/core/src/OCP/initialstate.js @@ -24,19 +24,19 @@ * @namespace OCP.InitialState */ -export function loadState (app, key) { - const elem = document.querySelector(`#initial-state-${app}-${key}`); +export function loadState(app, key) { + const elem = document.querySelector(`#initial-state-${app}-${key}`) if (elem === null) { const msg = `Could not find initial state ${key} of ${app}` - console.debug(msg); - throw new Error(msg); + console.debug(msg) + throw new Error(msg) } try { - return JSON.parse(atob(elem.value)); + return JSON.parse(atob(elem.value)) } catch (e) { const msg = `Could not parse initial state ${key} of ${app}` - console.debug(msg); - throw new Error(msg); + console.debug(msg) + throw new Error(msg) } } diff --git a/core/src/OCP/loader.js b/core/src/OCP/loader.js index 9f551b90a1f..7f72c47ca64 100644 --- a/core/src/OCP/loader.js +++ b/core/src/OCP/loader.js @@ -1,4 +1,4 @@ -/* +/** * @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net> * * @author Julius Härtl <jus@bitgrid.net> @@ -20,61 +20,60 @@ * */ -let loadedScripts = {}; -let loadedStylesheets = {}; +let loadedScripts = {} +let loadedStylesheets = {} /** * @namespace OCP * @class Loader */ export default { - /** * Load a script asynchronously * - * @param {string} app - * @param {string} file + * @param {string} app the app name + * @param {string} file the script file name * @returns {Promise} */ loadScript: function(app, file) { - const key = app + file; + const key = app + file if (loadedScripts.hasOwnProperty(key)) { - return Promise.resolve(); + return Promise.resolve() } - loadedScripts[key] = true; - return new Promise(function (resolve, reject) { - var scriptPath = OC.filePath(app, 'js', file); - var script = document.createElement('script'); - script.src = scriptPath; - script.setAttribute('nonce', btoa(OC.requestToken)); - script.onload = () => resolve(); - script.onerror = () => reject(`Failed to load script from ${scriptPath}`); - document.head.appendChild(script); - }); + loadedScripts[key] = true + return new Promise(function(resolve, reject) { + var scriptPath = OC.filePath(app, 'js', file) + var script = document.createElement('script') + script.src = scriptPath + script.setAttribute('nonce', btoa(OC.requestToken)) + script.onload = () => resolve() + script.onerror = () => reject(new Error(`Failed to load script from ${scriptPath}`)) + document.head.appendChild(script) + }) }, /** * Load a stylesheet file asynchronously * - * @param {string} app - * @param {string} file + * @param {string} app the app name + * @param {string} file the script file name * @returns {Promise} */ loadStylesheet: function(app, file) { - const key = app + file; + const key = app + file if (loadedStylesheets.hasOwnProperty(key)) { - return Promise.resolve(); + return Promise.resolve() } - loadedStylesheets[key] = true; - return new Promise(function (resolve, reject) { - var stylePath = OC.filePath(app, 'css', file); - var link = document.createElement('link'); - link.href = stylePath; - link.type = 'text/css'; - link.rel = 'stylesheet'; - link.onload = () => resolve(); - link.onerror = () => reject(`Failed to load stylesheet from ${stylePath}`); - document.head.appendChild(link); - }); - }, + loadedStylesheets[key] = true + return new Promise(function(resolve, reject) { + var stylePath = OC.filePath(app, 'css', file) + var link = document.createElement('link') + link.href = stylePath + link.type = 'text/css' + link.rel = 'stylesheet' + link.onload = () => resolve() + link.onerror = () => reject(new Error(`Failed to load stylesheet from ${stylePath}`)) + document.head.appendChild(link) + }) + } } diff --git a/core/src/OCP/toast.js b/core/src/OCP/toast.js index 113d37ab412..58f98d93480 100644 --- a/core/src/OCP/toast.js +++ b/core/src/OCP/toast.js @@ -33,34 +33,34 @@ const TOAST_TYPE_CLASES = { const Toast = { success(text, options = {}) { - options.type = 'success'; + options.type = 'success' return this.message(text, options) }, warning(text, options = {}) { - options.type = 'warning'; + options.type = 'warning' return this.message(text, options) }, error(text, options = {}) { - options.type = 'error'; + options.type = 'error' return this.message(text, options) }, info(text, options = {}) { - options.type = 'info'; + options.type = 'info' return this.message(text, options) }, message(text, options) { - options = options || {}; + options = options || {} _.defaults(options, { timeout: 7, isHTML: false, type: undefined, close: true, callback: () => {} - }); + }) if (!options.isHTML) { text = $('<div/>').text(text).html() } @@ -71,7 +71,7 @@ const Toast = { const toast = Toastify({ text: text, - duration: options.timeout ? options.timeout*1000 : null, + duration: options.timeout ? options.timeout * 1000 : null, callback: options.callback, close: options.close, gravity: 'top', @@ -82,7 +82,7 @@ const Toast = { }) toast.showToast() // add toastify object to the element for reference in legacy OC.Notification - toast.toastElement.toastify = toast; + toast.toastElement.toastify = toast return toast } } diff --git a/core/src/OCP/whatsnew.js b/core/src/OCP/whatsnew.js index 837cb23217c..c2935c5e78c 100644 --- a/core/src/OCP/whatsnew.js +++ b/core/src/OCP/whatsnew.js @@ -12,121 +12,121 @@ import $ from 'jquery' import OC from '../OC/index' -export function query (options) { - options = options || {}; - var dismissOptions = options.dismiss || {}; +export function query(options) { + options = options || {} + var dismissOptions = options.dismiss || {} $.ajax({ type: 'GET', url: options.url || OC.linkToOCS('core', 2) + 'whatsnew?format=json', - success: options.success || function (data, statusText, xhr) { - onQuerySuccess(data, statusText, xhr, dismissOptions); + success: options.success || function(data, statusText, xhr) { + onQuerySuccess(data, statusText, xhr, dismissOptions) }, error: options.error || onQueryError - }); + }) } -export function dismiss (version, options) { - options = options || {}; +export function dismiss(version, options) { + options = options || {} $.ajax({ type: 'POST', url: options.url || OC.linkToOCS('core', 2) + 'whatsnew', - data: {version: encodeURIComponent(version)}, + data: { version: encodeURIComponent(version) }, success: options.success || onDismissSuccess, error: options.error || onDismissError - }); + }) // remove element immediately - $('.whatsNewPopover').remove(); + $('.whatsNewPopover').remove() } -function onQuerySuccess (data, statusText, xhr, dismissOptions) { - console.debug('querying Whats New data was successful: ' + statusText); - console.debug(data); +function onQuerySuccess(data, statusText, xhr, dismissOptions) { + console.debug('querying Whats New data was successful: ' + statusText) + console.debug(data) if (xhr.status !== 200) { - return; + return } - var item, menuItem, text, icon; + var item, menuItem, text, icon - var div = document.createElement('div'); - div.classList.add('popovermenu', 'open', 'whatsNewPopover', 'menu-left'); + var div = document.createElement('div') + div.classList.add('popovermenu', 'open', 'whatsNewPopover', 'menu-left') - var list = document.createElement('ul'); + var list = document.createElement('ul') // header - item = document.createElement('li'); - menuItem = document.createElement('span'); - menuItem.className = "menuitem"; - - text = document.createElement('span'); - text.innerText = t('core', 'New in') + ' ' + data['ocs']['data']['product']; - text.className = 'caption'; - menuItem.appendChild(text); - - icon = document.createElement('span'); - icon.className = 'icon-close'; - icon.onclick = function () { - dismiss(data['ocs']['data']['version'], dismissOptions); - }; - menuItem.appendChild(icon); + item = document.createElement('li') + menuItem = document.createElement('span') + menuItem.className = 'menuitem' + + text = document.createElement('span') + text.innerText = t('core', 'New in') + ' ' + data['ocs']['data']['product'] + text.className = 'caption' + menuItem.appendChild(text) + + icon = document.createElement('span') + icon.className = 'icon-close' + icon.onclick = function() { + dismiss(data['ocs']['data']['version'], dismissOptions) + } + menuItem.appendChild(icon) - item.appendChild(menuItem); - list.appendChild(item); + item.appendChild(menuItem) + list.appendChild(item) // Highlights for (var i in data['ocs']['data']['whatsNew']['regular']) { - var whatsNewTextItem = data['ocs']['data']['whatsNew']['regular'][i]; - item = document.createElement('li'); + var whatsNewTextItem = data['ocs']['data']['whatsNew']['regular'][i] + item = document.createElement('li') - menuItem = document.createElement('span'); - menuItem.className = "menuitem"; + menuItem = document.createElement('span') + menuItem.className = 'menuitem' - icon = document.createElement('span'); - icon.className = 'icon-checkmark'; - menuItem.appendChild(icon); + icon = document.createElement('span') + icon.className = 'icon-checkmark' + menuItem.appendChild(icon) - text = document.createElement('p'); - text.innerHTML = _.escape(whatsNewTextItem); - menuItem.appendChild(text); + text = document.createElement('p') + text.innerHTML = _.escape(whatsNewTextItem) + menuItem.appendChild(text) - item.appendChild(menuItem); - list.appendChild(item); + item.appendChild(menuItem) + list.appendChild(item) } // Changelog URL if (!_.isUndefined(data['ocs']['data']['changelogURL'])) { - item = document.createElement('li'); + item = document.createElement('li') - menuItem = document.createElement('a'); - menuItem.href = data['ocs']['data']['changelogURL']; - menuItem.rel = 'noreferrer noopener'; - menuItem.target = '_blank'; + menuItem = document.createElement('a') + menuItem.href = data['ocs']['data']['changelogURL'] + menuItem.rel = 'noreferrer noopener' + menuItem.target = '_blank' - icon = document.createElement('span'); - icon.className = 'icon-link'; - menuItem.appendChild(icon); + icon = document.createElement('span') + icon.className = 'icon-link' + menuItem.appendChild(icon) - text = document.createElement('span'); - text.innerText = t('core', 'View changelog'); - menuItem.appendChild(text); + text = document.createElement('span') + text.innerText = t('core', 'View changelog') + menuItem.appendChild(text) - item.appendChild(menuItem); - list.appendChild(item); + item.appendChild(menuItem) + list.appendChild(item) } - div.appendChild(list); - document.body.appendChild(div); + div.appendChild(list) + document.body.appendChild(div) } -function onQueryError (x, t, e) { - console.debug('querying Whats New Data resulted in an error: ' + t + e); - console.debug(x); +function onQueryError(x, t, e) { + console.debug('querying Whats New Data resulted in an error: ' + t + e) + console.debug(x) } -function onDismissSuccess (data) { - //noop +function onDismissSuccess(data) { + // noop } -function onDismissError (data) { - console.debug('dismissing Whats New data resulted in an error: ' + data); -}
\ No newline at end of file +function onDismissError(data) { + console.debug('dismissing Whats New data resulted in an error: ' + data) +} diff --git a/core/src/Polyfill/console.js b/core/src/Polyfill/console.js index 72a1165e437..faa32c457c6 100644 --- a/core/src/Polyfill/console.js +++ b/core/src/Polyfill/console.js @@ -1,4 +1,5 @@ -/* +/* eslint-disable no-console */ +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -19,13 +20,13 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -if (typeof console === "undefined" || typeof console.log === "undefined") { +if (typeof console === 'undefined' || typeof console.log === 'undefined') { if (!window.console) { - window.console = {}; + window.console = {} } - const noOp = () => {}; - const methods = ['log', 'debug', 'warn', 'info', 'error', 'assert', 'time', 'timeEnd']; + const noOp = () => {} + const methods = ['log', 'debug', 'warn', 'info', 'error', 'assert', 'time', 'timeEnd'] for (var i = 0; i < methods.length; i++) { - console[methods[i]] = noOp; + console[methods[i]] = noOp } } diff --git a/core/src/Polyfill/tooltip.js b/core/src/Polyfill/tooltip.js index 0ad3686d016..08cc58c338c 100644 --- a/core/src/Polyfill/tooltip.js +++ b/core/src/Polyfill/tooltip.js @@ -22,16 +22,16 @@ $.prototype.tooltip = (function(tooltip) { return function(config) { try { - return tooltip.call(this, config); + return tooltip.call(this, config) } catch (ex) { if (ex instanceof TypeError && config === 'destroy') { - console.error('Deprecated call $.tooltip(\'destroy\') has been deprecated and should be removed'); - return tooltip.call(this, 'dispose'); + console.error('Deprecated call $.tooltip(\'destroy\') has been deprecated and should be removed') + return tooltip.call(this, 'dispose') } if (ex instanceof TypeError && config === 'fixTitle') { - console.error('Deprecated call $.tooltip(\'fixTitle\') has been deprecated and should be removed'); - return tooltip.call(this, '_fixTitle'); + console.error('Deprecated call $.tooltip(\'fixTitle\') has been deprecated and should be removed') + return tooltip.call(this, '_fixTitle') } } - }; -})($.prototype.tooltip); + } +})($.prototype.tooltip) diff --git a/core/src/Polyfill/windows-phone.js b/core/src/Polyfill/windows-phone.js index 3d59074856b..983e412e453 100644 --- a/core/src/Polyfill/windows-phone.js +++ b/core/src/Polyfill/windows-phone.js @@ -20,10 +20,10 @@ */ // fix device width on windows phone -if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) { - const msViewportStyle = document.createElement("style"); +if ('-ms-user-select' in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) { + const msViewportStyle = document.createElement('style') msViewportStyle.appendChild( - document.createTextNode("@-ms-viewport{width:auto!important}") - ); - document.getElementsByTagName("head")[0].appendChild(msViewportStyle); + document.createTextNode('@-ms-viewport{width:auto!important}') + ) + document.getElementsByTagName('head')[0].appendChild(msViewportStyle) } diff --git a/core/src/Util/escapeHTML.js b/core/src/Util/escapeHTML.js index f6cf868a6d0..b6596d44d21 100644 --- a/core/src/Util/escapeHTML.js +++ b/core/src/Util/escapeHTML.js @@ -22,9 +22,9 @@ /** * Sanitizes a HTML string by replacing all potential dangerous characters with HTML entities * @param {string} s String to sanitize - * @return {string} Sanitized string + * @returns {string} Sanitized string */ -export default function escapeHTML (s) { +export default function escapeHTML(s) { return s.toString() .split('&') .join('&') @@ -32,5 +32,5 @@ export default function escapeHTML (s) { .join('<').split('>') .join('>').split('"') .join('"').split('\'') - .join('''); + .join(''') } diff --git a/core/src/Util/format-date.js b/core/src/Util/format-date.js index 04a2d274de5..9551804d4ab 100644 --- a/core/src/Util/format-date.js +++ b/core/src/Util/format-date.js @@ -25,10 +25,10 @@ import OC from '../OC/index' /** * Format an UNIX timestamp to a human understandable format * @param {number} timestamp UNIX timestamp - * @return {string} Human readable format + * @returns {string} Human readable format * @deprecated 16.0.0 use OC.Util.formatDate instead */ -export default function formatDate (timestamp) { +export default function formatDate(timestamp) { console.warn('formatDate is deprecated, use OC.Util.formatDate instead') - return OC.Util.formatDate(timestamp); + return OC.Util.formatDate(timestamp) } diff --git a/core/src/Util/get-url-parameter.js b/core/src/Util/get-url-parameter.js index 6051e923e9d..6f809994f10 100644 --- a/core/src/Util/get-url-parameter.js +++ b/core/src/Util/get-url-parameter.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -23,10 +23,11 @@ * Get the value of a URL parameter * @link http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery * @param {string} name URL parameter - * @return {string} + * @returns {string} */ -export default function getURLParameter (name) { +export default function getURLParameter(name) { return decodeURIComponent( + // eslint-disable-next-line no-sparse-arrays (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ''])[1].replace(/\+/g, '%20') - ) || ''; + ) || '' } diff --git a/core/src/Util/human-file-size.js b/core/src/Util/human-file-size.js index e671a86d053..586ef0e9267 100644 --- a/core/src/Util/human-file-size.js +++ b/core/src/Util/human-file-size.js @@ -23,29 +23,29 @@ * Returns a human readable file size * @param {number} size Size in bytes * @param {boolean} skipSmallSizes return '< 1 kB' for small files - * @return {string} + * @returns {string} */ -export default function humanFileSize (size, skipSmallSizes) { - var humanList = ['B', 'KB', 'MB', 'GB', 'TB']; +export default function humanFileSize(size, skipSmallSizes) { + var humanList = ['B', 'KB', 'MB', 'GB', 'TB'] // Calculate Log with base 1024: size = 1024 ** order - var order = size > 0 ? Math.floor(Math.log(size) / Math.log(1024)) : 0; + var order = size > 0 ? Math.floor(Math.log(size) / Math.log(1024)) : 0 // Stay in range of the byte sizes that are defined - order = Math.min(humanList.length - 1, order); - var readableFormat = humanList[order]; - var relativeSize = (size / Math.pow(1024, order)).toFixed(1); + order = Math.min(humanList.length - 1, order) + var readableFormat = humanList[order] + var relativeSize = (size / Math.pow(1024, order)).toFixed(1) if (skipSmallSizes === true && order === 0) { - if (relativeSize !== "0.0") { - return '< 1 KB'; + if (relativeSize !== '0.0') { + return '< 1 KB' } else { - return '0 KB'; + return '0 KB' } } if (order < 2) { - relativeSize = parseFloat(relativeSize).toFixed(0); + relativeSize = parseFloat(relativeSize).toFixed(0) } else if (relativeSize.substr(relativeSize.length - 2, 2) === '.0') { - relativeSize = relativeSize.substr(0, relativeSize.length - 2); + relativeSize = relativeSize.substr(0, relativeSize.length - 2) } else { - relativeSize = parseFloat(relativeSize).toLocaleString(OC.getCanonicalLocale()); + relativeSize = parseFloat(relativeSize).toLocaleString(OC.getCanonicalLocale()) } - return relativeSize + ' ' + readableFormat; + return relativeSize + ' ' + readableFormat } diff --git a/core/src/Util/relative-modified-date.js b/core/src/Util/relative-modified-date.js index 3837d2c372e..4e41f939250 100644 --- a/core/src/Util/relative-modified-date.js +++ b/core/src/Util/relative-modified-date.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -24,14 +24,16 @@ import OC from '../OC/index' /** * Takes an absolute timestamp and return a string with a human-friendly relative date + * * @param {number} timestamp A Unix timestamp * @deprecated use OC.Util.relativeModifiedDate instead but beware the argument value + * @returns {string} */ -export default function relative_modified_date (timestamp) { - console.warn('relative_modified_date is deprecated, use OC.Util.relativeModifiedDate instead') +export default function relativeModifiedDate(timestamp) { + console.warn('relativeModifiedDate is deprecated, use OC.Util.relativeModifiedDate instead') /* Were multiplying by 1000 to bring the timestamp back to its original value per https://github.com/owncloud/core/pull/10647#discussion_r16790315 */ - return OC.Util.relativeModifiedDate(timestamp * 1000); + return OC.Util.relativeModifiedDate(timestamp * 1000) } diff --git a/core/src/components/ContactsMenu.js b/core/src/components/ContactsMenu.js index 8243b9ca1f2..661b6d8e7c6 100644 --- a/core/src/components/ContactsMenu.js +++ b/core/src/components/ContactsMenu.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -20,13 +20,13 @@ */ import $ from 'jquery' - import OC from '../OC' /** * @todo move to contacts menu code https://github.com/orgs/nextcloud/projects/31#card-21213129 */ export const setUp = () => { + // eslint-disable-next-line no-new new OC.ContactsMenu({ el: $('#contactsmenu .menu'), trigger: $('#contactsmenu .menutoggle') diff --git a/core/src/components/login/LoginForm.vue b/core/src/components/login/LoginForm.vue index 3ba13b4f025..e9f44cccb8f 100644 --- a/core/src/components/login/LoginForm.vue +++ b/core/src/components/login/LoginForm.vue @@ -21,195 +21,195 @@ <template> <form method="post" - name="login" - :action="OC.generateUrl('login')" - @submit="submit"> + name="login" + :action="OC.generateUrl('login')" + @submit="submit"> <fieldset> <div v-if="apacheAuthFailed" - class="warning"> + class="warning"> {{ t('core', 'Server side authentication failed!') }}<br> <small>{{ t('core', 'Please contact your administrator.') }} </small> </div> - <div v-for="message in messages" - class="warning"> + <div v-for="(message, index) in messages" + :key="index" + class="warning"> {{ message }}<br> </div> <div v-if="internalException" - class="warning"> + class="warning"> {{ t('core', 'An internal error occurred.') }}<br> <small>{{ t('core', 'Please try again or contact your administrator.') }} </small> </div> <div id="message" - class="hidden"> - <img class="float-spinner" alt="" - :src="OC.imagePath('core', 'loading-dark.gif')"> - <span id="messageText"></span> + class="hidden"> + <img class="float-spinner" + alt="" + :src="OC.imagePath('core', 'loading-dark.gif')"> + <span id="messageText" /> <!-- the following div ensures that the spinner is always inside the #message div --> - <div style="clear: both;"></div> + <div style="clear: both;" /> </div> <p class="grouptop" - :class="{shake: invalidPassword}"> - <input type="text" - name="user" - id="user" - ref="user" - :autocomplete="autoCompleteAllowed ? 'on' : 'off'" - :placeholder="t('core', 'Username or email')" - :aria-label="t('core', 'Username or email')" - v-model="user" - @change="updateUsername" - required> + :class="{shake: invalidPassword}"> + <input id="user" + ref="user" + v-model="user" + type="text" + name="user" + :autocomplete="autoCompleteAllowed ? 'on' : 'off'" + :placeholder="t('core', 'Username or email')" + :aria-label="t('core', 'Username or email')" + required + @change="updateUsername"> <label for="user" class="infield">{{ t('core', 'Username or email') }}</label> </p> <p class="groupbottom" - :class="{shake: invalidPassword}"> - <input :type="passwordInputType" - class="password-with-toggle" - name="password" - id="password" - ref="password" - :autocomplete="autoCompleteAllowed ? 'on' : 'off'" - :placeholder="t('core', 'Password')" - :aria-label="t('core', 'Password')" - required> + :class="{shake: invalidPassword}"> + <input id="password" + ref="password" + :type="passwordInputType" + class="password-with-toggle" + name="password" + :autocomplete="autoCompleteAllowed ? 'on' : 'off'" + :placeholder="t('core', 'Password')" + :aria-label="t('core', 'Password')" + required> <label for="password" - class="infield">{{ t('Password') }}</label> - <a href="#" @click.stop.prevent="togglePassword" class="toggle-password"> - <img :src="OC.imagePath('core', 'actions/toggle.svg')"/> + class="infield">{{ t('Password') }}</label> + <a href="#" class="toggle-password" @click.stop.prevent="togglePassword"> + <img :src="OC.imagePath('core', 'actions/toggle.svg')"> </a> </p> <div id="submit-wrapper"> - <input type="submit" - class="login primary" - name="submit" - id="submit-form" - title="" - :value="!loading ? t('core', 'Log in') : t('core', 'Logging in …')" /> + <input id="submit-form" + type="submit" + class="login primary" + title="" + :value="!loading ? t('core', 'Log in') : t('core', 'Logging in …')"> <div class="submit-icon" - :class="{ - 'icon-confirm-white': !loading, - 'icon-loading-small': loading && invertedColors, - 'icon-loading-small-dark': loading && !invertedColors, - }"></div> + :class="{ + 'icon-confirm-white': !loading, + 'icon-loading-small': loading && invertedColors, + 'icon-loading-small-dark': loading && !invertedColors, + }" /> </div> <p v-if="invalidPassword" - class="warning wrongPasswordMsg"> + class="warning wrongPasswordMsg"> {{ t('core', 'Wrong username or password.') }} </p> <p v-else-if="userDisabled" - class="warning userDisabledMsg"> + class="warning userDisabledMsg"> {{ t('lib', 'User disabled') }} </p> <p v-if="throttleDelay && throttleDelay > 5000" - class="warning throttledMsg"> + class="warning throttledMsg"> {{ t('core', 'We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds.') }} </p> <input v-if="redirectUrl" - type="hidden" - name="redirect_url" - :value="redirectUrl"> + type="hidden" + name="redirect_url" + :value="redirectUrl"> <input type="hidden" - name="timezone" - :value="timezone" /> + name="timezone" + :value="timezone"> <input type="hidden" - name="timezone_offset" - :value="timezoneOffset"/> + name="timezone_offset" + :value="timezoneOffset"> <input type="hidden" - name="requesttoken" - :value="OC.requestToken"> + name="requesttoken" + :value="OC.requestToken"> </fieldset> </form> </template> <script> - import jstz from 'jstimezonedetect' +import jstz from 'jstimezonedetect' - export default { - name: 'LoginForm', - props: { - username: { - type: String, - default: '', - }, - redirectUrl: { - type: String, - }, - errors: { - type: Array, - default: () => [], - }, - messages: { - type: Array, - default: () => [], - }, - throttleDelay: { - type: Number, - }, - invertedColors: { - type: Boolean, - default: false, - }, - autoCompleteAllowed: { - type: Boolean, - default: true, - }, +export default { + name: 'LoginForm', + props: { + username: { + type: String, + default: '' }, - data () { - return { - loading: false, - timezone: jstz.determine().name(), - timezoneOffset: (-new Date().getTimezoneOffset() / 60), - user: this.username, - password: '', - passwordInputType: 'password', - } + redirectUrl: { + type: String + }, + errors: { + type: Array, + default: () => [] + }, + messages: { + type: Array, + default: () => [] + }, + throttleDelay: { + type: Number }, - computed: { - apacheAuthFailed () { - return this.errors.indexOf('apacheAuthFailed') !== -1 - }, - internalException () { - return this.errors.indexOf('internalexception') !== -1 - }, - invalidPassword () { - return this.errors.indexOf('invalidpassword') !== -1 - }, - userDisabled () { - return this.errors.indexOf('userdisabled') !== -1 - }, + invertedColors: { + type: Boolean, + default: false + }, + autoCompleteAllowed: { + type: Boolean, + default: true + } + }, + data() { + return { + loading: false, + timezone: jstz.determine().name(), + timezoneOffset: (-new Date().getTimezoneOffset() / 60), + user: this.username, + password: '', + passwordInputType: 'password' + } + }, + computed: { + apacheAuthFailed() { + return this.errors.indexOf('apacheAuthFailed') !== -1 }, - mounted () { - if (this.username === '') { - this.$refs.user.focus() + internalException() { + return this.errors.indexOf('internalexception') !== -1 + }, + invalidPassword() { + return this.errors.indexOf('invalidpassword') !== -1 + }, + userDisabled() { + return this.errors.indexOf('userdisabled') !== -1 + } + }, + mounted() { + if (this.username === '') { + this.$refs.user.focus() + } else { + this.$refs.password.focus() + } + }, + methods: { + togglePassword() { + if (this.passwordInputType === 'password') { + this.passwordInputType = 'text' } else { - this.$refs.password.focus() + this.passwordInputType = 'password' } }, - methods: { - togglePassword () { - if(this.passwordInputType === 'password'){ - this.passwordInputType = 'text' - } - else{ - this.passwordInputType = 'password' - } - }, - updateUsername () { - this.$emit('update:username', this.user) - }, - submit () { - this.loading = true - this.$emit('submit') - } + updateUsername() { + this.$emit('update:username', this.user) + }, + submit() { + this.loading = true + this.$emit('submit') } } +} </script> <style scoped> diff --git a/core/src/components/login/ResetPassword.vue b/core/src/components/login/ResetPassword.vue index ac152342d4f..0fd50e43ea9 100644 --- a/core/src/components/login/ResetPassword.vue +++ b/core/src/components/login/ResetPassword.vue @@ -22,125 +22,123 @@ <template> <form @submit.prevent="submit"> <p> - <input type="text" - name="user" - id="user" - :placeholder="t('core', 'Username or email')" - :aria-label="t('core', 'Username or email')" - v-model="user" - @change="updateUsername" - required> + <input id="user" + v-model="user" + type="text" + name="user" + :placeholder="t('core', 'Username or email')" + :aria-label="t('core', 'Username or email')" + required + @change="updateUsername"> <!--<?php p($_['user_autofocus'] ? 'autofocus' : ''); ?> autocomplete="<?php p($_['login_form_autocomplete']); ?>" autocapitalize="none" autocorrect="off"--> <label for="user" class="infield">{{ t('core', 'Username or email') }}</label> </p> <div id="reset-password-wrapper"> - <input type="submit" - id="reset-password-submit" - class="login primary" - title="" - :value="t('core', 'Reset password')"/> + <input id="reset-password-submit" + type="submit" + class="login primary" + title="" + :value="t('core', 'Reset password')"> <div class="submit-icon" - :class="{ - 'icon-confirm-white': !loading, - 'icon-loading-small': loading && invertedColors, - 'icon-loading-small-dark': loading && !invertedColors, - }"></div> + :class="{ + 'icon-confirm-white': !loading, + 'icon-loading-small': loading && invertedColors, + 'icon-loading-small-dark': loading && !invertedColors, + }" /> </div> <p v-if="message === 'send-success'" - class="update"> + class="update"> {{ t('core', 'A password reset message has been sent to the e-mail address of this account. If you do not receive it, check your spam/junk folders or ask your local administrator for help.') }} <br> {{ t('core', 'If it is not there ask your local administrator.') }} </p> <p v-else-if="message === 'send-error'" - class="update warning"> + class="update warning"> {{ t('core', 'Couldn\'t send reset email. Please contact your administrator.') }} </p> <p v-else-if="message === 'reset-error'" - class="update warning"> + class="update warning"> {{ t('core', 'Password can not be changed. Please contact your administrator.') }} </p> <p v-else-if="message" - class="update" - :class="{warning: error}"> - - </p> + class="update" + :class="{warning: error}" /> <a href="#" - @click.prevent="$emit('abort')"> + @click.prevent="$emit('abort')"> {{ t('core', 'Back to login') }} </a> </form> </template> <script> - import Axios from 'nextcloud-axios' +import axios from 'nextcloud-axios' - import {generateUrl} from '../../OC/routing' +import { generateUrl } from '../../OC/routing' - export default { - name: 'ResetPassword', - props: { - username: { - type: String, - required: true, - }, - resetPasswordLink: { - type: String, - required: true, - }, - invertedColors: { - type: Boolean, - default: false, - } +export default { + name: 'ResetPassword', + props: { + username: { + type: String, + required: true }, - data() { - return { - error: false, - loading: false, - message: undefined, - user: this.username, - } + resetPasswordLink: { + type: String, + required: true }, - watch: { - username (value) { - this.user = value - } + invertedColors: { + type: Boolean, + default: false + } + }, + data() { + return { + error: false, + loading: false, + message: undefined, + user: this.username + } + }, + watch: { + username(value) { + this.user = value + } + }, + methods: { + updateUsername() { + this.$emit('update:username', this.user) }, - methods: { - updateUsername () { - this.$emit('update:username', this.user) - }, - submit () { - this.loading = true - this.error = false - this.message = '' - const url = generateUrl('/lostpassword/email'); + submit() { + this.loading = true + this.error = false + this.message = '' + const url = generateUrl('/lostpassword/email') - const data = { - user: this.user, - } + const data = { + user: this.user + } - return Axios.post(url, data) - .then(resp => resp.data) - .then(data => { - if (data.status !== 'success') { - throw new Error(`got status ${data.status}`) - } + return axios.post(url, data) + .then(resp => resp.data) + .then(data => { + if (data.status !== 'success') { + throw new Error(`got status ${data.status}`) + } - this.message = 'send-success' - }) - .catch(e => { - console.error('could not send reset e-mail request', e) + this.message = 'send-success' + }) + .catch(e => { + console.error('could not send reset e-mail request', e) - this.error = true - this.message = 'send-error' - }) - .then(() => this.loading = false) - } - }, + this.error = true + this.message = 'send-error' + }) + .then(() => { this.loading = false }) + } } +} </script> <style scoped> diff --git a/core/src/components/login/UpdatePassword.vue b/core/src/components/login/UpdatePassword.vue index 3b5ac32133d..c0976bf0d6f 100644 --- a/core/src/components/login/UpdatePassword.vue +++ b/core/src/components/login/UpdatePassword.vue @@ -25,32 +25,38 @@ <fieldset> <p> <label for="password" class="infield">{{ t('core', 'New password') }}</label> - <input type="password" name="password" - id="password" v-model="password" required - :placeholder="t('core', 'New password')" /> + <input id="password" + v-model="password" + type="password" + name="password" + required + :placeholder="t('core', 'New password')"> </p> <div v-if="encrypted" class="update"> <p> {{ t('core', 'Your files are encrypted. There will be no way to get your data back after your password is reset. If you are not sure what to do, please contact your administrator before you continue. Do you really want to continue?') }} </p> - <input type="checkbox" class="checkbox" - id="encrypted-continue" v-model="proceed" /> + <input id="encrypted-continue" + v-model="proceed" + type="checkbox" + class="checkbox"> <label for="encrypted-continue"> {{ t('core', 'I know what I\'m doing') }} </label> </div> <div id="submit-wrapper"> - <input type="submit" - id="submit" - class="login primary" - title="" - :value="!loading ? t('core', 'Reset password') : t('core', 'Resetting password')" /> - <div class="submit-icon" :class="{ - 'icon-loading-small': loading && invertedColors, - 'icon-loading-small-dark': loading && !invertedColors - }"></div> + <input id="submit" + type="submit" + class="login primary" + title="" + :value="!loading ? t('core', 'Reset password') : t('core', 'Resetting password')"> + <div class="submit-icon" + :class="{ + 'icon-loading-small': loading && invertedColors, + 'icon-loading-small-dark': loading && !invertedColors + }" /> </div> <p v-if="error && message" :class="{warning: error}"> @@ -61,71 +67,71 @@ </template> <script> - import Axios from 'nextcloud-axios' +import Axios from 'nextcloud-axios' - export default { - name: 'UpdatePassword', - props: { - username: { - type: String, - required: true, - }, - resetPasswordTarget: { - type: String, - required: true, - }, - invertedColors: { - type: Boolean, - default: false, - } +export default { + name: 'UpdatePassword', + props: { + username: { + type: String, + required: true }, - data() { - return { - error: false, - loading: false, - message: undefined, - user: this.username, - password: '', - encrypted: false, - proceed: false - } + resetPasswordTarget: { + type: String, + required: true }, - watch: { - username (value) { - this.user = value - } - }, - methods: { - async submit () { - this.loading = true - this.error = false - this.message = '' + invertedColors: { + type: Boolean, + default: false + } + }, + data() { + return { + error: false, + loading: false, + message: undefined, + user: this.username, + password: '', + encrypted: false, + proceed: false + } + }, + watch: { + username(value) { + this.user = value + } + }, + methods: { + async submit() { + this.loading = true + this.error = false + this.message = '' - try { - const { data } = await Axios.post(this.resetPasswordTarget, { - password: this.password, - proceed: this.proceed - }) - if (data && data.status === 'success') { - this.message = 'send-success' - this.$emit('update:username', this.user) - this.$emit('done') - } else if (data && data.encryption) { - this.encrypted = true - } else if (data && data.msg) { - throw new Error(data.msg) - } else { - throw new Error() - } - } catch (e) { - this.error = true - this.message = e.message ? e.message : t('core', 'Password can not be changed. Please contact your administrator.') - } finally { - this.loading = false + try { + const { data } = await Axios.post(this.resetPasswordTarget, { + password: this.password, + proceed: this.proceed + }) + if (data && data.status === 'success') { + this.message = 'send-success' + this.$emit('update:username', this.user) + this.$emit('done') + } else if (data && data.encryption) { + this.encrypted = true + } else if (data && data.msg) { + throw new Error(data.msg) + } else { + throw new Error() } + } catch (e) { + this.error = true + this.message = e.message ? e.message : t('core', 'Password can not be changed. Please contact your administrator.') + } finally { + this.loading = false } - }, + } } +} </script> <style scoped> diff --git a/core/src/globals.js b/core/src/globals.js index 8f0fe6dbf86..eb72a9fef30 100644 --- a/core/src/globals.js +++ b/core/src/globals.js @@ -1,3 +1,4 @@ +/* eslint-disable nextcloud/no-deprecations */ /** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * @@ -19,7 +20,46 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -import {initCore} from './init' +import { initCore } from './init' + +import _ from 'underscore' +import $ from 'jquery' +import 'jquery-migrate/dist/jquery-migrate.min' +// TODO: switch to `jquery-ui` package and import widgets and effects individually +// `jquery-ui-dist` is used as a workaround for the issue of missing effects +import 'jquery-ui-dist/jquery-ui' +import 'jquery-ui-dist/jquery-ui.css' +import 'jquery-ui-dist/jquery-ui.theme.css' +// END TODO +import autosize from 'autosize' +import Backbone from 'backbone' +import 'bootstrap/js/dist/tooltip' +import './Polyfill/tooltip' +import ClipboardJS from 'clipboard' +import dav from 'davclient.js' +import DOMPurify from 'dompurify' +import Handlebars from 'handlebars' +import 'jcrop/js/jquery.Jcrop' +import 'jcrop/css/jquery.Jcrop.css' +import jstimezonedetect from 'jstimezonedetect' +import marked from 'marked' +import md5 from 'blueimp-md5' +import moment from 'moment' +import 'select2' +import 'select2/select2.css' +import 'snap.js/dist/snap' +import 'strengthify' +import 'strengthify/strengthify.css' + +import OC from './OC/index' +import OCP from './OCP/index' +import OCA from './OCA/index' +import escapeHTML from './Util/escapeHTML' +import formatDate from './Util/format-date' +import { getToken as getRequestToken } from './OC/requesttoken' +import getURLParameter from './Util/get-url-parameter' +import humanFileSize from './Util/human-file-size' +import relativeModifiedDate from './Util/relative-modified-date' const warnIfNotTesting = function() { if (window.TESTING === undefined) { @@ -28,9 +68,12 @@ const warnIfNotTesting = function() { } /** + * Mark a function as deprecated and automatically + * warn if used! * * @param {Function} func the library to deprecate * @param {String} funcName the name of the library + * @returns {function} */ const deprecate = (func, funcName) => { const oldFunc = func @@ -59,53 +102,12 @@ const setDeprecatedProp = (global, cb, msg) => { }) } -import _ from 'underscore' -import $ from 'jquery' -import 'jquery-migrate/dist/jquery-migrate.min' -// TODO: switch to `jquery-ui` package and import widgets and effects individually -// `jquery-ui-dist` is used as a workaround for the issue of missing effects -import 'jquery-ui-dist/jquery-ui' -import 'jquery-ui-dist/jquery-ui.css' -import 'jquery-ui-dist/jquery-ui.theme.css' -// END TODO -import autosize from 'autosize' -import Backbone from 'backbone' -import 'bootstrap/js/dist/tooltip' -import './Polyfill/tooltip' -import ClipboardJS from 'clipboard' -import cssVars from 'css-vars-ponyfill' -import dav from 'davclient.js' -import DOMPurify from 'dompurify' -import Handlebars from 'handlebars' -import 'jcrop/js/jquery.Jcrop' -import 'jcrop/css/jquery.Jcrop.css' -import jstimezonedetect from 'jstimezonedetect' -import marked from 'marked' -import md5 from 'blueimp-md5' -import moment from 'moment' -import 'select2' -import 'select2/select2.css' -import 'snap.js/dist/snap' -import 'strengthify' -import 'strengthify/strengthify.css' - -import OC from './OC/index' -import OCP from './OCP/index' -import OCA from './OCA/index' -import escapeHTML from './Util/escapeHTML' -import formatDate from './Util/format-date' -import {getToken as getRequestToken} from './OC/requesttoken' -import getURLParameter from './Util/get-url-parameter' -import humanFileSize from './Util/human-file-size' -import relative_modified_date from './Util/relative-modified-date' - window['_'] = _ window['$'] = $ window['autosize'] = autosize window['Backbone'] = Backbone window['Clipboard'] = ClipboardJS window['ClipboardJS'] = ClipboardJS -window['cssVars'] = cssVars window['dav'] = dav setDeprecatedProp('DOMPurify', () => DOMPurify, 'The global DOMPurify is deprecated, ship your own') window['Handlebars'] = Handlebars @@ -118,7 +120,7 @@ window['moment'] = moment window['OC'] = OC setDeprecatedProp('initCore', () => initCore, 'this is an internal function') -setDeprecatedProp('oc_appswebroots', () => OC.appswebroots, 'use OC.appswebroots instead') +setDeprecatedProp('oc_appswebroots', () => OC.appswebroots, 'use OC.appswebroots instead') setDeprecatedProp('oc_capabilities', OC.getCapabilities, 'use OC.getCapabilities instead') setDeprecatedProp('oc_config', () => OC.config, 'use OC.config instead') setDeprecatedProp('oc_current_user', () => OC.getCurrentUser().uid, 'use OC.getCurrentUser().uid instead') @@ -134,7 +136,7 @@ window['escapeHTML'] = deprecate(escapeHTML, 'escapeHTML') window['formatDate'] = deprecate(formatDate, 'formatDate') window['getURLParameter'] = deprecate(getURLParameter, 'getURLParameter') window['humanFileSize'] = deprecate(humanFileSize, 'humanFileSize') -window['relative_modified_date'] = deprecate(relative_modified_date, 'relative_modified_date') +window['relative_modified_date'] = deprecate(relativeModifiedDate, 'relative_modified_date') $.fn.select2 = deprecate($.fn.select2, 'select2') /** @@ -145,7 +147,7 @@ $.fn.select2 = deprecate($.fn.select2, 'select2') * @param {number} [count] number to replace %n with * @return {string} */ -window.t = _.bind(OC.L10N.translate, OC.L10N); +window.t = _.bind(OC.L10N.translate, OC.L10N) /** * translate a string @@ -156,4 +158,4 @@ window.t = _.bind(OC.L10N.translate, OC.L10N); * @param [vars] map of placeholder key to value * @return {string} Translated string */ -window.n = _.bind(OC.L10N.translatePlural, OC.L10N); +window.n = _.bind(OC.L10N.translatePlural, OC.L10N) diff --git a/core/src/init.js b/core/src/init.js index b6cdf319739..ee232e8fdbf 100644 --- a/core/src/init.js +++ b/core/src/init.js @@ -1,4 +1,5 @@ -/* +/* globals Snap */ +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -22,16 +23,17 @@ import _ from 'underscore' import $ from 'jquery' import moment from 'moment' +import cssVars from 'css-vars-ponyfill' -import {initSessionHeartBeat} from './session-heartbeat' +import { initSessionHeartBeat } from './session-heartbeat' import OC from './OC/index' -import {setUp as setUpContactsMenu} from './components/ContactsMenu' -import {setUp as setUpMainMenu} from './components/MainMenu' -import {setUp as setUpUserMenu} from './components/UserMenu' +import { setUp as setUpContactsMenu } from './components/ContactsMenu' +import { setUp as setUpMainMenu } from './components/MainMenu' +import { setUp as setUpUserMenu } from './components/UserMenu' import PasswordConfirmation from './OC/password-confirmation' // keep in sync with core/css/variables.scss -const breakpoint_mobile_width = 1024; +const breakpointMobileWidth = 1024 const resizeMenu = () => { const appList = $('#appmenu li') @@ -40,7 +42,7 @@ const resizeMenu = () => { const usePercentualAppMenuLimit = 0.33 const minAppsDesktop = 8 let availableWidth = headerWidth - $('#nextcloud').outerWidth() - (rightHeaderWidth > 210 ? rightHeaderWidth : 210) - const isMobile = $(window).width() < breakpoint_mobile_width + const isMobile = $(window).width() < breakpointMobileWidth if (!isMobile) { availableWidth = availableWidth * usePercentualAppMenuLimit } @@ -90,7 +92,7 @@ const resizeMenu = () => { const initLiveTimestamps = () => { // Update live timestamps every 30 seconds setInterval(() => { - $('.live-relative-timestamp').each(function () { + $('.live-relative-timestamp').each(function() { $(this).text(OC.Util.relativeModifiedDate(parseInt($(this).attr('data-timestamp'), 10))) }) }, 30 * 1000) @@ -129,7 +131,7 @@ export const initCore = () => { }) } - $(window).on('unload.main', () => OC._unloadCalled = true) + $(window).on('unload.main', () => { OC._unloadCalled = true }) $(window).on('beforeunload.main', () => { // super-trick thanks to http://stackoverflow.com/a/4651049 // in case another handler displays a confirmation dialog (ex: navigating away @@ -150,14 +152,14 @@ export const initCore = () => { }, 10000) }, 1) }) - $(document).on('ajaxError.main', function (event, request, settings) { + $(document).on('ajaxError.main', function(event, request, settings) { if (settings && settings.allowAuthErrors) { return } OC._processAjaxError(request) }) - initSessionHeartBeat(); + initSessionHeartBeat() OC.registerMenu($('#expand'), $('#expanddiv'), false, true) @@ -184,7 +186,7 @@ export const initCore = () => { const caretPosition = $('.header-appname + .icon-caret').offset().left - 2 if (caretPosition > 255) { // if the app name is longer than the menu, just put the triangle in the middle - return + } else { $('head').append('<style id="menu-css-helper">#navigation:after { left: ' + caretPosition + 'px }</style>') } @@ -235,20 +237,20 @@ export const initCore = () => { $appNavigation.delegate('a, :button', 'click', event => { const $target = $(event.target) // don't hide navigation when changing settings or adding things - if ($target.is('.app-navigation-noclose') || - $target.closest('.app-navigation-noclose').length) { + if ($target.is('.app-navigation-noclose') + || $target.closest('.app-navigation-noclose').length) { return } - if ($target.is('.app-navigation-entry-utils-menu-button') || - $target.closest('.app-navigation-entry-utils-menu-button').length) { + if ($target.is('.app-navigation-entry-utils-menu-button') + || $target.closest('.app-navigation-entry-utils-menu-button').length) { return } - if ($target.is('.add-new') || - $target.closest('.add-new').length) { + if ($target.is('.add-new') + || $target.closest('.add-new').length) { return } - if ($target.is('#app-settings') || - $target.closest('#app-settings').length) { + if ($target.is('#app-settings') + || $target.closest('#app-settings').length) { return } snapper.close() @@ -282,7 +284,7 @@ export const initCore = () => { } const toggleSnapperOnSize = () => { - if ($(window).width() > breakpoint_mobile_width) { + if ($(window).width() > breakpointMobileWidth) { snapper.close() snapper.disable() diff --git a/core/src/jquery/avatar.js b/core/src/jquery/avatar.js index 75aef6d958f..eaedce1461b 100644 --- a/core/src/jquery/avatar.js +++ b/core/src/jquery/avatar.js @@ -64,46 +64,46 @@ import OC from '../OC' * */ -$.fn.avatar = function (user, size, ie8fix, hidedefault, callback, displayname) { - var setAvatarForUnknownUser = function (target) { - target.imageplaceholder('?'); - target.css('background-color', '#b9b9b9'); - }; +$.fn.avatar = function(user, size, ie8fix, hidedefault, callback, displayname) { + var setAvatarForUnknownUser = function(target) { + target.imageplaceholder('?') + target.css('background-color', '#b9b9b9') + } if (typeof (user) !== 'undefined') { - user = String(user); + user = String(user) } if (typeof (displayname) !== 'undefined') { - displayname = String(displayname); + displayname = String(displayname) } if (typeof (size) === 'undefined') { if (this.height() > 0) { - size = this.height(); + size = this.height() } else if (this.data('size') > 0) { - size = this.data('size'); + size = this.data('size') } else { - size = 64; + size = 64 } } - this.height(size); - this.width(size); + this.height(size) + this.width(size) if (typeof (user) === 'undefined') { if (typeof (this.data('user')) !== 'undefined') { - user = this.data('user'); + user = this.data('user') } else { - setAvatarForUnknownUser(this); - return; + setAvatarForUnknownUser(this) + return } } // sanitize - user = String(user).replace(/\//g, ''); + user = String(user).replace(/\//g, '') - var $div = this; - var url; + var $div = this + var url // If this is our own avatar we have to use the version attribute if (user === OC.getCurrentUser().uid) { @@ -113,50 +113,50 @@ $.fn.avatar = function (user, size, ie8fix, hidedefault, callback, displayname) user: user, size: Math.ceil(size * window.devicePixelRatio), version: oc_userconfig.avatar.version - }); + }) } else { url = OC.generateUrl( '/avatar/{user}/{size}', { user: user, size: Math.ceil(size * window.devicePixelRatio) - }); + }) } - var img = new Image(); + var img = new Image() // If the new image loads successfully set it. - img.onload = function () { - $div.clearimageplaceholder(); - $div.append(img); + img.onload = function() { + $div.clearimageplaceholder() + $div.append(img) if (typeof callback === 'function') { - callback(); + callback() } - }; + } // Fallback when avatar loading fails: // Use old placeholder when a displayname attribute is defined, // otherwise show the unknown user placeholder. - img.onerror = function () { - $div.clearimageplaceholder(); + img.onerror = function() { + $div.clearimageplaceholder() if (typeof (displayname) !== 'undefined') { - $div.imageplaceholder(user, displayname); + $div.imageplaceholder(user, displayname) } else { - setAvatarForUnknownUser($div); + setAvatarForUnknownUser($div) } if (typeof callback === 'function') { - callback(); + callback() } - }; + } if (size < 32) { - $div.addClass('icon-loading-small'); + $div.addClass('icon-loading-small') } else { - $div.addClass('icon-loading'); + $div.addClass('icon-loading') } - img.width = size; - img.height = size; - img.src = url; - img.alt = ''; -}; + img.width = size + img.height = size + img.src = url + img.alt = '' +} diff --git a/core/src/jquery/contactsmenu.js b/core/src/jquery/contactsmenu.js index 4f90640eda0..389c8809be0 100644 --- a/core/src/jquery/contactsmenu.js +++ b/core/src/jquery/contactsmenu.js @@ -32,96 +32,92 @@ const LIST = '' + ' </a>' + ' </li>' + ' </ul>' - + '</div>'; + + '</div>' -const entryTemplate = require('./contactsmenu/jquery_entry.handlebars'); +const entryTemplate = require('./contactsmenu/jquery_entry.handlebars') -$.fn.contactsMenu = function (shareWith, shareType, appendTo) { +$.fn.contactsMenu = function(shareWith, shareType, appendTo) { // 0 - user, 4 - email, 6 - remote - var allowedTypes = [0, 4, 6]; + var allowedTypes = [0, 4, 6] if (allowedTypes.indexOf(shareType) === -1) { - return; + return } - var $div = this; - appendTo.append(LIST); - var $list = appendTo.find('div.contactsmenu-popover'); + var $div = this + appendTo.append(LIST) + var $list = appendTo.find('div.contactsmenu-popover') - $div.click(function () { + $div.click(function() { if (!$list.hasClass('hidden')) { - $list.addClass('hidden'); - $list.hide(); - return; + $list.addClass('hidden') + $list.hide() + return } - $list.removeClass('hidden'); - $list.show(); + $list.removeClass('hidden') + $list.show() if ($list.hasClass('loaded')) { - return; + return } - $list.addClass('loaded'); + $list.addClass('loaded') $.ajax(OC.generateUrl('/contactsmenu/findOne'), { method: 'POST', data: { shareType: shareType, shareWith: shareWith } - }).then(function (data) { - $list.find('ul').find('li').addClass('hidden'); + }).then(function(data) { + $list.find('ul').find('li').addClass('hidden') - var actions; + var actions if (!data.topAction) { actions = [{ hyperlink: '#', title: t('core', 'No action available') - }]; + }] } else { - actions = [data.topAction].concat(data.actions); + actions = [data.topAction].concat(data.actions) } - actions.forEach(function (action) { - var template = entryTemplate; - $list.find('ul').append(template(action)); - }); + actions.forEach(function(action) { + var template = entryTemplate + $list.find('ul').append(template(action)) + }) + }, function(jqXHR) { + $list.find('ul').find('li').addClass('hidden') - if (actions.length === 0) { - - } - }, function (jqXHR) { - $list.find('ul').find('li').addClass('hidden'); - - var title; + var title if (jqXHR.status === 404) { - title = t('core', 'No action available'); + title = t('core', 'No action available') } else { - title = t('core', 'Error fetching contact actions'); + title = t('core', 'Error fetching contact actions') } - var template = entryTemplate; + var template = entryTemplate $list.find('ul').append(template({ hyperlink: '#', title: title - })); - }); - }); + })) + }) + }) - $(document).click(function (event) { - var clickedList = ($list.has(event.target).length > 0); - var clickedTarget = ($div.has(event.target).length > 0); + $(document).click(function(event) { + var clickedList = ($list.has(event.target).length > 0) + var clickedTarget = ($div.has(event.target).length > 0) - $div.each(function () { + $div.each(function() { if ($(this).is(event.target)) { - clickedTarget = true; + clickedTarget = true } - }); + }) if (clickedList || clickedTarget) { - return; + return } - $list.addClass('hidden'); - $list.hide(); - }); -}; + $list.addClass('hidden') + $list.hide() + }) +} diff --git a/core/src/jquery/exists.js b/core/src/jquery/exists.js index bdf62ab7d4b..3481faeb6cd 100644 --- a/core/src/jquery/exists.js +++ b/core/src/jquery/exists.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -25,7 +25,8 @@ import $ from 'jquery' * check if an element exists. * allows you to write if ($('#myid').exists()) to increase readability * @link http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery + * @returns {boolean} */ -$.fn.exists = function () { - return this.length > 0; -}; +$.fn.exists = function() { + return this.length > 0 +} diff --git a/core/src/jquery/filterattr.js b/core/src/jquery/filterattr.js index 7675eaa1e2d..204d04b46a0 100644 --- a/core/src/jquery/filterattr.js +++ b/core/src/jquery/filterattr.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2018 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -23,9 +23,13 @@ import $ from 'jquery' /** * Filter jQuery selector by attribute value + * + * @param {string} attrName attribute name + * @param {string} attrValue attribute value + * @returns {Void} */ -$.fn.filterAttr = function (attrName, attrValue) { - return this.filter(function () { - return $(this).attr(attrName) === attrValue; - }); -}; +$.fn.filterAttr = function(attrName, attrValue) { + return this.filter(function() { + return $(this).attr(attrName) === attrValue + }) +} diff --git a/core/src/jquery/index.js b/core/src/jquery/index.js index e2efc76bdf1..d131ae5245a 100644 --- a/core/src/jquery/index.js +++ b/core/src/jquery/index.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -59,5 +59,5 @@ $.ajaxSetup({ * * This thus mitigates some unexpected XSS vectors. */ -$.globalEval = function () { +$.globalEval = function() { } diff --git a/core/src/jquery/ocdialog.js b/core/src/jquery/ocdialog.js index 8899d9433d1..68384311531 100644 --- a/core/src/jquery/ocdialog.js +++ b/core/src/jquery/ocdialog.js @@ -29,17 +29,17 @@ $.widget('oc.ocdialog', { closeOnEscape: true, modal: false }, - _create: function () { - var self = this; + _create: function() { + var self = this this.originalCss = { display: this.element[0].style.display, width: this.element[0].style.width, height: this.element[0].style.height - }; + } - this.originalTitle = this.element.attr('title'); - this.options.title = this.options.title || this.originalTitle; + this.originalTitle = this.element.attr('title') + this.options.title = this.options.title || this.originalTitle this.$dialog = $('<div class="oc-dialog" />') .attr({ @@ -47,224 +47,224 @@ $.widget('oc.ocdialog', { tabIndex: -1, role: 'dialog' }) - .insertBefore(this.element); - this.$dialog.append(this.element.detach()); - this.element.removeAttr('title').addClass('oc-dialog-content').appendTo(this.$dialog); + .insertBefore(this.element) + this.$dialog.append(this.element.detach()) + this.element.removeAttr('title').addClass('oc-dialog-content').appendTo(this.$dialog) this.$dialog.css({ display: 'inline-block', position: 'fixed' - }); + }) - this.enterCallback = null; + this.enterCallback = null - $(document).on('keydown keyup', function (event) { + $(document).on('keydown keyup', function(event) { if ( - event.target !== self.$dialog.get(0) && - self.$dialog.find($(event.target)).length === 0 + event.target !== self.$dialog.get(0) + && self.$dialog.find($(event.target)).length === 0 ) { - return; + return } // Escape if ( - event.keyCode === 27 && - event.type === 'keydown' && - self.options.closeOnEscape + event.keyCode === 27 + && event.type === 'keydown' + && self.options.closeOnEscape ) { - event.stopImmediatePropagation(); - self.close(); - return false; + event.stopImmediatePropagation() + self.close() + return false } // Enter if (event.keyCode === 13) { - event.stopImmediatePropagation(); + event.stopImmediatePropagation() if (self.enterCallback !== null) { - self.enterCallback(); - event.preventDefault(); - return false; + self.enterCallback() + event.preventDefault() + return false } if (event.type === 'keyup') { - event.preventDefault(); - return false; + event.preventDefault() + return false } // If no button is selected we trigger the primary if ( - self.$buttonrow && - self.$buttonrow.find($(event.target)).length === 0 + self.$buttonrow + && self.$buttonrow.find($(event.target)).length === 0 ) { - var $button = self.$buttonrow.find('button.primary'); + var $button = self.$buttonrow.find('button.primary') if ($button && !$button.prop('disabled')) { - $button.trigger('click'); + $button.trigger('click') } } else if (self.$buttonrow) { - $(event.target).trigger('click'); + $(event.target).trigger('click') } - return false; + return false } - }); + }) - this._setOptions(this.options); - this._createOverlay(); + this._setOptions(this.options) + this._createOverlay() }, - _init: function () { - this.$dialog.focus(); - this._trigger('open'); + _init: function() { + this.$dialog.focus() + this._trigger('open') }, - _setOption: function (key, value) { - var self = this; + _setOption: function(key, value) { + var self = this switch (key) { - case 'title': - if (this.$title) { - this.$title.text(value); - } else { - var $title = $('<h2 class="oc-dialog-title">' + case 'title': + if (this.$title) { + this.$title.text(value) + } else { + var $title = $('<h2 class="oc-dialog-title">' + value - + '</h2>'); - this.$title = $title.prependTo(this.$dialog); - } - this._setSizes(); - break; - case 'buttons': - if (this.$buttonrow) { - this.$buttonrow.empty(); - } else { - var $buttonrow = $('<div class="oc-dialog-buttonrow" />'); - this.$buttonrow = $buttonrow.appendTo(this.$dialog); - } - if (value.length === 1) { - this.$buttonrow.addClass('onebutton'); - } else if (value.length === 2) { - this.$buttonrow.addClass('twobuttons'); - } else if (value.length === 3) { - this.$buttonrow.addClass('threebuttons'); - } - $.each(value, function (idx, val) { - var $button = $('<button>').text(val.text); - if (val.classes) { - $button.addClass(val.classes); - } - if (val.defaultButton) { - $button.addClass('primary'); - self.$defaultButton = $button; - } - self.$buttonrow.append($button); - $button.click(function () { - val.click.apply(self.element[0], arguments); - }); - }); - this.$buttonrow.find('button') - .on('focus', function (event) { - self.$buttonrow.find('button').removeClass('primary'); - $(this).addClass('primary'); - }); - this._setSizes(); - break; - case 'style': - if (value.buttons !== undefined) { - this.$buttonrow.addClass(value.buttons); + + '</h2>') + this.$title = $title.prependTo(this.$dialog) + } + this._setSizes() + break + case 'buttons': + if (this.$buttonrow) { + this.$buttonrow.empty() + } else { + var $buttonrow = $('<div class="oc-dialog-buttonrow" />') + this.$buttonrow = $buttonrow.appendTo(this.$dialog) + } + if (value.length === 1) { + this.$buttonrow.addClass('onebutton') + } else if (value.length === 2) { + this.$buttonrow.addClass('twobuttons') + } else if (value.length === 3) { + this.$buttonrow.addClass('threebuttons') + } + $.each(value, function(idx, val) { + var $button = $('<button>').text(val.text) + if (val.classes) { + $button.addClass(val.classes) } - break; - case 'closeButton': - if (value) { - var $closeButton = $('<a class="oc-dialog-close"></a>'); - this.$dialog.prepend($closeButton); - $closeButton.on('click', function () { - self.close(); - }); - } else { - this.$dialog.find('.oc-dialog-close').remove(); + if (val.defaultButton) { + $button.addClass('primary') + self.$defaultButton = $button } - break; - case 'width': - this.$dialog.css('width', value); - break; - case 'height': - this.$dialog.css('height', value); - break; - case 'close': - this.closeCB = value; - break; + self.$buttonrow.append($button) + $button.click(function() { + val.click.apply(self.element[0], arguments) + }) + }) + this.$buttonrow.find('button') + .on('focus', function(event) { + self.$buttonrow.find('button').removeClass('primary') + $(this).addClass('primary') + }) + this._setSizes() + break + case 'style': + if (value.buttons !== undefined) { + this.$buttonrow.addClass(value.buttons) + } + break + case 'closeButton': + if (value) { + var $closeButton = $('<a class="oc-dialog-close"></a>') + this.$dialog.prepend($closeButton) + $closeButton.on('click', function() { + self.close() + }) + } else { + this.$dialog.find('.oc-dialog-close').remove() + } + break + case 'width': + this.$dialog.css('width', value) + break + case 'height': + this.$dialog.css('height', value) + break + case 'close': + this.closeCB = value + break } - //this._super(key, value); - $.Widget.prototype._setOption.apply(this, arguments); + // this._super(key, value); + $.Widget.prototype._setOption.apply(this, arguments) }, - _setOptions: function (options) { - //this._super(options); - $.Widget.prototype._setOptions.apply(this, arguments); + _setOptions: function(options) { + // this._super(options); + $.Widget.prototype._setOptions.apply(this, arguments) }, - _setSizes: function () { - var lessHeight = 0; + _setSizes: function() { + var lessHeight = 0 if (this.$title) { - lessHeight += this.$title.outerHeight(true); + lessHeight += this.$title.outerHeight(true) } if (this.$buttonrow) { - lessHeight += this.$buttonrow.outerHeight(true); + lessHeight += this.$buttonrow.outerHeight(true) } this.element.css({ 'height': 'calc(100% - ' + lessHeight + 'px)' - }); + }) }, - _createOverlay: function () { + _createOverlay: function() { if (!this.options.modal) { - return; + return } - var self = this; + var self = this this.overlay = $('<div>') .addClass('oc-dialog-dim') - .appendTo($('#content')); - this.overlay.on('click keydown keyup', function (event) { + .appendTo($('#content')) + this.overlay.on('click keydown keyup', function(event) { if (event.target !== self.$dialog.get(0) && self.$dialog.find($(event.target)).length === 0) { - event.preventDefault(); - event.stopPropagation(); - return; + event.preventDefault() + event.stopPropagation() + } - }); + }) }, - _destroyOverlay: function () { + _destroyOverlay: function() { if (!this.options.modal) { - return; + return } if (this.overlay) { - this.overlay.off('click keydown keyup'); - this.overlay.remove(); - this.overlay = null; + this.overlay.off('click keydown keyup') + this.overlay.remove() + this.overlay = null } }, - widget: function () { - return this.$dialog; + widget: function() { + return this.$dialog }, - setEnterCallback: function (callback) { - this.enterCallback = callback; + setEnterCallback: function(callback) { + this.enterCallback = callback }, - unsetEnterCallback: function () { - this.enterCallback = null; + unsetEnterCallback: function() { + this.enterCallback = null }, - close: function () { - this._destroyOverlay(); - var self = this; + close: function() { + this._destroyOverlay() + var self = this // Ugly hack to catch remaining keyup events. - setTimeout(function () { - self._trigger('close', self); - }, 200); + setTimeout(function() { + self._trigger('close', self) + }, 200) - self.$dialog.remove(); - this.destroy(); + self.$dialog.remove() + this.destroy() }, - destroy: function () { + destroy: function() { if (this.$title) { - this.$title.remove(); + this.$title.remove() } if (this.$buttonrow) { - this.$buttonrow.remove(); + this.$buttonrow.remove() } if (this.originalTitle) { - this.element.attr('title', this.originalTitle); + this.element.attr('title', this.originalTitle) } this.element.removeClass('oc-dialog-content') - .css(this.originalCss).detach().insertBefore(this.$dialog); - this.$dialog.remove(); + .css(this.originalCss).detach().insertBefore(this.$dialog) + this.$dialog.remove() } -}); +}) diff --git a/core/src/jquery/octemplate.js b/core/src/jquery/octemplate.js index 61fbea2af5f..24df6739225 100644 --- a/core/src/jquery/octemplate.js +++ b/core/src/jquery/octemplate.js @@ -56,49 +56,49 @@ import escapeHTML from '../Util/escapeHTML' * Inspired by micro templating done by e.g. underscore.js */ const Template = { - init: function (vars, options, elem) { + init: function(vars, options, elem) { // Mix in the passed in options with the default options - this.vars = vars; - this.options = $.extend({}, this.options, options); + this.vars = vars + this.options = $.extend({}, this.options, options) - this.elem = elem; - var self = this; + this.elem = elem + var self = this if (typeof this.options.escapeFunction === 'function') { - var keys = Object.keys(this.vars); + var keys = Object.keys(this.vars) for (var key = 0; key < keys.length; key++) { if (typeof this.vars[keys[key]] === 'string') { - this.vars[keys[key]] = self.options.escapeFunction(this.vars[keys[key]]); + this.vars[keys[key]] = self.options.escapeFunction(this.vars[keys[key]]) } } } - var _html = this._build(this.vars); - return $(_html); + var _html = this._build(this.vars) + return $(_html) }, // From stackoverflow.com/questions/1408289/best-way-to-do-variable-interpolation-in-javascript - _build: function (o) { - var data = this.elem.attr('type') === 'text/template' ? this.elem.html() : this.elem.get(0).outerHTML; + _build: function(o) { + var data = this.elem.attr('type') === 'text/template' ? this.elem.html() : this.elem.get(0).outerHTML try { return data.replace(/{([^{}]*)}/g, - function (a, b) { - var r = o[b]; - return typeof r === 'string' || typeof r === 'number' ? r : a; + function(a, b) { + var r = o[b] + return typeof r === 'string' || typeof r === 'number' ? r : a } - ); + ) } catch (e) { - console.error(e, 'data:', data); + console.error(e, 'data:', data) } }, options: { escapeFunction: escapeHTML } -}; +} -$.fn.octemplate = function (vars, options) { - vars = vars || {}; +$.fn.octemplate = function(vars, options) { + vars = vars || {} if (this.length) { - var _template = Object.create(Template); - return _template.init(vars, options, this); + var _template = Object.create(Template) + return _template.init(vars, options, this) } -}; +} diff --git a/core/src/jquery/placeholder.js b/core/src/jquery/placeholder.js index 074ad5029b5..029071c4d99 100644 --- a/core/src/jquery/placeholder.js +++ b/core/src/jquery/placeholder.js @@ -1,3 +1,4 @@ +/* eslint-disable */ /** * ownCloud * @@ -61,114 +62,114 @@ import $ from 'jquery' * */ -String.prototype.toRgb = function () { +String.prototype.toRgb = function() { // Normalize hash - var hash = this.toLowerCase(); + var hash = this.toLowerCase() // Already a md5 hash? if (hash.match(/^([0-9a-f]{4}-?){8}$/) === null) { - hash = md5(hash); + hash = md5(hash) } - hash = hash.replace(/[^0-9a-f]/g, ''); + hash = hash.replace(/[^0-9a-f]/g, '') - function Color (r, g, b) { - this.r = r; - this.g = g; - this.b = b; + function Color(r, g, b) { + this.r = r + this.g = g + this.b = b } - function stepCalc (steps, ends) { - var step = new Array(3); - step[0] = (ends[1].r - ends[0].r) / steps; - step[1] = (ends[1].g - ends[0].g) / steps; - step[2] = (ends[1].b - ends[0].b) / steps; - return step; + function stepCalc(steps, ends) { + var step = new Array(3) + step[0] = (ends[1].r - ends[0].r) / steps + step[1] = (ends[1].g - ends[0].g) / steps + step[2] = (ends[1].b - ends[0].b) / steps + return step } - function mixPalette (steps, color1, color2) { - var count = steps + 1; - var palette = new Array(); - palette.push(color1); + function mixPalette(steps, color1, color2) { + var count = steps + 1 + var palette = new Array() + palette.push(color1) var step = stepCalc(steps, [color1, color2]) for (var i = 1; i < steps; i++) { - var r = parseInt(color1.r + (step[0] * i)); - var g = parseInt(color1.g + (step[1] * i)); - var b = parseInt(color1.b + (step[2] * i)); - palette.push(new Color(r, g, b)); + var r = parseInt(color1.r + (step[0] * i)) + var g = parseInt(color1.g + (step[1] * i)) + var b = parseInt(color1.b + (step[2] * i)) + palette.push(new Color(r, g, b)) } - return palette; + return palette } - var red = new Color(182, 70, 157); - var yellow = new Color(221, 203, 85); - var blue = new Color(0, 130, 201); // Nextcloud blue + var red = new Color(182, 70, 157) + var yellow = new Color(221, 203, 85) + var blue = new Color(0, 130, 201) // Nextcloud blue // Number of steps to go from a color to another // 3 colors * 6 will result in 18 generated colors - var steps = 6; + var steps = 6 - var palette1 = mixPalette(steps, red, yellow); - var palette2 = mixPalette(steps, yellow, blue); - var palette3 = mixPalette(steps, blue, red); + var palette1 = mixPalette(steps, red, yellow) + var palette2 = mixPalette(steps, yellow, blue) + var palette3 = mixPalette(steps, blue, red) - var finalPalette = palette1.concat(palette2).concat(palette3); + var finalPalette = palette1.concat(palette2).concat(palette3) // Convert a string to an integer evenly - function hashToInt (hash, maximum) { - var finalInt = 0; - var result = Array(); + function hashToInt(hash, maximum) { + var finalInt = 0 + var result = Array() // Splitting evenly the string for (var i = 0; i < hash.length; i++) { // chars in md5 goes up to f, hex:16 - result.push(parseInt(hash.charAt(i), 16) % 16); + result.push(parseInt(hash.charAt(i), 16) % 16) } // Adds up all results for (var j in result) { - finalInt += result[j]; + finalInt += result[j] } // chars in md5 goes up to f, hex:16 // make sure we're always using int in our operation - return parseInt(parseInt(finalInt) % maximum); + return parseInt(parseInt(finalInt) % maximum) } - return finalPalette[hashToInt(hash, steps * 3)]; -}; + return finalPalette[hashToInt(hash, steps * 3)] +} -$.fn.imageplaceholder = function (seed, text, size) { - text = text || seed; +$.fn.imageplaceholder = function(seed, text, size) { + text = text || seed // Compute the hash - var rgb = seed.toRgb(); - this.css('background-color', 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')'); + var rgb = seed.toRgb() + this.css('background-color', 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')') // Placeholders are square - var height = this.height() || size || 32; - this.height(height); - this.width(height); + var height = this.height() || size || 32 + this.height(height) + this.width(height) // CSS rules - this.css('color', '#fff'); - this.css('font-weight', 'normal'); - this.css('text-align', 'center'); + this.css('color', '#fff') + this.css('font-weight', 'normal') + this.css('text-align', 'center') // calculate the height - this.css('line-height', height + 'px'); - this.css('font-size', (height * 0.55) + 'px'); + this.css('line-height', height + 'px') + this.css('font-size', (height * 0.55) + 'px') if (seed !== null && seed.length) { - this.html(text[0].toUpperCase()); + this.html(text[0].toUpperCase()) } -}; - -$.fn.clearimageplaceholder = function () { - this.css('background-color', ''); - this.css('color', ''); - this.css('font-weight', ''); - this.css('text-align', ''); - this.css('line-height', ''); - this.css('font-size', ''); - this.html(''); - this.removeClass('icon-loading'); - this.removeClass('icon-loading-small'); -}; +} + +$.fn.clearimageplaceholder = function() { + this.css('background-color', '') + this.css('color', '') + this.css('font-weight', '') + this.css('text-align', '') + this.css('line-height', '') + this.css('font-size', '') + this.html('') + this.removeClass('icon-loading') + this.removeClass('icon-loading-small') +} diff --git a/core/src/jquery/requesttoken.js b/core/src/jquery/requesttoken.js index a8fb024d04a..5f15d43aa17 100644 --- a/core/src/jquery/requesttoken.js +++ b/core/src/jquery/requesttoken.js @@ -21,11 +21,11 @@ import $ from 'jquery' -import {getToken} from '../OC/requesttoken' +import { getToken } from '../OC/requesttoken' -$(document).on('ajaxSend',function(elm, xhr, settings) { - if(settings.crossDomain === false) { - xhr.setRequestHeader('requesttoken', getToken()); - xhr.setRequestHeader('OCS-APIREQUEST', 'true'); +$(document).on('ajaxSend', function(elm, xhr, settings) { + if (settings.crossDomain === false) { + xhr.setRequestHeader('requesttoken', getToken()) + xhr.setRequestHeader('OCS-APIREQUEST', 'true') } -}); +}) diff --git a/core/src/jquery/selectrange.js b/core/src/jquery/selectrange.js index b7e20361805..b53bac4fc02 100644 --- a/core/src/jquery/selectrange.js +++ b/core/src/jquery/selectrange.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -24,20 +24,21 @@ import $ from 'jquery' /** * select a range in an input field * @link http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area - * @param {type} start - * @param {type} end + * @param {int} start start selection from + * @param {int} end number of char from start + * @returns {Void} */ -$.fn.selectRange = function (start, end) { - return this.each(function () { +$.fn.selectRange = function(start, end) { + return this.each(function() { if (this.setSelectionRange) { - this.focus(); - this.setSelectionRange(start, end); + this.focus() + this.setSelectionRange(start, end) } else if (this.createTextRange) { - var range = this.createTextRange(); - range.collapse(true); - range.moveEnd('character', end); - range.moveStart('character', start); - range.select(); + var range = this.createTextRange() + range.collapse(true) + range.moveEnd('character', end) + range.moveStart('character', start) + range.select() } - }); -}; + }) +} diff --git a/core/src/jquery/showpassword.js b/core/src/jquery/showpassword.js index 4dc39340e76..a9857f4d6d4 100644 --- a/core/src/jquery/showpassword.js +++ b/core/src/jquery/showpassword.js @@ -36,18 +36,18 @@ import $ from 'jquery' * @licens MIT License - http://www.opensource.org/licenses/mit-license.php */ $.fn.extend({ - showPassword: function (c) { + showPassword: function(c) { // Setup callback object - var callback = {'fn': null, 'args': {}}; - callback.fn = c; + var callback = { 'fn': null, 'args': {} } + callback.fn = c // Clones passwords and turn the clones into text inputs - var cloneElement = function (element) { + var cloneElement = function(element) { - var $element = $(element); + var $element = $(element) - var $clone = $("<input />"); + var $clone = $('<input />') // Name added for JQuery Validation compatibility // Element name is required to avoid script warning. @@ -59,91 +59,90 @@ $.fn.extend({ 'name': $element.attr('name') + '-clone', 'tabindex': $element.attr('tabindex'), 'autocomplete': 'off' - }); + }) if ($element.attr('placeholder') !== undefined) { - $clone.attr('placeholder', $element.attr('placeholder')); + $clone.attr('placeholder', $element.attr('placeholder')) } - return $clone; + return $clone - }; + } // Transfers values between two elements - var update = function (a, b) { - b.val(a.val()); - }; + var update = function(a, b) { + b.val(a.val()) + } // Shows a or b depending on checkbox - var setState = function (checkbox, a, b) { + var setState = function(checkbox, a, b) { if (checkbox.is(':checked')) { - update(a, b); - b.show(); - a.hide(); + update(a, b) + b.show() + a.hide() } else { - update(b, a); - b.hide(); - a.show(); + update(b, a) + b.hide() + a.show() } - }; + } - return this.each(function () { + return this.each(function() { - var $input = $(this), - $checkbox = $($input.data('typetoggle')); + var $input = $(this) + var $checkbox = $($input.data('typetoggle')) // Create clone - var $clone = cloneElement($input); - $clone.insertAfter($input); + var $clone = cloneElement($input) + $clone.insertAfter($input) // Set callback arguments if (callback.fn) { - callback.args.input = $input; - callback.args.checkbox = $checkbox; - callback.args.clone = $clone; + callback.args.input = $input + callback.args.checkbox = $checkbox + callback.args.clone = $clone } + $checkbox.bind('click', function() { + setState($checkbox, $input, $clone) + }) - $checkbox.bind('click', function () { - setState($checkbox, $input, $clone); - }); + $input.bind('keyup', function() { + update($input, $clone) + }) - $input.bind('keyup', function () { - update($input, $clone); - }); - - $clone.bind('keyup', function () { - update($clone, $input); + $clone.bind('keyup', function() { + update($clone, $input) // Added for JQuery Validation compatibility // This will trigger validation if it's ON for keyup event - $input.trigger('keyup'); + $input.trigger('keyup') - }); + }) // Added for JQuery Validation compatibility // This will trigger validation if it's ON for blur event - $clone.bind('blur', function () { - $input.trigger('focusout'); - }); + $clone.bind('blur', function() { + $input.trigger('focusout') + }) - setState($checkbox, $input, $clone); + setState($checkbox, $input, $clone) // set type of password field clone (type=text) to password right on submit // to prevent browser save the value of this field - $clone.closest('form').submit(function (e) { + $clone.closest('form').submit(function(e) { // .prop has to be used, because .attr throws // an error while changing a type of an input // element - $clone.prop('type', 'password'); - }); + $clone.prop('type', 'password') + }) if (callback.fn) { - callback.fn(callback.args); + callback.fn(callback.args) } - }); + }) } -}); +}) diff --git a/core/src/jquery/tipsy.js b/core/src/jquery/tipsy.js index 816a93fb9a9..75e90b1c060 100644 --- a/core/src/jquery/tipsy.js +++ b/core/src/jquery/tipsy.js @@ -1,4 +1,4 @@ -/* +/** * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> * * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> @@ -23,61 +23,63 @@ import $ from 'jquery' /** * $ tipsy shim for the bootstrap tooltip + * @param {Object} argument options + * @returns {Object} this * @deprecated */ -$.fn.tipsy = function (argument) { - console.warn('Deprecation warning: tipsy is deprecated. Use tooltip instead.'); +$.fn.tipsy = function(argument) { + console.warn('Deprecation warning: tipsy is deprecated. Use tooltip instead.') if (typeof argument === 'object' && argument !== null) { // tipsy defaults var options = { placement: 'bottom', - delay: {'show': 0, 'hide': 0}, + delay: { 'show': 0, 'hide': 0 }, trigger: 'hover', html: false, container: 'body' - }; + } if (argument.gravity) { switch (argument.gravity) { - case 'n': - case 'nw': - case 'ne': - options.placement = 'bottom'; - break; - case 's': - case 'sw': - case 'se': - options.placement = 'top'; - break; - case 'w': - options.placement = 'right'; - break; - case 'e': - options.placement = 'left'; - break; + case 'n': + case 'nw': + case 'ne': + options.placement = 'bottom' + break + case 's': + case 'sw': + case 'se': + options.placement = 'top' + break + case 'w': + options.placement = 'right' + break + case 'e': + options.placement = 'left' + break } } if (argument.trigger) { - options.trigger = argument.trigger; + options.trigger = argument.trigger } if (argument.delayIn) { - options.delay.show = argument.delayIn; + options.delay.show = argument.delayIn } if (argument.delayOut) { - options.delay.hide = argument.delayOut; + options.delay.hide = argument.delayOut } if (argument.html) { - options.html = true; + options.html = true } if (argument.fallback) { - options.title = argument.fallback; + options.title = argument.fallback } // destroy old tooltip in case the title has changed - $.fn.tooltip.call(this, 'destroy'); - $.fn.tooltip.call(this, options); + $.fn.tooltip.call(this, 'destroy') + $.fn.tooltip.call(this, options) } else { - this.tooltip(argument); - $.fn.tooltip.call(this, argument); + this.tooltip(argument) + $.fn.tooltip.call(this, argument) } - return this; -};
\ No newline at end of file + return this +} diff --git a/core/src/jquery/ui-fixes.js b/core/src/jquery/ui-fixes.js index d3cebfc346e..fb5ce4d7ba8 100644 --- a/core/src/jquery/ui-fixes.js +++ b/core/src/jquery/ui-fixes.js @@ -2,7 +2,7 @@ import $ from 'jquery' // Set autocomplete width the same as the related input // See http://stackoverflow.com/a/11845718 -$.ui.autocomplete.prototype._resizeMenu = function () { - var ul = this.menu.element; - ul.outerWidth(this.element.outerWidth()); -}; +$.ui.autocomplete.prototype._resizeMenu = function() { + var ul = this.menu.element + ul.outerWidth(this.element.outerWidth()) +} diff --git a/core/src/login.js b/core/src/login.js index 12f3a896308..4314da7ab07 100644 --- a/core/src/login.js +++ b/core/src/login.js @@ -19,25 +19,26 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. */ -import Vue from 'vue'; -import queryString from 'query-string'; +import Vue from 'vue' +import queryString from 'query-string' -import OC from './OC/index'; // TODO: Not needed but L10n breaks if removed -import LoginView from './views/Login.vue'; -import Nextcloud from './mixins/Nextcloud'; +// eslint-disable-next-line no-unused-vars +import OC from './OC/index' // TODO: Not needed but L10n breaks if removed +import LoginView from './views/Login.vue' +import Nextcloud from './mixins/Nextcloud' -const query = queryString.parse(location.search); +const query = queryString.parse(location.search) if (query.clear === '1') { try { - window.localStorage.clear(); - window.sessionStorage.clear(); - console.debug('Browser storage cleared'); + window.localStorage.clear() + window.sessionStorage.clear() + console.debug('Browser storage cleared') } catch (e) { - console.error('Could not clear browser storage', e); + console.error('Could not clear browser storage', e) } } -Vue.mixin(Nextcloud); +Vue.mixin(Nextcloud) const fromStateOr = (key, orValue) => { try { @@ -47,7 +48,7 @@ const fromStateOr = (key, orValue) => { } } -const View = Vue.extend(LoginView); +const View = Vue.extend(LoginView) new View({ propsData: { errors: fromStateOr('loginErrors', []), @@ -60,6 +61,6 @@ new View({ resetPasswordLink: fromStateOr('loginResetPasswordLink', ''), autoCompleteAllowed: fromStateOr('loginAutocomplete', true), resetPasswordTarget: fromStateOr('resetPasswordTarget', ''), - resetPasswordUser: fromStateOr('resetPasswordUser', ''), + resetPasswordUser: fromStateOr('resetPasswordUser', '') } -}).$mount('#login'); +}).$mount('#login') diff --git a/core/src/main.js b/core/src/main.js index 1f8f12c1a0f..b8c1c23628f 100644 --- a/core/src/main.js +++ b/core/src/main.js @@ -24,15 +24,15 @@ import '@babel/polyfill' import './Polyfill/index' // If you remove the line below, tests won't pass +// eslint-disable-next-line no-unused-vars import OC from './OC/index' import './globals' import './jquery/index' -import {initCore} from './init' -import {registerAppsSlideToggle} from './OC/apps' +import { initCore } from './init' +import { registerAppsSlideToggle } from './OC/apps' -$(document).ready(function () { - initCore(); - - registerAppsSlideToggle(); -}); +$(document).ready(function() { + initCore() + registerAppsSlideToggle() +}) diff --git a/core/src/maintenance.js b/core/src/maintenance.js index 4715b65c021..14451b59fd0 100644 --- a/core/src/maintenance.js +++ b/core/src/maintenance.js @@ -40,10 +40,10 @@ const check = () => { console.info('Nextcloud is still in maintenance mode') // Wait 20sec before the next request - setTimeout(check, 20 * 1000); + setTimeout(check, 20 * 1000) }) .catch(console.error.bind(this)) -}; +} // Off we go! -check(); +check() diff --git a/core/src/mixins/Nextcloud.js b/core/src/mixins/Nextcloud.js index 3ca755b3052..53c30b297ce 100644 --- a/core/src/mixins/Nextcloud.js +++ b/core/src/mixins/Nextcloud.js @@ -25,11 +25,11 @@ import OC from '../OC/index' export default { data() { return { - OC, + OC } }, methods: { t: L10n.translate.bind(L10n), - n: L10n.translatePlural.bind(L10n), - }, + n: L10n.translatePlural.bind(L10n) + } } diff --git a/core/src/session-heartbeat.js b/core/src/session-heartbeat.js index 9a4981e4bb7..49cf547aa36 100644 --- a/core/src/session-heartbeat.js +++ b/core/src/session-heartbeat.js @@ -21,13 +21,13 @@ import $ from 'jquery' -import {generateUrl} from './OC/routing' +import { generateUrl } from './OC/routing' import OC from './OC' -import {setToken as setRequestToken} from './OC/requesttoken' +import { setToken as setRequestToken } from './OC/requesttoken' /** * session heartbeat (defaults to enabled) - * @return {boolean} + * @returns {boolean} */ const keepSessionAlive = () => { return OC.config.session_keepalive === undefined @@ -36,7 +36,7 @@ const keepSessionAlive = () => { /** * get interval in seconds - * @return {Number} + * @returns {Number} */ const getInterval = () => { let interval = NaN @@ -61,7 +61,7 @@ const getInterval = () => { export const initSessionHeartBeat = () => { if (!keepSessionAlive()) { console.info('session heartbeat disabled') - return; + return } setInterval(() => { diff --git a/core/src/views/Login.vue b/core/src/views/Login.vue index d1127e05f95..dd65261ffc6 100644 --- a/core/src/views/Login.vue +++ b/core/src/views/Login.vue @@ -23,7 +23,7 @@ <div> <transition name="fade" mode="out-in"> <div v-if="!resetPassword && resetPasswordTarget === ''" - key="login"> + key="login"> <LoginForm :username.sync="user" :redirect-url="redirectUrl" @@ -32,103 +32,103 @@ :throttle-delay="throttleDelay" :inverted-colors="invertedColors" :auto-complete-allowed="autoCompleteAllowed" - @submit="loading = true"/> + @submit="loading = true" /> <a v-if="canResetPassword && resetPasswordLink !== ''" - id="lost-password" - :href="resetPasswordLink"> + id="lost-password" + :href="resetPasswordLink"> {{ t('core', 'Forgot password?') }} </a> <a v-else-if="canResetPassword && !resetPassword" - id="lost-password" - :href="resetPasswordLink" - @click.prevent="resetPassword = true"> + id="lost-password" + :href="resetPasswordLink" + @click.prevent="resetPassword = true"> {{ t('core', 'Forgot password?') }} </a> </div> <div v-else-if="!loading && canResetPassword" - key="reset" - class="login-additional"> + key="reset" + class="login-additional"> <div class="lost-password-container"> <ResetPassword v-if="resetPassword" - :username.sync="user" - :reset-password-link="resetPasswordLink" - :inverted-colors="invertedColors" - @abort="resetPassword = false"/> + :username.sync="user" + :reset-password-link="resetPasswordLink" + :inverted-colors="invertedColors" + @abort="resetPassword = false" /> </div> </div> <div v-else-if="resetPasswordTarget !== ''"> <UpdatePassword :username.sync="user" - :reset-password-target="resetPasswordTarget" - :inverted-colors="invertedColors" - @done="passwordResetFinished"/> + :reset-password-target="resetPasswordTarget" + :inverted-colors="invertedColors" + @done="passwordResetFinished" /> </div> </transition> </div> </template> <script> - import LoginForm from '../components/login/LoginForm.vue' - import ResetPassword from '../components/login/ResetPassword.vue' - import UpdatePassword from '../components/login/UpdatePassword.vue' +import LoginForm from '../components/login/LoginForm.vue' +import ResetPassword from '../components/login/ResetPassword.vue' +import UpdatePassword from '../components/login/UpdatePassword.vue' - export default { - name: 'Login', - props: { - username: { - type: String, - default: '', - }, - redirectUrl: { - type: String, - }, - errors: { - type: Array, - default: () => [], - }, - messages: { - type: Array, - default: () => [], - }, - throttleDelay: { - type: Number, - }, - canResetPassword: { - type: Boolean, - default: false, - }, - resetPasswordLink: { - type: String, - }, - resetPasswordTarget: { - type: String, - }, - invertedColors: { - type: Boolean, - default: false, - }, - autoCompleteAllowed: { - type: Boolean, - default: true, - }, +export default { + name: 'Login', + components: { + LoginForm, + ResetPassword, + UpdatePassword + }, + props: { + username: { + type: String, + default: '' + }, + redirectUrl: { + type: String + }, + errors: { + type: Array, + default: () => [] + }, + messages: { + type: Array, + default: () => [] + }, + throttleDelay: { + type: Number }, - components: { - LoginForm, - ResetPassword, - UpdatePassword, + canResetPassword: { + type: Boolean, + default: false }, - data () { - return { - loading: false, - user: this.username, - resetPassword: false, - } + resetPasswordLink: { + type: String }, - methods: { - passwordResetFinished() { - this.resetPasswordTarget = '' - } + resetPasswordTarget: { + type: String + }, + invertedColors: { + type: Boolean, + default: false + }, + autoCompleteAllowed: { + type: Boolean, + default: true + } + }, + data() { + return { + loading: false, + user: this.username, + resetPassword: false + } + }, + methods: { + passwordResetFinished() { + this.resetPasswordTarget = '' } } +} </script> <style> |