2 * @brief Friendica people autocomplete
4 * require jQuery, jquery.textcomplete
6 * for further documentation look at:
7 * http://yuku-t.com/jquery-textcomplete/
9 * https://github.com/yuku-t/jquery-textcomplete/blob/master/doc/how_to_use.md
13 function contact_search(term, callback, backend_url, type, mode) {
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+$/);
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] = {};
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
41 postdata['conversation'] = conv_id[0];
44 postdata['mode'] = mode;
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;
58 var items = data.items.slice(0);
59 items.unshift({taggable:false, text: term, replace: term});
62 }).fail(function () {callback([]); }); // Callback must be invoked even if something went wrong.
64 contact_search.cache = {};
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);
77 return "<div>" + item.text + "</div>";
80 function editor_replace(item) {
81 if(typeof item.replace !== 'undefined') {
82 return '$1$2' + item.replace;
85 // $2 ensures that prefix (@,@!) is preserved
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).
90 id = item.id.substring(0,16);
92 return '$1$2' + item.nick.replace(' ', '') + '+' + id + ' ';
95 function basic_replace(item) {
96 if(typeof item.replace !== 'undefined')
97 return '$1'+item.replace;
99 return '$1'+item.name+' ';
102 function trim_replace(item) {
103 if(typeof item.replace !== 'undefined')
104 return '$1'+item.replace;
106 return '$1'+item.name;
110 function submit_form(e) {
111 $(e).parents('form').submit();
114 function getWord(text, caretPos) {
115 var index = text.indexOf(caretPos);
116 var postText = text.substring(caretPos, caretPos+8);
117 if ((postText.indexOf("[/list]") > 0) || postText.indexOf("[/ul]") > 0 || postText.indexOf("[/ol]") > 0) {
122 function getCaretPosition(ctrl) {
123 var CaretPos = 0; // IE Support
124 if (document.selection) {
126 var Sel = document.selection.createRange();
127 Sel.moveStart('character', -ctrl.value.length);
128 CaretPos = Sel.text.length;
131 else if (ctrl.selectionStart || ctrl.selectionStart == '0')
132 CaretPos = ctrl.selectionStart;
136 function setCaretPosition(ctrl, pos){
137 if(ctrl.setSelectionRange) {
139 ctrl.setSelectionRange(pos,pos);
141 else if (ctrl.createTextRange) {
142 var range = ctrl.createTextRange();
143 range.collapse(true);
144 range.moveEnd('character', pos);
145 range.moveStart('character', pos);
150 function listNewLineAutocomplete(id) {
151 var text = document.getElementById(id);
152 var caretPos = getCaretPosition(text)
153 var word = getWord(text.value, caretPos);
155 var textBefore = text.value.substring(0, caretPos);
156 var textAfter = text.value.substring(caretPos, text.length);
157 $('#' + id).val(textBefore + '\r\n[*] ' + textAfter);
158 setCaretPosition(text, caretPos + 5);
163 function string2bb(element) {
164 if(element == 'bold') return 'b';
165 else if(element == 'italic') return 'i';
166 else if(element == 'underline') return 'u';
167 else if(element == 'overline') return 'o';
168 else if(element == 'strike') return 's';
173 * jQuery plugin 'editor_autocomplete'
176 $.fn.editor_autocomplete = function(backend_url) {
178 // Autocomplete contacts
180 match: /(^|\s)(@\!*)([^ \n]+)$/,
182 search: function(term, callback) { contact_search(term, callback, backend_url, 'c'); },
183 replace: editor_replace,
184 template: contact_format,
187 // Autocomplete smilies e.g. ":like"
189 match: /(^|\s)(:[a-z]{2,})$/,
191 search: function(term, callback) { $.getJSON('smilies/json').done(function(data) { callback($.map(data, function(entry) { return entry.text.indexOf(term) === 0 ? entry : null; })); }); },
192 template: function(item) { return item.icon + ' ' + item.text; },
193 replace: function(item) { return "$1" + item.text + ' '; },
196 this.attr('autocomplete','off');
197 this.textcomplete([contacts,smilies], {className:'acpopup', zIndex:10000});
202 * jQuery plugin 'search_autocomplete'
205 $.fn.search_autocomplete = function(backend_url) {
206 // Autocomplete contacts
208 match: /(^@)([^\n]{2,})$/,
210 search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'contact'); },
211 replace: basic_replace,
212 template: contact_format,
215 // Autocomplete forum accounts
217 match: /(^!)([^\n]{2,})$/,
219 search: function(term, callback) { contact_search(term, callback, backend_url, 'x', 'community'); },
220 replace: basic_replace,
221 template: contact_format,
223 this.attr('autocomplete', 'off');
224 var a = this.textcomplete([contacts, community], {className:'acpopup', maxCount:100, zIndex: 10000, appendTo:'nav'});
225 a.on('textComplete:select', function(e, value, strategy) { submit_form(this); });
230 $.fn.contact_autocomplete = function(backend_url, typ, autosubmit, onselect) {
231 if(typeof typ === 'undefined') typ = '';
232 if(typeof autosubmit === 'undefined') autosubmit = false;
234 // Autocomplete contacts
236 match: /(^)([^\n]+)$/,
238 search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
239 replace: basic_replace,
240 template: contact_format,
243 this.attr('autocomplete','off');
244 var a = this.textcomplete([contacts], {className:'acpopup', zIndex:10000});
247 a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
249 if(typeof onselect !== 'undefined')
250 a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
256 $.fn.name_autocomplete = function(backend_url, typ, autosubmit, onselect) {
257 if(typeof typ === 'undefined') typ = '';
258 if(typeof autosubmit === 'undefined') autosubmit = false;
260 // Autocomplete contacts
262 match: /(^)([^\n]+)$/,
264 search: function(term, callback) { contact_search(term, callback, backend_url, typ); },
265 replace: trim_replace,
266 template: contact_format,
269 this.attr('autocomplete','off');
270 var a = this.textcomplete([names], {className:'acpopup', zIndex:10000});
273 a.on('textComplete:select', function(e,value,strategy) { submit_form(this); });
275 if(typeof onselect !== 'undefined')
276 a.on('textComplete:select', function(e, value, strategy) { onselect(value); });
281 $.fn.bbco_autocomplete = function(type) {
284 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'];
285 var open_elements = ['*', 'hr'];
287 var elements = open_close_elements.concat(open_elements);
291 match: /\[(\w*\**)$/,
292 search: function (term, callback) {
293 callback($.map(elements, function (element) {
294 return element.indexOf(term) === 0 ? element : null;
298 replace: function (element) {
299 element = string2bb(element);
300 if(open_elements.indexOf(element) < 0) {
301 if(element === 'list' || element === 'ol' || element === 'ul') {
302 return ['\[' + element + '\]' + '\n\[*\] ', '\n\[/' + element + '\]'];
304 else if(element === 'table') {
305 return ['\[' + element + '\]' + '\n\[tr\]', '\[/tr\]\n\[/' + element + '\]'];
308 return ['\[' + element + '\]', '\[/' + element + '\]'];
312 return '\[' + element + '\] ';
317 this.attr('autocomplete','off');
318 var a = this.textcomplete([bbco], {className:'acpopup', zIndex:10000});
320 a.on('textComplete:select', function(e, value, strategy) { value; });
322 a.keypress(function(e){
323 e.stopImmediatePropagation();
324 if (e.keyCode == 13) {
325 var x = listNewLineAutocomplete(this.id);
334 * Friendica people autocomplete legacy
335 * code which is needed for tinymce
337 * require jQuery, jquery.textareas
340 function ACPopup(elm,backend_url){
345 this.kp_timer = false;
346 this.url = backend_url;
348 this.conversation_id = null;
349 var conv_id = this.element.id.match(/\d+$/);
350 if (conv_id) this.conversation_id = conv_id[0];
351 console.log("ACPopup elm id",this.element.id,"conversation",this.conversation_id);
357 if(tinyMCE.activeEditor == null) {
358 style = $(elm).offset();
363 // I can't find an "official" way to get the element who get all
364 // this fraking thing that is tinyMCE.
365 // This code will broke again at some point...
366 var container = $(tinyMCE.activeEditor.getContainer()).find("table");
367 style = $(container).offset();
368 w = $(container).width();
369 h = $(container).height();
372 style.top=style.top+h;
374 style.position = 'absolute';
375 /* style['max-height'] = '150px';
376 style.border = '1px solid red';
377 style.background = '#cccccc';
379 style.overflow = 'auto';
380 style['z-index'] = '100000';
382 style.display = 'none';
384 this.cont = $("<div class='acpopup-mce'></div>");
385 this.cont.css(style);
387 $("body").append(this.cont);
390 ACPopup.prototype.close = function(){
391 $(this.cont).remove();
394 ACPopup.prototype.search = function(text){
396 this.searchText=text;
397 if (this.kp_timer) clearTimeout(this.kp_timer);
398 this.kp_timer = setTimeout( function(){that._search();}, 500);
401 ACPopup.prototype._search = function(){
402 console.log("_search");
407 search:this.searchText,
409 conversation: this.conversation_id,
417 success:function(data){
421 $(data.items).each(function(){
422 var html = "<img src='{0}' height='16px' width='16px'>{1} ({2})".format(this.photo, this.name, this.nick);
423 var nick = this.nick.replace(' ','');
424 if (this.id!=='') nick += '+' + this.id;
425 that.add(html, nick + ' - ' + this.link);
435 ACPopup.prototype.add = function(label, value){
437 var elm = $("<div class='acpopupitem' title='"+value+"'>"+label+"</div>");
438 elm.click(function(e){
439 t = $(this).attr('title').replace(new RegExp(' \- .*'),'');
440 if(typeof(that.element.container) === "undefined") {
442 sel = el.getSelection();
443 sel.start = sel.start- that.searchText.length;
444 el.setSelection(sel.start,sel.end).replaceSelectedText(t+' ').collapseSelection(false);
448 txt = tinyMCE.activeEditor.getContent();
449 // alert(that.searchText + ':' + t);
450 newtxt = txt.replace('@' + that.searchText,'@' + t +' ');
451 tinyMCE.activeEditor.setContent(newtxt);
452 tinyMCE.activeEditor.focus();
456 $(this.cont).append(elm);
459 ACPopup.prototype.onkey = function(event){
460 if (event.keyCode == '13') {
462 this.cont.children()[this.idsel].click();
463 event.preventDefault();
468 if (event.keyCode == '38') { //cursor up
469 cmax = this.cont.children().size()-1;
471 if (this.idsel<0) this.idsel=cmax;
472 event.preventDefault();
474 if (event.keyCode == '40' || event.keyCode == '9') { //cursor down
475 cmax = this.cont.children().size()-1;
477 if (this.idsel>cmax) this.idsel=0;
478 event.preventDefault();
481 if (event.keyCode == '38' || event.keyCode == '40' || event.keyCode == '9') {
482 this.cont.children().removeClass('selected');
483 $(this.cont.children()[this.idsel]).addClass('selected');
486 if (event.keyCode == '27') { //ESC