]> git.mxchange.org Git - friendica.git/blob - view/js/autocomplete.js
Fix tests (#5400)
[friendica.git] / view / js / autocomplete.js
1 /**
2  * @brief Friendica people autocomplete
3  *
4  * require jQuery, jquery.textcomplete
5  *
6  * for further documentation look at:
7  * http://yuku-t.com/jquery-textcomplete/
8  *
9  * https://github.com/yuku-t/jquery-textcomplete/blob/master/doc/how_to_use.md
10  */
11
12
13 function contact_search(term, callback, backend_url, type, mode) {
14
15         // Check if there is a conversation id to include the unkonwn contacts of the conversation
16         var conv_id = document.activeElement.id.match(/\d+$/);
17
18         // Check if there is a cached result that contains the same information we would get with a full server-side search
19         var bt = backend_url+type;
20         if(!(bt in contact_search.cache)) contact_search.cache[bt] = {};
21
22         var lterm = term.toLowerCase(); // Ignore case
23         for(var t in contact_search.cache[bt]) {
24                 if(lterm.indexOf(t) >= 0) { // A more broad search has been performed already, so use those results
25                         // Filter old results locally
26                         var matching = contact_search.cache[bt][t].filter(function (x) { return (x.name.toLowerCase().indexOf(lterm) >= 0 || (typeof x.nick !== 'undefined' && x.nick.toLowerCase().indexOf(lterm) >= 0)); }); // Need to check that nick exists because groups don't have one
27                         matching.unshift({forum:false, text: term, replace: term});
28                         setTimeout(function() { callback(matching); } , 1); // Use "pseudo-thread" to avoid some problems
29                         return;
30                 }
31         }
32
33         var postdata = {
34                 start:0,
35                 count:100,
36                 search:term,
37                 type:type,
38         };
39
40         if(conv_id !== null)
41                 postdata['conversation'] = conv_id[0];
42
43         if(mode !== null)
44                 postdata['smode'] = mode;
45
46
47         $.ajax({
48                 type:'POST',
49                 url: backend_url,
50                 data: postdata,
51                 dataType: 'json',
52                 success: function(data){
53                         // Cache results if we got them all (more information would not improve results)
54                         // data.count represents the maximum number of items
55                         if(data.items.length -1 < data.count) {
56                                 contact_search.cache[bt][lterm] = data.items;
57                         }
58                         var items = data.items.slice(0);
59                         items.unshift({taggable:false, text: term, replace: term});
60                         callback(items);
61                 },
62         }).fail(function () {callback([]); }); // Callback must be invoked even if something went wrong.
63 }
64 contact_search.cache = {};
65
66
67 function contact_format(item) {
68         // Show contact information if not explicitly told to show something else
69         if(typeof item.text === 'undefined') {
70                 var desc = ((item.label) ? item.nick + ' ' + item.label : item.nick);
71                 var forum = ((item.forum) ? 'forum' : '');
72                 if(typeof desc === 'undefined') desc = '';
73                 if(desc) desc = ' ('+desc+')';
74                 return "<div class='{0}' title='{4}'><img class='acpopup-img' src='{1}'><span class='acpopup-contactname'>{2}</span><span class='acpopup-sub-text'>{3}</span><div class='clear'></div></div>".format(forum, item.photo, item.name, desc, item.link);
75         }
76         else
77                 return "<div>" + item.text + "</div>";
78 }
79
80 function tag_format(item) {
81         return "<div class='dropdown-item'>" + '#' + item.text + "</div>";
82 }
83
84 function editor_replace(item) {
85         if (typeof item.replace !== 'undefined') {
86                 return '$1$2' + item.replace;
87         }
88
89         if (typeof item.addr !== 'undefined') {
90                 return '$1$2' + item.addr + ' ';
91         }
92
93         // $2 ensures that prefix (@,@!) is preserved
94         var id = item.id;
95
96         // don't add the id if it is empty (the id empty eg. if there are unknow contacts in thread)
97         if (id.length < 1) {
98                 return '$1$2' + item.nick.replace(' ', '') + ' ';
99         }
100         // 16 chars of hash should be enough. Full hash could be used if it can be done in a visually appealing way.
101         // 16 chars is also the minimum length in the backend (otherwise it's interpreted as a local id).
102         if (id.length > 16) {
103                 id = item.id.substring(0,16);
104         }
105         return '$1$2' + item.nick.replace(' ', '') + '+' + id + ' ';
106 }
107
108 function basic_replace(item) {
109         if(typeof item.replace !== 'undefined')
110                 return '$1'+item.replace;
111
112         return '$1'+item.name+' ';
113 }
114
115 function webbie_replace(item) {
116         if(typeof item.replace !== 'undefined')
117                 return '$1'+item.replace;
118
119         return '$1'+item.nick+' ';
120 }
121
122 function trim_replace(item) {
123         if(typeof item.replace !== 'undefined')
124                 return '$1'+item.replace;
125
126         return '$1'+item.name;
127 }
128
129
130 function submit_form(e) {
131         $(e).parents('form').submit();
132 }
133
134 function getWord(text, caretPos) {
135         var index = text.indexOf(caretPos);
136         var postText = text.substring(caretPos, caretPos+8);
137         if ((postText.indexOf("[/list]") > 0) || postText.indexOf("[/ul]") > 0 || postText.indexOf("[/ol]") > 0) {
138                 return postText;
139         }
140 }
141
142 function getCaretPosition(ctrl) {
143         var CaretPos = 0;   // IE Support
144         if (document.selection) {
145                 ctrl.focus();
146                 var Sel = document.selection.createRange();
147                 Sel.moveStart('character', -ctrl.value.length);
148                 CaretPos = Sel.text.length;
149         }
150         // Firefox support
151         else if (ctrl.selectionStart || ctrl.selectionStart == '0')
152                 CaretPos = ctrl.selectionStart;
153         return (CaretPos);
154 }
155
156 function setCaretPosition(ctrl, pos){
157         if(ctrl.setSelectionRange) {
158                 ctrl.focus();
159                 ctrl.setSelectionRange(pos,pos);
160         }
161         else if (ctrl.createTextRange) {
162                 var range = ctrl.createTextRange();
163                 range.collapse(true);
164                 range.moveEnd('character', pos);
165                 range.moveStart('character', pos);
166                 range.select();
167         }
168 }
169
170 function listNewLineAutocomplete(id) {
171         var text = document.getElementById(id);
172         var caretPos = getCaretPosition(text)
173         var word = getWord(text.value, caretPos);
174         if (word != null) {
175                 var textBefore = text.value.substring(0, caretPos);
176                 var textAfter  = text.value.substring(caretPos, text.length);
177                 $('#' + id).val(textBefore + '\r\n[*] ' + textAfter).trigger('change');
178                 setCaretPosition(text, caretPos + 5);
179                 return true;
180         }
181         else {
182                 return false;
183         }
184 }
185
186 function string2bb(element) {
187         if(element == 'bold') return 'b';
188         else if(element == 'italic') return 'i';
189         else if(element == 'underline') return 'u';
190         else if(element == 'overline') return 'o';
191         else if(element == 'strike') return 's';
192         else return element;
193 }
194
195 /**
196  * jQuery plugin 'editor_autocomplete'
197  */
198 (function( $ ) {
199         $.fn.editor_autocomplete = function(backend_url) {
200
201                 // Autocomplete contacts
202                 contacts = {
203                         match: /(^|\s)(@\!*)([^ \n]+)$/,
204                         index: 3,
205                         search: function(term, callback) { contact_search(term, callback, backend_url, 'c'); },
206                         replace: editor_replace,
207                         template: contact_format,
208                 };
209
210                 // Autocomplete forums
211                 forums = {
212                         match: /(^|\s)(!\!*)([^ \n]+)$/,
213                         index: 3,
214                         search: function(term, callback) { contact_search(term, callback, backend_url, 'f'); },
215                         replace: editor_replace,
216                         template: contact_format,
217                 };
218
219                 // Autocomplete hashtags
220                 tags = {
221                         match: /(^|\s)(\#)([^ \n]{2,})$/,
222                         index: 3,
223                         search: function(term, callback) {
224                                 $.getJSON(baseurl + '/hashtag/' + '?f=&t=' + term)
225                                 .done(function(data) {
226                                         callback($.map(data, function(entry) {
227                                                 // .toLowerCase() enables case-insensitive search
228                                                 return entry.text.toLowerCase().indexOf(term.toLowerCase()) === 0 ? entry : null;
229                                         }));
230                                 });
231                         },
232                         replace: function(item) { return "$1$2" + item.text + ' '; },
233                         template: tag_format
234                 };
235
236                 // Autocomplete smilies e.g. ":like"
237                 smilies = {
238                         match: /(^|\s)(:[a-z]{2,})$/,
239                         index: 2,
240                         search: function(term, callback) { $.getJSON('smilies/json').done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
241                         template: function(item) { return item.icon + ' ' + item.text; },
242                         replace: function(item) { return "$1" + item.text + ' '; },
243                 };
244
245                 this.attr('autocomplete','off');
246                 this.textcomplete([contacts, forums, smilies, tags], {className:'acpopup', zIndex:10000});
247         };
248 })( jQuery );
249
250 /**
251  * jQuery plugin 'search_autocomplete'
252  */
253 (function( $ ) {
254         $.fn.search_autocomplete = function(backend_url) {
255                 // Autocomplete contacts
256                 contacts = {
257                         match: /(^@)([^\n]{2,})$/,
258                         index: 2,
259                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'contact'); },
260                         replace: webbie_replace,
261                         template: contact_format,
262                 };
263
264                 // Autocomplete forum accounts
265                 community = {
266                         match: /(^!)([^\n]{2,})$/,
267                         index: 2,
268                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'community'); },
269                         replace: webbie_replace,
270                         template: contact_format,
271                 };
272
273                 // Autocomplete hashtags
274                 tags = {
275                         match: /(^|\s)(\#)([^ \n]{2,})$/,
276                         index: 3,
277                         search: function(term, callback) { $.getJSON(baseurl + '/hashtag/' + '?f=&t=' + term).done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
278                         replace: function(item) { return "$1$2" + item.text; },
279                         template: tag_format
280                 };
281
282                 this.attr('autocomplete', 'off');
283                 var a = this.textcomplete([contacts, community, tags], {className:'acpopup', maxCount:100, zIndex: 10000, appendTo:'nav'});
284                 a.on('textComplete:select', function(e, value, strategy) { submit_form(this); });
285         };
286 })( jQuery );
287
288 (function( $ ) {
289         $.fn.contact_autocomplete = function(backend_url, typ, autosubmit, onselect) {
290                 if(typeof typ === 'undefined') typ = '';
291                 if(typeof autosubmit === 'undefined') autosubmit = false;
292
293                 // Autocomplete contacts
294                 contacts = {
295                         match: /(^)([^\n]+)$/,
296                         index: 2,
297                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
298                         replace: basic_replace,
299                         template: contact_format,
300                 };
301
302                 this.attr('autocomplete','off');
303                 var a = this.textcomplete([contacts], {className:'acpopup', zIndex:10000});
304
305                 if(autosubmit)
306                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
307
308                 if(typeof onselect !== 'undefined')
309                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
310         };
311 })( jQuery );
312
313
314 (function( $ ) {
315         $.fn.name_autocomplete = function(backend_url, typ, autosubmit, onselect) {
316                 if(typeof typ === 'undefined') typ = '';
317                 if(typeof autosubmit === 'undefined') autosubmit = false;
318
319                 // Autocomplete contacts
320                 names = {
321                         match: /(^)([^\n]+)$/,
322                         index: 2,
323                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
324                         replace: trim_replace,
325                         template: contact_format,
326                 };
327
328                 this.attr('autocomplete','off');
329                 var a = this.textcomplete([names], {className:'acpopup', zIndex:10000});
330
331                 if(autosubmit)
332                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
333
334                 if(typeof onselect !== 'undefined')
335                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
336         };
337 })( jQuery );
338
339 (function( $ ) {
340         $.fn.bbco_autocomplete = function(type) {
341
342                 if(type=='bbcode') {
343                         var open_close_elements = ['bold', 'italic', 'underline', 'overline', 'strike', 'quote', 'code', 'spoiler', 'map', 'img', 'url', 'audio', 'video', 'embed', 'youtube', 'vimeo', 'list', 'ul', 'ol', 'li', 'table', 'tr', 'th', 'td', 'center', 'color', 'font', 'size', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'nobb', 'noparse', 'pre', 'abstract'];
344                         var open_elements = ['*', 'hr'];
345
346                         var elements = open_close_elements.concat(open_elements);
347                 }
348
349                 bbco = {
350                         match: /\[(\w*\**)$/,
351                         search: function (term, callback) {
352                                 callback($.map(elements, function (element) {
353                                         return element.indexOf(term) === 0 ? element : null;
354                                 }));
355                         },
356                         index: 1,
357                         replace: function (element) {
358                                 element = string2bb(element);
359                                 if(open_elements.indexOf(element) < 0) {
360                                         if(element === 'list' || element === 'ol' || element === 'ul') {
361                                                 return ['\[' + element + '\]' + '\n\[*\] ', '\n\[/' + element + '\]'];
362                                         }
363                                         else if(element === 'table') {
364                                                 return ['\[' + element + '\]' + '\n\[tr\]', '\[/tr\]\n\[/' + element + '\]'];
365                                         }
366                                         else {
367                                                 return ['\[' + element + '\]', '\[/' + element + '\]'];
368                                         }
369                                 }
370                                 else {
371                                         return '\[' + element + '\] ';
372                                 }
373                         }
374                 };
375
376                 this.attr('autocomplete','off');
377                 var a = this.textcomplete([bbco], {className:'acpopup', zIndex:10000});
378
379                 a.on('textComplete:select', function(e, value, strategy) { value; });
380
381                 a.keypress(function(e){
382                         if (e.keyCode == 13) {
383                                 var x = listNewLineAutocomplete(this.id);
384                                 if(x) {
385                                         e.stopImmediatePropagation();
386                                         e.preventDefault();
387                                 }
388                         }
389                 });
390         };
391 })( jQuery );
392
393 /**
394  * Friendica people autocomplete legacy code
395  *
396  * require jQuery, jquery.textareas
397  */
398 function ACPopup(elm, backend_url){
399         this.idsel = -1;
400         this.element = elm;
401         this.searchText = '';
402         this.ready = true;
403         this.kp_timer = false;
404         this.url = backend_url;
405
406         this.conversation_id = null;
407         var conv_id = this.element.id.match(/\d+$/);
408         if (conv_id) {
409                 this.conversation_id = conv_id[0];
410         }
411
412         var w = $(elm).width();
413         var h = $(elm).height();
414
415         var style = $(elm).offset();
416         style.top = style.top + h;
417         style.width = w;
418         style.position = 'absolute';
419         style.display = 'none';
420
421         this.cont = $('<div class="acpopup-mce"></div>');
422         this.cont.css(style);
423
424         $('body').append(this.cont);
425 }
426
427 ACPopup.prototype.close = function(){
428         $(this.cont).remove();
429         this.ready=false;
430 }
431 ACPopup.prototype.search = function(text){
432         var that = this;
433         this.searchText=text;
434         if (this.kp_timer) clearTimeout(this.kp_timer);
435         this.kp_timer = setTimeout( function(){that._search();}, 500);
436 }
437
438 ACPopup.prototype._search = function(){
439         console.log("_search");
440         var that = this;
441         var postdata = {
442                 start:0,
443                 count:100,
444                 search:this.searchText,
445                 type:'c',
446                 conversation: this.conversation_id,
447         }
448
449         $.ajax({
450                 type:'POST',
451                 url: this.url,
452                 data: postdata,
453                 dataType: 'json',
454                 success:function(data){
455                         that.cont.html("");
456                         if (data.tot>0){
457                                 that.cont.show();
458                                 $(data.items).each(function(){
459                                         var html = "<img src='{0}' height='16px' width='16px'>{1} ({2})".format(this.photo, this.name, this.nick);
460                                         var nick = this.nick.replace(' ','');
461                                         if (this.id!=='')  nick += '+' + this.id;
462                                         that.add(html, nick + ' - ' + this.link);
463                                 });
464                         } else {
465                                 that.cont.hide();
466                         }
467                 }
468         });
469
470 }
471
472 ACPopup.prototype.add = function(label, value){
473         var that = this;
474         var elm = $('<div class="acpopupitem" title="' + value + '">' + label + '</div>');
475         elm.click(function(e){
476                 t = $(this).attr('title').replace(new RegExp(' \- .*'), '');
477                 el = $(that.element);
478                 sel = el.getSelection();
479                 sel.start = sel.start - that.searchText.length;
480                 el.setSelection(sel.start, sel.end).replaceSelectedText(t + ' ').collapseSelection(false);
481                 that.close();
482         });
483         $(this.cont).append(elm);
484 }
485
486 ACPopup.prototype.onkey = function(event){
487         if (event.keyCode == '13') {
488                 if(this.idsel > -1) {
489                         this.cont.children()[this.idsel].click();
490                         event.preventDefault();
491                 } else {
492                         this.close();
493                 }
494         }
495         if (event.keyCode == '38') { //cursor up
496                 var cmax = this.cont.children().size() - 1;
497                 this.idsel--;
498                 if (this.idsel < 0) {
499                         this.idsel = cmax;
500                 }
501                 event.preventDefault();
502         }
503         if (event.keyCode == '40' || event.keyCode == '9') { //cursor down
504                 var cmax = this.cont.children().size() - 1;
505                 this.idsel++;
506                 if (this.idsel > cmax) {
507                         this.idsel = 0;
508                 }
509                 event.preventDefault();
510         }
511
512         if (event.keyCode == '38' || event.keyCode == '40' || event.keyCode == '9') {
513                 this.cont.children().removeClass('selected');
514                 $(this.cont.children()[this.idsel]).addClass('selected');
515         }
516
517         if (event.keyCode == '27') { //ESC
518                 this.close();
519         }
520 }
521