]> git.mxchange.org Git - friendica.git/blob - view/js/autocomplete.js
Merge pull request #13690 from annando/channel-settings
[friendica.git] / view / js / autocomplete.js
1 // @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt Expat
2 /**
3  * 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 unknown 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 circles don't have one
28                         matching.unshift({group: 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 group = ((item.group) ? 'group' : '');
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(group, 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         let textcompleteObjects = [];
201
202         // jQuery wrapper for yuku/old-textcomplete
203         // uses a local object directory to avoid recreating Textcomplete objects
204         $.fn.textcomplete = function (strategies, options) {
205                 return this.each(function () {
206                         let $this = $(this);
207                         if (!($this.data('textcompleteId') in textcompleteObjects)) {
208                                 let editor = new Textcomplete.editors.Textarea($this.get(0));
209
210                                 $this.data('textcompleteId', textcompleteObjects.length);
211                                 textcompleteObjects.push(new Textcomplete(editor, options));
212                         }
213
214                         textcompleteObjects[$this.data('textcompleteId')].register(strategies);
215                 });
216         };
217
218         /**
219          * This function should be called immediately after $.textcomplete() to prevent the escape key press to propagate
220          * after the autocompletion dropdown has closed.
221          * This avoids the input textarea to lose focus, the modal window to close, etc... when the expected behavior is
222          * to just close the autocomplete dropdown.
223          *
224          * The custom event listener name allows removing this specific event listener, the "real" event this listens to
225          * is the part before the first dot.
226          *
227          * @returns {*}
228          */
229         $.fn.fixTextcompleteEscape = function () {
230                 if (this.data('textcompleteEscapeFixed')) {
231                         return this;
232                 }
233
234                 this.data('textcompleteEscapeFixed', true);
235
236                 return this.on({
237                         'textComplete:show': function (e) {
238                                 $(this).on('keydown.friendica.escape', function (e) {
239                                         if (e.key === 'Escape') {
240                                                 e.stopPropagation();
241                                         }
242                                 });
243                         },
244                         'textComplete:hide': function (e) {
245                                 $(this).off('keydown.friendica.escape');
246                         },
247                 });
248         }
249
250         $.fn.editor_autocomplete = function(backend_url) {
251
252                 // Autocomplete contacts
253                 contacts = {
254                         match: /(^|\s)(@\!*)([^ \n]+)$/,
255                         index: 3,
256                         search: function(term, callback) { contact_search(term, callback, backend_url, 'c'); },
257                         replace: editor_replace,
258                         template: contact_format,
259                 };
260
261                 // Autocomplete groups
262                 groups = {
263                         match: /(^|\s)(!\!*)([^ \n]+)$/,
264                         index: 3,
265                         search: function(term, callback) { contact_search(term, callback, backend_url, 'f'); },
266                         replace: editor_replace,
267                         template: contact_format,
268                 };
269
270                 // Autocomplete hashtags
271                 tags = {
272                         match: /(^|\s)(\#)([^ \n]{2,})$/,
273                         index: 3,
274                         search: function(term, callback) {
275                                 $.getJSON(baseurl + '/hashtag/' + '?t=' + term)
276                                 .done(function(data) {
277                                         callback($.map(data, function(entry) {
278                                                 // .toLowerCase() enables case-insensitive search
279                                                 return entry.text.toLowerCase().indexOf(term.toLowerCase()) === 0 ? entry : null;
280                                         }));
281                                 });
282                         },
283                         replace: function(item) { return "$1$2" + item.text + ' '; },
284                         template: tag_format
285                 };
286
287                 // Autocomplete smilies e.g. ":like"
288                 smilies = {
289                         match: /(^|\s)(:[a-z]{2,})$/,
290                         index: 2,
291                         search: function(term, callback) { $.getJSON('smilies/json').done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
292                         template: function(item) { return item.icon + ' ' + item.text; },
293                         replace: function(item) { return "$1" + item.text + ' '; },
294                 };
295
296                 this.attr('autocomplete','off');
297                 this.textcomplete([contacts, groups, smilies, tags], {dropdown: {className:'acpopup'}});
298                 this.fixTextcompleteEscape();
299
300                 return this;
301         };
302
303         $.fn.search_autocomplete = function(backend_url) {
304                 // Autocomplete contacts
305                 contacts = {
306                         match: /(^@)([^\n]{2,})$/,
307                         index: 2,
308                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'contact'); },
309                         replace: webbie_replace,
310                         template: contact_format,
311                 };
312
313                 // Autocomplete group accounts
314                 community = {
315                         match: /(^!)([^\n]{2,})$/,
316                         index: 2,
317                         search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'community'); },
318                         replace: webbie_replace,
319                         template: contact_format,
320                 };
321
322                 // Autocomplete hashtags
323                 tags = {
324                         match: /(^|\s)(\#)([^ \n]{2,})$/,
325                         index: 3,
326                         search: function(term, callback) { $.getJSON(baseurl + '/hashtag/' + '?t=' + term).done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
327                         replace: function(item) { return "$1$2" + item.text; },
328                         template: tag_format
329                 };
330
331                 this.attr('autocomplete', 'off');
332                 this.textcomplete([contacts, community, tags], {dropdown: {className:'acpopup', maxCount:100}});
333                 this.fixTextcompleteEscape();
334                 this.on('textComplete:select', function(e, value, strategy) { submit_form(this); });
335
336                 return this;
337         };
338
339         $.fn.name_autocomplete = function(backend_url, typ, autosubmit, onselect) {
340                 if(typeof typ === 'undefined') typ = '';
341                 if(typeof autosubmit === 'undefined') autosubmit = false;
342
343                 // Autocomplete contacts
344                 names = {
345                         match: /(^)([^\n]+)$/,
346                         index: 2,
347                         search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
348                         replace: trim_replace,
349                         template: contact_format,
350                 };
351
352                 this.attr('autocomplete','off');
353                 this.textcomplete([names], {dropdown: {className:'acpopup'}});
354                 this.fixTextcompleteEscape();
355
356                 if(autosubmit) {
357                         this.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
358                 }
359
360                 if(typeof onselect !== 'undefined') {
361                         this.on('textComplete:select', function(e, value, strategy) { onselect(value); });
362                 }
363
364                 return this;
365         };
366
367         $.fn.bbco_autocomplete = function(type) {
368                 if (type === 'bbcode') {
369                         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', 'share'];
370                         var open_elements = ['*', 'hr'];
371
372                         var elements = open_close_elements.concat(open_elements);
373                 }
374
375                 bbco = {
376                         match: /\[(\w*\**)$/,
377                         search: function (term, callback) {
378                                 callback($.map(elements, function (element) {
379                                         return element.indexOf(term) === 0 ? element : null;
380                                 }));
381                         },
382                         index: 1,
383                         replace: function (element) {
384                                 element = string2bb(element);
385                                 if(open_elements.indexOf(element) < 0) {
386                                         if(element === 'list' || element === 'ol' || element === 'ul') {
387                                                 return ['\[' + element + '\]' + '\n\[*\] ', '\n\[/' + element + '\]'];
388                                         }
389                                         else if(element === 'table') {
390                                                 return ['\[' + element + '\]' + '\n\[tr\]', '\[/tr\]\n\[/' + element + '\]'];
391                                         }
392                                         else {
393                                                 return ['\[' + element + '\]', '\[/' + element + '\]'];
394                                         }
395                                 }
396                                 else {
397                                         return '\[' + element + '\] ';
398                                 }
399                         }
400                 };
401
402                 this.attr('autocomplete','off');
403                 this.textcomplete([bbco], {dropdown: {className:'acpopup'}});
404                 this.fixTextcompleteEscape();
405
406                 this.on('textComplete:select', function(e, value, strategy) { value; });
407
408                 this.keypress(function(e){
409                         if (e.keyCode == 13) {
410                                 var x = listNewLineAutocomplete(this.id);
411                                 if(x) {
412                                         e.stopImmediatePropagation();
413                                         e.preventDefault();
414                                 }
415                         }
416                 });
417
418                 return this;
419         };
420 })( jQuery );
421 // @license-end