]> git.mxchange.org Git - friendica.git/blob - js/autocomplete.js
Merge pull request #2531 from rabuzarus/frio_merge
[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 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);
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', '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
351  * code which is needed for tinymce
352  *
353  * require jQuery, jquery.textareas
354  */
355
356 function ACPopup(elm,backend_url){
357         this.idsel=-1;
358         this.element = elm;
359         this.searchText="";
360         this.ready=true;
361         this.kp_timer = false;
362         this.url = backend_url;
363
364         this.conversation_id = null;
365         var conv_id = this.element.id.match(/\d+$/);
366         if (conv_id) this.conversation_id = conv_id[0];
367         console.log("ACPopup elm id",this.element.id,"conversation",this.conversation_id);
368
369         var w = 530;
370         var h = 130;
371
372
373         if(tinyMCE.activeEditor == null) {
374                 style = $(elm).offset();
375                 w = $(elm).width();
376                 h = $(elm).height();
377         }
378         else {
379                 // I can't find an "official" way to get the element who get all
380                 // this fraking thing that is tinyMCE.
381                 // This code will broke again at some point...
382                 var container = $(tinyMCE.activeEditor.getContainer()).find("table");
383                 style = $(container).offset();
384                 w = $(container).width();
385                 h = $(container).height();
386         }
387
388         style.top=style.top+h;
389         style.width = w;
390         style.position = 'absolute';
391         /*      style['max-height'] = '150px';
392                 style.border = '1px solid red';
393                 style.background = '#cccccc';
394
395                 style.overflow = 'auto';
396                 style['z-index'] = '100000';
397         */
398         style.display = 'none';
399
400         this.cont = $("<div class='acpopup-mce'></div>");
401         this.cont.css(style);
402
403         $("body").append(this.cont);
404     }
405
406 ACPopup.prototype.close = function(){
407         $(this.cont).remove();
408         this.ready=false;
409 }
410 ACPopup.prototype.search = function(text){
411         var that = this;
412         this.searchText=text;
413         if (this.kp_timer) clearTimeout(this.kp_timer);
414         this.kp_timer = setTimeout( function(){that._search();}, 500);
415 }
416
417 ACPopup.prototype._search = function(){
418         console.log("_search");
419         var that = this;
420         var postdata = {
421                 start:0,
422                 count:100,
423                 search:this.searchText,
424                 type:'c',
425                 conversation: this.conversation_id,
426         }
427
428         $.ajax({
429                 type:'POST',
430                 url: this.url,
431                 data: postdata,
432                 dataType: 'json',
433                 success:function(data){
434                         that.cont.html("");
435                         if (data.tot>0){
436                                 that.cont.show();
437                                 $(data.items).each(function(){
438                                         var html = "<img src='{0}' height='16px' width='16px'>{1} ({2})".format(this.photo, this.name, this.nick);
439                                         var nick = this.nick.replace(' ','');
440                                         if (this.id!=='')  nick += '+' + this.id;
441                                         that.add(html, nick + ' - ' + this.link);
442                                 });
443                         } else {
444                                 that.cont.hide();
445                         }
446                 }
447         });
448
449 }
450
451 ACPopup.prototype.add = function(label, value){
452         var that=this;
453         var elm = $("<div class='acpopupitem' title='"+value+"'>"+label+"</div>");
454         elm.click(function(e){
455                 t = $(this).attr('title').replace(new RegExp(' \- .*'),'');
456                 if(typeof(that.element.container) === "undefined") {
457                         el=$(that.element);
458                         sel = el.getSelection();
459                         sel.start = sel.start- that.searchText.length;
460                         el.setSelection(sel.start,sel.end).replaceSelectedText(t+' ').collapseSelection(false);
461                         that.close();
462                 }
463                 else {
464                         txt = tinyMCE.activeEditor.getContent();
465                         //                      alert(that.searchText + ':' + t);
466                         newtxt = txt.replace('@' + that.searchText,'@' + t +' ');
467                         tinyMCE.activeEditor.setContent(newtxt);
468                         tinyMCE.activeEditor.focus();
469                         that.close();
470                 }
471         });
472         $(this.cont).append(elm);
473 }
474
475 ACPopup.prototype.onkey = function(event){
476         if (event.keyCode == '13') {
477                 if(this.idsel>-1) {
478                         this.cont.children()[this.idsel].click();
479                         event.preventDefault();
480                 }
481                 else
482                         this.close();
483         }
484         if (event.keyCode == '38') { //cursor up
485                 cmax = this.cont.children().size()-1;
486                 this.idsel--;
487                 if (this.idsel<0) this.idsel=cmax;
488                 event.preventDefault();
489         }
490         if (event.keyCode == '40' || event.keyCode == '9') { //cursor down
491                 cmax = this.cont.children().size()-1;
492                 this.idsel++;
493                 if (this.idsel>cmax) this.idsel=0;
494                 event.preventDefault();
495         }
496
497         if (event.keyCode == '38' || event.keyCode == '40' || event.keyCode == '9') {
498                 this.cont.children().removeClass('selected');
499                 $(this.cont.children()[this.idsel]).addClass('selected');
500         }
501
502         if (event.keyCode == '27') { //ESC
503                 this.close();
504         }
505 }
506