]> git.mxchange.org Git - friendica.git/blob - view/js/autocomplete.js
Add EOF EOL to view/global.css
[friendica.git] / view / js / autocomplete.js
1 // @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt Expat
2 /**
3  * @brief Friendica people autocomplete
4  *
5  * require jQuery, jquery.textcomplete
6  *
7  * for further documentation look at:
8  * http://yuku-t.com/jquery-textcomplete/
9  *
10  * https://github.com/yuku-t/jquery-textcomplete/blob/master/doc/how_to_use.md
11  */
12
13
14 function contact_search(term, callback, backend_url, type, mode) {
15
16         // Check if there is a conversation id to include the unkonwn contacts of the conversation
17         var conv_id = document.activeElement.id.match(/\d+$/);
18
19         // Check if there is a cached result that contains the same information we would get with a full server-side search
20         var bt = backend_url+type;
21         if(!(bt in contact_search.cache)) contact_search.cache[bt] = {};
22
23         var lterm = term.toLowerCase(); // Ignore case
24         for(var t in contact_search.cache[bt]) {
25                 if(lterm.indexOf(t) >= 0) { // A more broad search has been performed already, so use those results
26                         // Filter old results locally
27                         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
28                         matching.unshift({forum:false, text: term, replace: term});
29                         setTimeout(function() { callback(matching); } , 1); // Use "pseudo-thread" to avoid some problems
30                         return;
31                 }
32         }
33
34         var postdata = {
35                 start:0,
36                 count:100,
37                 search:term,
38                 type:type,
39         };
40
41         if(conv_id !== null)
42                 postdata['conversation'] = conv_id[0];
43
44         if(mode !== null)
45                 postdata['smode'] = mode;
46
47
48         $.ajax({
49                 type:'POST',
50                 url: backend_url,
51                 data: postdata,
52                 dataType: 'json',
53                 success: function(data){
54                         // Cache results if we got them all (more information would not improve results)
55                         // data.count represents the maximum number of items
56                         if(data.items.length -1 < data.count) {
57                                 contact_search.cache[bt][lterm] = data.items;
58                         }
59                         var items = data.items.slice(0);
60                         items.unshift({taggable:false, text: term, replace: term});
61                         callback(items);
62                 },
63         }).fail(function () {callback([]); }); // Callback must be invoked even if something went wrong.
64 }
65 contact_search.cache = {};
66
67
68 function contact_format(item) {
69         // Show contact information if not explicitly told to show something else
70         if(typeof item.text === 'undefined') {
71                 var desc = ((item.label) ? item.nick + ' ' + item.label : item.nick);
72                 var forum = ((item.forum) ? 'forum' : '');
73                 if(typeof desc === 'undefined') desc = '';
74                 if(desc) desc = ' ('+desc+')';
75                 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);
76         }
77         else
78                 return "<div>" + item.text + "</div>";
79 }
80
81 function tag_format(item) {
82         return "<div class='dropdown-item'>" + '#' + item.text + "</div>";
83 }
84
85 function editor_replace(item) {
86         if (typeof item.replace !== 'undefined') {
87                 return '$1$2' + item.replace;
88         }
89
90         if (typeof item.addr !== 'undefined') {
91                 return '$1$2' + item.addr + ' ';
92         }
93
94         // $2 ensures that prefix (@,@!) is preserved
95         var id = item.id;
96
97         // don't add the id if it is empty (the id empty eg. if there are unknow contacts in thread)
98         if (id.length < 1) {
99                 return '$1$2' + item.nick.replace(' ', '') + ' ';
100         }
101         // 16 chars of hash should be enough. Full hash could be used if it can be done in a visually appealing way.
102         // 16 chars is also the minimum length in the backend (otherwise it's interpreted as a local id).
103         if (id.length > 16) {
104                 id = item.id.substring(0,16);
105         }
106         return '$1$2' + item.nick.replace(' ', '') + '+' + id + ' ';
107 }
108
109 function basic_replace(item) {
110         if(typeof item.replace !== 'undefined')
111                 return '$1'+item.replace;
112
113         return '$1'+item.name+' ';
114 }
115
116 function webbie_replace(item) {
117         if(typeof item.replace !== 'undefined')
118                 return '$1'+item.replace;
119
120         return '$1'+item.nick+' ';
121 }
122
123 function trim_replace(item) {
124         if(typeof item.replace !== 'undefined')
125                 return '$1'+item.replace;
126
127         return '$1'+item.name;
128 }
129
130
131 function submit_form(e) {
132         $(e).parents('form').submit();
133 }
134
135 function getWord(text, caretPos) {
136         var index = text.indexOf(caretPos);
137         var postText = text.substring(caretPos, caretPos+8);
138         if ((postText.indexOf("[/list]") > 0) || postText.indexOf("[/ul]") > 0 || postText.indexOf("[/ol]") > 0) {
139                 return postText;
140         }
141 }
142
143 function getCaretPosition(ctrl) {
144         var CaretPos = 0;   // IE Support
145         if (document.selection) {
146                 ctrl.focus();
147                 var Sel = document.selection.createRange();
148                 Sel.moveStart('character', -ctrl.value.length);
149                 CaretPos = Sel.text.length;
150         }
151         // Firefox support
152         else if (ctrl.selectionStart || ctrl.selectionStart == '0')
153                 CaretPos = ctrl.selectionStart;
154         return (CaretPos);
155 }
156
157 function setCaretPosition(ctrl, pos){
158         if(ctrl.setSelectionRange) {
159                 ctrl.focus();
160                 ctrl.setSelectionRange(pos,pos);
161         }
162         else if (ctrl.createTextRange) {
163                 var range = ctrl.createTextRange();
164                 range.collapse(true);
165                 range.moveEnd('character', pos);
166                 range.moveStart('character', pos);
167                 range.select();
168         }
169 }
170
171 function listNewLineAutocomplete(id) {
172         var text = document.getElementById(id);
173         var caretPos = getCaretPosition(text)
174         var word = getWord(text.value, caretPos);
175         if (word != null) {
176                 var textBefore = text.value.substring(0, caretPos);
177                 var textAfter  = text.value.substring(caretPos, text.length);
178                 $('#' + id).val(textBefore + '\r\n[*] ' + textAfter).trigger('change');
179                 setCaretPosition(text, caretPos + 5);
180                 return true;
181         }
182         else {
183                 return false;
184         }
185 }
186
187 function string2bb(element) {
188         if(element == 'bold') return 'b';
189         else if(element == 'italic') return 'i';
190         else if(element == 'underline') return 'u';
191         else if(element == 'overline') return 'o';
192         else if(element == 'strike') return 's';
193         else return element;
194 }
195
196 /**
197  * jQuery plugin 'editor_autocomplete'
198  */
199 (function( $ ) {
200         $.fn.editor_autocomplete = function(backend_url) {
201
202                 // Autocomplete contacts
203                 contacts = {
204                         match: /(^|\s)(@\!*)([^ \n]+)$/,
205                         index: 3,
206                         search: function(term, callback) { contact_search(term, callback, backend_url, 'c'); },
207                         replace: editor_replace,
208                         template: contact_format,
209                 };
210
211                 // Autocomplete forums
212                 forums = {
213                         match: /(^|\s)(!\!*)([^ \n]+)$/,
214                         index: 3,
215                         search: function(term, callback) { contact_search(term, callback, backend_url, 'f'); },
216                         replace: editor_replace,
217                         template: contact_format,
218                 };
219
220                 // Autocomplete hashtags
221                 tags = {
222                         match: /(^|\s)(\#)([^ \n]{2,})$/,
223                         index: 3,
224                         search: function(term, callback) {
225                                 $.getJSON(baseurl + '/hashtag/' + '?f=&t=' + term)
226                                 .done(function(data) {
227                                         callback($.map(data, function(entry) {
228                                                 // .toLowerCase() enables case-insensitive search
229                                                 return entry.text.toLowerCase().indexOf(term.toLowerCase()) === 0 ? entry : null;
230                                         }));
231                                 });
232                         },
233                         replace: function(item) { return "$1$2" + item.text + ' '; },
234                         template: tag_format
235                 };
236
237                 // Autocomplete smilies e.g. ":like"
238                 smilies = {
239                         match: /(^|\s)(:[a-z]{2,})$/,
240                         index: 2,
241                         search: function(term, callback) { $.getJSON('smilies/json').done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
242                         template: function(item) { return item.icon + ' ' + item.text; },
243                         replace: function(item) { return "$1" + item.text + ' '; },
244                 };
245
246                 this.attr('autocomplete','off');
247                 this.textcomplete([contacts, forums, smilies, tags], {className:'acpopup', zIndex:10000});
248         };
249 })( jQuery );
250
251 /**
252  * jQuery plugin 'search_autocomplete'
253  */
254 (function( $ ) {
255         $.fn.search_autocomplete = function(backend_url) {
256                 // Autocomplete contacts
257                 contacts = {
258                         match: /(^@)([^\n]{2,})$/,
259                         index: 2,
260                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'contact'); },
261                         replace: webbie_replace,
262                         template: contact_format,
263                 };
264
265                 // Autocomplete forum accounts
266                 community = {
267                         match: /(^!)([^\n]{2,})$/,
268                         index: 2,
269                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'community'); },
270                         replace: webbie_replace,
271                         template: contact_format,
272                 };
273
274                 // Autocomplete hashtags
275                 tags = {
276                         match: /(^|\s)(\#)([^ \n]{2,})$/,
277                         index: 3,
278                         search: function(term, callback) { $.getJSON(baseurl + '/hashtag/' + '?f=&t=' + term).done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
279                         replace: function(item) { return "$1$2" + item.text; },
280                         template: tag_format
281                 };
282
283                 this.attr('autocomplete', 'off');
284                 var a = this.textcomplete([contacts, community, tags], {className:'acpopup', maxCount:100, zIndex: 10000, appendTo:'nav'});
285                 a.on('textComplete:select', function(e, value, strategy) { submit_form(this); });
286         };
287 })( jQuery );
288
289 (function( $ ) {
290         $.fn.contact_autocomplete = function(backend_url, typ, autosubmit, onselect) {
291                 if(typeof typ === 'undefined') typ = '';
292                 if(typeof autosubmit === 'undefined') autosubmit = false;
293
294                 // Autocomplete contacts
295                 contacts = {
296                         match: /(^)([^\n]+)$/,
297                         index: 2,
298                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
299                         replace: basic_replace,
300                         template: contact_format,
301                 };
302
303                 this.attr('autocomplete','off');
304                 var a = this.textcomplete([contacts], {className:'acpopup', zIndex:10000});
305
306                 if(autosubmit)
307                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
308
309                 if(typeof onselect !== 'undefined')
310                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
311         };
312 })( jQuery );
313
314
315 (function( $ ) {
316         $.fn.name_autocomplete = function(backend_url, typ, autosubmit, onselect) {
317                 if(typeof typ === 'undefined') typ = '';
318                 if(typeof autosubmit === 'undefined') autosubmit = false;
319
320                 // Autocomplete contacts
321                 names = {
322                         match: /(^)([^\n]+)$/,
323                         index: 2,
324                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
325                         replace: trim_replace,
326                         template: contact_format,
327                 };
328
329                 this.attr('autocomplete','off');
330                 var a = this.textcomplete([names], {className:'acpopup', zIndex:10000});
331
332                 if(autosubmit)
333                         a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
334
335                 if(typeof onselect !== 'undefined')
336                         a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
337         };
338 })( jQuery );
339
340 (function( $ ) {
341         $.fn.bbco_autocomplete = function(type) {
342
343                 if(type=='bbcode') {
344                         var open_close_elements = ['bold', 'italic', 'underline', 'overline', 'strike', 'quote', 'code', 'spoiler', 'map', 'img', 'url', 'audio', 'video', 'embed', 'youtube', 'vimeo', 'list', 'ul', 'ol', 'li', 'table', 'tr', 'th', 'td', 'center', 'color', 'font', 'size', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'nobb', 'noparse', 'pre', 'abstract'];
345                         var open_elements = ['*', 'hr'];
346
347                         var elements = open_close_elements.concat(open_elements);
348                 }
349
350                 bbco = {
351                         match: /\[(\w*\**)$/,
352                         search: function (term, callback) {
353                                 callback($.map(elements, function (element) {
354                                         return element.indexOf(term) === 0 ? element : null;
355                                 }));
356                         },
357                         index: 1,
358                         replace: function (element) {
359                                 element = string2bb(element);
360                                 if(open_elements.indexOf(element) < 0) {
361                                         if(element === 'list' || element === 'ol' || element === 'ul') {
362                                                 return ['\[' + element + '\]' + '\n\[*\] ', '\n\[/' + element + '\]'];
363                                         }
364                                         else if(element === 'table') {
365                                                 return ['\[' + element + '\]' + '\n\[tr\]', '\[/tr\]\n\[/' + element + '\]'];
366                                         }
367                                         else {
368                                                 return ['\[' + element + '\]', '\[/' + element + '\]'];
369                                         }
370                                 }
371                                 else {
372                                         return '\[' + element + '\] ';
373                                 }
374                         }
375                 };
376
377                 this.attr('autocomplete','off');
378                 var a = this.textcomplete([bbco], {className:'acpopup', zIndex:10000});
379
380                 a.on('textComplete:select', function(e, value, strategy) { value; });
381
382                 a.keypress(function(e){
383                         if (e.keyCode == 13) {
384                                 var x = listNewLineAutocomplete(this.id);
385                                 if(x) {
386                                         e.stopImmediatePropagation();
387                                         e.preventDefault();
388                                 }
389                         }
390                 });
391         };
392 })( jQuery );
393
394 /**
395  * Friendica people autocomplete legacy code
396  *
397  * require jQuery, jquery.textareas
398  */
399 function ACPopup(elm, backend_url){
400         this.idsel = -1;
401         this.element = elm;
402         this.searchText = '';
403         this.ready = true;
404         this.kp_timer = false;
405         this.url = backend_url;
406
407         this.conversation_id = null;
408         var conv_id = this.element.id.match(/\d+$/);
409         if (conv_id) {
410                 this.conversation_id = conv_id[0];
411         }
412
413         var w = $(elm).width();
414         var h = $(elm).height();
415
416         var style = $(elm).offset();
417         style.top = style.top + h;
418         style.width = w;
419         style.position = 'absolute';
420         style.display = 'none';
421
422         this.cont = $('<div class="acpopup-mce"></div>');
423         this.cont.css(style);
424
425         $('body').append(this.cont);
426 }
427
428 ACPopup.prototype.close = function(){
429         $(this.cont).remove();
430         this.ready=false;
431 }
432 ACPopup.prototype.search = function(text){
433         var that = this;
434         this.searchText=text;
435         if (this.kp_timer) clearTimeout(this.kp_timer);
436         this.kp_timer = setTimeout( function(){that._search();}, 500);
437 }
438
439 ACPopup.prototype._search = function(){
440         console.log("_search");
441         var that = this;
442         var postdata = {
443                 start:0,
444                 count:100,
445                 search:this.searchText,
446                 type:'c',
447                 conversation: this.conversation_id,
448         }
449
450         $.ajax({
451                 type:'POST',
452                 url: this.url,
453                 data: postdata,
454                 dataType: 'json',
455                 success:function(data){
456                         that.cont.html("");
457                         if (data.tot>0){
458                                 that.cont.show();
459                                 $(data.items).each(function(){
460                                         var html = "<img src='{0}' height='16px' width='16px'>{1} ({2})".format(this.photo, this.name, this.nick);
461                                         var nick = this.nick.replace(' ','');
462                                         if (this.id!=='')  nick += '+' + this.id;
463                                         that.add(html, nick + ' - ' + this.link);
464                                 });
465                         } else {
466                                 that.cont.hide();
467                         }
468                 }
469         });
470
471 }
472
473 ACPopup.prototype.add = function(label, value){
474         var that = this;
475         var elm = $('<div class="acpopupitem" title="' + value + '">' + label + '</div>');
476         elm.click(function(e){
477                 t = $(this).attr('title').replace(new RegExp(' \- .*'), '');
478                 el = $(that.element);
479                 sel = el.getSelection();
480                 sel.start = sel.start - that.searchText.length;
481                 el.setSelection(sel.start, sel.end).replaceSelectedText(t + ' ').collapseSelection(false);
482                 that.close();
483         });
484         $(this.cont).append(elm);
485 }
486
487 ACPopup.prototype.onkey = function(event){
488         if (event.keyCode == '13') {
489                 if(this.idsel > -1) {
490                         this.cont.children()[this.idsel].click();
491                         event.preventDefault();
492                 } else {
493                         this.close();
494                 }
495         }
496         if (event.keyCode == '38') { //cursor up
497                 var cmax = this.cont.children().size() - 1;
498                 this.idsel--;
499                 if (this.idsel < 0) {
500                         this.idsel = cmax;
501                 }
502                 event.preventDefault();
503         }
504         if (event.keyCode == '40' || event.keyCode == '9') { //cursor down
505                 var cmax = this.cont.children().size() - 1;
506                 this.idsel++;
507                 if (this.idsel > cmax) {
508                         this.idsel = 0;
509                 }
510                 event.preventDefault();
511         }
512
513         if (event.keyCode == '38' || event.keyCode == '40' || event.keyCode == '9') {
514                 this.cont.children().removeClass('selected');
515                 $(this.cont.children()[this.idsel]).addClass('selected');
516         }
517
518         if (event.keyCode == '27') { //ESC
519                 this.close();
520         }
521 }
522 // @license-end