autocomplete.go.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /** Init for Autocomplete (requires jquery-ui)
  2. *
  3. * @package Plugin
  4. * @author Mikael Nordfeldth <mmn@hethane.se>
  5. * @copyright 2013 Free Software Foundation, Inc.
  6. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  7. * @link http://status.net/
  8. */
  9. var origInit = SN.Init.NoticeFormSetup;
  10. SN.Init.NoticeFormSetup = function(form) {
  11. origInit(form);
  12. // Only attach to traditional-style forms
  13. var textarea = form.find('.notice_data-text:first');
  14. if (textarea.length == 0) {
  15. return;
  16. }
  17. function termSplit(val) {
  18. return val.split(/ \s*/);
  19. }
  20. function extractLast( term ) {
  21. return termSplit(term).pop();
  22. }
  23. var apiUrl = $('#autocomplete-api').attr('data-url');
  24. // migrated "multiple" and "multipleSeparator" from
  25. // http://www.learningjquery.com/2010/06/autocomplete-migration-guide
  26. textarea
  27. .bind('keydown', function( event ) {
  28. if ( event.keyCode === $.ui.keyCode.TAB &&
  29. $( this ).data( "ui-autocomplete" ).menu.active ) {
  30. event.preventDefault();
  31. }
  32. })
  33. .autocomplete({
  34. minLength: 1, // 1 is default
  35. source: function (request, response) {
  36. $.getJSON( apiUrl, {
  37. term: extractLast(request.term)
  38. }, response );
  39. },
  40. search: function () {
  41. // custom minLength, we though we match the 1 below
  42. var term = extractLast(this.value);
  43. if (term.length <= 1) {
  44. return false;
  45. }
  46. },
  47. focus: function () {
  48. // prevent value inserted on focus
  49. return false;
  50. },
  51. select: function (event, ui) {
  52. var terms = termSplit(this.value);
  53. terms.pop(); // remove latest term
  54. terms.push(ui.item.value); // insert
  55. terms.push(''); // empty element, for the join()
  56. this.value = terms.join(' ');
  57. return false;
  58. },
  59. })
  60. .data('ui-autocomplete')._renderItem = function (ul, item) {
  61. return $('<li></li>')
  62. .data('ui-autocomplete-item', item)
  63. .append('<a><img style="display:inline; vertical-align: middle"><span /></a>')
  64. .find('img').attr('src', item.avatar).end()
  65. .find('span').text(item.label).end()
  66. .appendTo(ul);
  67. };
  68. };