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