]> git.mxchange.org Git - friendica.git/blob - view/js/autocomplete.js
eb9d5efbea9bdccd99c1614592d1afdb1ed27ee5
[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) { $.getJSON(baseurl + '/hashtag/' + '?f=&t=' + term).done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
224                         replace: function(item) { return "$1$2" + item.text + ' '; },
225                         template: tag_format
226                 };
227
228                 // Autocomplete smilies e.g. ":like"
229                 smilies = {
230                         match: /(^|\s)(:[a-z]{2,})$/,
231                         index: 2,
232                         search: function(term, callback) { $.getJSON('smilies/json').done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
233                         template: function(item) { return item.icon + ' ' + item.text; },
234                         replace: function(item) { return "$1" + item.text + ' '; },
235                 };
236
237                 this.attr('autocomplete','off');
238                 this.textcomplete([contacts, forums, smilies, tags], {className:'acpopup', zIndex:10000});
239         };
240 })( jQuery );
241
242 /**
243  * jQuery plugin 'search_autocomplete'
244  */
245 (function( $ ) {
246         $.fn.search_autocomplete = function(backend_url) {
247                 // Autocomplete contacts
248                 contacts = {
249                         match: /(^@)([^\n]{2,})$/,
250                         index: 2,
251                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'contact'); },
252                         replace: webbie_replace,
253                         template: contact_format,
254                 };
255
256                 // Autocomplete forum accounts
257                 community = {
258                         match: /(^!)([^\n]{2,})$/,
259                         index: 2,
260                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'community'); },
261                         replace: webbie_replace,
262                         template: contact_format,
263                 };
264
265                 // Autocomplete hashtags
266                 tags = {
267                         match: /(^|\s)(\#)([^ \n]{2,})$/,
268                         index: 3,
269                         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; })); }); },
270                         replace: function(item) { return "$1$2" + item.text; },
271                         template: tag_format
272                 };
273
274                 this.attr('autocomplete', 'off');
275                 var a = this.textcomplete([contacts, community, tags], {className:'acpopup', maxCount:100, zIndex: 10000, appendTo:'nav'});
276                 a.on('textComplete:select', function(e, value, strategy) { submit_form(this); });
277         };
278 })( jQuery );
279
280 (function( $ ) {
281         $.fn.contact_autocomplete = function(backend_url, typ, autosubmit, onselect) {
282                 if(typeof typ === 'undefined') typ = '';
283                 if(typeof autosubmit === 'undefined') autosubmit = false;
284
285                 // Autocomplete contacts
286                 contacts = {
287                         match: /(^)([^\n]+)$/,
288                         index: 2,
289                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
290                         replace: basic_replace,
291                         template: contact_format,
292                 };
293
294                 this.attr('autocomplete','off');
295                 var a = this.textcomplete([contacts], {className:'acpopup', zIndex:10000});
296
297                 if(autosubmit)
298                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
299
300                 if(typeof onselect !== 'undefined')
301                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
302         };
303 })( jQuery );
304
305
306 (function( $ ) {
307         $.fn.name_autocomplete = function(backend_url, typ, autosubmit, onselect) {
308                 if(typeof typ === 'undefined') typ = '';
309                 if(typeof autosubmit === 'undefined') autosubmit = false;
310
311                 // Autocomplete contacts
312                 names = {
313                         match: /(^)([^\n]+)$/,
314                         index: 2,
315                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
316                         replace: trim_replace,
317                         template: contact_format,
318                 };
319
320                 this.attr('autocomplete','off');
321                 var a = this.textcomplete([names], {className:'acpopup', zIndex:10000});
322
323                 if(autosubmit)
324                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
325
326                 if(typeof onselect !== 'undefined')
327                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
328         };
329 })( jQuery );
330
331 (function( $ ) {
332         $.fn.bbco_autocomplete = function(type) {
333
334                 if(type=='bbcode') {
335                         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'];
336                         var open_elements = ['*', 'hr'];
337
338                         var elements = open_close_elements.concat(open_elements);
339                 }
340
341                 bbco = {
342                         match: /\[(\w*\**)$/,
343                         search: function (term, callback) {
344                                 callback($.map(elements, function (element) {
345                                         return element.indexOf(term) === 0 ? element : null;
346                                 }));
347                         },
348                         index: 1,
349                         replace: function (element) {
350                                 element = string2bb(element);
351                                 if(open_elements.indexOf(element) < 0) {
352                                         if(element === 'list' || element === 'ol' || element === 'ul') {
353                                                 return ['\[' + element + '\]' + '\n\[*\] ', '\n\[/' + element + '\]'];
354                                         }
355                                         else if(element === 'table') {
356                                                 return ['\[' + element + '\]' + '\n\[tr\]', '\[/tr\]\n\[/' + element + '\]'];
357                                         }
358                                         else {
359                                                 return ['\[' + element + '\]', '\[/' + element + '\]'];
360                                         }
361                                 }
362                                 else {
363                                         return '\[' + element + '\] ';
364                                 }
365                         }
366                 };
367
368                 this.attr('autocomplete','off');
369                 var a = this.textcomplete([bbco], {className:'acpopup', zIndex:10000});
370
371                 a.on('textComplete:select', function(e, value, strategy) { value; });
372
373                 a.keypress(function(e){
374                         if (e.keyCode == 13) {
375                                 var x = listNewLineAutocomplete(this.id);
376                                 if(x) {
377                                         e.stopImmediatePropagation();
378                                         e.preventDefault();
379                                 }
380                         }
381                 });
382         };
383 })( jQuery );
384
385 /**
386  * Friendica people autocomplete legacy code
387  *
388  * require jQuery, jquery.textareas
389  */
390 function ACPopup(elm, backend_url){
391         this.idsel = -1;
392         this.element = elm;
393         this.searchText = '';
394         this.ready = true;
395         this.kp_timer = false;
396         this.url = backend_url;
397
398         this.conversation_id = null;
399         var conv_id = this.element.id.match(/\d+$/);
400         if (conv_id) {
401                 this.conversation_id = conv_id[0];
402         }
403
404         var w = $(elm).width();
405         var h = $(elm).height();
406
407         var style = $(elm).offset();
408         style.top = style.top + h;
409         style.width = w;
410         style.position = 'absolute';
411         style.display = 'none';
412
413         this.cont = $('<div class="acpopup-mce"></div>');
414         this.cont.css(style);
415
416         $('body').append(this.cont);
417 }
418
419 ACPopup.prototype.close = function(){
420         $(this.cont).remove();
421         this.ready=false;
422 }
423 ACPopup.prototype.search = function(text){
424         var that = this;
425         this.searchText=text;
426         if (this.kp_timer) clearTimeout(this.kp_timer);
427         this.kp_timer = setTimeout( function(){that._search();}, 500);
428 }
429
430 ACPopup.prototype._search = function(){
431         console.log("_search");
432         var that = this;
433         var postdata = {
434                 start:0,
435                 count:100,
436                 search:this.searchText,
437                 type:'c',
438                 conversation: this.conversation_id,
439         }
440
441         $.ajax({
442                 type:'POST',
443                 url: this.url,
444                 data: postdata,
445                 dataType: 'json',
446                 success:function(data){
447                         that.cont.html("");
448                         if (data.tot>0){
449                                 that.cont.show();
450                                 $(data.items).each(function(){
451                                         var html = "<img src='{0}' height='16px' width='16px'>{1} ({2})".format(this.photo, this.name, this.nick);
452                                         var nick = this.nick.replace(' ','');
453                                         if (this.id!=='')  nick += '+' + this.id;
454                                         that.add(html, nick + ' - ' + this.link);
455                                 });
456                         } else {
457                                 that.cont.hide();
458                         }
459                 }
460         });
461
462 }
463
464 ACPopup.prototype.add = function(label, value){
465         var that = this;
466         var elm = $('<div class="acpopupitem" title="' + value + '">' + label + '</div>');
467         elm.click(function(e){
468                 t = $(this).attr('title').replace(new RegExp(' \- .*'), '');
469                 el = $(that.element);
470                 sel = el.getSelection();
471                 sel.start = sel.start - that.searchText.length;
472                 el.setSelection(sel.start, sel.end).replaceSelectedText(t + ' ').collapseSelection(false);
473                 that.close();
474         });
475         $(this.cont).append(elm);
476 }
477
478 ACPopup.prototype.onkey = function(event){
479         if (event.keyCode == '13') {
480                 if(this.idsel > -1) {
481                         this.cont.children()[this.idsel].click();
482                         event.preventDefault();
483                 } else {
484                         this.close();
485                 }
486         }
487         if (event.keyCode == '38') { //cursor up
488                 var cmax = this.cont.children().size() - 1;
489                 this.idsel--;
490                 if (this.idsel < 0) {
491                         this.idsel = cmax;
492                 }
493                 event.preventDefault();
494         }
495         if (event.keyCode == '40' || event.keyCode == '9') { //cursor down
496                 var cmax = this.cont.children().size() - 1;
497                 this.idsel++;
498                 if (this.idsel > cmax) {
499                         this.idsel = 0;
500                 }
501                 event.preventDefault();
502         }
503
504         if (event.keyCode == '38' || event.keyCode == '40' || event.keyCode == '9') {
505                 this.cont.children().removeClass('selected');
506                 $(this.cont.children()[this.idsel]).addClass('selected');
507         }
508
509         if (event.keyCode == '27') { //ESC
510                 this.close();
511         }
512 }
513