MDL-78632 core: Update upgrade versions
[moodle.git] / comment / comment.js
blobf421bb7a95db616f4db8d41ba1a4ef7cb76dcca5
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: async 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 = await 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: async 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                         list[i].clientid = this.client_id;
196                         list[i].content += await this.renderDeleteIcon(list[i]);
197                     }
198                     val = val.replace('___time___', list[i].time);
199                     val = val.replace('___picture___', list[i].avatar);
200                     val = val.replace('___content___', list[i].content);
201                     val = '<li id="'+htmlid+'">'+val+'</li>';
202                     ret.ids.push(htmlid);
203                     html = (val+html);
204                 }
205                 ret.html = html;
206                 return ret;
207             },
208             renderDeleteIcon: async function(list) {
209                 return new Promise(function(resolve) {
210                     require(['core/templates', 'core/str'], (Templates, Str) => {
211                         return Str.get_string('deletecommentbyon', 'moodle', {
212                             user: list.fullname,
213                             time: list.time
214                         }).then(function(deleteStr) {
215                             return Templates.renderPix('t/delete', 'core', deleteStr).then(function(deleteIcon) {
216                                 var deleteDiv = document.createElement('div');
217                                 deleteDiv.className = 'comment-delete';
219                                 var deleteLink = document.createElement('a');
220                                 deleteLink.href = '#';
221                                 deleteLink.role = 'button';
222                                 deleteLink.title = deleteStr;
223                                 deleteLink.id = `comment-delete-${list.clientid}-${list.id}`;
224                                 deleteLink.innerHTML = deleteIcon;
226                                 deleteDiv.appendChild(deleteLink);
228                                 resolve(deleteDiv.outerHTML);
230                                 return true;
231                             });
232                         });
233                     });
234                 });
235             },
236             load: function(page) {
237                 var scope = this;
238                 var container = Y.one('#comment-ctrl-'+this.client_id);
239                 var params = {
240                     'action': 'get',
241                     'page': page
242                 };
243                 this.request({
244                     scope: scope,
245                     params: params,
246                     callback: async function(id, ret, args) {
247                         var linkText = Y.one('#comment-link-text-' + scope.client_id);
248                         if (ret.count && linkText) {
249                             linkText.set('innerHTML', M.util.get_string('commentscount', 'moodle', ret.count));
250                         }
251                         var container = Y.one('#comment-list-'+scope.client_id);
252                         var pagination = Y.one('#comment-pagination-'+scope.client_id);
253                         if (ret.pagination) {
254                             pagination.set('innerHTML', ret.pagination);
255                         } else {
256                             //empty paging bar
257                             pagination.set('innerHTML', '');
258                         }
259                         if (ret.error == 'require_login') {
260                             var result = {};
261                             result.html = M.util.get_string('commentsrequirelogin', 'moodle');
262                         } else {
263                             var result = await scope.render(ret.list);
264                         }
265                         container.set('innerHTML', result.html);
266                         var img = Y.one('#comment-img-'+scope.client_id);
267                         if (img) {
268                             img.set('src', M.util.image_url('t/expanded', 'core'));
269                         }
270                         args.scope.register_pagination();
271                         args.scope.register_delete_buttons();
272                     }
273                 });
274             },
276             dodelete: function(id) { // note: delete is a reserved word in javascript, chrome and safary do not like it at all here!
277                 var scope = this,
278                     cid = scope.client_id,
279                     params = {'commentid': id};
280                 function remove_dom(type, anim, cmt) {
281                     cmt.remove();
282                     var linkText = Y.one('#comment-link-text-' + cid),
283                         comments = Y.all('#comment-list-' + cid + ' li');
284                     if (linkText && comments) {
285                         linkText.set('innerHTML', M.util.get_string('commentscount', 'moodle', comments.size()));
286                     }
287                 }
288                 this.request({
289                     action: 'delete',
290                     scope: scope,
291                     params: params,
292                     callback: function(id, resp, args) {
293                         var htmlid= 'comment-'+resp.commentid+'-'+resp.client_id;
294                         var attributes = {
295                             width:{to:0},
296                             height:{to:0}
297                         };
298                         var cmt = Y.one('#'+htmlid);
299                         cmt.setStyle('overflow', 'hidden');
300                         var anim = new Y.YUI2.util.Anim(htmlid, attributes, 1, Y.YUI2.util.Easing.easeOut);
301                         anim.onComplete.subscribe(remove_dom, cmt, this);
302                         anim.animate();
303                     }
304                 }, true);
305             },
306             register_actions: function() {
307                 // add new comment
308                 var action_btn = Y.one('#comment-action-post-'+this.client_id);
309                 if (action_btn) {
310                     action_btn.on('click', function(e) {
311                         e.preventDefault();
312                         this.post();
313                         return false;
314                     }, this);
315                 }
316                 // cancel comment box
317                 var cancel = Y.one('#comment-action-cancel-'+this.client_id);
318                 if (cancel) {
319                     cancel.on('click', function(e) {
320                         e.preventDefault();
321                         this.view(0);
322                         return false;
323                     }, this);
324                 }
325             },
326             register_delete_buttons: function() {
327                 var scope = this;
328                 // page buttons
329                 Y.all('div.comment-delete a').each(
330                     function(node, id) {
331                         var theid = node.get('id');
332                         var parseid = new RegExp("comment-delete-"+scope.client_id+"-(\\d+)", "i");
333                         var commentid = theid.match(parseid);
334                         if (!commentid) {
335                             return;
336                         }
337                         if (commentid[1]) {
338                             Y.Event.purgeElement('#'+theid, false, 'click');
339                         }
340                         node.on('click', function(e) {
341                             e.preventDefault();
342                             if (commentid[1]) {
343                                 scope.dodelete(commentid[1]);
344                             }
345                         });
346                         // Also handle space/enter key.
347                         node.on('key', function(e) {
348                             e.preventDefault();
349                             if (commentid[1]) {
350                                 scope.dodelete(commentid[1]);
351                             }
352                         }, '13,32');
353                         // 13 and 32 are the keycodes for space and enter.
354                     }
355                 );
356             },
357             register_pagination: function() {
358                 var scope = this;
359                 // page buttons
360                 Y.all('#comment-pagination-'+this.client_id+' a').each(
361                     function(node, id) {
362                         node.on('click', function(e, node) {
363                             e.preventDefault();
364                             var id = node.get('id');
365                             var re = new RegExp("comment-page-"+this.client_id+"-(\\d+)", "i");
366                             var result = id.match(re);
367                             this.load(result[1]);
368                         }, scope, node);
369                     }
370                 );
371             },
372             view: function(page) {
373                 var commenttoggler = Y.one('#comment-link-' + this.client_id);
374                 var container = Y.one('#comment-ctrl-'+this.client_id);
375                 var ta = Y.one('#dlg-content-'+this.client_id);
376                 var img = Y.one('#comment-img-'+this.client_id);
377                 var d = container.getStyle('display');
378                 if (d=='none'||d=='') {
379                     // show
380                     if (!this.autostart) {
381                         this.load(page);
382                     } else {
383                         this.register_delete_buttons();
384                         this.register_pagination();
385                     }
386                     container.setStyle('display', 'block');
387                     if (img) {
388                         img.set('src', M.util.image_url('t/expanded', 'core'));
389                     }
390                     if (commenttoggler) {
391                         commenttoggler.setAttribute('aria-expanded', 'true');
392                     }
393                 } else {
394                     // hide
395                     container.setStyle('display', 'none');
396                     var collapsedimage = 't/collapsed'; // ltr mode
397                     if ( Y.one(document.body).hasClass('dir-rtl') ) {
398                         collapsedimage = 't/collapsed_rtl';
399                     } else {
400                         collapsedimage = 't/collapsed';
401                     }
402                     if (img) {
403                         img.set('src', M.util.image_url(collapsedimage, 'core'));
404                     }
405                     if (ta) {
406                         ta.set('value','');
407                     }
408                     if (commenttoggler) {
409                         commenttoggler.setAttribute('aria-expanded', 'false');
410                     }
411                 }
412                 if (ta) {
413                     //toggle_textarea.apply(ta, [false]);
414                     //// reset textarea size
415                     ta.on('focus', function() {
416                         this.toggle_textarea(true);
417                     }, this);
418                     //ta.onkeypress = function() {
419                         //if (this.scrollHeight > this.clientHeight && !window.opera)
420                             //this.rows += 1;
421                     //}
422                     ta.on('blur', function() {
423                         this.toggle_textarea(false);
424                     }, this);
425                 }
426                 this.register_actions();
427                 return false;
428             },
429             toggle_textarea: function(focus) {
430                 var t = Y.one('#dlg-content-'+this.client_id);
431                 if (!t) {
432                     return false;
433                 }
434                 if (focus) {
435                     if (t.get('value') == M.util.get_string('addcomment', 'moodle')) {
436                         t.set('value', '');
437                         t.setStyle('color', 'black');
438                     }
439                 }else{
440                     if (t.get('value') == '') {
441                         t.set('value', M.util.get_string('addcomment', 'moodle'));
442                         t.setStyle('color','grey');
443                         t.set('rows', 2);
444                     }
445                 }
446             },
447             wait: function() {
448                 var container = Y.one('#comment-list-'+this.client_id);
449                 container.set('innerHTML', '<div class="mdl-align"><img src="'+M.util.image_url('i/loading_small', 'core')+'" /></div>');
450             }
451         });
453         new CommentHelper(options);
454     }