Merge branch 'MDL-60826-master-fix' of https://github.com/lameze/moodle
[moodle.git] / comment / comment.js
blob6e30eed05b57821a9d42ce9ed0cb5a13e8add377
1 // This file is part of Moodle - http://moodle.org/
2 //
3 // Moodle is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
7 //
8 // Moodle is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16 /**
17  * Comment Helper
18  * @author Dongsheng Cai <dongsheng@moodle.com>
19  */
20 M.core_comment = {
21     /**
22      * Initialize commenting system
23      */
24     init: function(Y, options) {
25         var CommentHelper = function(args) {
26             CommentHelper.superclass.constructor.apply(this, arguments);
27         };
28         CommentHelper.NAME = "COMMENT";
29         CommentHelper.ATTRS = {
30             options: {},
31             lang: {}
32         };
33         Y.extend(CommentHelper, Y.Base, {
34             api: M.cfg.wwwroot+'/comment/comment_ajax.php',
35             initializer: function(args) {
36                 var scope = this;
37                 this.client_id = args.client_id;
38                 this.itemid = args.itemid;
39                 this.commentarea = args.commentarea;
40                 this.component = args.component;
41                 this.courseid = args.courseid;
42                 this.contextid = args.contextid;
43                 this.autostart = (args.autostart);
44                 // expand comments?
45                 if (this.autostart) {
46                     this.view(args.page);
47                 }
48                 // load comments
49                 var handle = Y.one('#comment-link-'+this.client_id);
50                 // hide toggle link
51                 if (handle) {
52                     if (args.notoggle) {
53                         handle.setStyle('display', 'none');
54                     }
55                     handle.on('click', function(e) {
56                         e.preventDefault();
57                         this.view(0);
58                         return false;
59                     }, this);
60                     // Also handle space/enter key.
61                     handle.on('key', function(e) {
62                         e.preventDefault();
63                         this.view(0);
64                         return false;
65                     }, '13,32', this);
66                 }
67                 scope.toggle_textarea(false);
68             },
69             post: function() {
70                 var ta = Y.one('#dlg-content-'+this.client_id);
71                 var scope = this;
72                 var value = ta.get('value');
73                 if (value && value != M.util.get_string('addcomment', 'moodle')) {
74                     ta.set('disabled', true);
75                     ta.setStyles({
76                         'backgroundImage': 'url(' + M.util.image_url('i/loading_small', 'core') + ')',
77                         'backgroundRepeat': 'no-repeat',
78                         'backgroundPosition': 'center center'
79                     });
80                     var params = {'content': value};
81                     this.request({
82                         action: 'add',
83                         scope: scope,
84                         params: params,
85                         callback: function(id, obj, args) {
86                             var scope = args.scope;
87                             var cid = scope.client_id;
88                             var ta = Y.one('#dlg-content-'+cid);
89                             ta.set('value', '');
90                             ta.set('disabled', false);
91                             ta.setStyle('backgroundImage', 'none');
92                             scope.toggle_textarea(false);
93                             var container = Y.one('#comment-list-'+cid);
94                             var result = scope.render([obj], true);
95                             var newcomment = Y.Node.create(result.html);
96                             container.appendChild(newcomment);
97                             var ids = result.ids;
98                             var linkText = Y.one('#comment-link-text-' + cid);
99                             if (linkText) {
100                                 linkText.set('innerHTML', M.util.get_string('commentscount', 'moodle', obj.count));
101                             }
102                             for(var i in ids) {
103                                 var attributes = {
104                                     color: { to: '#06e' },
105                                     backgroundColor: { to: '#FFE390' }
106                                 };
107                                 var anim = new Y.YUI2.util.ColorAnim(ids[i], attributes);
108                                 anim.animate();
109                             }
110                             scope.register_pagination();
111                             scope.register_delete_buttons();
112                         }
113                     }, true);
114                 } else {
115                     var attributes = {
116                         backgroundColor: { from: '#FFE390', to:'#FFFFFF' }
117                     };
118                     var anim = new Y.YUI2.util.ColorAnim('dlg-content-'+cid, attributes);
119                     anim.animate();
120                 }
121             },
122             request: function(args, noloading) {
123                 var params = {};
124                 var scope = this;
125                 if (args['scope']) {
126                     scope = args['scope'];
127                 }
128                 //params['page'] = args.page?args.page:'';
129                 // the form element only accept certain file types
130                 params['sesskey']   = M.cfg.sesskey;
131                 params['action']    = args.action?args.action:'';
132                 params['client_id'] = this.client_id;
133                 params['itemid']    = this.itemid;
134                 params['area']      = this.commentarea;
135                 params['courseid']  = this.courseid;
136                 params['contextid'] = this.contextid;
137                 params['component'] = this.component;
138                 if (args['params']) {
139                     for (i in args['params']) {
140                         params[i] = args['params'][i];
141                     }
142                 }
143                 var cfg = {
144                     method: 'POST',
145                     on: {
146                         complete: function(id,o,p) {
147                             if (!o) {
148                                 alert('IO FATAL');
149                                 return false;
150                             }
151                             var data = Y.JSON.parse(o.responseText);
152                             if (data.error) {
153                                 if (data.error == 'require_login') {
154                                     args.callback(id,data,p);
155                                     return true;
156                                 }
157                                 alert(data.error);
158                                 return false;
159                             } else {
160                                 args.callback(id,data,p);
161                                 return true;
162                             }
163                         }
164                     },
165                     arguments: {
166                         scope: scope
167                     },
168                     headers: {
169                         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
170                     },
171                     data: build_querystring(params)
172                 };
173                 if (args.form) {
174                     cfg.form = args.form;
175                 }
176                 Y.io(this.api, cfg);
177                 if (!noloading) {
178                     this.wait();
179                 }
180             },
181             render: function(list, newcmt) {
182                 var ret = {};
183                 ret.ids = [];
184                 var template = Y.one('#cmt-tmpl');
185                 var html = '';
186                 for(var i in list) {
187                     var htmlid = 'comment-'+list[i].id+'-'+this.client_id;
188                     var val = template.get('innerHTML');
189                     if (list[i].profileurl) {
190                         val = val.replace('___name___', '<a href="'+list[i].profileurl+'">'+list[i].fullname+'</a>');
191                     } else {
192                         val = val.replace('___name___', list[i].fullname);
193                     }
194                     if (list[i]['delete']||newcmt) {
195                         var tokens = {
196                             user: list[i].fullname,
197                             time: list[i].time
198                         };
199                         var deleteStr = Y.Escape.html(M.util.get_string('deletecommentbyon', 'moodle', tokens));
200                         list[i].content = '<div class="comment-delete">' +
201                             '<a href="#" role="button" id ="comment-delete-' + this.client_id + '-' + list[i].id + '"' +
202                             '   title="' + deleteStr + '">' +
203                             '<span></span>' +
204                             '</a>' +
205                             '</div>' + list[i].content;
206                     }
207                     val = val.replace('___time___', list[i].time);
208                     val = val.replace('___picture___', list[i].avatar);
209                     val = val.replace('___content___', list[i].content);
210                     val = '<li id="'+htmlid+'">'+val+'</li>';
211                     ret.ids.push(htmlid);
212                     html = (val+html);
213                 }
214                 ret.html = html;
215                 return ret;
216             },
217             load: function(page) {
218                 var scope = this;
219                 var container = Y.one('#comment-ctrl-'+this.client_id);
220                 var params = {
221                     'action': 'get',
222                     'page': page
223                 };
224                 this.request({
225                     scope: scope,
226                     params: params,
227                     callback: function(id, ret, args) {
228                         var linkText = Y.one('#comment-link-text-' + scope.client_id);
229                         if (ret.count && linkText) {
230                             linkText.set('innerHTML', M.util.get_string('commentscount', 'moodle', ret.count));
231                         }
232                         var container = Y.one('#comment-list-'+scope.client_id);
233                         var pagination = Y.one('#comment-pagination-'+scope.client_id);
234                         if (ret.pagination) {
235                             pagination.set('innerHTML', ret.pagination);
236                         } else {
237                             //empty paging bar
238                             pagination.set('innerHTML', '');
239                         }
240                         if (ret.error == 'require_login') {
241                             var result = {};
242                             result.html = M.util.get_string('commentsrequirelogin', 'moodle');
243                         } else {
244                             var result = scope.render(ret.list);
245                         }
246                         container.set('innerHTML', result.html);
247                         var img = Y.one('#comment-img-'+scope.client_id);
248                         if (img) {
249                             img.set('src', M.util.image_url('t/expanded', 'core'));
250                         }
251                         args.scope.register_pagination();
252                         args.scope.register_delete_buttons();
253                     }
254                 });
255             },
257             dodelete: function(id) { // note: delete is a reserved word in javascript, chrome and safary do not like it at all here!
258                 var scope = this,
259                     cid = scope.client_id,
260                     params = {'commentid': id};
261                 function remove_dom(type, anim, cmt) {
262                     cmt.remove();
263                     var linkText = Y.one('#comment-link-text-' + cid),
264                         comments = Y.all('#comment-list-' + cid + ' li');
265                     if (linkText && comments) {
266                         linkText.set('innerHTML', M.util.get_string('commentscount', 'moodle', comments.size()));
267                     }
268                 }
269                 this.request({
270                     action: 'delete',
271                     scope: scope,
272                     params: params,
273                     callback: function(id, resp, args) {
274                         var htmlid= 'comment-'+resp.commentid+'-'+resp.client_id;
275                         var attributes = {
276                             width:{to:0},
277                             height:{to:0}
278                         };
279                         var cmt = Y.one('#'+htmlid);
280                         cmt.setStyle('overflow', 'hidden');
281                         var anim = new Y.YUI2.util.Anim(htmlid, attributes, 1, Y.YUI2.util.Easing.easeOut);
282                         anim.onComplete.subscribe(remove_dom, cmt, this);
283                         anim.animate();
284                     }
285                 }, true);
286             },
287             register_actions: function() {
288                 // add new comment
289                 var action_btn = Y.one('#comment-action-post-'+this.client_id);
290                 if (action_btn) {
291                     action_btn.on('click', function(e) {
292                         e.preventDefault();
293                         this.post();
294                         return false;
295                     }, this);
296                 }
297                 // cancel comment box
298                 var cancel = Y.one('#comment-action-cancel-'+this.client_id);
299                 if (cancel) {
300                     cancel.on('click', function(e) {
301                         e.preventDefault();
302                         this.view(0);
303                         return false;
304                     }, this);
305                 }
306             },
307             register_delete_buttons: function() {
308                 var scope = this;
309                 // page buttons
310                 Y.all('div.comment-delete a').each(
311                     function(node, id) {
312                         var theid = node.get('id');
313                         var parseid = new RegExp("comment-delete-"+scope.client_id+"-(\\d+)", "i");
314                         var commentid = theid.match(parseid);
315                         if (!commentid) {
316                             return;
317                         }
318                         if (commentid[1]) {
319                             Y.Event.purgeElement('#'+theid, false, 'click');
320                         }
321                         node.on('click', function(e) {
322                             e.preventDefault();
323                             if (commentid[1]) {
324                                 scope.dodelete(commentid[1]);
325                             }
326                         });
327                         // Also handle space/enter key.
328                         node.on('key', function(e) {
329                             e.preventDefault();
330                             if (commentid[1]) {
331                                 scope.dodelete(commentid[1]);
332                             }
333                         }, '13,32');
334                         // 13 and 32 are the keycodes for space and enter.
336                         require(['core/templates', 'core/notification'], function(Templates, Notification) {
337                             var title = node.getAttribute('title');
338                             Templates.renderPix('t/delete', 'core', title).then(function(html) {
339                                 node.set('innerHTML', html);
340                             }).catch(Notification.exception);
341                         });
342                     }
343                 );
344             },
345             register_pagination: function() {
346                 var scope = this;
347                 // page buttons
348                 Y.all('#comment-pagination-'+this.client_id+' a').each(
349                     function(node, id) {
350                         node.on('click', function(e, node) {
351                             e.preventDefault();
352                             var id = node.get('id');
353                             var re = new RegExp("comment-page-"+this.client_id+"-(\\d+)", "i");
354                             var result = id.match(re);
355                             this.load(result[1]);
356                         }, scope, node);
357                     }
358                 );
359             },
360             view: function(page) {
361                 var commenttoggler = Y.one('#comment-link-' + this.client_id);
362                 var container = Y.one('#comment-ctrl-'+this.client_id);
363                 var ta = Y.one('#dlg-content-'+this.client_id);
364                 var img = Y.one('#comment-img-'+this.client_id);
365                 var d = container.getStyle('display');
366                 if (d=='none'||d=='') {
367                     // show
368                     if (!this.autostart) {
369                         this.load(page);
370                     } else {
371                         this.register_delete_buttons();
372                         this.register_pagination();
373                     }
374                     container.setStyle('display', 'block');
375                     if (img) {
376                         img.set('src', M.util.image_url('t/expanded', 'core'));
377                     }
378                     if (commenttoggler) {
379                         commenttoggler.setAttribute('aria-expanded', 'true');
380                     }
381                 } else {
382                     // hide
383                     container.setStyle('display', 'none');
384                     var collapsedimage = 't/collapsed'; // ltr mode
385                     if ( Y.one(document.body).hasClass('dir-rtl') ) {
386                         collapsedimage = 't/collapsed_rtl';
387                     } else {
388                         collapsedimage = 't/collapsed';
389                     }
390                     if (img) {
391                         img.set('src', M.util.image_url(collapsedimage, 'core'));
392                     }
393                     if (ta) {
394                         ta.set('value','');
395                     }
396                     if (commenttoggler) {
397                         commenttoggler.setAttribute('aria-expanded', 'false');
398                     }
399                 }
400                 if (ta) {
401                     //toggle_textarea.apply(ta, [false]);
402                     //// reset textarea size
403                     ta.on('focus', function() {
404                         this.toggle_textarea(true);
405                     }, this);
406                     //ta.onkeypress = function() {
407                         //if (this.scrollHeight > this.clientHeight && !window.opera)
408                             //this.rows += 1;
409                     //}
410                     ta.on('blur', function() {
411                         this.toggle_textarea(false);
412                     }, this);
413                 }
414                 this.register_actions();
415                 return false;
416             },
417             toggle_textarea: function(focus) {
418                 var t = Y.one('#dlg-content-'+this.client_id);
419                 if (!t) {
420                     return false;
421                 }
422                 if (focus) {
423                     if (t.get('value') == M.util.get_string('addcomment', 'moodle')) {
424                         t.set('value', '');
425                         t.setStyle('color', 'black');
426                     }
427                 }else{
428                     if (t.get('value') == '') {
429                         t.set('value', M.util.get_string('addcomment', 'moodle'));
430                         t.setStyle('color','grey');
431                         t.set('rows', 2);
432                     }
433                 }
434             },
435             wait: function() {
436                 var container = Y.one('#comment-list-'+this.client_id);
437                 container.set('innerHTML', '<div class="mdl-align"><img src="'+M.util.image_url('i/loading_small', 'core')+'" /></div>');
438             }
439         });
441         new CommentHelper(options);
442     },
443     init_admin: function(Y) {
444         var select_all = Y.one('#comment_select_all');
445         if (select_all) {
446             select_all.on('click', function(e) {
447                 var comments = document.getElementsByName('comments');
448                 var checked = false;
449                 for (var i in comments) {
450                     if (comments[i].checked) {
451                         checked=true;
452                     }
453                 }
454                 for (i in comments) {
455                     comments[i].checked = !checked;
456                 }
457                 this.set('checked', !checked);
458             });
459         }
461         var comments_delete = Y.one('#comments_delete');
462         if (comments_delete) {
463             comments_delete.on('click', function(e) {
464                 e.preventDefault();
465                 var list = '';
466                 var comments = document.getElementsByName('comments');
467                 for (var i in comments) {
468                     if (typeof comments[i] == 'object' && comments[i].checked) {
469                         list += (comments[i].value + '-');
470                     }
471                 }
472                 if (!list) {
473                     return;
474                 }
475                 var args = {};
476                 args.message = M.util.get_string('confirmdeletecomments', 'admin');
477                 args.callback = function() {
478                     var url = M.cfg.wwwroot + '/comment/index.php';
480                     var data = {
481                         'commentids': list,
482                         'sesskey': M.cfg.sesskey,
483                         'action': 'delete'
484                     };
485                     var cfg = {
486                         method: 'POST',
487                         on: {
488                             complete: function(id,o,p) {
489                                 if (!o) {
490                                     alert('IO FATAL');
491                                     return;
492                                 }
493                                 if (o.responseText == 'yes') {
494                                     location.reload();
495                                 }
496                             }
497                         },
498                         arguments: {
499                             scope: this
500                         },
501                         headers: {
502                             'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
503                         },
504                         data: build_querystring(data)
505                     };
506                     Y.io(url, cfg);
507                 };
508                 M.util.show_confirm_dialog(e, args);
509             });
510         }
511     }