diff --git a/apps/comments/.bowerrc b/apps/comments/.bowerrc new file mode 100644 index 0000000000000..faee1372545d4 --- /dev/null +++ b/apps/comments/.bowerrc @@ -0,0 +1,3 @@ +{ + "directory": "js/vendor" +} \ No newline at end of file diff --git a/apps/comments/appinfo/app.php b/apps/comments/appinfo/app.php index 067e01e47ef78..f6e022e81793f 100644 --- a/apps/comments/appinfo/app.php +++ b/apps/comments/appinfo/app.php @@ -27,6 +27,7 @@ function() { \OCP\Util::addScript('oc-backbone-webdav'); \OCP\Util::addScript('comments', 'merged'); + \OCP\Util::addStyle('comments', 'autocomplete'); \OCP\Util::addStyle('comments', 'comments'); } ); diff --git a/apps/comments/appinfo/info.xml b/apps/comments/appinfo/info.xml index b67def1fb9dc4..6fcfa4bd399e3 100644 --- a/apps/comments/appinfo/info.xml +++ b/apps/comments/appinfo/info.xml @@ -28,4 +28,10 @@ OCA\Comments\Activity\Provider + + + + OCA\Comments\Collaboration\CommentersSorter + + diff --git a/apps/comments/composer/composer/autoload_classmap.php b/apps/comments/composer/composer/autoload_classmap.php index 299dc305641c5..0000ab9081a69 100644 --- a/apps/comments/composer/composer/autoload_classmap.php +++ b/apps/comments/composer/composer/autoload_classmap.php @@ -11,8 +11,10 @@ 'OCA\\Comments\\Activity\\Provider' => $baseDir . '/../lib/Activity/Provider.php', 'OCA\\Comments\\Activity\\Setting' => $baseDir . '/../lib/Activity/Setting.php', 'OCA\\Comments\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php', + 'OCA\\Comments\\Collaboration\\CommentersSorter' => $baseDir . '/../lib/Collaboration/CommentersSorter.php', 'OCA\\Comments\\Controller\\Notifications' => $baseDir . '/../lib/Controller/Notifications.php', 'OCA\\Comments\\EventHandler' => $baseDir . '/../lib/EventHandler.php', + 'OCA\\Comments\\JSSettingsHelper' => $baseDir . '/../lib/JSSettingsHelper.php', 'OCA\\Comments\\Notification\\Listener' => $baseDir . '/../lib/Notification/Listener.php', 'OCA\\Comments\\Notification\\Notifier' => $baseDir . '/../lib/Notification/Notifier.php', ); diff --git a/apps/comments/composer/composer/autoload_static.php b/apps/comments/composer/composer/autoload_static.php index 932a6316898a5..662f77f89dc4f 100644 --- a/apps/comments/composer/composer/autoload_static.php +++ b/apps/comments/composer/composer/autoload_static.php @@ -26,8 +26,10 @@ class ComposerStaticInitComments 'OCA\\Comments\\Activity\\Provider' => __DIR__ . '/..' . '/../lib/Activity/Provider.php', 'OCA\\Comments\\Activity\\Setting' => __DIR__ . '/..' . '/../lib/Activity/Setting.php', 'OCA\\Comments\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php', + 'OCA\\Comments\\Collaboration\\CommentersSorter' => __DIR__ . '/..' . '/../lib/Collaboration/CommentersSorter.php', 'OCA\\Comments\\Controller\\Notifications' => __DIR__ . '/..' . '/../lib/Controller/Notifications.php', 'OCA\\Comments\\EventHandler' => __DIR__ . '/..' . '/../lib/EventHandler.php', + 'OCA\\Comments\\JSSettingsHelper' => __DIR__ . '/..' . '/../lib/JSSettingsHelper.php', 'OCA\\Comments\\Notification\\Listener' => __DIR__ . '/..' . '/../lib/Notification/Listener.php', 'OCA\\Comments\\Notification\\Notifier' => __DIR__ . '/..' . '/../lib/Notification/Notifier.php', ); diff --git a/apps/comments/css/autocomplete.scss b/apps/comments/css/autocomplete.scss new file mode 100644 index 0000000000000..10e56f154202d --- /dev/null +++ b/apps/comments/css/autocomplete.scss @@ -0,0 +1,77 @@ +/** + * based upon apps/comments/js/vendor/At.js/dist/css/jquery.atwho.css, + * only changed colors and font-weight + */ + +.atwho-view { + position:absolute; + top: 0; + left: 0; + display: none; + margin-top: 18px; + background: $color-main-background; + color: $color-main-text; + border: 1px solid $color-border; + border-radius: 3px; + box-shadow: 0 0 5px $color-box-shadow; + min-width: 120px; + z-index: 11110 !important; +} + +.atwho-view .atwho-header { + padding: 5px; + margin: 5px; + cursor: pointer; + border-bottom: solid 1px $color-border; + color: $color-main-text; + font-size: 11px; + font-weight: bold; +} + +.atwho-view .atwho-header .small { + color: $color-main-text; + float: right; + padding-top: 2px; + margin-right: -5px; + font-size: 12px; + font-weight: normal; +} + +.atwho-view .atwho-header:hover { + cursor: default; +} + +.atwho-view .cur { + background: $color-primary; + color: $color-primary-text; +} +.atwho-view .cur small { + color: $color-primary-text; +} +.atwho-view strong { + color: $color-main-text; + font-weight: normal; +} +.atwho-view .cur strong { + color: $color-primary-text; + font-weight: normal; +} +.atwho-view ul { + /* width: 100px; */ + list-style:none; + padding:0; + margin:auto; + max-height: 200px; + overflow-y: auto; +} +.atwho-view ul li { + display: block; + padding: 5px 10px; + border-bottom: 1px solid $color-border; + cursor: pointer; +} +.atwho-view small { + font-size: smaller; + color: $color-main-text; + font-weight: normal; +} diff --git a/apps/comments/css/comments.css b/apps/comments/css/comments.css index d63211391f6b6..09771b4e9544b 100644 --- a/apps/comments/css/comments.css +++ b/apps/comments/css/comments.css @@ -48,22 +48,30 @@ margin-right: 6px; } -#commentsTabView .newCommentForm textarea { +#commentsTabView .newCommentForm div.message { resize: none; } +#commentsTabView .newCommentForm div.message:empty:before { + content: attr(data-placeholder); + color: grey; +} + #commentsTabView .comment { position: relative; margin-bottom: 30px; } -#commentsTabView .comment .avatar { +#commentsTabView .comment .avatar, +.atwho-view-ul * .avatar{ width: 32px; height: 32px; line-height: 32px; } -#commentsTabView .comment .message .avatar { +#commentsTabView .comment .message .avatar, +.atwho-view-ul * .avatar +{ display: inline-block; } @@ -112,11 +120,16 @@ } #commentsTabView .comments li .message .avatar-name-wrapper, +.atwho-view-ul * .avatar-name-wrapper, #commentsTabView .comment .authorRow { position: relative; cursor: pointer; } +.atwho-view-ul * .avatar-name-wrapper { + white-space: nowrap; +} + #commentsTabView .comment .author, #commentsTabView .comment .date { opacity: .5; diff --git a/apps/comments/js/commentstabview.js b/apps/comments/js/commentstabview.js index 3a20604326b0e..7398a709421d5 100644 --- a/apps/comments/js/commentstabview.js +++ b/apps/comments/js/commentstabview.js @@ -30,7 +30,7 @@ '{{/if}}' + ' ' + '
' + - ' ' + + '
{{message}}
' + ' ' + '{{#if isEditMode}}' + ' ' + @@ -62,6 +62,7 @@ /** @lends OCA.Comments.CommentsTabView.prototype */ { id: 'commentsTabView', className: 'tab commentsTabView', + _autoCompleteData: undefined, events: { 'submit .newCommentForm': '_onSubmitComment', @@ -69,7 +70,11 @@ 'click .action.edit': '_onClickEditComment', 'click .action.delete': '_onClickDeleteComment', 'click .cancel': '_onClickCloseComment', - 'click .comment': '_onClickComment' + 'click .comment': '_onClickComment', + 'keyup div.message': '_onTextChange', + 'change div.message': '_onTextChange', + 'input div.message': '_onTextChange', + 'paste div.message': '_onPaste' }, _commentMaxLength: 1000, @@ -80,11 +85,12 @@ this.collection.on('request', this._onRequest, this); this.collection.on('sync', this._onEndRequest, this); this.collection.on('add', this._onAddModel, this); + this.collection.on('change:message', this._onChangeModel, this); this._commentMaxThreshold = this._commentMaxLength * 0.9; // TODO: error handling - _.bindAll(this, '_onTypeComment'); + _.bindAll(this, '_onTypeComment', '_initAutoComplete', '_onAutoComplete'); }, template: function(params) { @@ -140,8 +146,10 @@ setFileInfo: function(fileInfo) { if (fileInfo) { this.model = fileInfo; + this.render(); - this.collection.setObjectId(fileInfo.id); + this._initAutoComplete($('#commentsTabView').find('.newCommentForm .message')); + this.collection.setObjectId(this.model.id); // reset to first page this.collection.reset([], {silent: true}); this.nextPage(); @@ -164,7 +172,85 @@ this.delegateEvents(); this.$el.find('.message').on('keydown input change', this._onTypeComment); - autosize(this.$el.find('.newCommentRow textarea')) + autosize(this.$el.find('.newCommentRow .message')) + }, + + _initAutoComplete: function($target) { + var s = this; + var limit = 10; + if(!_.isUndefined(OC.appConfig.comments)) { + limit = OC.appConfig.comments.maxAutoCompleteResults; + } + $target.atwho({ + at: '@', + limit: limit, + callbacks: { + remoteFilter: s._onAutoComplete, + highlighter: function (li) { + // misuse the highlighter callback to instead of + // highlighting loads the avatars. + var $li = $(li); + $li.find('.avatar').avatar(undefined, 32); + return $li; + }, + sorter: function (q, items) { return items; } + }, + displayTpl: '
  • ' + + '' + + '
    ' + + ' ${label}' + + '
  • ', + insertTpl: '' + + '' + + '
    ' + + ' ${label}' + + '
    ', + searchKey: "label" + }); + $target.on('inserted.atwho', function (je, $el) { + s._postRenderItem( + // we need to pass the parent of the inserted element + // passing the whole comments form would re-apply and request + // avatars from the server + $(je.target).find( + 'div[data-username="' + $el.find('[data-username]').data('username') + '"]' + ).parent() + ); + }); + }, + + _onAutoComplete: function(query, callback) { + if(_.isEmpty(query)) { + return; + } + var s = this; + if(!_.isUndefined(this._autoCompleteRequestTimer)) { + clearTimeout(this._autoCompleteRequestTimer); + } + this._autoCompleteRequestTimer = _.delay(function() { + if(!_.isUndefined(this._autoCompleteRequestCall)) { + this._autoCompleteRequestCall.abort(); + } + this._autoCompleteRequestCall = $.get( + OC.generateUrl('/autocomplete/get'), + { + search: query, + itemType: 'files', + itemId: s.model.get('id'), + sorter: 'commenters|share-recipients', + limit: OC.appConfig.comments.maxAutoCompleteResults + }, + function (data) { + callback(data); + } + ); + }, 400); }, _formatItem: function(commentModel) { @@ -215,15 +301,80 @@ } }, + /** + * takes care of post-rendering after a new comment was added to the + * collection + * + * @param model + * @param collection + * @param options + * @private + */ _onAddModel: function(model, collection, options) { - var $el = $(this.commentTemplate(this._formatItem(model))); + // we need to render it immediately, to ensure that the right + // order of comments is kept on opening comments tab + var $comment = $(this.commentTemplate(this._formatItem(model))); if (!_.isUndefined(options.at) && collection.length > 1) { - this.$container.find('li').eq(options.at).before($el); + this.$container.find('li').eq(options.at).before($comment); } else { - this.$container.append($el); + this.$container.append($comment); } + this._postRenderItem($comment); + $('#commentsTabView').find('.newCommentForm div.message').text('').prop('disabled', false); + + // we need to update the model, because it consists of client data + // only, but the server might add meta data, e.g. about mentions + var oldMentions = model.get('mentions'); + var self = this; + model.fetch({ + success: function (model) { + if(_.isEqual(oldMentions, model.get('mentions'))) { + // don't attempt to render if unnecessary, avoids flickering + return; + } + var $updated = $(self.commentTemplate(self._formatItem(model))); + $comment.html($updated.html()); + self._postRenderItem($comment); + } + }) - this._postRenderItem($el); + }, + + /** + * takes care of post-rendering after a new comment was edited + * + * @param model + * @private + */ + _onChangeModel: function (model) { + if(model.get('message').trim() === model.previous('message').trim()) { + return; + } + + var $form = this.$container.find('.comment[data-id="' + model.id + '"] form'); + var $row = $form.closest('.comment'); + var $target = $row.data('commentEl'); + if(_.isUndefined($target)) { + // ignore noise – this is only set after editing a comment and hitting post + return; + } + var self = this; + + // we need to update the model, because it consists of client data + // only, but the server might add meta data, e.g. about mentions + model.fetch({ + success: function (model) { + $target.removeClass('hidden'); + $row.remove(); + + var $message = $target.find('.message'); + $message + .html(self._formatMessage(model.get('message'), model.get('mentions'))) + .find('.avatar') + .each(function () { $(this).avatar(); }); + self._postRenderItem($message); + } + }); }, _postRenderItem: function($el) { @@ -240,6 +391,10 @@ } var $message = $el.find('.message'); + if($message.length === 0) { + // it is the case when writing a comment and mentioning a person + $message = $el; + } this._postRenderMessage($message); }, @@ -261,19 +416,15 @@ message = escapeHTML(message).replace(/\n/g, '
    '); for(var i in mentions) { + if(!mentions.hasOwnProperty(i)) { + return; + } var mention = '@' + mentions[i].mentionId; - var avatar = '
    '; - // escape possible regex characters in the name mention = mention.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - var displayName = '' - + '' - + avatar + ' '+ _.escape(mentions[i].mentionDisplayName)+'' - + ''; + + var displayName = this._composeHTMLMention(mentions[i].mentionId, mentions[i].mentionDisplayName); // replace every mention either at the start of the input or after a whitespace // followed by a non-word character. @@ -284,10 +435,24 @@ } ); } - return message; }, + _composeHTMLMention: function(uid, displayName) { + var avatar = '
    '; + + return '' + + '' + + '' + + avatar + ' '+ _.escape(displayName)+'' + + '' + + ''; + }, + nextPage: function() { if (this._loading || !this.collection.hasMoreResults()) { return; @@ -310,14 +475,24 @@ // spawn form $comment.after($formRow); $formRow.data('commentEl', $comment); - $formRow.find('textarea').on('keydown input change', this._onTypeComment); + $formRow.find('.message').on('keydown input change', this._onTypeComment); // copy avatar element from original to avoid flickering $formRow.find('.avatar:first').replaceWith($comment.find('.avatar:first').clone()); $formRow.find('.has-tooltip').tooltip(); + var $message = $formRow.find('.message'); + $message + .html(this._formatMessage(commentToEdit.get('message'), commentToEdit.get('mentions'))) + .find('.avatar') + .each(function () { $(this).avatar(); }); + this._postRenderItem($message); + // Enable autosize - autosize($formRow.find('textarea')); + autosize($formRow.find('.message')); + + // enable autocomplete + this._initAutoComplete($formRow.find('.message')); return false; }, @@ -393,48 +568,41 @@ }, /** - * takes care of updating comment elements after submit (either new + * takes care of updating comment element states after submit (either new * comment or edit). * * @param {OC.Backbone.Model} model * @param {jQuery} $form - * @param {string|undefined} commentId * @private */ - _onSubmitSuccess: function(model, $form, commentId) { - var self = this; + _onSubmitSuccess: function(model, $form) { var $submit = $form.find('.submit'); var $loading = $form.find('.submitLoading'); - var $textArea = $form.find('.message'); - model.fetch({ - success: function(model) { - $submit.removeClass('hidden'); - $loading.addClass('hidden'); - var $target; - - if(!_.isUndefined(commentId)) { - var $row = $form.closest('.comment'); - $target = $row.data('commentEl'); - $target.removeClass('hidden'); - $row.remove(); - } else { - $target = $('.commentsTabView .comments').find('li:first'); - $textArea.val('').prop('disabled', false); - } + $submit.removeClass('hidden'); + $loading.addClass('hidden'); + }, - var $message = $target.find('.message'); - $message - .html(self._formatMessage(model.get('message'), model.get('mentions'))) - .find('.avatar') - .each(function () { $(this).avatar(); }); + _commentBodyHTML2Plain: function($el) { + var $comment = $el.clone(); - self._postRenderMessage($message); - }, - error: function () { - self._onSubmitError($form, commentId); - } + $comment.find('.avatar-name-wrapper').each(function () { + var $this = $(this); + var $inserted = $this.parent(); + $inserted.html('@' + $this.find('.avatar').data('username')); }); + + var oldHtml; + var html = $comment.html(); + do { + // replace works one by one + oldHtml = html; + html = oldHtml.replace("
    ", "\n"); // preserve line breaks + console.warn(html) + } while(oldHtml !== html); + $comment.html(html); + + return $comment.text(); }, _onSubmitComment: function(e) { @@ -444,26 +612,27 @@ var currentUser = OC.getCurrentUser(); var $submit = $form.find('.submit'); var $loading = $form.find('.submitLoading'); - var $textArea = $form.find('.message'); - var message = $textArea.val().trim(); + var $commentField = $form.find('.message'); + var message = $commentField.text().trim(); e.preventDefault(); if (!message.length || message.length > this._commentMaxLength) { return; } - $textArea.prop('disabled', true); + $commentField.prop('disabled', true); $submit.addClass('hidden'); $loading.removeClass('hidden'); + message = this._commentBodyHTML2Plain($commentField); if (commentId) { // edit mode var comment = this.collection.get(commentId); comment.save({ - message: $textArea.val() + message: message }, { success: function(model) { - self._onSubmitSuccess(model, $form, commentId); + self._onSubmitSuccess(model, $form); }, error: function() { self._onSubmitError($form, commentId); @@ -475,7 +644,7 @@ actorDisplayName: currentUser.displayName, actorType: 'users', verb: 'comment', - message: $textArea.val(), + message: message, creationDateTime: (new Date()).toUTCString() }, { at: 0, @@ -485,7 +654,7 @@ self._onSubmitSuccess(model, $form); }, error: function() { - self._onSubmitError($form); + self._onSubmitError($form, undefined); } }); } @@ -513,6 +682,31 @@ } }, + /** + * ensures the contenteditable div is really empty, when user removed + * all input, so that the placeholder will be shown again + * + * @private + */ + _onTextChange: function() { + var $message = $('#commentsTabView').find('.newCommentForm div.message'); + if(!$message.text().trim().length) { + $message.empty(); + } + }, + + /** + * Limit pasting to plain text + * + * @param e + * @private + */ + _onPaste: function (e) { + e.preventDefault(); + var text = e.originalEvent.clipboardData.getData("text/plain"); + document.execCommand('insertText', false, text); + }, + /** * Returns whether the given message is long and needs * collapsing diff --git a/apps/comments/js/merged.json b/apps/comments/js/merged.json index 66a63e88d1745..0202c7ff55a3d 100644 --- a/apps/comments/js/merged.json +++ b/apps/comments/js/merged.json @@ -5,5 +5,7 @@ "commentsummarymodel.js", "commentstabview.js", "filesplugin.js", - "activitytabviewplugin.js" + "activitytabviewplugin.js", + "vendor/Caret.js/dist/jquery.caret.min.js", + "vendor/At.js/dist/js/jquery.atwho.min.js" ] diff --git a/apps/comments/js/vendor/At.js/dist/js/jquery.atwho.min.js b/apps/comments/js/vendor/At.js/dist/js/jquery.atwho.min.js new file mode 100644 index 0000000000000..d1e60152b4cf2 --- /dev/null +++ b/apps/comments/js/vendor/At.js/dist/js/jquery.atwho.min.js @@ -0,0 +1 @@ +!function(t,e){"function"==typeof define&&define.amd?define(["jquery"],function(t){return e(t)}):"object"==typeof exports?module.exports=e(require("jquery")):e(jQuery)}(this,function(t){var e,i;i={ESC:27,TAB:9,ENTER:13,CTRL:17,A:65,P:80,N:78,LEFT:37,UP:38,RIGHT:39,DOWN:40,BACKSPACE:8,SPACE:32},e={beforeSave:function(t){return r.arrayToDefaultHash(t)},matcher:function(t,e,i,n){var r,o,s,a,h;return t=t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),i&&(t="(?:^|\\s)"+t),r=decodeURI("%C3%80"),o=decodeURI("%C3%BF"),h=n?" ":"",a=new RegExp(t+"([A-Za-z"+r+"-"+o+"0-9_"+h+"'.+-]*)$|"+t+"([^\\x00-\\xff]*)$","gi"),s=a.exec(e),s?s[2]||s[1]:null},filter:function(t,e,i){var n,r,o,s;for(n=[],r=0,s=e.length;s>r;r++)o=e[r],~new String(o[i]).toLowerCase().indexOf(t.toLowerCase())&&n.push(o);return n},remoteFilter:null,sorter:function(t,e,i){var n,r,o,s;if(!t)return e;for(n=[],r=0,s=e.length;s>r;r++)o=e[r],o.atwho_order=new String(o[i]).toLowerCase().indexOf(t.toLowerCase()),o.atwho_order>-1&&n.push(o);return n.sort(function(t,e){return t.atwho_order-e.atwho_order})},tplEval:function(t,e){var i,n,r;r=t;try{return"string"!=typeof t&&(r=t(e)),r.replace(/\$\{([^\}]*)\}/g,function(t,i,n){return e[i]})}catch(n){return i=n,""}},highlighter:function(t,e){var i;return e?(i=new RegExp(">\\s*([^<]*?)("+e.replace("+","\\+")+")([^<]*)\\s*<","ig"),t.replace(i,function(t,e,i,n){return"> "+e+""+i+""+n+" <"})):t},beforeInsert:function(t,e,i){return t},beforeReposition:function(t){return t},afterMatchFailed:function(t,e){}};var n;n=function(){function e(e){this.currentFlag=null,this.controllers={},this.aliasMaps={},this.$inputor=t(e),this.setupRootElement(),this.listen()}return e.prototype.createContainer=function(e){var i;return null!=(i=this.$el)&&i.remove(),t(e.body).append(this.$el=t("
    "))},e.prototype.setupRootElement=function(e,i){var n,r;if(null==i&&(i=!1),e)this.window=e.contentWindow,this.document=e.contentDocument||this.window.document,this.iframe=e;else{this.document=this.$inputor[0].ownerDocument,this.window=this.document.defaultView||this.document.parentWindow;try{this.iframe=this.window.frameElement}catch(r){if(n=r,this.iframe=null,t.fn.atwho.debug)throw new Error("iframe auto-discovery is failed.\nPlease use `setIframe` to set the target iframe manually.\n"+n)}}return this.createContainer((this.iframeAsRoot=i)?this.document:document)},e.prototype.controller=function(t){var e,i,n,r;if(this.aliasMaps[t])i=this.controllers[this.aliasMaps[t]];else{r=this.controllers;for(n in r)if(e=r[n],n===t){i=e;break}}return i?i:this.controllers[this.currentFlag]},e.prototype.setContextFor=function(t){return this.currentFlag=t,this},e.prototype.reg=function(t,e){var i,n;return n=(i=this.controllers)[t]||(i[t]=this.$inputor.is("[contentEditable]")?new l(this,t):new s(this,t)),e.alias&&(this.aliasMaps[e.alias]=t),n.init(e),this},e.prototype.listen=function(){return this.$inputor.on("compositionstart",function(t){return function(e){var i;return null!=(i=t.controller())&&i.view.hide(),t.isComposing=!0,null}}(this)).on("compositionend",function(t){return function(e){return t.isComposing=!1,setTimeout(function(e){return t.dispatch(e)}),null}}(this)).on("keyup.atwhoInner",function(t){return function(e){return t.onKeyup(e)}}(this)).on("keydown.atwhoInner",function(t){return function(e){return t.onKeydown(e)}}(this)).on("blur.atwhoInner",function(t){return function(e){var i;return(i=t.controller())?(i.expectedQueryCBId=null,i.view.hide(e,i.getOpt("displayTimeout"))):void 0}}(this)).on("click.atwhoInner",function(t){return function(e){return t.dispatch(e)}}(this)).on("scroll.atwhoInner",function(t){return function(){var e;return e=t.$inputor.scrollTop(),function(i){var n,r;return n=i.target.scrollTop,e!==n&&null!=(r=t.controller())&&r.view.hide(i),e=n,!0}}}(this)())},e.prototype.shutdown=function(){var t,e,i;i=this.controllers;for(t in i)e=i[t],e.destroy(),delete this.controllers[t];return this.$inputor.off(".atwhoInner"),this.$el.remove()},e.prototype.dispatch=function(t){var e,i,n,r;n=this.controllers,r=[];for(e in n)i=n[e],r.push(i.lookUp(t));return r},e.prototype.onKeyup=function(e){var n;switch(e.keyCode){case i.ESC:e.preventDefault(),null!=(n=this.controller())&&n.view.hide();break;case i.DOWN:case i.UP:case i.CTRL:case i.ENTER:t.noop();break;case i.P:case i.N:e.ctrlKey||this.dispatch(e);break;default:this.dispatch(e)}},e.prototype.onKeydown=function(e){var n,r;if(r=null!=(n=this.controller())?n.view:void 0,r&&r.visible())switch(e.keyCode){case i.ESC:e.preventDefault(),r.hide(e);break;case i.UP:e.preventDefault(),r.prev();break;case i.DOWN:e.preventDefault(),r.next();break;case i.P:if(!e.ctrlKey)return;e.preventDefault(),r.prev();break;case i.N:if(!e.ctrlKey)return;e.preventDefault(),r.next();break;case i.TAB:case i.ENTER:case i.SPACE:if(!r.visible())return;if(!this.controller().getOpt("spaceSelectsMatch")&&e.keyCode===i.SPACE)return;if(!this.controller().getOpt("tabSelectsMatch")&&e.keyCode===i.TAB)return;r.highlighted()?(e.preventDefault(),r.choose(e)):r.hide(e);break;default:t.noop()}},e}();var r,o=[].slice;r=function(){function i(e,i){this.app=e,this.at=i,this.$inputor=this.app.$inputor,this.id=this.$inputor[0].id||this.uid(),this.expectedQueryCBId=null,this.setting=null,this.query=null,this.pos=0,this.range=null,0===(this.$el=t("#atwho-ground-"+this.id,this.app.$el)).length&&this.app.$el.append(this.$el=t("
    ")),this.model=new u(this),this.view=new c(this)}return i.prototype.uid=function(){return(Math.random().toString(16)+"000000000").substr(2,8)+(new Date).getTime()},i.prototype.init=function(e){return this.setting=t.extend({},this.setting||t.fn.atwho["default"],e),this.view.init(),this.model.reload(this.setting.data)},i.prototype.destroy=function(){return this.trigger("beforeDestroy"),this.model.destroy(),this.view.destroy(),this.$el.remove()},i.prototype.callDefault=function(){var i,n,r,s;s=arguments[0],i=2<=arguments.length?o.call(arguments,1):[];try{return e[s].apply(this,i)}catch(r){return n=r,t.error(n+" Or maybe At.js doesn't have function "+s)}},i.prototype.trigger=function(t,e){var i,n;return null==e&&(e=[]),e.push(this),i=this.getOpt("alias"),n=i?t+"-"+i+".atwho":t+".atwho",this.$inputor.trigger(n,e)},i.prototype.callbacks=function(t){return this.getOpt("callbacks")[t]||e[t]},i.prototype.getOpt=function(t,e){var i,n;try{return this.setting[t]}catch(n){return i=n,null}},i.prototype.insertContentFor=function(e){var i,n;return n=this.getOpt("insertTpl"),i=t.extend({},e.data("item-data"),{"atwho-at":this.at}),this.callbacks("tplEval").call(this,n,i,"onInsert")},i.prototype.renderView=function(t){var e;return e=this.getOpt("searchKey"),t=this.callbacks("sorter").call(this,this.query.text,t.slice(0,1001),e),this.view.render(t.slice(0,this.getOpt("limit")))},i.arrayToDefaultHash=function(e){var i,n,r,o;if(!t.isArray(e))return e;for(o=[],i=0,r=e.length;r>i;i++)n=e[i],t.isPlainObject(n)?o.push(n):o.push({name:n});return o},i.prototype.lookUp=function(t){var e,i;if((!t||"click"!==t.type||this.getOpt("lookUpOnClick"))&&(!this.getOpt("suspendOnComposing")||!this.app.isComposing))return(e=this.catchQuery(t))?(this.app.setContextFor(this.at),(i=this.getOpt("delay"))?this._delayLookUp(e,i):this._lookUp(e),e):(this.expectedQueryCBId=null,e)},i.prototype._delayLookUp=function(t,e){var i,n;return i=Date.now?Date.now():(new Date).getTime(),this.previousCallTime||(this.previousCallTime=i),n=e-(i-this.previousCallTime),n>0&&e>n?(this.previousCallTime=i,this._stopDelayedCall(),this.delayedCallTimeout=setTimeout(function(e){return function(){return e.previousCallTime=0,e.delayedCallTimeout=null,e._lookUp(t)}}(this),e)):(this._stopDelayedCall(),this.previousCallTime!==i&&(this.previousCallTime=0),this._lookUp(t))},i.prototype._stopDelayedCall=function(){return this.delayedCallTimeout?(clearTimeout(this.delayedCallTimeout),this.delayedCallTimeout=null):void 0},i.prototype._generateQueryCBId=function(){return{}},i.prototype._lookUp=function(e){var i;return i=function(t,e){return t===this.expectedQueryCBId?e&&e.length>0?this.renderView(this.constructor.arrayToDefaultHash(e)):this.view.hide():void 0},this.expectedQueryCBId=this._generateQueryCBId(),this.model.query(e.text,t.proxy(i,this,this.expectedQueryCBId))},i}();var s,a=function(t,e){function i(){this.constructor=t}for(var n in e)h.call(e,n)&&(t[n]=e[n]);return i.prototype=e.prototype,t.prototype=new i,t.__super__=e.prototype,t},h={}.hasOwnProperty;s=function(e){function i(){return i.__super__.constructor.apply(this,arguments)}return a(i,e),i.prototype.catchQuery=function(){var t,e,i,n,r,o,s;return e=this.$inputor.val(),t=this.$inputor.caret("pos",{iframe:this.app.iframe}),s=e.slice(0,t),r=this.callbacks("matcher").call(this,this.at,s,this.getOpt("startWithSpace"),this.getOpt("acceptSpaceBar")),n="string"==typeof r,n&&r.length0?t.getRangeAt(0):void 0},n.prototype._setRange=function(e,i,n){return null==n&&(n=this._getRange()),n&&i?(i=t(i)[0],"after"===e?(n.setEndAfter(i),n.setStartAfter(i)):(n.setEndBefore(i),n.setStartBefore(i)),n.collapse(!1),this._clearRange(n)):void 0},n.prototype._clearRange=function(t){var e;return null==t&&(t=this._getRange()),e=this.app.window.getSelection(),null==this.ctrl_a_pressed?(e.removeAllRanges(),e.addRange(t)):void 0},n.prototype._movingEvent=function(t){var e;return"click"===t.type||(e=t.which)===i.RIGHT||e===i.LEFT||e===i.UP||e===i.DOWN},n.prototype._unwrap=function(e){var i;return e=t(e).unwrap().get(0),(i=e.nextSibling)&&i.nodeValue&&(e.nodeValue+=i.nodeValue,t(i).remove()),e},n.prototype.catchQuery=function(e){var n,r,o,s,a,h,l,u,c,p,f,d;if((d=this._getRange())&&d.collapsed){if(e.which===i.ENTER)return(r=t(d.startContainer).closest(".atwho-query")).contents().unwrap(),r.is(":empty")&&r.remove(),(r=t(".atwho-query",this.app.document)).text(r.text()).contents().last().unwrap(),void this._clearRange();if(/firefox/i.test(navigator.userAgent)){if(t(d.startContainer).is(this.$inputor))return void this._clearRange();e.which===i.BACKSPACE&&d.startContainer.nodeType===document.ELEMENT_NODE&&(c=d.startOffset-1)>=0?(o=d.cloneRange(),o.setStart(d.startContainer,c),t(o.cloneContents()).contents().last().is(".atwho-inserted")&&(a=t(d.startContainer).contents().get(c),this._setRange("after",t(a).contents().last()))):e.which===i.LEFT&&d.startContainer.nodeType===document.TEXT_NODE&&(n=t(d.startContainer.previousSibling),n.is(".atwho-inserted")&&0===d.startOffset&&this._setRange("after",n.contents().last()))}if(t(d.startContainer).closest(".atwho-inserted").addClass("atwho-query").siblings().removeClass("atwho-query"),(r=t(".atwho-query",this.app.document)).length>0&&r.is(":empty")&&0===r.text().length&&r.remove(),this._movingEvent(e)||r.removeClass("atwho-inserted"),r.length>0)switch(e.which){case i.LEFT:return this._setRange("before",r.get(0),d),void r.removeClass("atwho-query");case i.RIGHT:return this._setRange("after",r.get(0).nextSibling,d),void r.removeClass("atwho-query")}if(r.length>0&&(f=r.attr("data-atwho-at-query"))&&(r.empty().html(f).attr("data-atwho-at-query",null),this._setRange("after",r.get(0),d)),o=d.cloneRange(),o.setStart(d.startContainer,0),u=this.callbacks("matcher").call(this,this.at,o.toString(),this.getOpt("startWithSpace"),this.getOpt("acceptSpaceBar")),h="string"==typeof u,0===r.length&&h&&(s=d.startOffset-this.at.length-u.length)>=0&&(d.setStart(d.startContainer,s),r=t("",this.app.document).attr(this.getOpt("editableAtwhoQueryAttrs")).addClass("atwho-query"),d.surroundContents(r.get(0)),l=r.contents().last().get(0),l&&(/firefox/i.test(navigator.userAgent)?(d.setStart(l,l.length),d.setEnd(l,l.length),this._clearRange(d)):this._setRange("after",l,d))),!(h&&u.length=0&&(this._movingEvent(e)&&r.hasClass("atwho-inserted")?r.removeClass("atwho-query"):!1!==this.callbacks("afterMatchFailed").call(this,this.at,r)&&this._setRange("after",this._unwrap(r.text(r.text()).contents().first()))),null)}},n.prototype.rect=function(){var e,i,n;return n=this.query.el.offset(),n&&this.query.el[0].getClientRects().length?(this.app.iframe&&!this.app.iframeAsRoot&&(i=(e=t(this.app.iframe)).offset(),n.left+=i.left-this.$inputor.scrollLeft(),n.top+=i.top-this.$inputor.scrollTop()),n.bottom=n.top+this.query.el.height(),n):void 0},n.prototype.insert=function(t,e){var i,n,r,o,s;return this.$inputor.is(":focus")||this.$inputor.focus(),n=this.getOpt("functionOverrides"),n.insert?n.insert.call(this,t,e):(o=""===(o=this.getOpt("suffix"))?o:o||" ",i=e.data("item-data"),this.query.el.removeClass("atwho-query").addClass("atwho-inserted").html(t).attr("data-atwho-at-query",""+i["atwho-at"]+this.query.text).attr("contenteditable","false"),(r=this._getRange())&&(this.query.el.length&&r.setEndAfter(this.query.el[0]),r.collapse(!1),r.insertNode(s=this.app.document.createTextNode(""+o)),this._setRange("after",s,r)),this.$inputor.is(":focus")||this.$inputor.focus(),this.$inputor.change())},n}(r);var u;u=function(){function e(t){this.context=t,this.at=this.context.at,this.storage=this.context.$inputor}return e.prototype.destroy=function(){return this.storage.data(this.at,null)},e.prototype.saved=function(){return this.fetch()>0},e.prototype.query=function(t,e){var i,n,r;return n=this.fetch(),r=this.context.getOpt("searchKey"),n=this.context.callbacks("filter").call(this.context,t,n,r)||[],i=this.context.callbacks("remoteFilter"),n.length>0||!i&&0===n.length?e(n):i.call(this.context,t,e)},e.prototype.fetch=function(){return this.storage.data(this.at)||[]},e.prototype.save=function(t){return this.storage.data(this.at,this.context.callbacks("beforeSave").call(this.context,t||[]))},e.prototype.load=function(t){return!this.saved()&&t?this._load(t):void 0},e.prototype.reload=function(t){return this._load(t)},e.prototype._load=function(e){return"string"==typeof e?t.ajax(e,{dataType:"json"}).done(function(t){return function(e){return t.save(e)}}(this)):this.save(e)},e}();var c;c=function(){function e(e){this.context=e,this.$el=t("
      "),this.$elUl=this.$el.children(),this.timeoutID=null,this.context.$el.append(this.$el),this.bindEvent()}return e.prototype.init=function(){var t,e;return e=this.context.getOpt("alias")||this.context.at.charCodeAt(0),t=this.context.getOpt("headerTpl"),t&&1===this.$el.children().length&&this.$el.prepend(t),this.$el.attr({id:"at-view-"+e})},e.prototype.destroy=function(){return this.$el.remove()},e.prototype.bindEvent=function(){var e,i,n;return e=this.$el.find("ul"),i=0,n=0,e.on("mousemove.atwho-view","li",function(r){return function(r){var o;if((i!==r.clientX||n!==r.clientY)&&(i=r.clientX,n=r.clientY,o=t(r.currentTarget),!o.hasClass("cur")))return e.find(".cur").removeClass("cur"),o.addClass("cur")}}(this)).on("click.atwho-view","li",function(i){return function(n){return e.find(".cur").removeClass("cur"),t(n.currentTarget).addClass("cur"),i.choose(n),n.preventDefault()}}(this))},e.prototype.visible=function(){return t.expr.filters.visible(this.$el[0])},e.prototype.highlighted=function(){return this.$el.find(".cur").length>0},e.prototype.choose=function(t){var e,i;return(e=this.$el.find(".cur")).length&&(i=this.context.insertContentFor(e),this.context._stopDelayedCall(),this.context.insert(this.context.callbacks("beforeInsert").call(this.context,i,e,t),e),this.context.trigger("inserted",[e,t]),this.hide(t)),this.context.getOpt("hideWithoutSuffix")?this.stopShowing=!0:void 0},e.prototype.reposition=function(e){var i,n,r,o;return i=this.context.app.iframeAsRoot?this.context.app.window:window,e.bottom+this.$el.height()-t(i).scrollTop()>t(i).height()&&(e.bottom=e.top-this.$el.height()),e.left>(r=t(i).width()-this.$el.width()-5)&&(e.left=r),n={left:e.left,top:e.bottom},null!=(o=this.context.callbacks("beforeReposition"))&&o.call(this.context,n),this.$el.offset(n),this.context.trigger("reposition",[n])},e.prototype.next=function(){var t,e,i,n;return t=this.$el.find(".cur").removeClass("cur"),e=t.next(),e.length||(e=this.$el.find("li:first")),e.addClass("cur"),i=e[0],n=i.offsetTop+i.offsetHeight+(i.nextSibling?i.nextSibling.offsetHeight:0),this.scrollTop(Math.max(0,n-this.$el.height()))},e.prototype.prev=function(){var t,e,i,n;return t=this.$el.find(".cur").removeClass("cur"),i=t.prev(),i.length||(i=this.$el.find("li:last")),i.addClass("cur"),n=i[0],e=n.offsetTop+n.offsetHeight+(n.nextSibling?n.nextSibling.offsetHeight:0),this.scrollTop(Math.max(0,e-this.$el.height()))},e.prototype.scrollTop=function(t){var e;return e=this.context.getOpt("scrollDuration"),e?this.$elUl.animate({scrollTop:t},e):this.$elUl.scrollTop(t)},e.prototype.show=function(){var t;return this.stopShowing?void(this.stopShowing=!1):(this.visible()||(this.$el.show(),this.$el.scrollTop(0),this.context.trigger("shown")),(t=this.context.rect())?this.reposition(t):void 0)},e.prototype.hide=function(t,e){var i;if(this.visible())return isNaN(e)?(this.$el.hide(),this.context.trigger("hidden",[t])):(i=function(t){return function(){return t.hide()}}(this),clearTimeout(this.timeoutID),this.timeoutID=setTimeout(i,e))},e.prototype.render=function(e){var i,n,r,o,s,a,h;if(!(t.isArray(e)&&e.length>0))return void this.hide();for(this.$el.find("ul").empty(),n=this.$el.find("ul"),h=this.context.getOpt("displayTpl"),r=0,s=e.length;s>r;r++)o=e[r],o=t.extend({},o,{"atwho-at":this.context.at}),a=this.context.callbacks("tplEval").call(this.context,h,o,"onDisplay"),i=t(this.context.callbacks("highlighter").call(this.context,a,this.context.query.text)),i.data("item-data",o),n.append(i);return this.show(),this.context.getOpt("highlightFirst")?n.find("li:first").addClass("cur"):void 0},e}();var p;p={load:function(t,e){var i;return(i=this.controller(t))?i.model.load(e):void 0},isSelecting:function(){var t;return!!(null!=(t=this.controller())?t.view.visible():void 0)},hide:function(){var t;return null!=(t=this.controller())?t.view.hide():void 0},reposition:function(){var t;return(t=this.controller())?t.view.reposition(t.rect()):void 0},setIframe:function(t,e){return this.setupRootElement(t,e),null},run:function(){return this.dispatch()},destroy:function(){return this.shutdown(),this.$inputor.data("atwho",null)}},t.fn.atwho=function(e){var i,r;return i=arguments,r=null,this.filter('textarea, input, [contenteditable=""], [contenteditable=true]').each(function(){var o,s;return(s=(o=t(this)).data("atwho"))||o.data("atwho",s=new n(this)),"object"!=typeof e&&e?p[e]&&s?r=p[e].apply(s,Array.prototype.slice.call(i,1)):t.error("Method "+e+" does not exist on jQuery.atwho"):s.reg(e.at,e)}),null!=r?r:this},t.fn.atwho["default"]={at:void 0,alias:void 0,data:null,displayTpl:"
    • ${name}
    • ",insertTpl:"${atwho-at}${name}",headerTpl:null,callbacks:e,functionOverrides:{},searchKey:"name",suffix:void 0,hideWithoutSuffix:!1,startWithSpace:!0,acceptSpaceBar:!1,highlightFirst:!0,limit:5,maxLen:20,minLen:0,displayTimeout:300,delay:null,spaceSelectsMatch:!1,tabSelectsMatch:!0,editableAtwhoQueryAttrs:{},scrollDuration:150,suspendOnComposing:!0,lookUpOnClick:!0},t.fn.atwho.debug=!1}); \ No newline at end of file diff --git a/apps/comments/js/vendor/Caret.js/dist/jquery.caret.min.js b/apps/comments/js/vendor/Caret.js/dist/jquery.caret.min.js new file mode 100644 index 0000000000000..a4d02eae24750 --- /dev/null +++ b/apps/comments/js/vendor/Caret.js/dist/jquery.caret.min.js @@ -0,0 +1,2 @@ +/*! jquery.caret 2015-02-01 */ +!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(c){return a.returnExportsGlobal=b(c)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){"use strict";var b,c,d,e,f,g,h,i,j,k,l;k="caret",b=function(){function b(a){this.$inputor=a,this.domInputor=this.$inputor[0]}return b.prototype.setPos=function(){return this.domInputor},b.prototype.getIEPosition=function(){return this.getPosition()},b.prototype.getPosition=function(){var a,b;return b=this.getOffset(),a=this.$inputor.offset(),b.left-=a.left,b.top-=a.top,b},b.prototype.getOldIEPos=function(){var a,b;return b=h.selection.createRange(),a=h.body.createTextRange(),a.moveToElementText(this.domInputor),a.setEndPoint("EndToEnd",b),a.text.length},b.prototype.getPos=function(){var a,b,c;return(c=this.range())?(a=c.cloneRange(),a.selectNodeContents(this.domInputor),a.setEnd(c.endContainer,c.endOffset),b=a.toString().length,a.detach(),b):h.selection?this.getOldIEPos():void 0},b.prototype.getOldIEOffset=function(){var a,b;return a=h.selection.createRange().duplicate(),a.moveStart("character",-1),b=a.getBoundingClientRect(),{height:b.bottom-b.top,left:b.left,top:b.top}},b.prototype.getOffset=function(){var b,c,d,e,f;return j.getSelection&&(d=this.range())?(d.endOffset-1>0&&d.endContainer===!this.domInputor&&(b=d.cloneRange(),b.setStart(d.endContainer,d.endOffset-1),b.setEnd(d.endContainer,d.endOffset),e=b.getBoundingClientRect(),c={height:e.height,left:e.left+e.width,top:e.top},b.detach()),c&&0!==(null!=c?c.height:void 0)||(b=d.cloneRange(),f=a(h.createTextNode("|")),b.insertNode(f[0]),b.selectNode(f[0]),e=b.getBoundingClientRect(),c={height:e.height,left:e.left,top:e.top},f.remove(),b.detach())):h.selection&&(c=this.getOldIEOffset()),c&&(c.top+=a(j).scrollTop(),c.left+=a(j).scrollLeft()),c},b.prototype.range=function(){var a;if(j.getSelection)return a=j.getSelection(),a.rangeCount>0?a.getRangeAt(0):null},b}(),c=function(){function b(a){this.$inputor=a,this.domInputor=this.$inputor[0]}return b.prototype.getIEPos=function(){var a,b,c,d,e,f,g;return b=this.domInputor,f=h.selection.createRange(),e=0,f&&f.parentElement()===b&&(d=b.value.replace(/\r\n/g,"\n"),c=d.length,g=b.createTextRange(),g.moveToBookmark(f.getBookmark()),a=b.createTextRange(),a.collapse(!1),e=g.compareEndPoints("StartToEnd",a)>-1?c:-g.moveStart("character",-c)),e},b.prototype.getPos=function(){return h.selection?this.getIEPos():this.domInputor.selectionStart},b.prototype.setPos=function(a){var b,c;return b=this.domInputor,h.selection?(c=b.createTextRange(),c.move("character",a),c.select()):b.setSelectionRange&&b.setSelectionRange(a,a),b},b.prototype.getIEOffset=function(a){var b,c,d,e;return c=this.domInputor.createTextRange(),a||(a=this.getPos()),c.move("character",a),d=c.boundingLeft,e=c.boundingTop,b=c.boundingHeight,{left:d,top:e,height:b}},b.prototype.getOffset=function(b){var c,d,e;return c=this.$inputor,h.selection?(d=this.getIEOffset(b),d.top+=a(j).scrollTop()+c.scrollTop(),d.left+=a(j).scrollLeft()+c.scrollLeft(),d):(d=c.offset(),e=this.getPosition(b),d={left:d.left+e.left-c.scrollLeft(),top:d.top+e.top-c.scrollTop(),height:e.height})},b.prototype.getPosition=function(a){var b,c,e,f,g,h,i;return b=this.$inputor,f=function(a){return a=a.replace(/<|>|`|"|&/g,"?").replace(/\r\n|\r|\n/g,"
      "),/firefox/i.test(navigator.userAgent)&&(a=a.replace(/\s/g," ")),a},void 0===a&&(a=this.getPos()),i=b.val().slice(0,a),e=b.val().slice(a),g=""+f(i)+"",g+="|",g+=""+f(e)+"",h=new d(b),c=h.create(g).rect()},b.prototype.getIEPosition=function(a){var b,c,d,e,f;return d=this.getIEOffset(a),c=this.$inputor.offset(),e=d.left-c.left,f=d.top-c.top,b=d.height,{left:e,top:f,height:b}},b}(),d=function(){function b(a){this.$inputor=a}return b.prototype.css_attr=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopStyle","borderRightStyle","borderBottomStyle","borderLeftStyle","borderTopWidth","boxSizing","fontFamily","fontSize","fontWeight","height","letterSpacing","lineHeight","marginBottom","marginLeft","marginRight","marginTop","outlineWidth","overflow","overflowX","overflowY","paddingBottom","paddingLeft","paddingRight","paddingTop","textAlign","textOverflow","textTransform","whiteSpace","wordBreak","wordWrap"],b.prototype.mirrorCss=function(){var b,c=this;return b={position:"absolute",left:-9999,top:0,zIndex:-2e4},"TEXTAREA"===this.$inputor.prop("tagName")&&this.css_attr.push("width"),a.each(this.css_attr,function(a,d){return b[d]=c.$inputor.css(d)}),b},b.prototype.create=function(b){return this.$mirror=a("
      "),this.$mirror.css(this.mirrorCss()),this.$mirror.html(b),this.$inputor.after(this.$mirror),this},b.prototype.rect=function(){var a,b,c;return a=this.$mirror.find("#caret"),b=a.position(),c={left:b.left,top:b.top,height:a.height()},this.$mirror.remove(),c},b}(),e={contentEditable:function(a){return!(!a[0].contentEditable||"true"!==a[0].contentEditable)}},g={pos:function(a){return a||0===a?this.setPos(a):this.getPos()},position:function(a){return h.selection?this.getIEPosition(a):this.getPosition(a)},offset:function(a){var b;return b=this.getOffset(a)}},h=null,j=null,i=null,l=function(a){var b;return(b=null!=a?a.iframe:void 0)?(i=b,j=b.contentWindow,h=b.contentDocument||j.document):(i=void 0,j=window,h=document)},f=function(a){var b;h=a[0].ownerDocument,j=h.defaultView||h.parentWindow;try{return i=j.frameElement}catch(c){b=c}},a.fn.caret=function(d,f,h){var i;return g[d]?(a.isPlainObject(f)?(l(f),f=void 0):l(h),i=e.contentEditable(this)?new b(this):new c(this),g[d].apply(i,[f])):a.error("Method "+d+" does not exist on jQuery.caret")},a.fn.caret.EditableCaret=b,a.fn.caret.InputCaret=c,a.fn.caret.Utils=e,a.fn.caret.apis=g}); \ No newline at end of file diff --git a/apps/comments/lib/AppInfo/Application.php b/apps/comments/lib/AppInfo/Application.php index f168779cd0d6d..a863ca506b7ef 100644 --- a/apps/comments/lib/AppInfo/Application.php +++ b/apps/comments/lib/AppInfo/Application.php @@ -22,7 +22,9 @@ namespace OCA\Comments\AppInfo; use OCA\Comments\Controller\Notifications; +use OCA\Comments\JSSettingsHelper; use OCP\AppFramework\App; +use OCP\Util; class Application extends App { @@ -31,5 +33,8 @@ public function __construct (array $urlParams = array()) { $container = $this->getContainer(); $container->registerAlias('NotificationsController', Notifications::class); + + $jsSettingsHelper = new JSSettingsHelper($container->getServer()); + Util::connectHook('\OCP\Config', 'js', $jsSettingsHelper, 'extend'); } } diff --git a/apps/comments/lib/Collaboration/CommentersSorter.php b/apps/comments/lib/Collaboration/CommentersSorter.php new file mode 100644 index 0000000000000..b8bb745b3b82a --- /dev/null +++ b/apps/comments/lib/Collaboration/CommentersSorter.php @@ -0,0 +1,115 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Comments\Collaboration; + + +use OCP\Collaboration\AutoComplete\ISorter; +use OCP\Comments\ICommentsManager; + +class CommentersSorter implements ISorter { + + /** @var ICommentsManager */ + private $commentsManager; + + public function __construct(ICommentsManager $commentsManager) { + $this->commentsManager = $commentsManager; + } + + public function getId() { + return 'commenters'; + } + + /** + * Sorts people who commented on the given item atop (descelating) of the + * others + * + * @param array $sortArray + * @param array $context + */ + public function sort(array &$sortArray, array $context) { + $commenters = $this->retrieveCommentsInformation($context['itemType'], $context['itemId']); + if(count($commenters) === 0) { + return; + } + + foreach ($sortArray as $type => &$byType) { + if(!isset($commenters[$type])) { + continue; + } + + // at least on PHP 5.6 usort turned out to be not stable. So we add + // the current index to the value and compare it on a draw + $i = 0; + $workArray = array_map(function($element) use (&$i) { + return [$i++, $element]; + }, $byType); + + usort($workArray, function ($a, $b) use ($commenters, $type) { + $r = $this->compare($a[1], $b[1], $commenters[$type]); + if($r === 0) { + $r = $a[0] - $b[0]; + } + return $r; + }); + + // and remove the index values again + $byType = array_column($workArray, 1); + } + } + + /** + * @param $type + * @param $id + * @return array + */ + protected function retrieveCommentsInformation($type, $id) { + $comments = $this->commentsManager->getForObject($type, $id); + if(count($comments) === 0) { + return []; + } + + $actors = []; + foreach ($comments as $comment) { + if(!isset($actors[$comment->getActorType()])) { + $actors[$comment->getActorType()] = []; + } + if(!isset($actors[$comment->getActorType()][$comment->getActorId()])) { + $actors[$comment->getActorType()][$comment->getActorId()] = 1; + } else { + $actors[$comment->getActorType()][$comment->getActorId()]++; + } + } + return $actors; + } + + protected function compare(array $a, array $b, array $commenters) { + $a = $a['value']['shareWith']; + $b = $b['value']['shareWith']; + + $valueA = isset($commenters[$a]) ? $commenters[$a] : 0; + $valueB = isset($commenters[$b]) ? $commenters[$b] : 0; + + return $valueB - $valueA; + } +} diff --git a/apps/comments/lib/JSSettingsHelper.php b/apps/comments/lib/JSSettingsHelper.php new file mode 100644 index 0000000000000..dab68a48925a3 --- /dev/null +++ b/apps/comments/lib/JSSettingsHelper.php @@ -0,0 +1,45 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Comments; + + +use OCP\IServerContainer; + +class JSSettingsHelper { + /** @var IServerContainer */ + private $c; + + public function __construct(IServerContainer $c) { + $this->c = $c; + } + + public function extend(array $settings) { + $appConfig = json_decode($settings['array']['oc_appconfig'], true); + + $value = (int)$this->c->getConfig()->getAppValue('comments', 'maxAutoCompleteResults', 10); + $appConfig['comments']['maxAutoCompleteResults'] = $value; + + $settings['array']['oc_appconfig'] = json_encode($appConfig); + } +} diff --git a/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php b/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php new file mode 100644 index 0000000000000..0cc3e3d4b6164 --- /dev/null +++ b/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php @@ -0,0 +1,160 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Comments\Tests\Unit\Collaboration; + + +use OCA\Comments\Collaboration\CommentersSorter; +use OCP\Comments\IComment; +use OCP\Comments\ICommentsManager; +use OCP\IConfig; +use Test\TestCase; + +class CommentersSorterTest extends TestCase { + /** @var ICommentsManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $commentsManager; + /** @var CommentersSorter */ + protected $sorter; + + public function setUp() { + parent::setUp(); + + $this->commentsManager = $this->createMock(ICommentsManager::class); + + $this->sorter = new CommentersSorter($this->commentsManager); + } + + /** + * @dataProvider sortDataProvider + * @param $data + */ + public function testSort($data) { + $commentMocks = []; + foreach($data['actors'] as $actorType => $actors) { + foreach ($actors as $actorId => $noOfComments) { + for($i=0;$i<$noOfComments;$i++) { + $mock = $this->createMock(IComment::class); + $mock->expects($this->atLeastOnce()) + ->method('getActorType') + ->willReturn($actorType); + $mock->expects($this->atLeastOnce()) + ->method('getActorId') + ->willReturn($actorId); + $commentMocks[] = $mock; + } + } + } + + $this->commentsManager->expects($this->once()) + ->method('getForObject') + ->willReturn($commentMocks); + + $workArray = $data['input']; + $this->sorter->sort($workArray, ['itemType' => 'files', 'itemId' => '24']); + + $this->assertEquals($data['expected'], $workArray); + } + + public function sortDataProvider() { + return [[ + [ + #1 – sort properly and otherwise keep existing order + 'actors' => ['users' => ['celia' => 3, 'darius' => 7, 'faruk' => 5, 'gail' => 5], 'bots' => ['r2-d2' => 8]], + 'input' => [ + 'users' => + [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'elena']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'c-3po']], + ['value' => ['shareWith' => 'r2-d2']], + ] + ], + 'expected' => [ + 'users' => + [ + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'elena']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'r2-d2']], + ['value' => ['shareWith' => 'c-3po']], + ] + ], + ], + [ + #2 – no commentors, input equals output + 'actors' => [], + 'input' => [ + 'users' => + [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'elena']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'c-3po']], + ['value' => ['shareWith' => 'r2-d2']], + ] + ], + 'expected' => [ + 'users' => + [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'elena']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'c-3po']], + ['value' => ['shareWith' => 'r2-d2']], + ] + ], + ], + [ + #3 – no nothing + 'actors' => [], + 'input' => [], + 'expected' => [], + ], + ]]; + } +} diff --git a/apps/comments/tests/Unit/JSSettingsHelperTest.php b/apps/comments/tests/Unit/JSSettingsHelperTest.php new file mode 100644 index 0000000000000..ad2f34c7aab9a --- /dev/null +++ b/apps/comments/tests/Unit/JSSettingsHelperTest.php @@ -0,0 +1,73 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Comments\Tests\Unit; + +use OCA\Comments\JSSettingsHelper; +use OCP\IConfig; +use OCP\IServerContainer; +use Test\TestCase; + +class JSSettingsHelperTest extends TestCase { + /** @var IServerContainer|\PHPUnit_Framework_MockObject_MockObject */ + protected $c; + /** @var JSSettingsHelper */ + protected $helper; + + public function setUp() { + parent::setUp(); + + $this->c = $this->createMock(IServerContainer::class); + + $this->helper = new JSSettingsHelper($this->c); + } + + public function testExtend() { + $config = $this->createMock(IConfig::class); + $config->expects($this->once()) + ->method('getAppValue') + ->with('comments', 'maxAutoCompleteResults') + ->willReturn(13); + + $this->c->expects($this->once()) + ->method('getConfig') + ->willReturn($config); + + $config = [ + 'oc_appconfig' => json_encode([ + 'anotherapp' => [ + 'foo' => 'bar', + 'foobar' => true + ] + ]) + ]; + + $this->helper->extend(['array' => &$config]); + + $appConfig = json_decode($config['oc_appconfig'], true); + $this->assertTrue(isset($appConfig['comments'])); + $this->assertTrue(isset($appConfig['anotherapp'])); + $this->assertSame(2, count($appConfig['anotherapp'])); + $this->assertSame(13, $appConfig['comments']['maxAutoCompleteResults']); + } +} diff --git a/apps/comments/tests/js/commentstabviewSpec.js b/apps/comments/tests/js/commentstabviewSpec.js index 63a27956f9f99..8b99ad081cd0e 100644 --- a/apps/comments/tests/js/commentstabviewSpec.js +++ b/apps/comments/tests/js/commentstabviewSpec.js @@ -157,7 +157,7 @@ describe('OCA.Comments.CommentsTabView tests', function() { expect($comment.find('.avatar[data-user=macbeth] ~ .contactsmenu-popover').length).toEqual(1); expect($comment.find('.avatar[data-user=banquo]').length).toEqual(1); - expect($comment.find('.avatar-name-wrapper:last-child strong').text()).toEqual('Lord Banquo'); + expect($comment.find('.avatar[data-user=banquo] ~ strong').text()).toEqual('Lord Banquo'); expect($comment.find('.avatar[data-user=banquo] ~ .contactsmenu-popover').length).toEqual(1); }); @@ -239,7 +239,7 @@ describe('OCA.Comments.CommentsTabView tests', function() { }); it('creates a new comment when clicking post button', function() { - view.$el.find('.message').val('New message'); + view.$el.find('.message').text('New message'); view.$el.find('form').submit(); expect(createStub.calledOnce).toEqual(true); @@ -253,7 +253,7 @@ describe('OCA.Comments.CommentsTabView tests', function() { }); }); it('creates a new comment with mentions when clicking post button', function() { - view.$el.find('.message').val('New message @anotheruser'); + view.$el.find('.message').text('New message @anotheruser'); view.$el.find('form').submit(); var createStubExpectedData = { @@ -439,7 +439,7 @@ describe('OCA.Comments.CommentsTabView tests', function() { var $formRow = view.$el.find('.newCommentRow.comment[data-id=1]'); expect($formRow.length).toEqual(1); - $formRow.find('textarea').val('modified message'); + $formRow.find('div.message').text('modified message'); $formRow.find('form').submit(); expect(saveStub.calledOnce).toEqual(true); @@ -451,8 +451,9 @@ describe('OCA.Comments.CommentsTabView tests', function() { // simulate the fact that save sets the attribute model.set('message', 'modified\nmessage'); saveStub.yieldTo('success', model); + view.collection.get(model); - expect(fetchStub.calledOnce).toEqual(true); + expect(fetchStub.called).toEqual(true); fetchStub.yieldTo('success', model); // original comment element is visible again @@ -472,7 +473,7 @@ describe('OCA.Comments.CommentsTabView tests', function() { var $formRow = view.$el.find('.newCommentRow.comment[data-id=3]'); expect($formRow.length).toEqual(1); - $formRow.find('textarea').val('modified\nmessage @anotheruser'); + $formRow.find('div.message').text('modified\nmessage @anotheruser'); $formRow.find('form').submit(); expect(saveStub.calledOnce).toEqual(true); @@ -485,7 +486,7 @@ describe('OCA.Comments.CommentsTabView tests', function() { model.set('message', 'modified\nmessage @anotheruser'); saveStub.yieldTo('success', model); - expect(fetchStub.calledOnce).toEqual(true); + expect(fetchStub.called).toEqual(true); // simulate the fact that fetch sets the attribute model.set('mentions', { diff --git a/apps/files_sharing/appinfo/info.xml b/apps/files_sharing/appinfo/info.xml index f4119a559728a..e98d29aeb8a9a 100644 --- a/apps/files_sharing/appinfo/info.xml +++ b/apps/files_sharing/appinfo/info.xml @@ -59,4 +59,10 @@ Turning the feature off removes shared files and folders on the server for all s OCA\Files_Sharing\Migration\SetPasswordColumn + + + + OCA\Files_Sharing\Collaboration\ShareRecipientSorter + + diff --git a/apps/files_sharing/composer/composer/autoload_classmap.php b/apps/files_sharing/composer/composer/autoload_classmap.php index 48b9651a00d4c..a68db3421b6b9 100644 --- a/apps/files_sharing/composer/composer/autoload_classmap.php +++ b/apps/files_sharing/composer/composer/autoload_classmap.php @@ -19,6 +19,7 @@ 'OCA\\Files_Sharing\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php', 'OCA\\Files_Sharing\\Cache' => $baseDir . '/../lib/Cache.php', 'OCA\\Files_Sharing\\Capabilities' => $baseDir . '/../lib/Capabilities.php', + 'OCA\\Files_Sharing\\Collaboration\\ShareRecipientSorter' => $baseDir . '/../lib/Collaboration/ShareRecipientSorter.php', 'OCA\\Files_Sharing\\Command\\CleanupRemoteStorages' => $baseDir . '/../lib/Command/CleanupRemoteStorages.php', 'OCA\\Files_Sharing\\Controller\\ExternalSharesController' => $baseDir . '/../lib/Controller/ExternalSharesController.php', 'OCA\\Files_Sharing\\Controller\\PublicPreviewController' => $baseDir . '/../lib/Controller/PublicPreviewController.php', diff --git a/apps/files_sharing/composer/composer/autoload_static.php b/apps/files_sharing/composer/composer/autoload_static.php index b8a61eaadd1ba..328d6aca01d57 100644 --- a/apps/files_sharing/composer/composer/autoload_static.php +++ b/apps/files_sharing/composer/composer/autoload_static.php @@ -34,6 +34,7 @@ class ComposerStaticInitFiles_Sharing 'OCA\\Files_Sharing\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php', 'OCA\\Files_Sharing\\Cache' => __DIR__ . '/..' . '/../lib/Cache.php', 'OCA\\Files_Sharing\\Capabilities' => __DIR__ . '/..' . '/../lib/Capabilities.php', + 'OCA\\Files_Sharing\\Collaboration\\ShareRecipientSorter' => __DIR__ . '/..' . '/../lib/Collaboration/ShareRecipientSorter.php', 'OCA\\Files_Sharing\\Command\\CleanupRemoteStorages' => __DIR__ . '/..' . '/../lib/Command/CleanupRemoteStorages.php', 'OCA\\Files_Sharing\\Controller\\ExternalSharesController' => __DIR__ . '/..' . '/../lib/Controller/ExternalSharesController.php', 'OCA\\Files_Sharing\\Controller\\PublicPreviewController' => __DIR__ . '/..' . '/../lib/Controller/PublicPreviewController.php', diff --git a/apps/files_sharing/lib/Collaboration/ShareRecipientSorter.php b/apps/files_sharing/lib/Collaboration/ShareRecipientSorter.php new file mode 100644 index 0000000000000..db21339811895 --- /dev/null +++ b/apps/files_sharing/lib/Collaboration/ShareRecipientSorter.php @@ -0,0 +1,110 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Files_Sharing\Collaboration; + + +use OCP\Collaboration\AutoComplete\ISorter; +use OCP\Files\Folder; +use OCP\Files\IRootFolder; +use OCP\Files\Node; +use OCP\IUserSession; +use OCP\Share\IManager; + +class ShareRecipientSorter implements ISorter { + + /** @var IManager */ + private $shareManager; + /** @var Folder */ + private $rootFolder; + /** @var IUserSession */ + private $userSession; + + public function __construct(IManager $shareManager, IRootFolder $rootFolder, IUserSession $userSession) { + $this->shareManager = $shareManager; + $this->rootFolder = $rootFolder; + $this->userSession = $userSession; + } + + public function getId() { + return 'share-recipients'; + } + + public function sort(array &$sortArray, array $context) { + // let's be tolerant. Comments uses "files" by default, other usages are often singular + if($context['itemType'] !== 'files' && $context['itemType'] !== 'file') { + return; + } + $user = $this->userSession->getUser(); + if($user === null) { + return; + } + $userFolder = $this->rootFolder->getUserFolder($user->getUID()); + /** @var Node[] $nodes */ + $nodes = $userFolder->getById((int)$context['itemId']); + if(count($nodes) === 0) { + return; + } + $al = $this->shareManager->getAccessList($nodes[0]); + + foreach ($sortArray as $type => &$byType) { + if(!isset($al[$type]) || !is_array($al[$type])) { + continue; + } + + // at least on PHP 5.6 usort turned out to be not stable. So we add + // the current index to the value and compare it on a draw + $i = 0; + $workArray = array_map(function($element) use (&$i) { + return [$i++, $element]; + }, $byType); + + usort($workArray, function ($a, $b) use ($al, $type) { + $result = $this->compare($a[1], $b[1], $al[$type]); + if($result === 0) { + $result = $a[0] - $b[0]; + } + return $result; + }); + + // and remove the index values again + $byType = array_column($workArray, 1); + } + } + + /** + * @param array $a + * @param array $b + * @param array $al + * @return int + */ + protected function compare(array $a, array $b, array $al) { + $a = $a['value']['shareWith']; + $b = $b['value']['shareWith']; + + $valueA = (int)in_array($a, $al, true); + $valueB = (int)in_array($b, $al, true); + + return $valueB - $valueA; + } +} diff --git a/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php b/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php new file mode 100644 index 0000000000000..8f5167887611b --- /dev/null +++ b/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php @@ -0,0 +1,258 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Files_Sharing\Tests\Collaboration; + + +use OCA\Files_Sharing\Collaboration\ShareRecipientSorter; +use OCP\Files\Folder; +use OCP\Files\IRootFolder; +use OCP\Files\Node; +use OCP\IUser; +use OCP\IUserSession; +use OCP\Share\IManager; +use Test\TestCase; + +class ShareRecipientSorterTest extends TestCase { + /** @var IManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $shareManager; + /** @var IRootFolder|\PHPUnit_Framework_MockObject_MockObject */ + protected $rootFolder; + /** @var IUserSession|\PHPUnit_Framework_MockObject_MockObject */ + protected $userSession; + /** @var ShareRecipientSorter */ + protected $sorter; + + public function setUp() { + parent::setUp(); + + $this->shareManager = $this->createMock(IManager::class); + $this->rootFolder = $this->createMock(IRootFolder::class); + $this->userSession = $this->createMock(IUserSession::class); + + $this->sorter = new ShareRecipientSorter($this->shareManager, $this->rootFolder, $this->userSession); + } + + /** + * @dataProvider sortDataProvider + * @param $data + */ + public function testSort($data) { + $node = $this->createMock(Node::class); + + /** @var Folder|\PHPUnit_Framework_MockObject_MockObject $folder */ + $folder = $this->createMock(Folder::class); + $this->rootFolder->expects($this->any()) + ->method('getUserFolder') + ->willReturn($folder); + + $user = $this->createMock(IUser::class); + $user->expects($this->any()) + ->method('getUID') + ->willReturn('yvonne'); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->willReturn($user); + + if ($data['context']['itemType'] === 'files') { + $folder->expects($this->once()) + ->method('getById') + ->with($data['context']['itemId']) + ->willReturn([$node]); + + $this->shareManager->expects($this->once()) + ->method('getAccessList') + ->with($node) + ->willReturn($data['accessList']); + } else { + $folder->expects($this->never()) + ->method('getById'); + $this->shareManager->expects($this->never()) + ->method('getAccessList'); + } + + $workArray = $data['input']; + $this->sorter->sort($workArray, $data['context']); + + $this->assertEquals($data['expected'], $workArray); + } + + public function testSortNoNodes() { + /** @var Folder|\PHPUnit_Framework_MockObject_MockObject $folder */ + $folder = $this->createMock(Folder::class); + $this->rootFolder->expects($this->any()) + ->method('getUserFolder') + ->willReturn($folder); + + $folder->expects($this->once()) + ->method('getById') + ->willReturn([]); + + $user = $this->createMock(IUser::class); + $user->expects($this->any()) + ->method('getUID') + ->willReturn('yvonne'); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->willReturn($user); + + $this->shareManager->expects($this->never()) + ->method('getAccessList'); + + $originalArray = [ + 'users' => [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ] + ]; + $workArray = $originalArray; + $this->sorter->sort($workArray, ['itemType' => 'files', 'itemId' => 404]); + + $this->assertEquals($originalArray, $workArray); + } + + public function sortDataProvider() { + return [[ + [ + #0 – sort properly and otherwise keep existing order + 'context' => ['itemType' => 'files', 'itemId' => 42], + 'accessList' => ['users' => ['celia', 'darius', 'faruk', 'gail'], 'bots' => ['r2-d2']], + 'input' => [ + 'users' => + [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'elena']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'c-3po']], + ['value' => ['shareWith' => 'r2-d2']], + ] + ], + 'expected' => [ + 'users' => + [ + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'elena']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'r2-d2']], + ['value' => ['shareWith' => 'c-3po']], + ] + ], + ], + [ + #1 – no recipients + 'context' => ['itemType' => 'files', 'itemId' => 42], + 'accessList' => ['users' => false], + 'input' => [ + 'users' => + [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'elena']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'c-3po']], + ['value' => ['shareWith' => 'r2-d2']], + ] + ], + 'expected' => [ + 'users' => + [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'elena']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'c-3po']], + ['value' => ['shareWith' => 'r2-d2']], + ] + ], + ], + [ + #2 – unsupported item type + 'context' => ['itemType' => 'announcements', 'itemId' => 42], + 'accessList' => null, // not needed + 'input' => [ + 'users' => + [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'elena']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'c-3po']], + ['value' => ['shareWith' => 'r2-d2']], + ] + ], + 'expected' => [ + 'users' => + [ + ['value' => ['shareWith' => 'alice']], + ['value' => ['shareWith' => 'bob']], + ['value' => ['shareWith' => 'celia']], + ['value' => ['shareWith' => 'darius']], + ['value' => ['shareWith' => 'elena']], + ['value' => ['shareWith' => 'faruk']], + ['value' => ['shareWith' => 'gail']], + ], + 'bots' => [ + ['value' => ['shareWith' => 'c-3po']], + ['value' => ['shareWith' => 'r2-d2']], + ] + ], + ], + [ + #3 – no nothing + 'context' => ['itemType' => 'files', 'itemId' => 42], + 'accessList' => [], + 'input' => [], + 'expected' => [], + ], + ]]; + } +} diff --git a/apps/user_ldap/lib/Access.php b/apps/user_ldap/lib/Access.php index b6674cf0332ec..bbf07165090c1 100644 --- a/apps/user_ldap/lib/Access.php +++ b/apps/user_ldap/lib/Access.php @@ -1853,20 +1853,19 @@ private function initPagedSearch($filter, $bases, $attr, $limit, $offset) { $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); if(empty($cookie) && $cookie !== "0" && ($offset > 0)) { - // no cookie known, although the offset is not 0. Maybe cache run out. We need - // to start all over *sigh* (btw, Dear Reader, did you know LDAP paged - // searching was designed by MSFT?) - // Lukas: No, but thanks to reading that source I finally know! - // '0' is valid, because 389ds - $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit; - //a bit recursive, $offset of 0 is the exit - \OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO); - $this->search($filter, array($base), $attr, $limit, $reOffset, true); + // no cookie known from a potential previous search. We need + // to start from 0 to come to the desired page. cookie value + // of '0' is valid, because 389ds + $reOffset = 0; + while($reOffset < $offset) { + $this->search($filter, array($base), $attr, $limit, $reOffset, true); + $reOffset += $limit; + } $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); //still no cookie? obviously, the server does not like us. Let's skip paging efforts. + // '0' is valid, because 389ds //TODO: remember this, probably does not change in the next request... if(empty($cookie) && $cookie !== '0') { - // '0' is valid, because 389ds $cookie = null; } } diff --git a/apps/user_ldap/lib/Connection.php b/apps/user_ldap/lib/Connection.php index 3350dd6a5cd34..9e84cbde35b98 100644 --- a/apps/user_ldap/lib/Connection.php +++ b/apps/user_ldap/lib/Connection.php @@ -122,7 +122,7 @@ public function __clone() { /** * @param string $name - * @return bool|mixed|void + * @return bool|mixed */ public function __get($name) { if(!$this->configured) { diff --git a/config/config.sample.php b/config/config.sample.php index ed2ecbb87b340..f8723c7d9b01a 100644 --- a/config/config.sample.php +++ b/config/config.sample.php @@ -1232,7 +1232,6 @@ */ 'sharing.minSearchStringLength' => 0, - /** * All other configuration options */ diff --git a/core/Controller/AutoCompleteController.php b/core/Controller/AutoCompleteController.php new file mode 100644 index 0000000000000..2e01f85c6398f --- /dev/null +++ b/core/Controller/AutoCompleteController.php @@ -0,0 +1,102 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OC\Core\Controller; + +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http\DataResponse; +use OCP\Collaboration\AutoComplete\IManager; +use OCP\Collaboration\Collaborators\ISearch; +use OCP\IConfig; +use OCP\IRequest; +use OCP\Share; + +class AutoCompleteController extends Controller { + /** @var ISearch */ + private $collaboratorSearch; + /** @var IManager */ + private $autoCompleteManager; + /** @var IConfig */ + private $config; + + public function __construct( + $appName, + IRequest $request, + ISearch $collaboratorSearch, + IManager $autoCompleteManager, + IConfig $config + ) { + parent::__construct($appName, $request); + + $this->collaboratorSearch = $collaboratorSearch; + $this->autoCompleteManager = $autoCompleteManager; + $this->config = $config; + } + + /** + * @NoAdminRequired + * + * @param string $search + * @param string $itemType + * @param string $itemId + * @param string|null $sorter can be piped, top prio first, e.g.: "commenters|share-recipients" + * @param array $shareTypes + * @param int $limit + * @return DataResponse + */ + public function get($search, $itemType, $itemId, $sorter = null, $shareTypes = [Share::SHARE_TYPE_USER], $limit = 10) { + // if enumeration/user listings are disabled, we'll receive an empty + // result from search() – thus nothing else to do here. + list($results,) = $this->collaboratorSearch->search($search, $shareTypes, false, $limit, 0); + + $exactMatches = $results['exact']; + unset($results['exact']); + $results = array_merge_recursive($exactMatches, $results); + + $sorters = array_reverse(explode('|', $sorter)); + $this->autoCompleteManager->runSorters($sorters, $results, [ + 'itemType' => $itemType, + 'itemId' => $itemId, + ]); + + // transform to expected format + $results = $this->prepareResultArray($results); + + return new DataResponse($results); + } + + + protected function prepareResultArray(array $results) { + $output = []; + foreach ($results as $type => $subResult) { + foreach ($subResult as $result) { + $output[] = [ + 'id' => $result['value']['shareWith'], + 'label' => $result['label'], + 'source' => $type, + ]; + } + } + return $output; + } +} diff --git a/core/css/guest.css b/core/css/guest.css index ee6d44d98e887..576efafec5ff5 100644 --- a/core/css/guest.css +++ b/core/css/guest.css @@ -152,7 +152,7 @@ form #datadirField legend { applied to the button instead. */ } -input, textarea, select, button { +input, textarea, select, button, div[contenteditable=true] { font-family: 'Open Sans', Frutiger, Calibri, 'Myriad Pro', Myriad, sans-serif; } input { @@ -664,16 +664,16 @@ p.info { margin: -9px 0 0 -9px; } /* Css replaced elements don't have ::after nor ::before */ -img.icon-loading, object.icon-loading, video.icon-loading, button.icon-loading, textarea.icon-loading, input.icon-loading, select.icon-loading { +img.icon-loading, object.icon-loading, video.icon-loading, button.icon-loading, textarea.icon-loading, input.icon-loading, select.icon-loading, div[contenteditable=true].icon-loading { background-image: url('../img/loading.gif'); } -img.icon-loading-dark, object.icon-loading-dark, video.icon-loading-dark, button.icon-loading-dark, textarea.icon-loading-dark, input.icon-loading-dark, select.icon-loading-dark { +img.icon-loading-dark, object.icon-loading-dark, video.icon-loading-dark, button.icon-loading-dark, textarea.icon-loading-dark, input.icon-loading-dark, select.icon-loading-dark, div[contenteditable=true].icon-loading-dark { background-image: url('../img/loading-dark.gif'); } -img.icon-loading-small, object.icon-loading-small, video.icon-loading-small, button.icon-loading-small, textarea.icon-loading-small, input.icon-loading-small, select.icon-loading-small { +img.icon-loading-small, object.icon-loading-small, video.icon-loading-small, button.icon-loading-small, textarea.icon-loading-small, input.icon-loading-small, select.icon-loading-small, div[contenteditable=true].icon-loading-small { background-image: url('../img/loading-small.gif'); } -img.icon-loading-small-dark, object.icon-loading-small-dark, video.icon-loading-small-dark, button.icon-loading-small-dark, textarea.icon-loading-small-dark, input.icon-loading-small-dark, select.icon-loading-small-dark { +img.icon-loading-small-dark, object.icon-loading-small-dark, video.icon-loading-small-dark, button.icon-loading-small-dark, textarea.icon-loading-small-dark, input.icon-loading-small-dark, select.icon-loading-small-dark, div[contenteditable=true].icon-loading-small-dark { background-image: url('../img/loading-small-dark.gif'); } @-webkit-keyframes rotate { diff --git a/core/css/icons.scss b/core/css/icons.scss index 36c550575ded4..bdef106e3cdc2 100644 --- a/core/css/icons.scss +++ b/core/css/icons.scss @@ -61,7 +61,7 @@ } /* Css replaced elements don't have ::after nor ::before */ -img, object, video, button, textarea, input, select { +img, object, video, button, textarea, input, select, div[contenteditable=true] { .icon-loading { background-image: url('../img/loading.gif'); } diff --git a/core/css/inputs.scss b/core/css/inputs.scss index eb7d20cf8af7e..5143ec518ed21 100644 --- a/core/css/inputs.scss +++ b/core/css/inputs.scss @@ -13,7 +13,7 @@ */ /* Specifically override browser styles */ -input, textarea, select, button { +input, textarea, select, button, div[contenteditable=true] { font-family: 'Open Sans', Frutiger, Calibri, 'Myriad Pro', Myriad, sans-serif; } .select2-container-multi .select2-choices .select2-search-field input, .select2-search input, .ui-widget { @@ -24,7 +24,8 @@ input, textarea, select, button { select, button, input, -textarea { +textarea, +div[contenteditable=true] { width: 130px; min-height: 32px; box-sizing: border-box; @@ -35,6 +36,7 @@ select, button, .button, input:not([type='range']), textarea, +div[contenteditable=true], .pager li a { margin: 3px 3px 3px 0; padding: 7px 6px; @@ -154,7 +156,7 @@ button, .button { } } -textarea { +textarea, div[contenteditable=true] { color: nc-lighten($color-main-text, 33%); cursor: text; font-family: inherit; diff --git a/core/routes.php b/core/routes.php index af445d9da8f8c..75d8fb140a710 100644 --- a/core/routes.php +++ b/core/routes.php @@ -62,6 +62,7 @@ ['name' => 'Js#getJs', 'url' => '/js/{appName}/{fileName}', 'verb' => 'GET'], ['name' => 'contactsMenu#index', 'url' => '/contactsmenu/contacts', 'verb' => 'POST'], ['name' => 'contactsMenu#findOne', 'url' => '/contactsmenu/findOne', 'verb' => 'POST'], + ['name' => 'AutoComplete#get', 'url' => 'autocomplete/get', 'verb' => 'GET'] ], 'ocs' => [ ['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'], diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php index 5c55c83b054d0..0e550b7253267 100644 --- a/lib/composer/composer/autoload_classmap.php +++ b/lib/composer/composer/autoload_classmap.php @@ -68,6 +68,8 @@ 'OCP\\BackgroundJob\\IJobList' => $baseDir . '/lib/public/BackgroundJob/IJobList.php', 'OCP\\Capabilities\\ICapability' => $baseDir . '/lib/public/Capabilities/ICapability.php', 'OCP\\Capabilities\\IPublicCapability' => $baseDir . '/lib/public/Capabilities/IPublicCapability.php', + 'OCP\\Collaboration\\AutoComplete\\IManager' => $baseDir . '/lib/public/Collaboration/AutoComplete/IManager.php', + 'OCP\\Collaboration\\AutoComplete\\ISorter' => $baseDir . '/lib/public/Collaboration/AutoComplete/ISorter.php', 'OCP\\Collaboration\\Collaborators\\ISearch' => $baseDir . '/lib/public/Collaboration/Collaborators/ISearch.php', 'OCP\\Collaboration\\Collaborators\\ISearchPlugin' => $baseDir . '/lib/public/Collaboration/Collaborators/ISearchPlugin.php', 'OCP\\Collaboration\\Collaborators\\ISearchResult' => $baseDir . '/lib/public/Collaboration/Collaborators/ISearchResult.php', @@ -390,6 +392,7 @@ 'OC\\Cache\\CappedMemoryCache' => $baseDir . '/lib/private/Cache/CappedMemoryCache.php', 'OC\\Cache\\File' => $baseDir . '/lib/private/Cache/File.php', 'OC\\CapabilitiesManager' => $baseDir . '/lib/private/CapabilitiesManager.php', + 'OC\\Collaboration\\AutoComplete\\Manager' => $baseDir . '/lib/private/Collaboration/AutoComplete/Manager.php', 'OC\\Collaboration\\Collaborators\\GroupPlugin' => $baseDir . '/lib/private/Collaboration/Collaborators/GroupPlugin.php', 'OC\\Collaboration\\Collaborators\\LookupPlugin' => $baseDir . '/lib/private/Collaboration/Collaborators/LookupPlugin.php', 'OC\\Collaboration\\Collaborators\\MailPlugin' => $baseDir . '/lib/private/Collaboration/Collaborators/MailPlugin.php', @@ -495,6 +498,7 @@ 'OC\\Core\\Command\\User\\Report' => $baseDir . '/core/Command/User/Report.php', 'OC\\Core\\Command\\User\\ResetPassword' => $baseDir . '/core/Command/User/ResetPassword.php', 'OC\\Core\\Command\\User\\Setting' => $baseDir . '/core/Command/User/Setting.php', + 'OC\\Core\\Controller\\AutoCompleteController' => $baseDir . '/core/Controller/AutoCompleteController.php', 'OC\\Core\\Controller\\AvatarController' => $baseDir . '/core/Controller/AvatarController.php', 'OC\\Core\\Controller\\ClientFlowLoginController' => $baseDir . '/core/Controller/ClientFlowLoginController.php', 'OC\\Core\\Controller\\ContactsMenuController' => $baseDir . '/core/Controller/ContactsMenuController.php', diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php index 23fd2d4280b7c..563c039d03357 100644 --- a/lib/composer/composer/autoload_static.php +++ b/lib/composer/composer/autoload_static.php @@ -98,6 +98,8 @@ class ComposerStaticInit53792487c5a8370acc0b06b1a864ff4c 'OCP\\BackgroundJob\\IJobList' => __DIR__ . '/../../..' . '/lib/public/BackgroundJob/IJobList.php', 'OCP\\Capabilities\\ICapability' => __DIR__ . '/../../..' . '/lib/public/Capabilities/ICapability.php', 'OCP\\Capabilities\\IPublicCapability' => __DIR__ . '/../../..' . '/lib/public/Capabilities/IPublicCapability.php', + 'OCP\\Collaboration\\AutoComplete\\IManager' => __DIR__ . '/../../..' . '/lib/public/Collaboration/AutoComplete/IManager.php', + 'OCP\\Collaboration\\AutoComplete\\ISorter' => __DIR__ . '/../../..' . '/lib/public/Collaboration/AutoComplete/ISorter.php', 'OCP\\Collaboration\\Collaborators\\ISearch' => __DIR__ . '/../../..' . '/lib/public/Collaboration/Collaborators/ISearch.php', 'OCP\\Collaboration\\Collaborators\\ISearchPlugin' => __DIR__ . '/../../..' . '/lib/public/Collaboration/Collaborators/ISearchPlugin.php', 'OCP\\Collaboration\\Collaborators\\ISearchResult' => __DIR__ . '/../../..' . '/lib/public/Collaboration/Collaborators/ISearchResult.php', @@ -420,6 +422,7 @@ class ComposerStaticInit53792487c5a8370acc0b06b1a864ff4c 'OC\\Cache\\CappedMemoryCache' => __DIR__ . '/../../..' . '/lib/private/Cache/CappedMemoryCache.php', 'OC\\Cache\\File' => __DIR__ . '/../../..' . '/lib/private/Cache/File.php', 'OC\\CapabilitiesManager' => __DIR__ . '/../../..' . '/lib/private/CapabilitiesManager.php', + 'OC\\Collaboration\\AutoComplete\\Manager' => __DIR__ . '/../../..' . '/lib/private/Collaboration/AutoComplete/Manager.php', 'OC\\Collaboration\\Collaborators\\GroupPlugin' => __DIR__ . '/../../..' . '/lib/private/Collaboration/Collaborators/GroupPlugin.php', 'OC\\Collaboration\\Collaborators\\LookupPlugin' => __DIR__ . '/../../..' . '/lib/private/Collaboration/Collaborators/LookupPlugin.php', 'OC\\Collaboration\\Collaborators\\MailPlugin' => __DIR__ . '/../../..' . '/lib/private/Collaboration/Collaborators/MailPlugin.php', @@ -525,6 +528,7 @@ class ComposerStaticInit53792487c5a8370acc0b06b1a864ff4c 'OC\\Core\\Command\\User\\Report' => __DIR__ . '/../../..' . '/core/Command/User/Report.php', 'OC\\Core\\Command\\User\\ResetPassword' => __DIR__ . '/../../..' . '/core/Command/User/ResetPassword.php', 'OC\\Core\\Command\\User\\Setting' => __DIR__ . '/../../..' . '/core/Command/User/Setting.php', + 'OC\\Core\\Controller\\AutoCompleteController' => __DIR__ . '/../../..' . '/core/Controller/AutoCompleteController.php', 'OC\\Core\\Controller\\AvatarController' => __DIR__ . '/../../..' . '/core/Controller/AvatarController.php', 'OC\\Core\\Controller\\ClientFlowLoginController' => __DIR__ . '/../../..' . '/core/Controller/ClientFlowLoginController.php', 'OC\\Core\\Controller\\ContactsMenuController' => __DIR__ . '/../../..' . '/core/Controller/ContactsMenuController.php', diff --git a/lib/private/Collaboration/AutoComplete/Manager.php b/lib/private/Collaboration/AutoComplete/Manager.php new file mode 100644 index 0000000000000..eedc4fb5b401e --- /dev/null +++ b/lib/private/Collaboration/AutoComplete/Manager.php @@ -0,0 +1,81 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OC\Collaboration\AutoComplete; + +use OCP\Collaboration\AutoComplete\IManager; +use OCP\Collaboration\AutoComplete\ISorter; +use OCP\IServerContainer; + +class Manager implements IManager { + /** @var string[] */ + protected $sorters =[]; + + /** @var ISorter[] */ + protected $sorterInstances = []; + /** @var IServerContainer */ + private $c; + + public function __construct(IServerContainer $container) { + $this->c = $container; + } + + public function runSorters(array $sorters, array &$sortArray, array $context) { + $sorterInstances = $this->getSorters(); + while($sorter = array_shift($sorters)) { + if(isset($sorterInstances[$sorter])) { + $sorterInstances[$sorter]->sort($sortArray, $context); + } else { + $this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [ + 'app' => 'core', 'id' => $sorter + ]); + } + } + } + + public function registerSorter($className) { + $this->sorters[] = $className; + } + + protected function getSorters() { + if(count($this->sorterInstances) === 0) { + foreach ($this->sorters as $sorter) { + /** @var ISorter $instance */ + $instance = $this->c->resolve($sorter); + if(!$instance instanceof ISorter) { + $this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}', + ['app' => 'core', 'class' => $sorter]); + continue; + } + $sorterId = trim($instance->getId()); + if(trim($sorterId) === '') { + $this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}', + ['app' => 'core', 'class' => $sorter]); + continue; + } + $this->sorterInstances[$sorterId] = $instance; + } + } + return $this->sorterInstances; + } +} diff --git a/lib/private/Server.php b/lib/private/Server.php index 84c09c8e6db6b..c461d3842cd52 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -106,6 +106,7 @@ use OCP\App\IAppManager; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Collaboration\AutoComplete\IManager; use OCP\Defaults; use OCA\Theming\Util; use OCP\Federation\ICloudIdManager; @@ -1011,6 +1012,8 @@ public function __construct($webRoot, \OC\Config $config) { }); $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class); + $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class); + $this->registerService('SettingsManager', function (Server $c) { $manager = new \OC\Settings\Manager( $c->getLogger(), @@ -1801,6 +1804,13 @@ public function getCollaboratorSearch() { return $this->query('CollaboratorSearch'); } + /** + * @return \OCP\Collaboration\AutoComplete\IManager + */ + public function getAutoCompleteManager(){ + return $this->query(IManager::class); + } + /** * Returns the LDAP Provider * diff --git a/lib/private/Share20/Manager.php b/lib/private/Share20/Manager.php index bcef85bd17a2a..379d87633ab19 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -1322,7 +1322,7 @@ public function userDeletedFromGroup($uid, $gid) { * * @param \OCP\Files\Node $path * @param bool $recursive Should we check all parent folders as well - * @param bool $currentAccess Should the user have currently access to the file + * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it) * @return array */ public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) { diff --git a/lib/private/legacy/app.php b/lib/private/legacy/app.php index 519bb2cad2e6f..49fac2f4d96a7 100644 --- a/lib/private/legacy/app.php +++ b/lib/private/legacy/app.php @@ -185,6 +185,8 @@ public static function loadApp($app) { 'class' => $plugin['@value'], ]; \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo); + } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') { + \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']); } } } diff --git a/lib/public/Collaboration/AutoComplete/IManager.php b/lib/public/Collaboration/AutoComplete/IManager.php new file mode 100644 index 0000000000000..e9f33727cd287 --- /dev/null +++ b/lib/public/Collaboration/AutoComplete/IManager.php @@ -0,0 +1,46 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCP\Collaboration\AutoComplete; + +/** + * Interface IManager + * + * @package OCP\Collaboration\AutoComplete + * @since 13.0.0 + */ +interface IManager { + /** + * @param string $className – class name of the ISorter implementation + * @since 13.0.0 + */ + public function registerSorter($className); + + /** + * @param array $sorters list of sorter IDs, seperated by "|" + * @param array $sortArray array representation of OCP\Collaboration\Collaborators\ISearchResult + * @param array $context context info of the search, keys: itemType, itemId + * @since 13.0.0 + */ + public function runSorters(array $sorters, array &$sortArray, array $context); +} diff --git a/lib/public/Collaboration/AutoComplete/ISorter.php b/lib/public/Collaboration/AutoComplete/ISorter.php new file mode 100644 index 0000000000000..538ca41003d78 --- /dev/null +++ b/lib/public/Collaboration/AutoComplete/ISorter.php @@ -0,0 +1,50 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCP\Collaboration\AutoComplete; + +/** + * Interface ISorter + * + * Sorts the list of .e.g users for auto completion + * + * @package OCP\Collaboration\AutoComplete + * @since 13.0.0 + */ +interface ISorter { + + /** + * @return string The ID of the sorter, e.g. commenters + * @since 13.0.0 + */ + public function getId(); + + /** + * executes the sort action + * + * @param array $sortArray the array to be sorted, provided as reference + * @param array $context carries key 'itemType' and 'itemId' of the source object (e.g. a file) + * @since 13.0.0 + */ + public function sort(array &$sortArray, array $context); +} diff --git a/tests/Core/Controller/AutoCompleteControllerTest.php b/tests/Core/Controller/AutoCompleteControllerTest.php new file mode 100644 index 0000000000000..bcd0d6e1cd344 --- /dev/null +++ b/tests/Core/Controller/AutoCompleteControllerTest.php @@ -0,0 +1,118 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace Tests\Core\Controller; + + +use OC\Core\Controller\AutoCompleteController; +use OCP\Collaboration\AutoComplete\IManager; +use OCP\Collaboration\Collaborators\ISearch; +use OCP\IConfig; +use OCP\IRequest; +use Test\TestCase; + +class AutoCompleteControllerTest extends TestCase { + /** @var ISearch|\PHPUnit_Framework_MockObject_MockObject */ + protected $collaboratorSearch; + /** @var IManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $autoCompleteManager; + /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ + protected $config; + /** @var AutoCompleteController */ + protected $controller; + + protected function setUp() { + parent::setUp(); + + /** @var IRequest $request */ + $request = $this->createMock(IRequest::class); + $this->collaboratorSearch = $this->createMock(ISearch::class); + $this->autoCompleteManager = $this->createMock(IManager::class); + $this->config = $this->createMock(IConfig::class); + + $this->controller = new AutoCompleteController( + 'core', + $request, + $this->collaboratorSearch, + $this->autoCompleteManager, + $this->config + ); + } + + public function testGet() { + $searchResults = [ + 'exact' => [ + 'users' => [], + 'robots' => [], + ], + 'users' => [ + ['label' => 'Alice A.', 'value' => ['shareWith' => 'alice']], + ['label' => 'Bob Y.', 'value' => ['shareWith' => 'bob']], + ], + ]; + + $expected = [ + [ 'id' => 'alice', 'label' => 'Alice A.', 'source' => 'users'], + [ 'id' => 'bob', 'label' => 'Bob Y.', 'source' => 'users'], + ]; + + $this->collaboratorSearch->expects($this->once()) + ->method('search') + ->willReturn([$searchResults, false]); + + $response = $this->controller->get('', 'files', '42', null); + + $list = $response->getData(); + $this->assertEquals($expected, $list); // has better error output… + $this->assertSame($expected, $list); + } + + public function testGetWithExactMatch() { + $searchResults = [ + 'exact' => [ + 'users' => [ + ['label' => 'Bob Y.', 'value' => ['shareWith' => 'bob']], + ], + 'robots' => [], + ], + 'users' => [ + ['label' => 'Robert R.', 'value' => ['shareWith' => 'bobby']], + ], + ]; + + $expected = [ + [ 'id' => 'bob', 'label' => 'Bob Y.', 'source' => 'users'], + [ 'id' => 'bobby', 'label' => 'Robert R.', 'source' => 'users'], + ]; + + $this->collaboratorSearch->expects($this->once()) + ->method('search') + ->willReturn([$searchResults, false]); + + $response = $this->controller->get('bob', 'files', '42', null); + + $list = $response->getData(); + $this->assertEquals($expected, $list); // has better error output… + $this->assertSame($expected, $list); + } +} diff --git a/tests/acceptance/config/behat.yml b/tests/acceptance/config/behat.yml index 10e1d42502210..3495769457d27 100644 --- a/tests/acceptance/config/behat.yml +++ b/tests/acceptance/config/behat.yml @@ -10,6 +10,7 @@ default: - NextcloudTestServerContext - AppNavigationContext + - CommentsAppContext - FeatureContext - FilesAppContext - FilesSharingAppContext diff --git a/tests/acceptance/features/app-comments.feature b/tests/acceptance/features/app-comments.feature new file mode 100644 index 0000000000000..81fc6f89ad112 --- /dev/null +++ b/tests/acceptance/features/app-comments.feature @@ -0,0 +1,8 @@ +Feature: app-comments + + Scenario: Writing a comment + Given I am logged in + And I open the details view for "welcome.txt" + And I open the "Comments" tab in the details view + When I create a new comment with "Hello world" as message + Then I see that a comment was added diff --git a/tests/acceptance/features/bootstrap/CommentsAppContext.php b/tests/acceptance/features/bootstrap/CommentsAppContext.php new file mode 100644 index 0000000000000..64d1dc69bc4a4 --- /dev/null +++ b/tests/acceptance/features/bootstrap/CommentsAppContext.php @@ -0,0 +1,82 @@ + + * + * @author Arthur Schiwon + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +use Behat\Behat\Context\Context; + +class CommentsAppContext implements Context, ActorAwareInterface { + use ActorAware; + + + /** + * @When /^I create a new comment with "([^"]*)" as message$/ + */ + public function iCreateANewCommentWithAsMessage($commentText) { + $this->actor->find(self::newCommentField(), 2)->setValue($commentText); + $this->actor->find(self::submitNewCommentButton(), 2)->click(); + } + + /** + * @Then /^I see that a comment was added$/ + */ + public function iSeeThatACommentWasAdded() { + $self = $this; + + $result = Utils::waitFor(function () use ($self) { + return $self->isCommentAdded(); + }, 5, 0.5); + + PHPUnit_Framework_Assert::assertTrue($result); + } + + public function isCommentAdded() { + try { + $locator = self::commentFields(); + $comments = $this->actor->getSession()->getPage()->findAll($locator->getSelector(), $locator->getLocator()); + PHPUnit_Framework_Assert::assertSame(1, count($comments)); + } catch (PHPUnit_Framework_ExpectationFailedException $e) { + return false; + } + return true; + } + + /** + * @return Locator + */ + public static function newCommentField() { + return Locator::forThe()->css("div.newCommentRow .message")->descendantOf(FilesAppContext::currentSectionDetailsView())-> + describedAs("New comment field in the details view in Files app"); + } + + public static function commentFields() { + return Locator::forThe()->css(".comments .comment .message")->descendantOf(FilesAppContext::currentSectionDetailsView())-> + describedAs("Comment fields in the details view in Files app"); + } + + /** + * @return Locator + */ + public static function submitNewCommentButton() { + return Locator::forThe()->css("div.newCommentRow .submit")->descendantOf(FilesAppContext::currentSectionDetailsView())-> + describedAs("Submit new comment button in the details view in Files app"); + } +} diff --git a/tests/karma.config.js b/tests/karma.config.js index 07dc2965346a7..fb613857e919a 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -88,6 +88,8 @@ module.exports = function(config) { srcFiles: [ // need to enforce loading order... 'apps/comments/js/app.js', + 'apps/comments/js/vendor/Caret.js/dist/jquery.caret.min.js', + 'apps/comments/js/vendor/At.js/dist/js/jquery.atwho.min.js', 'apps/comments/js/commentmodel.js', 'apps/comments/js/commentcollection.js', 'apps/comments/js/commentsummarymodel.js', diff --git a/tests/lib/Comments/FakeManager.php b/tests/lib/Comments/FakeManager.php index 840961fb90136..d3dd1dfb58a05 100644 --- a/tests/lib/Comments/FakeManager.php +++ b/tests/lib/Comments/FakeManager.php @@ -1,12 +1,14 @@ getManager(); } @@ -109,7 +110,7 @@ public function testGetComment() { $id = strval($qb->getLastInsertId()); $comment = $manager->get($id); - $this->assertTrue($comment instanceof \OCP\Comments\IComment); + $this->assertTrue($comment instanceof IComment); $this->assertSame($comment->getId(), $id); $this->assertSame($comment->getParentId(), '2'); $this->assertSame($comment->getTopmostParentId(), '1'); @@ -152,14 +153,14 @@ public function testGetTree() { // Verifying the root comment $this->assertTrue(isset($tree['comment'])); - $this->assertTrue($tree['comment'] instanceof \OCP\Comments\IComment); + $this->assertTrue($tree['comment'] instanceof IComment); $this->assertSame($tree['comment']->getId(), strval($headId)); $this->assertTrue(isset($tree['replies'])); $this->assertSame(count($tree['replies']), 3); // one level deep foreach ($tree['replies'] as $reply) { - $this->assertTrue($reply['comment'] instanceof \OCP\Comments\IComment); + $this->assertTrue($reply['comment'] instanceof IComment); $this->assertSame($reply['comment']->getId(), strval($id)); $this->assertSame(count($reply['replies']), 0); $id--; @@ -174,7 +175,7 @@ public function testGetTreeNoReplies() { // Verifying the root comment $this->assertTrue(isset($tree['comment'])); - $this->assertTrue($tree['comment'] instanceof \OCP\Comments\IComment); + $this->assertTrue($tree['comment'] instanceof IComment); $this->assertSame($tree['comment']->getId(), strval($id)); $this->assertTrue(isset($tree['replies'])); $this->assertSame(count($tree['replies']), 0); @@ -200,14 +201,14 @@ public function testGetTreeWithLimitAndOffset() { // Verifying the root comment $this->assertTrue(isset($tree['comment'])); - $this->assertTrue($tree['comment'] instanceof \OCP\Comments\IComment); + $this->assertTrue($tree['comment'] instanceof IComment); $this->assertSame($tree['comment']->getId(), strval($headId)); $this->assertTrue(isset($tree['replies'])); $this->assertSame(count($tree['replies']), 2); // one level deep foreach ($tree['replies'] as $reply) { - $this->assertTrue($reply['comment'] instanceof \OCP\Comments\IComment); + $this->assertTrue($reply['comment'] instanceof IComment); $this->assertSame($reply['comment']->getId(), strval($idToVerify)); $this->assertSame(count($reply['replies']), 0); $idToVerify--; @@ -223,7 +224,7 @@ public function testGetForObject() { $this->assertTrue(is_array($comments)); $this->assertSame(count($comments), 1); - $this->assertTrue($comments[0] instanceof \OCP\Comments\IComment); + $this->assertTrue($comments[0] instanceof IComment); $this->assertSame($comments[0]->getMessage(), 'nice one'); } @@ -243,7 +244,7 @@ public function testGetForObjectWithLimitAndOffset() { $this->assertTrue(is_array($comments)); foreach ($comments as $comment) { - $this->assertTrue($comment instanceof \OCP\Comments\IComment); + $this->assertTrue($comment instanceof IComment); $this->assertSame($comment->getMessage(), 'nice one'); $this->assertSame($comment->getId(), strval($idToVerify)); $idToVerify--; @@ -282,7 +283,7 @@ public function testGetForObjectWithLimitAndOffsetAndDateTimeConstraint() { $this->assertTrue(is_array($comments)); foreach ($comments as $comment) { - $this->assertTrue($comment instanceof \OCP\Comments\IComment); + $this->assertTrue($comment instanceof IComment); $this->assertSame($comment->getMessage(), 'nice one'); $this->assertSame($comment->getId(), strval($idToVerify)); $this->assertTrue(intval($comment->getId()) >= 4); @@ -334,6 +335,7 @@ public function testGetNumberOfUnreadCommentsForFolder() { $this->addDatabaseEntry(0, 0, null, null, $fileIds[$i]); } $this->addDatabaseEntry(0, 0, (new \DateTime())->modify('-2 days'), null, $fileIds[0]); + /** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */ $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') @@ -368,6 +370,10 @@ public function invalidCreateArgsProvider() { /** * @dataProvider invalidCreateArgsProvider * @expectedException \InvalidArgumentException + * @param string $aType + * @param string $aId + * @param string $oType + * @param string $oId */ public function testCreateCommentInvalidArguments($aType, $aId, $oType, $oId) { $manager = $this->getManager(); @@ -381,7 +387,7 @@ public function testCreateComment() { $objectId = 'bielefeld'; $comment = $this->getManager()->create($actorType, $actorId, $objectType, $objectId); - $this->assertTrue($comment instanceof \OCP\Comments\IComment); + $this->assertTrue($comment instanceof IComment); $this->assertSame($comment->getActorType(), $actorType); $this->assertSame($comment->getActorId(), $actorId); $this->assertSame($comment->getObjectType(), $objectType); @@ -405,7 +411,7 @@ public function testDelete() { $id = strval($this->addDatabaseEntry(0, 0)); $comment = $manager->get($id); - $this->assertTrue($comment instanceof \OCP\Comments\IComment); + $this->assertTrue($comment instanceof IComment); $done = $manager->delete($id); $this->assertTrue($done); $manager->get($id); @@ -515,6 +521,8 @@ public function invalidActorArgsProvider() { /** * @dataProvider invalidActorArgsProvider * @expectedException \InvalidArgumentException + * @param string $type + * @param string $id */ public function testDeleteReferencesOfActorInvalidInput($type, $id) { $manager = $this->getManager(); @@ -551,7 +559,7 @@ public function testDeleteReferencesOfActor() { public function testDeleteReferencesOfActorWithUserManagement() { $user = \OC::$server->getUserManager()->createUser('xenia', '123456'); - $this->assertTrue($user instanceof \OCP\IUser); + $this->assertTrue($user instanceof IUser); $manager = \OC::$server->getCommentsManager(); $comment = $manager->create('users', $user->getUID(), 'files', 'file64'); @@ -565,8 +573,8 @@ public function testDeleteReferencesOfActorWithUserManagement() { $user->delete(); $comment = $manager->get($commentID); - $this->assertSame($comment->getActorType(), \OCP\Comments\ICommentsManager::DELETED_USER); - $this->assertSame($comment->getActorId(), \OCP\Comments\ICommentsManager::DELETED_USER); + $this->assertSame($comment->getActorType(), ICommentsManager::DELETED_USER); + $this->assertSame($comment->getActorId(), ICommentsManager::DELETED_USER); } public function invalidObjectArgsProvider() { @@ -581,6 +589,8 @@ public function invalidObjectArgsProvider() { /** * @dataProvider invalidObjectArgsProvider * @expectedException \InvalidArgumentException + * @param string $type + * @param string $id */ public function testDeleteCommentsAtObjectInvalidInput($type, $id) { $manager = $this->getManager(); @@ -607,7 +617,7 @@ public function testDeleteCommentsAtObject() { foreach ($ids as $id) { try { $manager->get(strval($id)); - } catch (\OCP\Comments\NotFoundException $e) { + } catch (NotFoundException $e) { $verified++; } } @@ -620,6 +630,7 @@ public function testDeleteCommentsAtObject() { } public function testSetMarkRead() { + /** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */ $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') @@ -636,6 +647,7 @@ public function testSetMarkRead() { } public function testSetMarkReadUpdate() { + /** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */ $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') @@ -655,6 +667,7 @@ public function testSetMarkReadUpdate() { } public function testReadMarkDeleteUser() { + /** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */ $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') @@ -672,6 +685,7 @@ public function testReadMarkDeleteUser() { } public function testReadMarkDeleteObject() { + /** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */ $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID')