]> git.mxchange.org Git - friendica.git/blob - js/autocomplete.js
Doxygen structure added
[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 /**
115  * jQuery plugin 'editor_autocomplete'
116  */
117 (function( $ ) {
118         $.fn.editor_autocomplete = function(backend_url) {
119
120                 // list of supported bbtags
121                 var bbelements = ['b', 'u', 'i', 'img', 'url', 'quote', 'code', 'spoiler', 'audio', 'video', 'youtube', 'map', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 's', 'o', 'list', 'center', 'nosmile', 'vimeo' ];
122
123                 // Autocomplete contacts
124                 contacts = {
125                         match: /(^|\s)(@\!*)([^ \n]+)$/,
126                         index: 3,
127                         search: function(term, callback) { contact_search(term, callback, backend_url, 'c'); },
128                         replace: editor_replace,
129                         template: contact_format,
130                 };
131
132                 // Autocomplete smilies e.g. ":like"
133                 smilies = {
134                         match: /(^|\s)(:[a-z]{2,})$/,
135                         index: 2,
136                         search: function(term, callback) { $.getJSON('smilies/json').done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
137                         template: function(item) { return item.icon + ' ' + item.text; },
138                         replace: function(item) { return "$1" + item.text + ' '; },
139                 };
140
141                 // Autocomplete BBTags
142                 bbtags = {
143                         match: /\[(\w*)$/,
144                         index: 1,
145                         search: function (term, callback) { callback($.map(bbelements, function (element) { return element.indexOf(term) === 0 ? element : null; })); },
146                         replace: function (element) { return ['[' + element + ']', '[/' + element + ']']; },
147                 };
148                 this.attr('autocomplete','off');
149                 this.textcomplete([contacts,smilies, bbtags], {className:'acpopup', zIndex:1020});
150         };
151 })( jQuery );
152
153 /**
154  * jQuery plugin 'search_autocomplete'
155  */
156 (function( $ ) {
157         $.fn.search_autocomplete = function(backend_url) {
158                 // Autocomplete contacts
159                 contacts = {
160                         match: /(^@)([^\n]{2,})$/,
161                         index: 2,
162                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'contact'); },
163                         replace: basic_replace,
164                         template: contact_format,
165                 };
166
167                 // Autocomplete forum accounts
168                 community = {
169                         match: /(^!)([^\n]{2,})$/,
170                         index: 2,
171                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'community'); },
172                         replace: basic_replace,
173                         template: contact_format,
174                 };
175                 this.attr('autocomplete', 'off');
176                 var a = this.textcomplete([contacts, community], {className:'acpopup', maxCount:100, zIndex: 1020, appendTo:'#nav-search-box'});
177                 a.on('textComplete:select', function(e, value, strategy) { submit_form(this); });
178         };
179 })( jQuery );
180
181 (function( $ ) {
182         $.fn.contact_autocomplete = function(backend_url, typ, autosubmit, onselect) {
183                 if(typeof typ === 'undefined') typ = '';
184                 if(typeof autosubmit === 'undefined') autosubmit = false;
185
186                 // Autocomplete contacts
187                 contacts = {
188                         match: /(^)([^\n]+)$/,
189                         index: 2,
190                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
191                         replace: basic_replace,
192                         template: contact_format,
193                 };
194
195                 this.attr('autocomplete','off');
196                 var a = this.textcomplete([contacts], {className:'acpopup', zIndex:1020});
197
198                 if(autosubmit)
199                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
200
201                 if(typeof onselect !== 'undefined')
202                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
203         };
204 })( jQuery );
205
206
207 (function( $ ) {
208         $.fn.name_autocomplete = function(backend_url, typ, autosubmit, onselect) {
209                 if(typeof typ === 'undefined') typ = '';
210                 if(typeof autosubmit === 'undefined') autosubmit = false;
211
212                 // Autocomplete contacts
213                 names = {
214                         match: /(^)([^\n]+)$/,
215                         index: 2,
216                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
217                         replace: trim_replace,
218                         template: contact_format,
219                 };
220
221                 this.attr('autocomplete','off');
222                 var a = this.textcomplete([names], {className:'acpopup', zIndex:1020});
223
224                 if(autosubmit)
225                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
226
227                 if(typeof onselect !== 'undefined')
228                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
229         };
230 })( jQuery );
231
232
233 /**
234  * Friendica people autocomplete legacy
235  * code which is needed for tinymce
236  *
237  * require jQuery, jquery.textareas
238  */
239
240 function ACPopup(elm,backend_url){
241         this.idsel=-1;
242         this.element = elm;
243         this.searchText="";
244         this.ready=true;
245         this.kp_timer = false;
246         this.url = backend_url;
247
248         this.conversation_id = null;
249         var conv_id = this.element.id.match(/\d+$/);
250         if (conv_id) this.conversation_id = conv_id[0];
251         console.log("ACPopup elm id",this.element.id,"conversation",this.conversation_id);
252
253         var w = 530;
254         var h = 130;
255
256
257         if(tinyMCE.activeEditor == null) {
258                 style = $(elm).offset();
259                 w = $(elm).width();
260                 h = $(elm).height();
261         }
262         else {
263                 // I can't find an "official" way to get the element who get all
264                 // this fraking thing that is tinyMCE.
265                 // This code will broke again at some point...
266                 var container = $(tinyMCE.activeEditor.getContainer()).find("table");
267                 style = $(container).offset();
268                 w = $(container).width();
269                 h = $(container).height();
270         }
271
272         style.top=style.top+h;
273         style.width = w;
274         style.position = 'absolute';
275         /*      style['max-height'] = '150px';
276                 style.border = '1px solid red';
277                 style.background = '#cccccc';
278
279                 style.overflow = 'auto';
280                 style['z-index'] = '100000';
281         */
282         style.display = 'none';
283
284         this.cont = $("<div class='acpopup-mce'></div>");
285         this.cont.css(style);
286
287         $("body").append(this.cont);
288     }
289
290 ACPopup.prototype.close = function(){
291         $(this.cont).remove();
292         this.ready=false;
293 }
294 ACPopup.prototype.search = function(text){
295         var that = this;
296         this.searchText=text;
297         if (this.kp_timer) clearTimeout(this.kp_timer);
298         this.kp_timer = setTimeout( function(){that._search();}, 500);
299 }
300
301 ACPopup.prototype._search = function(){
302         console.log("_search");
303         var that = this;
304         var postdata = {
305                 start:0,
306                 count:100,
307                 search:this.searchText,
308                 type:'c',
309                 conversation: this.conversation_id,
310         }
311
312         $.ajax({
313                 type:'POST',
314                 url: this.url,
315                 data: postdata,
316                 dataType: 'json',
317                 success:function(data){
318                         that.cont.html("");
319                         if (data.tot>0){
320                                 that.cont.show();
321                                 $(data.items).each(function(){
322                                         var html = "<img src='{0}' height='16px' width='16px'>{1} ({2})".format(this.photo, this.name, this.nick);
323                                         var nick = this.nick.replace(' ','');
324                                         if (this.id!=='')  nick += '+' + this.id;
325                                         that.add(html, nick + ' - ' + this.link);
326                                 });
327                         } else {
328                                 that.cont.hide();
329                         }
330                 }
331         });
332
333 }
334
335 ACPopup.prototype.add = function(label, value){
336         var that=this;
337         var elm = $("<div class='acpopupitem' title='"+value+"'>"+label+"</div>");
338         elm.click(function(e){
339                 t = $(this).attr('title').replace(new RegExp(' \- .*'),'');
340                 if(typeof(that.element.container) === "undefined") {
341                         el=$(that.element);
342                         sel = el.getSelection();
343                         sel.start = sel.start- that.searchText.length;
344                         el.setSelection(sel.start,sel.end).replaceSelectedText(t+' ').collapseSelection(false);
345                         that.close();
346                 }
347                 else {
348                         txt = tinyMCE.activeEditor.getContent();
349                         //                      alert(that.searchText + ':' + t);
350                         newtxt = txt.replace('@' + that.searchText,'@' + t +' ');
351                         tinyMCE.activeEditor.setContent(newtxt);
352                         tinyMCE.activeEditor.focus();
353                         that.close();
354                 }
355         });
356         $(this.cont).append(elm);
357 }
358
359 ACPopup.prototype.onkey = function(event){
360         if (event.keyCode == '13') {
361                 if(this.idsel>-1) {
362                         this.cont.children()[this.idsel].click();
363                         event.preventDefault();
364                 }
365                 else
366                         this.close();
367         }
368         if (event.keyCode == '38') { //cursor up
369                 cmax = this.cont.children().size()-1;
370                 this.idsel--;
371                 if (this.idsel<0) this.idsel=cmax;
372                 event.preventDefault();
373         }
374         if (event.keyCode == '40' || event.keyCode == '9') { //cursor down
375                 cmax = this.cont.children().size()-1;
376                 this.idsel++;
377                 if (this.idsel>cmax) this.idsel=0;
378                 event.preventDefault();
379         }
380
381         if (event.keyCode == '38' || event.keyCode == '40' || event.keyCode == '9') {
382                 this.cont.children().removeClass('selected');
383                 $(this.cont.children()[this.idsel]).addClass('selected');
384         }
385
386         if (event.keyCode == '27') { //ESC
387                 this.close();
388         }
389 }
390