]> git.mxchange.org Git - friendica.git/blob - js/autocomplete.js
3ed9fa30f9f2b23ae3007dda2348b0c9bb963abd
[friendica.git] / 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 editor_replace(item) {
81         if(typeof item.replace !== 'undefined') {
82                 return '$1$2' + item.replace;
83         }
84
85         // $2 ensures that prefix (@,@!) is preserved
86         var id = item.id;
87
88         // don't add the id if it is empty (the id empty eg. if there are unknow contacts in thread)
89         if(id.length < 1)
90                 return '$1$2' + item.nick.replace(' ', '') + ' ';
91
92         // 16 chars of hash should be enough. Full hash could be used if it can be done in a visually appealing way.
93         // 16 chars is also the minimum length in the backend (otherwise it's interpreted as a local id).
94         if(id.length > 16)
95                 id = item.id.substring(0,16);
96
97         return '$1$2' + item.nick.replace(' ', '') + '+' + id + ' ';
98 }
99
100 function basic_replace(item) {
101         if(typeof item.replace !== 'undefined')
102                 return '$1'+item.replace;
103
104         return '$1'+item.name+' ';
105 }
106
107 function webbie_replace(item) {
108         if(typeof item.replace !== 'undefined')
109                 return '$1'+item.replace;
110
111         return '$1'+item.nick+' ';
112 }
113
114 function trim_replace(item) {
115         if(typeof item.replace !== 'undefined')
116                 return '$1'+item.replace;
117
118         return '$1'+item.name;
119 }
120
121
122 function submit_form(e) {
123         $(e).parents('form').submit();
124 }
125
126 function getWord(text, caretPos) {
127         var index = text.indexOf(caretPos);
128         var postText = text.substring(caretPos, caretPos+8);
129         if ((postText.indexOf("[/list]") > 0) || postText.indexOf("[/ul]") > 0 || postText.indexOf("[/ol]") > 0) {
130                 return postText;
131         }
132 }
133
134 function getCaretPosition(ctrl) {
135         var CaretPos = 0;   // IE Support
136         if (document.selection) {
137                 ctrl.focus();
138                 var Sel = document.selection.createRange();
139                 Sel.moveStart('character', -ctrl.value.length);
140                 CaretPos = Sel.text.length;
141         }
142         // Firefox support
143         else if (ctrl.selectionStart || ctrl.selectionStart == '0')
144                 CaretPos = ctrl.selectionStart;
145         return (CaretPos);
146 }
147
148 function setCaretPosition(ctrl, pos){
149         if(ctrl.setSelectionRange) {
150                 ctrl.focus();
151                 ctrl.setSelectionRange(pos,pos);
152         }
153         else if (ctrl.createTextRange) {
154                 var range = ctrl.createTextRange();
155                 range.collapse(true);
156                 range.moveEnd('character', pos);
157                 range.moveStart('character', pos);
158                 range.select();
159         }
160 }
161
162 function listNewLineAutocomplete(id) {
163         var text = document.getElementById(id);
164         var caretPos = getCaretPosition(text)
165         var word = getWord(text.value, caretPos);
166         if (word != null) {
167                 var textBefore = text.value.substring(0, caretPos);
168                 var textAfter  = text.value.substring(caretPos, text.length);
169                 $('#' + id).val(textBefore + '\r\n[*] ' + textAfter).trigger('change');
170                 setCaretPosition(text, caretPos + 5);
171                 return true;
172         }
173         else {
174                 return false;
175         }
176 }
177
178 function string2bb(element) {
179         if(element == 'bold') return 'b';
180         else if(element == 'italic') return 'i';
181         else if(element == 'underline') return 'u';
182         else if(element == 'overline') return 'o';
183         else if(element == 'strike') return 's';
184         else return element;
185 }
186
187 /**
188  * jQuery plugin 'editor_autocomplete'
189  */
190 (function( $ ) {
191         $.fn.editor_autocomplete = function(backend_url) {
192
193                 // Autocomplete contacts
194                 contacts = {
195                         match: /(^|\s)(@\!*)([^ \n]+)$/,
196                         index: 3,
197                         search: function(term, callback) { contact_search(term, callback, backend_url, 'c'); },
198                         replace: editor_replace,
199                         template: contact_format,
200                 };
201
202                 // Autocomplete smilies e.g. ":like"
203                 smilies = {
204                         match: /(^|\s)(:[a-z]{2,})$/,
205                         index: 2,
206                         search: function(term, callback) { $.getJSON('smilies/json').done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
207                         template: function(item) { return item.icon + ' ' + item.text; },
208                         replace: function(item) { return "$1" + item.text + ' '; },
209                 };
210
211                 this.attr('autocomplete','off');
212                 this.textcomplete([contacts,smilies], {className:'acpopup', zIndex:10000});
213         };
214 })( jQuery );
215
216 /**
217  * jQuery plugin 'search_autocomplete'
218  */
219 (function( $ ) {
220         $.fn.search_autocomplete = function(backend_url) {
221                 // Autocomplete contacts
222                 contacts = {
223                         match: /(^@)([^\n]{2,})$/,
224                         index: 2,
225                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'contact'); },
226                         replace: webbie_replace,
227                         template: contact_format,
228                 };
229
230                 // Autocomplete forum accounts
231                 community = {
232                         match: /(^!)([^\n]{2,})$/,
233                         index: 2,
234                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'community'); },
235                         replace: webbie_replace,
236                         template: contact_format,
237                 };
238                 this.attr('autocomplete', 'off');
239                 var a = this.textcomplete([contacts, community], {className:'acpopup', maxCount:100, zIndex: 10000, appendTo:'nav'});
240                 a.on('textComplete:select', function(e, value, strategy) { submit_form(this); });
241         };
242 })( jQuery );
243
244 (function( $ ) {
245         $.fn.contact_autocomplete = function(backend_url, typ, autosubmit, onselect) {
246                 if(typeof typ === 'undefined') typ = '';
247                 if(typeof autosubmit === 'undefined') autosubmit = false;
248
249                 // Autocomplete contacts
250                 contacts = {
251                         match: /(^)([^\n]+)$/,
252                         index: 2,
253                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
254                         replace: basic_replace,
255                         template: contact_format,
256                 };
257
258                 this.attr('autocomplete','off');
259                 var a = this.textcomplete([contacts], {className:'acpopup', zIndex:10000});
260
261                 if(autosubmit)
262                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
263
264                 if(typeof onselect !== 'undefined')
265                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
266         };
267 })( jQuery );
268
269
270 (function( $ ) {
271         $.fn.name_autocomplete = function(backend_url, typ, autosubmit, onselect) {
272                 if(typeof typ === 'undefined') typ = '';
273                 if(typeof autosubmit === 'undefined') autosubmit = false;
274
275                 // Autocomplete contacts
276                 names = {
277                         match: /(^)([^\n]+)$/,
278                         index: 2,
279                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
280                         replace: trim_replace,
281                         template: contact_format,
282                 };
283
284                 this.attr('autocomplete','off');
285                 var a = this.textcomplete([names], {className:'acpopup', zIndex:10000});
286
287                 if(autosubmit)
288                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
289
290                 if(typeof onselect !== 'undefined')
291                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
292         };
293 })( jQuery );
294
295 (function( $ ) {
296         $.fn.bbco_autocomplete = function(type) {
297
298                 if(type=='bbcode') {
299                         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'];
300                         var open_elements = ['*', 'hr'];
301
302                         var elements = open_close_elements.concat(open_elements);
303                 }
304
305                 bbco = {
306                         match: /\[(\w*\**)$/,
307                         search: function (term, callback) {
308                                 callback($.map(elements, function (element) {
309                                         return element.indexOf(term) === 0 ? element : null;
310                                 }));
311                         },
312                         index: 1,
313                         replace: function (element) {
314                                 element = string2bb(element);
315                                 if(open_elements.indexOf(element) < 0) {
316                                         if(element === 'list' || element === 'ol' || element === 'ul') {
317                                                 return ['\[' + element + '\]' + '\n\[*\] ', '\n\[/' + element + '\]'];
318                                         }
319                                         else if(element === 'table') {
320                                                 return ['\[' + element + '\]' + '\n\[tr\]', '\[/tr\]\n\[/' + element + '\]'];
321                                         }
322                                         else {
323                                                 return ['\[' + element + '\]', '\[/' + element + '\]'];
324                                         }
325                                 }
326                                 else {
327                                         return '\[' + element + '\] ';
328                                 }
329                         }
330                 };
331
332                 this.attr('autocomplete','off');
333                 var a = this.textcomplete([bbco], {className:'acpopup', zIndex:10000});
334
335                 a.on('textComplete:select', function(e, value, strategy) { value; });
336
337                 a.keypress(function(e){
338                         if (e.keyCode == 13) {
339                                 var x = listNewLineAutocomplete(this.id);
340                                 if(x) {
341                                         e.stopImmediatePropagation();
342                                         e.preventDefault();
343                                 }
344                         }
345                 });
346         };
347 })( jQuery );
348
349 /**
350  * Friendica people autocomplete legacy code
351  *
352  * require jQuery, jquery.textareas
353  */
354 function ACPopup(elm, backend_url){
355         this.idsel = -1;
356         this.element = elm;
357         this.searchText = '';
358         this.ready = true;
359         this.kp_timer = false;
360         this.url = backend_url;
361
362         this.conversation_id = null;
363         var conv_id = this.element.id.match(/\d+$/);
364         if (conv_id) {
365                 this.conversation_id = conv_id[0];
366         }
367
368         var w = $(elm).width();
369         var h = $(elm).height();
370
371         var style = $(elm).offset();
372         style.top = style.top + h;
373         style.width = w;
374         style.position = 'absolute';
375         style.display = 'none';
376
377         this.cont = $('<div class="acpopup-mce"></div>');
378         this.cont.css(style);
379
380         $('body').append(this.cont);
381 }
382
383 ACPopup.prototype.close = function(){
384         $(this.cont).remove();
385         this.ready=false;
386 }
387 ACPopup.prototype.search = function(text){
388         var that = this;
389         this.searchText=text;
390         if (this.kp_timer) clearTimeout(this.kp_timer);
391         this.kp_timer = setTimeout( function(){that._search();}, 500);
392 }
393
394 ACPopup.prototype._search = function(){
395         console.log("_search");
396         var that = this;
397         var postdata = {
398                 start:0,
399                 count:100,
400                 search:this.searchText,
401                 type:'c',
402                 conversation: this.conversation_id,
403         }
404
405         $.ajax({
406                 type:'POST',
407                 url: this.url,
408                 data: postdata,
409                 dataType: 'json',
410                 success:function(data){
411                         that.cont.html("");
412                         if (data.tot>0){
413                                 that.cont.show();
414                                 $(data.items).each(function(){
415                                         var html = "<img src='{0}' height='16px' width='16px'>{1} ({2})".format(this.photo, this.name, this.nick);
416                                         var nick = this.nick.replace(' ','');
417                                         if (this.id!=='')  nick += '+' + this.id;
418                                         that.add(html, nick + ' - ' + this.link);
419                                 });
420                         } else {
421                                 that.cont.hide();
422                         }
423                 }
424         });
425
426 }
427
428 ACPopup.prototype.add = function(label, value){
429         var that = this;
430         var elm = $('<div class="acpopupitem" title="' + value + '">' + label + '</div>');
431         elm.click(function(e){
432                 t = $(this).attr('title').replace(new RegExp(' \- .*'), '');
433                 el = $(that.element);
434                 sel = el.getSelection();
435                 sel.start = sel.start - that.searchText.length;
436                 el.setSelection(sel.start, sel.end).replaceSelectedText(t + ' ').collapseSelection(false);
437                 that.close();
438         });
439         $(this.cont).append(elm);
440 }
441
442 ACPopup.prototype.onkey = function(event){
443         if (event.keyCode == '13') {
444                 if(this.idsel > -1) {
445                         this.cont.children()[this.idsel].click();
446                         event.preventDefault();
447                 } else {
448                         this.close();
449                 }
450         }
451         if (event.keyCode == '38') { //cursor up
452                 var cmax = this.cont.children().size() - 1;
453                 this.idsel--;
454                 if (this.idsel < 0) {
455                         this.idsel = cmax;
456                 }
457                 event.preventDefault();
458         }
459         if (event.keyCode == '40' || event.keyCode == '9') { //cursor down
460                 var cmax = this.cont.children().size() - 1;
461                 this.idsel++;
462                 if (this.idsel > cmax) {
463                         this.idsel = 0;
464                 }
465                 event.preventDefault();
466         }
467
468         if (event.keyCode == '38' || event.keyCode == '40' || event.keyCode == '9') {
469                 this.cont.children().removeClass('selected');
470                 $(this.cont.children()[this.idsel]).addClass('selected');
471         }
472
473         if (event.keyCode == '27') { //ESC
474                 this.close();
475         }
476 }
477