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