weekly release 5.0dev
[moodle.git] / comment / comment.js
blob13ab753fc10ae765ee541acc4355e8db245a5057
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                 // Fail fast if the comments element cannot be found, such as in embedded-type views where blocks may be loaded
45                 // then discarded.
46                 if (!Y.one('#comment-ctrl-'+this.client_id)) {
47                     return;
48                 }
49                 // expand comments?
50                 if (this.autostart) {
51                     this.view(args.page);
52                 }
53                 // load comments
54                 var handle = Y.one('#comment-link-'+this.client_id);
55                 // hide toggle link
56                 if (handle) {
57                     if (args.notoggle) {
58                         handle.setStyle('display', 'none');
59                     }
60                     handle.on('click', function(e) {
61                         e.preventDefault();
62                         this.view(0);
63                         return false;
64                     }, this);
65                     // Also handle space/enter key.
66                     handle.on('key', function(e) {
67                         e.preventDefault();
68                         this.view(0);
69                         return false;
70                     }, '13,32', this);
71                 }
72                 scope.toggle_textarea(false);
73             },
74             post: function() {
75                 var ta = Y.one('#dlg-content-'+this.client_id);
76                 var scope = this;
77                 var value = ta.get('value');
78                 if (value && value != M.util.get_string('addcomment', 'moodle')) {
79                     ta.set('disabled', true);
80                     ta.setStyles({
81                         'backgroundImage': 'url(' + M.util.image_url('i/loading_small', 'core') + ')',
82                         'backgroundRepeat': 'no-repeat',
83                         'backgroundPosition': 'center center'
84                     });
85                     var params = {'content': value};
86                     this.request({
87                         action: 'add',
88                         scope: scope,
89                         params: params,
90                         callback: async function(id, obj, args) {
91                             var scope = args.scope;
92                             var cid = scope.client_id;
93                             var ta = Y.one('#dlg-content-'+cid);
94                             ta.set('value', '');
95                             ta.set('disabled', false);
96                             ta.setStyle('backgroundImage', 'none');
97                             scope.toggle_textarea(false);
98                             var container = Y.one('#comment-list-'+cid);
99                             var result = await scope.render([obj], true);
100                             var newcomment = Y.Node.create(result.html);
101                             container.appendChild(newcomment);
102                             var ids = result.ids;
103                             var linkTextCount = Y.one('#comment-link-text-' + cid + ' .comment-link-count');
104                             if (linkTextCount) {
105                                 linkTextCount.set('innerHTML', obj.count);
106                             }
107                             for(var i in ids) {
108                                 var attributes = {
109                                     color: { to: '#06e' },
110                                     backgroundColor: { to: '#FFE390' }
111                                 };
112                                 var anim = new Y.YUI2.util.ColorAnim(ids[i], attributes);
113                                 anim.animate();
114                             }
115                             scope.register_pagination();
116                             scope.register_delete_buttons();
117                         }
118                     }, true);
119                 } else {
120                     var attributes = {
121                         backgroundColor: { from: '#FFE390', to:'#FFFFFF' }
122                     };
123                     var anim = new Y.YUI2.util.ColorAnim('dlg-content-'+cid, attributes);
124                     anim.animate();
125                 }
126             },
127             request: function(args, noloading) {
128                 var params = {};
129                 var scope = this;
130                 if (args['scope']) {
131                     scope = args['scope'];
132                 }
133                 //params['page'] = args.page?args.page:'';
134                 // the form element only accept certain file types
135                 params['sesskey']   = M.cfg.sesskey;
136                 params['action']    = args.action?args.action:'';
137                 params['client_id'] = this.client_id;
138                 params['itemid']    = this.itemid;
139                 params['area']      = this.commentarea;
140                 params['courseid']  = this.courseid;
141                 params['contextid'] = this.contextid;
142                 params['component'] = this.component;
143                 if (args['params']) {
144                     for (i in args['params']) {
145                         params[i] = args['params'][i];
146                     }
147                 }
148                 var cfg = {
149                     method: 'POST',
150                     on: {
151                         complete: function(id,o,p) {
152                             if (!o) {
153                                 alert('IO FATAL');
154                                 return false;
155                             }
156                             var data = Y.JSON.parse(o.responseText);
157                             if (data.error) {
158                                 if (data.error == 'require_login') {
159                                     args.callback(id,data,p);
160                                     return true;
161                                 }
162                                 alert(data.error);
163                                 return false;
164                             } else {
165                                 args.callback(id,data,p);
166                                 return true;
167                             }
168                         }
169                     },
170                     arguments: {
171                         scope: scope
172                     },
173                     headers: {
174                         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
175                     },
176                     data: build_querystring(params)
177                 };
178                 if (args.form) {
179                     cfg.form = args.form;
180                 }
181                 Y.io(this.api, cfg);
182                 if (!noloading) {
183                     this.wait();
184                 }
185             },
186             render: async function(list, newcmt) {
187                 var ret = {};
188                 ret.ids = [];
189                 var template = Y.one('#cmt-tmpl');
190                 var html = '';
191                 for(var i in list) {
192                     var htmlid = 'comment-'+list[i].id+'-'+this.client_id;
193                     var val = template.get('innerHTML');
194                     if (list[i].profileurl) {
195                         val = val.replace('___name___', '<a href="'+list[i].profileurl+'">'+list[i].fullname+'</a>');
196                     } else {
197                         val = val.replace('___name___', list[i].fullname);
198                     }
199                     if (list[i].delete || newcmt) {
200                         list[i].clientid = this.client_id;
201                         list[i].content += await this.renderDeleteIcon(list[i]);
202                     }
203                     val = val.replace('___time___', list[i].time);
204                     val = val.replace('___picture___', list[i].avatar);
205                     val = val.replace('___content___', list[i].content);
206                     val = '<li id="'+htmlid+'">'+val+'</li>';
207                     ret.ids.push(htmlid);
208                     html = (val+html);
209                 }
210                 ret.html = html;
211                 return ret;
212             },
213             renderDeleteIcon: async function(list) {
214                 return new Promise(function(resolve) {
215                     require(['core/templates', 'core/str'], (Templates, Str) => {
216                         return Str.get_string('deletecommentbyon', 'moodle', {
217                             user: list.fullname,
218                             time: list.time
219                         }).then(function(deleteStr) {
220                             return Templates.renderPix('t/delete', 'core', deleteStr).then(function(deleteIcon) {
221                                 var deleteDiv = document.createElement('div');
222                                 deleteDiv.className = 'comment-delete';
224                                 var deleteLink = document.createElement('a');
225                                 deleteLink.href = '#';
226                                 deleteLink.role = 'button';
227                                 deleteLink.title = deleteStr;
228                                 deleteLink.id = `comment-delete-${list.clientid}-${list.id}`;
229                                 deleteLink.innerHTML = deleteIcon;
231                                 deleteDiv.appendChild(deleteLink);
233                                 resolve(deleteDiv.outerHTML);
235                                 return true;
236                             });
237                         });
238                     });
239                 });
240             },
241             load: function(page) {
242                 var scope = this;
243                 var container = Y.one('#comment-ctrl-'+this.client_id);
244                 var params = {
245                     'action': 'get',
246                     'page': page
247                 };
248                 this.request({
249                     scope: scope,
250                     params: params,
251                     callback: async function(id, ret, args) {
252                         var linkTextCount = Y.one('#comment-link-text-' + scope.client_id + ' .comment-link-count');
253                         if (linkTextCount) {
254                             linkTextCount.set('innerHTML', ret.count);
255                         }
256                         var container = Y.one('#comment-list-'+scope.client_id);
257                         var pagination = Y.one('#comment-pagination-'+scope.client_id);
258                         if (ret.pagination) {
259                             pagination.set('innerHTML', ret.pagination);
260                         } else {
261                             //empty paging bar
262                             pagination.set('innerHTML', '');
263                         }
264                         if (ret.error == 'require_login') {
265                             var result = {};
266                             result.html = M.util.get_string('commentsrequirelogin', 'moodle');
267                         } else {
268                             var result = await scope.render(ret.list);
269                         }
270                         container.set('innerHTML', result.html);
271                         var img = Y.one('#comment-img-'+scope.client_id);
272                         if (img) {
273                             img.set('src', M.util.image_url('t/expanded', 'core'));
274                         }
275                         args.scope.register_pagination();
276                         args.scope.register_delete_buttons();
277                     }
278                 });
279             },
281             dodelete: function(id) { // note: delete is a reserved word in javascript, chrome and safary do not like it at all here!
282                 var scope = this,
283                     cid = scope.client_id,
284                     params = {'commentid': id};
285                 function remove_dom(type, anim, cmt) {
286                     cmt.remove();
287                     var linkTextCount = Y.one('#comment-link-text-' + cid + ' .comment-link-count'),
288                         comments = Y.all('#comment-list-' + cid + ' li');
289                     if (linkTextCount) {
290                         linkTextCount.set('innerHTML', comments.size());
291                     }
292                 }
293                 this.request({
294                     action: 'delete',
295                     scope: scope,
296                     params: params,
297                     callback: function(id, resp, args) {
298                         var htmlid= 'comment-'+resp.commentid+'-'+resp.client_id;
299                         var attributes = {
300                             width:{to:0},
301                             height:{to:0}
302                         };
303                         var cmt = Y.one('#'+htmlid);
304                         cmt.setStyle('overflow', 'hidden');
305                         var anim = new Y.YUI2.util.Anim(htmlid, attributes, 1, Y.YUI2.util.Easing.easeOut);
306                         anim.onComplete.subscribe(remove_dom, cmt, this);
307                         anim.animate();
308                     }
309                 }, true);
310             },
311             register_actions: function() {
312                 // add new comment
313                 var action_btn = Y.one('#comment-action-post-'+this.client_id);
314                 if (action_btn) {
315                     action_btn.on('click', function(e) {
316                         e.preventDefault();
317                         this.post();
318                         return false;
319                     }, this);
320                 }
321                 // cancel comment box
322                 var cancel = Y.one('#comment-action-cancel-'+this.client_id);
323                 if (cancel) {
324                     cancel.on('click', function(e) {
325                         e.preventDefault();
326                         this.view(0);
327                         return false;
328                     }, this);
329                 }
330             },
331             register_delete_buttons: function() {
332                 var scope = this;
333                 // page buttons
334                 Y.all('div.comment-delete a').each(
335                     function(node, id) {
336                         var theid = node.get('id');
337                         var parseid = new RegExp("comment-delete-"+scope.client_id+"-(\\d+)", "i");
338                         var commentid = theid.match(parseid);
339                         if (!commentid) {
340                             return;
341                         }
342                         if (commentid[1]) {
343                             Y.Event.purgeElement('#'+theid, false, 'click');
344                         }
345                         node.on('click', function(e) {
346                             e.preventDefault();
347                             if (commentid[1]) {
348                                 scope.dodelete(commentid[1]);
349                             }
350                         });
351                         // Also handle space/enter key.
352                         node.on('key', function(e) {
353                             e.preventDefault();
354                             if (commentid[1]) {
355                                 scope.dodelete(commentid[1]);
356                             }
357                         }, '13,32');
358                         // 13 and 32 are the keycodes for space and enter.
359                     }
360                 );
361             },
362             register_pagination: function() {
363                 var scope = this;
364                 // page buttons
365                 Y.all('#comment-pagination-'+this.client_id+' a').each(
366                     function(node, id) {
367                         node.on('click', function(e, node) {
368                             e.preventDefault();
369                             var id = node.get('id');
370                             var re = new RegExp("comment-page-"+this.client_id+"-(\\d+)", "i");
371                             var result = id.match(re);
372                             this.load(result[1]);
373                         }, scope, node);
374                     }
375                 );
376             },
377             view: function(page) {
378                 var commenttoggler = Y.one('#comment-link-' + this.client_id);
379                 var container = Y.one('#comment-ctrl-'+this.client_id);
380                 var ta = Y.one('#dlg-content-'+this.client_id);
381                 var img = Y.one('#comment-img-'+this.client_id);
382                 var d = container.getStyle('display');
383                 if (d=='none'||d=='') {
384                     // show
385                     if (!this.autostart) {
386                         this.load(page);
387                     } else {
388                         this.register_delete_buttons();
389                         this.register_pagination();
390                     }
391                     container.setStyle('display', 'block');
392                     if (img) {
393                         img.set('src', M.util.image_url('t/expanded', 'core'));
394                     }
395                     if (commenttoggler) {
396                         commenttoggler.setAttribute('aria-expanded', 'true');
397                     }
398                 } else {
399                     // hide
400                     container.setStyle('display', 'none');
401                     var collapsedimage = 't/collapsed'; // ltr mode
402                     if ( Y.one(document.body).hasClass('dir-rtl') ) {
403                         collapsedimage = 't/collapsed_rtl';
404                     } else {
405                         collapsedimage = 't/collapsed';
406                     }
407                     if (img) {
408                         img.set('src', M.util.image_url(collapsedimage, 'core'));
409                     }
410                     if (ta) {
411                         ta.set('value','');
412                     }
413                     if (commenttoggler) {
414                         commenttoggler.setAttribute('aria-expanded', 'false');
415                     }
416                 }
417                 if (ta) {
418                     //toggle_textarea.apply(ta, [false]);
419                     //// reset textarea size
420                     ta.on('focus', function() {
421                         this.toggle_textarea(true);
422                     }, this);
423                     //ta.onkeypress = function() {
424                         //if (this.scrollHeight > this.clientHeight && !window.opera)
425                             //this.rows += 1;
426                     //}
427                     ta.on('blur', function() {
428                         this.toggle_textarea(false);
429                     }, this);
430                 }
431                 this.register_actions();
432                 return false;
433             },
434             toggle_textarea: function(focus) {
435                 var t = Y.one('#dlg-content-'+this.client_id);
436                 if (!t) {
437                     return false;
438                 }
439                 if (focus) {
440                     if (t.get('value') == M.util.get_string('addcomment', 'moodle')) {
441                         t.set('value', '');
442                         t.setStyle('color', 'black');
443                     }
444                 }else{
445                     if (t.get('value') == '') {
446                         t.set('value', M.util.get_string('addcomment', 'moodle'));
447                         t.setStyle('color','grey');
448                         t.set('rows', 2);
449                     }
450                 }
451             },
452             wait: function() {
453                 var container = Y.one('#comment-list-'+this.client_id);
454                 container.set('innerHTML', '<div class="mdl-align"><img src="'+M.util.image_url('i/loading_small', 'core')+'" /></div>');
455             }
456         });
458         new CommentHelper(options);
459     }