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