jquery.atwho.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /*
  2. Implement Github like autocomplete mentions
  3. http://ichord.github.com/At.js
  4. Copyright (c) 2013 chord.luo@gmail.com
  5. Licensed under the MIT license.
  6. */
  7. (function() {
  8. var __slice = [].slice;
  9. (function(factory) {
  10. if (typeof define === 'function' && define.amd) {
  11. return define(['jquery'], factory);
  12. } else {
  13. return factory(window.jQuery);
  14. }
  15. })(function($) {
  16. var $CONTAINER, Api, App, Controller, DEFAULT_CALLBACKS, DEFAULT_TPL, KEY_CODE, Model, View;
  17. App = (function() {
  18. function App(inputor) {
  19. this.current_flag = null;
  20. this.controllers = {};
  21. this.$inputor = $(inputor);
  22. this.listen();
  23. }
  24. App.prototype.controller = function(key) {
  25. return this.controllers[key || this.current_flag];
  26. };
  27. App.prototype.set_context_for = function(key) {
  28. this.current_flag = key;
  29. return this;
  30. };
  31. App.prototype.reg = function(flag, setting) {
  32. var controller, _base;
  33. controller = (_base = this.controllers)[flag] || (_base[flag] = new Controller(this, flag));
  34. if (setting.alias) {
  35. this.controllers[setting.alias] = controller;
  36. }
  37. controller.init(setting);
  38. return this;
  39. };
  40. App.prototype.listen = function() {
  41. var _this = this;
  42. return this.$inputor.on('keyup.atwho', function(e) {
  43. return _this.on_keyup(e);
  44. }).on('keydown.atwho', function(e) {
  45. return _this.on_keydown(e);
  46. }).on('scroll.atwho', function(e) {
  47. var _ref;
  48. return (_ref = _this.controller()) != null ? _ref.view.hide() : void 0;
  49. }).on('blur.atwho', function(e) {
  50. var c;
  51. if (c = _this.controller()) {
  52. return c.view.hide(c.get_opt("display_timeout"));
  53. }
  54. });
  55. };
  56. App.prototype.dispatch = function() {
  57. var _this = this;
  58. return $.map(this.controllers, function(c) {
  59. if (c.look_up()) {
  60. return _this.set_context_for(c.key);
  61. }
  62. });
  63. };
  64. App.prototype.on_keyup = function(e) {
  65. var _ref;
  66. switch (e.keyCode) {
  67. case KEY_CODE.ESC:
  68. e.preventDefault();
  69. if ((_ref = this.controller()) != null) {
  70. _ref.view.hide();
  71. }
  72. break;
  73. case KEY_CODE.DOWN:
  74. case KEY_CODE.UP:
  75. $.noop();
  76. break;
  77. default:
  78. this.dispatch();
  79. }
  80. };
  81. App.prototype.on_keydown = function(e) {
  82. var view, _ref;
  83. view = (_ref = this.controller()) != null ? _ref.view : void 0;
  84. if (!(view && view.visible())) {
  85. return;
  86. }
  87. switch (e.keyCode) {
  88. case KEY_CODE.ESC:
  89. e.preventDefault();
  90. view.hide();
  91. break;
  92. case KEY_CODE.UP:
  93. e.preventDefault();
  94. view.prev();
  95. break;
  96. case KEY_CODE.DOWN:
  97. e.preventDefault();
  98. view.next();
  99. break;
  100. case KEY_CODE.TAB:
  101. case KEY_CODE.ENTER:
  102. if (!view.visible()) {
  103. return;
  104. }
  105. e.preventDefault();
  106. view.choose();
  107. break;
  108. default:
  109. $.noop();
  110. }
  111. };
  112. return App;
  113. })();
  114. Controller = (function() {
  115. var uuid, _uuid;
  116. _uuid = 0;
  117. uuid = function() {
  118. return _uuid += 1;
  119. };
  120. function Controller(app, key) {
  121. this.app = app;
  122. this.key = key;
  123. this.$inputor = this.app.$inputor;
  124. this.id = this.$inputor[0].id || uuid();
  125. this.setting = null;
  126. this.query = null;
  127. this.pos = 0;
  128. $CONTAINER.append(this.$el = $("<div id='atwho-ground-" + this.id + "'></div>"));
  129. this.model = new Model(this);
  130. this.view = new View(this);
  131. }
  132. Controller.prototype.init = function(setting) {
  133. this.setting = $.extend({}, this.setting || $.fn.atwho["default"], setting);
  134. return this.model.reload(this.setting.data);
  135. };
  136. Controller.prototype.super_call = function() {
  137. var args, func_name;
  138. func_name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
  139. try {
  140. return DEFAULT_CALLBACKS[func_name].apply(this, args);
  141. } catch (error) {
  142. return $.error("" + error + " Or maybe At.js doesn't have function " + func_name);
  143. }
  144. };
  145. Controller.prototype.trigger = function(name, data) {
  146. var alias, event_name;
  147. data.push(this);
  148. alias = this.get_opt('alias');
  149. event_name = alias ? "" + name + "-" + alias + ".atwho" : "" + name + ".atwho";
  150. return this.$inputor.trigger(event_name, data);
  151. };
  152. Controller.prototype.callbacks = function(func_name) {
  153. return this.get_opt("callbacks")[func_name] || DEFAULT_CALLBACKS[func_name];
  154. };
  155. Controller.prototype.get_opt = function(key, default_value) {
  156. try {
  157. return this.setting[key];
  158. } catch (e) {
  159. return null;
  160. }
  161. };
  162. Controller.prototype.catch_query = function() {
  163. var caret_pos, content, end, query, start, subtext;
  164. content = this.$inputor.val();
  165. caret_pos = this.$inputor.caret('pos');
  166. subtext = content.slice(0, caret_pos);
  167. query = this.callbacks("matcher").call(this, this.key, subtext);
  168. if (typeof query === "string" && query.length <= this.get_opt('max_len', 20)) {
  169. start = caret_pos - query.length;
  170. end = start + query.length;
  171. this.pos = start;
  172. query = {
  173. 'text': query.toLowerCase(),
  174. 'head_pos': start,
  175. 'end_pos': end
  176. };
  177. this.trigger("matched", [this.key, query.text]);
  178. } else {
  179. this.view.hide();
  180. }
  181. return this.query = query;
  182. };
  183. Controller.prototype.rect = function() {
  184. var c, scale_bottom;
  185. c = this.$inputor.caret('offset', this.pos - 1);
  186. scale_bottom = document.selection ? 0 : 2;
  187. return {
  188. left: c.left,
  189. top: c.top,
  190. bottom: c.top + c.height + scale_bottom
  191. };
  192. };
  193. Controller.prototype.insert = function(str) {
  194. var $inputor, flag_len, source, start_str, text;
  195. $inputor = this.$inputor;
  196. str = '' + str;
  197. source = $inputor.val();
  198. flag_len = this.get_opt("display_flag") ? 0 : this.key.length;
  199. start_str = source.slice(0, (this.query['head_pos'] || 0) - flag_len);
  200. text = "" + start_str + str + " " + (source.slice(this.query['end_pos'] || 0));
  201. $inputor.val(text);
  202. $inputor.caret('pos', start_str.length + str.length + 1);
  203. return $inputor.change();
  204. };
  205. Controller.prototype.render_view = function(data) {
  206. var search_key;
  207. search_key = this.get_opt("search_key");
  208. data = this.callbacks("sorter").call(this, this.query.text, data.slice(0, 1001), search_key);
  209. return this.view.render(data.slice(0, this.get_opt('limit')));
  210. };
  211. Controller.prototype.look_up = function() {
  212. var query, _callback;
  213. if (!(query = this.catch_query())) {
  214. return;
  215. }
  216. _callback = function(data) {
  217. if (data && data.length > 0) {
  218. return this.render_view(data);
  219. } else {
  220. return this.view.hide();
  221. }
  222. };
  223. this.model.query(query.text, $.proxy(_callback, this));
  224. return query;
  225. };
  226. return Controller;
  227. })();
  228. Model = (function() {
  229. var _storage;
  230. _storage = {};
  231. function Model(context) {
  232. this.context = context;
  233. this.key = this.context.key;
  234. }
  235. Model.prototype.saved = function() {
  236. return this.fetch() > 0;
  237. };
  238. Model.prototype.query = function(query, callback) {
  239. var data, search_key, _ref;
  240. data = this.fetch();
  241. search_key = this.context.get_opt("search_key");
  242. callback(data = this.context.callbacks('filter').call(this.context, query, data, search_key));
  243. if (!(data && data.length > 0)) {
  244. return (_ref = this.context.callbacks('remote_filter')) != null ? _ref.call(this.context, query, callback) : void 0;
  245. }
  246. };
  247. Model.prototype.fetch = function() {
  248. return _storage[this.key] || [];
  249. };
  250. Model.prototype.save = function(data) {
  251. return _storage[this.key] = this.context.callbacks("before_save").call(this.context, data || []);
  252. };
  253. Model.prototype.load = function(data) {
  254. if (!(this.saved() || !data)) {
  255. return this._load(data);
  256. }
  257. };
  258. Model.prototype.reload = function(data) {
  259. return this._load(data);
  260. };
  261. Model.prototype._load = function(data) {
  262. var _this = this;
  263. if (typeof data === "string") {
  264. return $.ajax(data, {
  265. dataType: "json"
  266. }).done(function(data) {
  267. return _this.save(data);
  268. });
  269. } else {
  270. return this.save(data);
  271. }
  272. };
  273. return Model;
  274. })();
  275. View = (function() {
  276. function View(context) {
  277. this.context = context;
  278. this.key = this.context.key;
  279. this.id = this.context.get_opt("alias") || ("at-view-" + (this.key.charCodeAt(0)));
  280. this.$el = $("<div id='" + this.id + "' class='atwho-view'><ul id='" + this.id + "-ul' class='atwho-view-url'></ul></div>");
  281. this.timeout_id = null;
  282. this.context.$el.append(this.$el);
  283. this.bind_event();
  284. }
  285. View.prototype.bind_event = function() {
  286. var $menu,
  287. _this = this;
  288. $menu = this.$el.find('ul');
  289. return $menu.on('mouseenter.view', 'li', function(e) {
  290. $menu.find('.cur').removeClass('cur');
  291. return $(e.currentTarget).addClass('cur');
  292. }).on('click', function(e) {
  293. _this.choose();
  294. return e.preventDefault();
  295. });
  296. };
  297. View.prototype.visible = function() {
  298. return this.$el.is(":visible");
  299. };
  300. View.prototype.choose = function() {
  301. var $li;
  302. $li = this.$el.find(".cur");
  303. this.context.insert(this.context.callbacks("before_insert").call(this.context, $li.data("value"), $li));
  304. this.context.trigger("inserted", [$li]);
  305. return this.hide();
  306. };
  307. View.prototype.reposition = function() {
  308. var offset, rect;
  309. rect = this.context.rect();
  310. if (rect.bottom + this.$el.height() - $(window).scrollTop() > $(window).height()) {
  311. rect.bottom = rect.top - this.$el.height();
  312. }
  313. offset = {
  314. left: rect.left,
  315. top: rect.bottom
  316. };
  317. this.$el.offset(offset);
  318. return this.context.trigger("reposition", [offset]);
  319. };
  320. View.prototype.next = function() {
  321. var cur, next;
  322. cur = this.$el.find('.cur').removeClass('cur');
  323. next = cur.next();
  324. if (!next.length) {
  325. next = this.$el.find('li:first');
  326. }
  327. return next.addClass('cur');
  328. };
  329. View.prototype.prev = function() {
  330. var cur, prev;
  331. cur = this.$el.find('.cur').removeClass('cur');
  332. prev = cur.prev();
  333. if (!prev.length) {
  334. prev = this.$el.find('li:last');
  335. }
  336. return prev.addClass('cur');
  337. };
  338. View.prototype.show = function() {
  339. if (!this.visible()) {
  340. this.$el.show();
  341. }
  342. return this.reposition();
  343. };
  344. View.prototype.hide = function(time) {
  345. var callback,
  346. _this = this;
  347. if (isNaN(time && this.visible())) {
  348. return this.$el.hide();
  349. } else {
  350. callback = function() {
  351. return _this.hide();
  352. };
  353. clearTimeout(this.timeout_id);
  354. return this.timeout_id = setTimeout(callback, time);
  355. }
  356. };
  357. View.prototype.render = function(list) {
  358. var $li, $ul, item, li, tpl, _i, _len;
  359. if (!$.isArray(list || list.length <= 0)) {
  360. this.hide();
  361. return;
  362. }
  363. this.$el.find('ul').empty();
  364. $ul = this.$el.find('ul');
  365. tpl = this.context.get_opt('tpl', DEFAULT_TPL);
  366. for (_i = 0, _len = list.length; _i < _len; _i++) {
  367. item = list[_i];
  368. li = this.context.callbacks("tpl_eval").call(this.context, tpl, item);
  369. $li = $(this.context.callbacks("highlighter").call(this.context, li, this.context.query.text));
  370. $li.data("atwho-info", item);
  371. $ul.append($li);
  372. }
  373. this.show();
  374. return $ul.find("li:first").addClass("cur");
  375. };
  376. return View;
  377. })();
  378. KEY_CODE = {
  379. DOWN: 40,
  380. UP: 38,
  381. ESC: 27,
  382. TAB: 9,
  383. ENTER: 13
  384. };
  385. DEFAULT_CALLBACKS = {
  386. before_save: function(data) {
  387. var item, _i, _len, _results;
  388. if (!$.isArray(data)) {
  389. return data;
  390. }
  391. _results = [];
  392. for (_i = 0, _len = data.length; _i < _len; _i++) {
  393. item = data[_i];
  394. if ($.isPlainObject(item)) {
  395. _results.push(item);
  396. } else {
  397. _results.push({
  398. name: item
  399. });
  400. }
  401. }
  402. return _results;
  403. },
  404. matcher: function(flag, subtext) {
  405. var match, regexp;
  406. flag = '(?:^|\\s)' + flag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  407. regexp = new RegExp(flag + '([A-Za-z0-9_\+\-]*)$|' + flag + '([^\\x00-\\xff]*)$', 'gi');
  408. match = regexp.exec(subtext);
  409. if (match) {
  410. return match[2] || match[1];
  411. } else {
  412. return null;
  413. }
  414. },
  415. filter: function(query, data, search_key) {
  416. var item, _i, _len, _results;
  417. _results = [];
  418. for (_i = 0, _len = data.length; _i < _len; _i++) {
  419. item = data[_i];
  420. if (~item[search_key].toLowerCase().indexOf(query)) {
  421. _results.push(item);
  422. }
  423. }
  424. return _results;
  425. },
  426. remote_filter: null,
  427. sorter: function(query, items, search_key) {
  428. var item, _i, _len, _results;
  429. if (!query) {
  430. return items;
  431. }
  432. _results = [];
  433. for (_i = 0, _len = items.length; _i < _len; _i++) {
  434. item = items[_i];
  435. item.atwho_order = item[search_key].toLowerCase().indexOf(query);
  436. if (item.atwho_order > -1) {
  437. _results.push(item);
  438. }
  439. }
  440. return _results.sort(function(a, b) {
  441. return a.atwho_order - b.atwho_order;
  442. });
  443. },
  444. tpl_eval: function(tpl, map) {
  445. try {
  446. return tpl.replace(/\$\{([^\}]*)\}/g, function(tag, key, pos) {
  447. return map[key];
  448. });
  449. } catch (error) {
  450. return "";
  451. }
  452. },
  453. highlighter: function(li, query) {
  454. var regexp;
  455. if (!query) {
  456. return li;
  457. }
  458. regexp = new RegExp(">\\s*(\\w*)(" + query.replace("+", "\\+") + ")(\\w*)\\s*<", 'ig');
  459. return li.replace(regexp, function(str, $1, $2, $3) {
  460. return '> ' + $1 + '<strong>' + $2 + '</strong>' + $3 + ' <';
  461. });
  462. },
  463. before_insert: function(value, $li) {
  464. return value;
  465. }
  466. };
  467. DEFAULT_TPL = "<li data-value='${name}'>${name}</li>";
  468. Api = {
  469. init: function(options) {
  470. var $this, app;
  471. app = ($this = $(this)).data("atwho");
  472. if (!app) {
  473. $this.data('atwho', (app = new App(this)));
  474. }
  475. return app.reg(options.at, options);
  476. },
  477. load: function(key, data) {
  478. var c;
  479. if (c = this.controller(key)) {
  480. return c.model.load(data);
  481. }
  482. },
  483. run: function() {
  484. return this.dispatch();
  485. }
  486. };
  487. $CONTAINER = $("<div id='atwho-container'></div>");
  488. $.fn.atwho = function(method) {
  489. var _args;
  490. _args = arguments;
  491. $('body').append($CONTAINER);
  492. return this.filter('textarea, input').each(function() {
  493. var app;
  494. if (typeof method === 'object' || !method) {
  495. return Api.init.apply(this, _args);
  496. } else if (Api[method]) {
  497. if (app = $(this).data('atwho')) {
  498. return Api[method].apply(app, Array.prototype.slice.call(_args, 1));
  499. }
  500. } else {
  501. return $.error("Method " + method + " does not exist on jQuery.caret");
  502. }
  503. });
  504. };
  505. return $.fn.atwho["default"] = {
  506. at: void 0,
  507. alias: void 0,
  508. data: null,
  509. tpl: DEFAULT_TPL,
  510. callbacks: DEFAULT_CALLBACKS,
  511. search_key: "name",
  512. limit: 5,
  513. max_len: 20,
  514. display_flag: true,
  515. display_timeout: 300
  516. };
  517. });
  518. }).call(this);