awesomplete.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /**
  2. * Simple, lightweight, usable local autocomplete library for modern browsers
  3. * Because there weren’t enough autocomplete scripts in the world? Because I’m completely insane and have NIH syndrome? Probably both. :P
  4. * @author Lea Verou http://leaverou.github.io/awesomplete
  5. * MIT license
  6. */
  7. (function () {
  8. var _ = function (input, o) {
  9. var me = this;
  10. // Keep track of number of instances for unique IDs
  11. Awesomplete.count = (Awesomplete.count || 0) + 1;
  12. this.count = Awesomplete.count;
  13. // Setup
  14. this.isOpened = false;
  15. this.input = $(input);
  16. this.input.setAttribute("autocomplete", "off");
  17. this.input.setAttribute("aria-owns", "awesomplete_list_" + this.count);
  18. this.input.setAttribute("role", "combobox");
  19. o = o || {};
  20. configure(this, {
  21. minChars: 2,
  22. maxItems: 10,
  23. autoFirst: false,
  24. data: _.DATA,
  25. filter: _.FILTER_CONTAINS,
  26. sort: o.sort === false ? false : _.SORT_BYLENGTH,
  27. item: _.ITEM,
  28. replace: _.REPLACE
  29. }, o);
  30. this.index = -1;
  31. // Create necessary elements
  32. this.container = $.create("div", {
  33. className: "awesomplete",
  34. around: input
  35. });
  36. this.ul = $.create("ul", {
  37. hidden: "hidden",
  38. role: "listbox",
  39. id: "awesomplete_list_" + this.count,
  40. inside: this.container
  41. });
  42. this.status = $.create("span", {
  43. className: "visually-hidden",
  44. role: "status",
  45. "aria-live": "assertive",
  46. "aria-atomic": true,
  47. inside: this.container,
  48. textContent: this.minChars != 0 ? ("Type " + this.minChars + " or more characters for results.") : "Begin typing for results."
  49. });
  50. // Bind events
  51. this._events = {
  52. input: {
  53. "input": this.evaluate.bind(this),
  54. "blur": this.close.bind(this, { reason: "blur" }),
  55. "keydown": function(evt) {
  56. var c = evt.keyCode;
  57. // If the dropdown `ul` is in view, then act on keydown for the following keys:
  58. // Enter / Esc / Up / Down
  59. if(me.opened) {
  60. if (c === 13 && me.selected) { // Enter
  61. evt.preventDefault();
  62. me.select();
  63. }
  64. else if (c === 27) { // Esc
  65. me.close({ reason: "esc" });
  66. }
  67. else if (c === 38 || c === 40) { // Down/Up arrow
  68. evt.preventDefault();
  69. me[c === 38? "previous" : "next"]();
  70. }
  71. }
  72. }
  73. },
  74. form: {
  75. "submit": this.close.bind(this, { reason: "submit" })
  76. },
  77. ul: {
  78. "mousedown": function(evt) {
  79. var li = evt.target;
  80. if (li !== this) {
  81. while (li && !/li/i.test(li.nodeName)) {
  82. li = li.parentNode;
  83. }
  84. if (li && evt.button === 0) { // Only select on left click
  85. evt.preventDefault();
  86. me.select(li, evt.target);
  87. }
  88. }
  89. }
  90. }
  91. };
  92. $.bind(this.input, this._events.input);
  93. $.bind(this.input.form, this._events.form);
  94. $.bind(this.ul, this._events.ul);
  95. if (this.input.hasAttribute("list")) {
  96. this.list = "#" + this.input.getAttribute("list");
  97. this.input.removeAttribute("list");
  98. }
  99. else {
  100. this.list = this.input.getAttribute("data-list") || o.list || [];
  101. }
  102. _.all.push(this);
  103. };
  104. _.prototype = {
  105. set list(list) {
  106. if (Array.isArray(list)) {
  107. this._list = list;
  108. }
  109. else if (typeof list === "string" && list.indexOf(",") > -1) {
  110. this._list = list.split(/\s*,\s*/);
  111. }
  112. else { // Element or CSS selector
  113. list = $(list);
  114. if (list && list.children) {
  115. var items = [];
  116. slice.apply(list.children).forEach(function (el) {
  117. if (!el.disabled) {
  118. var text = el.textContent.trim();
  119. var value = el.value || text;
  120. var label = el.label || text;
  121. if (value !== "") {
  122. items.push({ label: label, value: value });
  123. }
  124. }
  125. });
  126. this._list = items;
  127. }
  128. }
  129. if (document.activeElement === this.input) {
  130. this.evaluate();
  131. }
  132. },
  133. get selected() {
  134. return this.index > -1;
  135. },
  136. get opened() {
  137. return this.isOpened;
  138. },
  139. close: function (o) {
  140. if (!this.opened) {
  141. return;
  142. }
  143. this.ul.setAttribute("hidden", "");
  144. this.isOpened = false;
  145. this.index = -1;
  146. $.fire(this.input, "awesomplete-close", o || {});
  147. },
  148. open: function () {
  149. this.ul.removeAttribute("hidden");
  150. this.isOpened = true;
  151. if (this.autoFirst && this.index === -1) {
  152. this.goto(0);
  153. }
  154. $.fire(this.input, "awesomplete-open");
  155. },
  156. destroy: function() {
  157. //remove events from the input and its form
  158. $.unbind(this.input, this._events.input);
  159. $.unbind(this.input.form, this._events.form);
  160. //move the input out of the awesomplete container and remove the container and its children
  161. var parentNode = this.container.parentNode;
  162. parentNode.insertBefore(this.input, this.container);
  163. parentNode.removeChild(this.container);
  164. //remove autocomplete and aria-autocomplete attributes
  165. this.input.removeAttribute("autocomplete");
  166. this.input.removeAttribute("aria-autocomplete");
  167. //remove this awesomeplete instance from the global array of instances
  168. var indexOfAwesomplete = _.all.indexOf(this);
  169. if (indexOfAwesomplete !== -1) {
  170. _.all.splice(indexOfAwesomplete, 1);
  171. }
  172. },
  173. next: function () {
  174. var count = this.ul.children.length;
  175. this.goto(this.index < count - 1 ? this.index + 1 : (count ? 0 : -1) );
  176. },
  177. previous: function () {
  178. var count = this.ul.children.length;
  179. var pos = this.index - 1;
  180. this.goto(this.selected && pos !== -1 ? pos : count - 1);
  181. },
  182. // Should not be used, highlights specific item without any checks!
  183. goto: function (i) {
  184. var lis = this.ul.children;
  185. if (this.selected) {
  186. lis[this.index].setAttribute("aria-selected", "false");
  187. }
  188. this.index = i;
  189. if (i > -1 && lis.length > 0) {
  190. lis[i].setAttribute("aria-selected", "true");
  191. this.status.textContent = lis[i].textContent + ", list item " + (i + 1) + " of " + lis.length;
  192. this.input.setAttribute("aria-activedescendant", this.ul.id + "_item_" + this.index);
  193. // scroll to highlighted element in case parent's height is fixed
  194. this.ul.scrollTop = lis[i].offsetTop - this.ul.clientHeight + lis[i].clientHeight;
  195. $.fire(this.input, "awesomplete-highlight", {
  196. text: this.suggestions[this.index]
  197. });
  198. }
  199. },
  200. select: function (selected, origin) {
  201. if (selected) {
  202. this.index = $.siblingIndex(selected);
  203. } else {
  204. selected = this.ul.children[this.index];
  205. }
  206. if (selected) {
  207. var suggestion = this.suggestions[this.index];
  208. var allowed = $.fire(this.input, "awesomplete-select", {
  209. text: suggestion,
  210. origin: origin || selected
  211. });
  212. if (allowed) {
  213. this.replace(suggestion);
  214. this.close({ reason: "select" });
  215. $.fire(this.input, "awesomplete-selectcomplete", {
  216. text: suggestion
  217. });
  218. }
  219. }
  220. },
  221. evaluate: function() {
  222. var me = this;
  223. var value = this.input.value;
  224. if (value.length >= this.minChars && this._list.length > 0) {
  225. this.index = -1;
  226. // Populate list with options that match
  227. this.ul.innerHTML = "";
  228. this.suggestions = this._list
  229. .map(function(item) {
  230. return new Suggestion(me.data(item, value));
  231. })
  232. .filter(function(item) {
  233. return me.filter(item, value);
  234. });
  235. if (this.sort !== false) {
  236. this.suggestions = this.suggestions.sort(this.sort);
  237. }
  238. this.suggestions = this.suggestions.slice(0, this.maxItems);
  239. this.suggestions.forEach(function(text, index) {
  240. me.ul.appendChild(me.item(text, value, index));
  241. });
  242. if (this.ul.children.length === 0) {
  243. this.status.textContent = "No results found";
  244. this.close({ reason: "nomatches" });
  245. } else {
  246. this.open();
  247. this.status.textContent = this.ul.children.length + " results found";
  248. }
  249. }
  250. else {
  251. this.close({ reason: "nomatches" });
  252. this.status.textContent = "No results found";
  253. }
  254. }
  255. };
  256. // Static methods/properties
  257. _.all = [];
  258. _.FILTER_CONTAINS = function (text, input) {
  259. return RegExp($.regExpEscape(input.trim()), "i").test(text);
  260. };
  261. _.FILTER_STARTSWITH = function (text, input) {
  262. return RegExp("^" + $.regExpEscape(input.trim()), "i").test(text);
  263. };
  264. _.SORT_BYLENGTH = function (a, b) {
  265. if (a.length !== b.length) {
  266. return a.length - b.length;
  267. }
  268. return a < b? -1 : 1;
  269. };
  270. _.ITEM = function (text, input, item_id) {
  271. var html = input.trim() === "" ? text : text.replace(RegExp($.regExpEscape(input.trim()), "gi"), "<mark>$&</mark>");
  272. return $.create("li", {
  273. innerHTML: html,
  274. "aria-selected": "false",
  275. "id": "awesomplete_list_" + this.count + "_item_" + item_id
  276. });
  277. };
  278. _.REPLACE = function (text) {
  279. this.input.value = text.value;
  280. };
  281. _.DATA = function (item/*, input*/) { return item; };
  282. // Private functions
  283. function Suggestion(data) {
  284. var o = Array.isArray(data)
  285. ? { label: data[0], value: data[1] }
  286. : typeof data === "object" && "label" in data && "value" in data ? data : { label: data, value: data };
  287. this.label = o.label || o.value;
  288. this.value = o.value;
  289. }
  290. Object.defineProperty(Suggestion.prototype = Object.create(String.prototype), "length", {
  291. get: function() { return this.label.length; }
  292. });
  293. Suggestion.prototype.toString = Suggestion.prototype.valueOf = function () {
  294. return "" + this.label;
  295. };
  296. function configure(instance, properties, o) {
  297. for (var i in properties) {
  298. var initial = properties[i],
  299. attrValue = instance.input.getAttribute("data-" + i.toLowerCase());
  300. if (typeof initial === "number") {
  301. instance[i] = parseInt(attrValue);
  302. }
  303. else if (initial === false) { // Boolean options must be false by default anyway
  304. instance[i] = attrValue !== null;
  305. }
  306. else if (initial instanceof Function) {
  307. instance[i] = null;
  308. }
  309. else {
  310. instance[i] = attrValue;
  311. }
  312. if (!instance[i] && instance[i] !== 0) {
  313. instance[i] = (i in o)? o[i] : initial;
  314. }
  315. }
  316. }
  317. // Helpers
  318. var slice = Array.prototype.slice;
  319. function $(expr, con) {
  320. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  321. }
  322. function $$(expr, con) {
  323. return slice.call((con || document).querySelectorAll(expr));
  324. }
  325. $.create = function(tag, o) {
  326. var element = document.createElement(tag);
  327. for (var i in o) {
  328. var val = o[i];
  329. if (i === "inside") {
  330. $(val).appendChild(element);
  331. }
  332. else if (i === "around") {
  333. var ref = $(val);
  334. ref.parentNode.insertBefore(element, ref);
  335. element.appendChild(ref);
  336. }
  337. else if (i in element) {
  338. element[i] = val;
  339. }
  340. else {
  341. element.setAttribute(i, val);
  342. }
  343. }
  344. return element;
  345. };
  346. $.bind = function(element, o) {
  347. if (element) {
  348. for (var event in o) {
  349. var callback = o[event];
  350. event.split(/\s+/).forEach(function (event) {
  351. element.addEventListener(event, callback);
  352. });
  353. }
  354. }
  355. };
  356. $.unbind = function(element, o) {
  357. if (element) {
  358. for (var event in o) {
  359. var callback = o[event];
  360. event.split(/\s+/).forEach(function(event) {
  361. element.removeEventListener(event, callback);
  362. });
  363. }
  364. }
  365. };
  366. $.fire = function(target, type, properties) {
  367. var evt = document.createEvent("HTMLEvents");
  368. evt.initEvent(type, true, true );
  369. for (var j in properties) {
  370. evt[j] = properties[j];
  371. }
  372. return target.dispatchEvent(evt);
  373. };
  374. $.regExpEscape = function (s) {
  375. return s.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
  376. };
  377. $.siblingIndex = function (el) {
  378. /* eslint-disable no-cond-assign */
  379. for (var i = 0; el = el.previousElementSibling; i++);
  380. return i;
  381. };
  382. // Initialization
  383. function init() {
  384. $$("input.awesomplete").forEach(function (input) {
  385. new _(input);
  386. });
  387. }
  388. // Make sure to export Awesomplete on self when in a browser
  389. if (typeof self !== "undefined") {
  390. self.Awesomplete = _;
  391. }
  392. // Are we in a browser? Check for Document constructor
  393. if (typeof Document !== "undefined") {
  394. // DOM already loaded?
  395. if (document.readyState !== "loading") {
  396. init();
  397. }
  398. else {
  399. // Wait for it
  400. document.addEventListener("DOMContentLoaded", init);
  401. }
  402. }
  403. _.$ = $;
  404. _.$$ = $$;
  405. // Expose Awesomplete as a CJS module
  406. if (typeof module === "object" && module.exports) {
  407. module.exports = _;
  408. }
  409. return _;
  410. }());