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