show-hint.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. (function(mod) {
  2. if (typeof exports == "object" && typeof module == "object") // CommonJS
  3. mod(require("../../lib/codemirror"));
  4. else if (typeof define == "function" && define.amd) // AMD
  5. define(["../../lib/codemirror"], mod);
  6. else // Plain browser env
  7. mod(CodeMirror);
  8. })(function(CodeMirror) {
  9. "use strict";
  10. var HINT_ELEMENT_CLASS = "CodeMirror-hint";
  11. var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
  12. CodeMirror.showHint = function(cm, getHints, options) {
  13. // We want a single cursor position.
  14. if (cm.listSelections().length > 1 || cm.somethingSelected()) return;
  15. if (getHints == null) {
  16. if (options && options.async) return;
  17. else getHints = CodeMirror.hint.auto;
  18. }
  19. if (cm.state.completionActive) cm.state.completionActive.close();
  20. var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});
  21. CodeMirror.signal(cm, "startCompletion", cm);
  22. if (completion.options.async)
  23. getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);
  24. else
  25. return completion.showHints(getHints(cm, completion.options));
  26. };
  27. function Completion(cm, getHints, options) {
  28. this.cm = cm;
  29. this.getHints = getHints;
  30. this.options = options;
  31. this.widget = this.onClose = null;
  32. }
  33. Completion.prototype = {
  34. close: function() {
  35. if (!this.active()) return;
  36. this.cm.state.completionActive = null;
  37. if (this.widget) this.widget.close();
  38. if (this.onClose) this.onClose();
  39. CodeMirror.signal(this.cm, "endCompletion", this.cm);
  40. },
  41. active: function() {
  42. return this.cm.state.completionActive == this;
  43. },
  44. pick: function(data, i) {
  45. var completion = data.list[i];
  46. if (completion.hint) completion.hint(this.cm, data, completion);
  47. else this.cm.replaceRange(getText(completion), completion.from||data.from, completion.to||data.to);
  48. CodeMirror.signal(data, "pick", completion);
  49. this.close();
  50. },
  51. showHints: function(data) {
  52. if (!data || !data.list.length || !this.active()) return this.close();
  53. if (this.options.completeSingle != false && data.list.length == 1)
  54. this.pick(data, 0);
  55. else
  56. this.showWidget(data);
  57. },
  58. showWidget: function(data) {
  59. this.widget = new Widget(this, data);
  60. CodeMirror.signal(data, "shown");
  61. var debounce = 0, completion = this, finished;
  62. var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
  63. var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;
  64. var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
  65. return setTimeout(fn, 1000/60);
  66. };
  67. var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
  68. function done() {
  69. if (finished) return;
  70. finished = true;
  71. completion.close();
  72. completion.cm.off("cursorActivity", activity);
  73. if (data) CodeMirror.signal(data, "close");
  74. }
  75. function update() {
  76. if (finished) return;
  77. CodeMirror.signal(data, "update");
  78. if (completion.options.async)
  79. completion.getHints(completion.cm, finishUpdate, completion.options);
  80. else
  81. finishUpdate(completion.getHints(completion.cm, completion.options));
  82. }
  83. function finishUpdate(data_) {
  84. data = data_;
  85. if (finished) return;
  86. if (!data || !data.list.length) return done();
  87. completion.widget = new Widget(completion, data);
  88. }
  89. function clearDebounce() {
  90. if (debounce) {
  91. cancelAnimationFrame(debounce);
  92. debounce = 0;
  93. }
  94. }
  95. function activity() {
  96. clearDebounce();
  97. var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
  98. if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
  99. pos.ch < startPos.ch || completion.cm.somethingSelected() ||
  100. (pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) {
  101. completion.close();
  102. } else {
  103. debounce = requestAnimationFrame(update);
  104. if (completion.widget) completion.widget.close();
  105. }
  106. }
  107. this.cm.on("cursorActivity", activity);
  108. this.onClose = done;
  109. }
  110. };
  111. function getText(completion) {
  112. if (typeof completion == "string") return completion;
  113. else return completion.text;
  114. }
  115. function buildKeyMap(options, handle) {
  116. var baseMap = {
  117. Up: function() {handle.moveFocus(-1);},
  118. Down: function() {handle.moveFocus(1);},
  119. PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
  120. PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
  121. Home: function() {handle.setFocus(0);},
  122. End: function() {handle.setFocus(handle.length - 1);},
  123. Enter: handle.pick,
  124. Tab: handle.pick,
  125. Esc: handle.close
  126. };
  127. var ourMap = options.customKeys ? {} : baseMap;
  128. function addBinding(key, val) {
  129. var bound;
  130. if (typeof val != "string")
  131. bound = function(cm) { return val(cm, handle); };
  132. // This mechanism is deprecated
  133. else if (baseMap.hasOwnProperty(val))
  134. bound = baseMap[val];
  135. else
  136. bound = val;
  137. ourMap[key] = bound;
  138. }
  139. if (options.customKeys)
  140. for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))
  141. addBinding(key, options.customKeys[key]);
  142. if (options.extraKeys)
  143. for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))
  144. addBinding(key, options.extraKeys[key]);
  145. return ourMap;
  146. }
  147. function getHintElement(hintsElement, el) {
  148. while (el && el != hintsElement) {
  149. if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
  150. el = el.parentNode;
  151. }
  152. }
  153. function Widget(completion, data) {
  154. this.completion = completion;
  155. this.data = data;
  156. var widget = this, cm = completion.cm, options = completion.options;
  157. var hints = this.hints = document.createElement("ul");
  158. hints.className = "CodeMirror-hints";
  159. this.selectedHint = options.getDefaultSelection ? options.getDefaultSelection(cm,options,data) : 0;
  160. var completions = data.list;
  161. for (var i = 0; i < completions.length; ++i) {
  162. var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
  163. var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
  164. if (cur.className != null) className = cur.className + " " + className;
  165. elt.className = className;
  166. if (cur.render) cur.render(elt, data, cur);
  167. else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
  168. elt.hintId = i;
  169. }
  170. var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);
  171. var left = pos.left, top = pos.bottom, below = true;
  172. hints.style.left = left + "px";
  173. hints.style.top = top + "px";
  174. // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
  175. var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
  176. var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
  177. (options.container || document.body).appendChild(hints);
  178. var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
  179. if (overlapY > 0) {
  180. var height = box.bottom - box.top, curTop = box.top - (pos.bottom - pos.top);
  181. if (curTop - height > 0) { // Fits above cursor
  182. hints.style.top = (top = curTop - height) + "px";
  183. below = false;
  184. } else if (height > winH) {
  185. hints.style.height = (winH - 5) + "px";
  186. hints.style.top = (top = pos.bottom - box.top) + "px";
  187. var cursor = cm.getCursor();
  188. if (data.from.ch != cursor.ch) {
  189. pos = cm.cursorCoords(cursor);
  190. hints.style.left = (left = pos.left) + "px";
  191. box = hints.getBoundingClientRect();
  192. }
  193. }
  194. }
  195. var overlapX = box.left - winW;
  196. if (overlapX > 0) {
  197. if (box.right - box.left > winW) {
  198. hints.style.width = (winW - 5) + "px";
  199. overlapX -= (box.right - box.left) - winW;
  200. }
  201. hints.style.left = (left = pos.left - overlapX) + "px";
  202. }
  203. cm.addKeyMap(this.keyMap = buildKeyMap(options, {
  204. moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
  205. setFocus: function(n) { widget.changeActive(n); },
  206. menuSize: function() { return widget.screenAmount(); },
  207. length: completions.length,
  208. close: function() { completion.close(); },
  209. pick: function() { widget.pick(); },
  210. data: data
  211. }));
  212. if (options.closeOnUnfocus !== false) {
  213. var closingOnBlur;
  214. cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
  215. cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
  216. }
  217. var startScroll = cm.getScrollInfo();
  218. cm.on("scroll", this.onScroll = function() {
  219. var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
  220. var newTop = top + startScroll.top - curScroll.top;
  221. var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
  222. if (!below) point += hints.offsetHeight;
  223. if (point <= editor.top || point >= editor.bottom) return completion.close();
  224. hints.style.top = newTop + "px";
  225. hints.style.left = (left + startScroll.left - curScroll.left) + "px";
  226. });
  227. CodeMirror.on(hints, "dblclick", function(e) {
  228. var t = getHintElement(hints, e.target || e.srcElement);
  229. if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
  230. });
  231. CodeMirror.on(hints, "click", function(e) {
  232. var t = getHintElement(hints, e.target || e.srcElement);
  233. if (t && t.hintId != null) {
  234. widget.changeActive(t.hintId);
  235. if (options.completeOnSingleClick) widget.pick();
  236. }
  237. });
  238. CodeMirror.on(hints, "mousedown", function() {
  239. setTimeout(function(){cm.focus();}, 20);
  240. });
  241. CodeMirror.signal(data, "select", completions[0], hints.firstChild);
  242. return true;
  243. }
  244. Widget.prototype = {
  245. close: function() {
  246. if (this.completion.widget != this) return;
  247. this.completion.widget = null;
  248. this.hints.parentNode.removeChild(this.hints);
  249. this.completion.cm.removeKeyMap(this.keyMap);
  250. var cm = this.completion.cm;
  251. if (this.completion.options.closeOnUnfocus !== false) {
  252. cm.off("blur", this.onBlur);
  253. cm.off("focus", this.onFocus);
  254. }
  255. cm.off("scroll", this.onScroll);
  256. },
  257. pick: function() {
  258. this.completion.pick(this.data, this.selectedHint);
  259. },
  260. changeActive: function(i, avoidWrap) {
  261. if (i >= this.data.list.length)
  262. i = avoidWrap ? this.data.list.length - 1 : 0;
  263. else if (i < 0)
  264. i = avoidWrap ? 0 : this.data.list.length - 1;
  265. if (this.selectedHint == i) return;
  266. var node = this.hints.childNodes[this.selectedHint];
  267. node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
  268. node = this.hints.childNodes[this.selectedHint = i];
  269. node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
  270. if (node.offsetTop < this.hints.scrollTop)
  271. this.hints.scrollTop = node.offsetTop - 3;
  272. else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
  273. this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
  274. CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
  275. },
  276. screenAmount: function() {
  277. return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
  278. }
  279. };
  280. CodeMirror.registerHelper("hint", "auto", function(cm, options) {
  281. var helpers = cm.getHelpers(cm.getCursor(), "hint"), words;
  282. if (helpers.length) {
  283. for (var i = 0; i < helpers.length; i++) {
  284. var cur = helpers[i](cm, options);
  285. if (cur && cur.list.length) return cur;
  286. }
  287. } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
  288. if (words) return CodeMirror.hint.fromList(cm, {words: words});
  289. } else if (CodeMirror.hint.anyword) {
  290. return CodeMirror.hint.anyword(cm, options);
  291. }
  292. });
  293. CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
  294. var cur = cm.getCursor(), token = cm.getTokenAt(cur);
  295. var found = [];
  296. for (var i = 0; i < options.words.length; i++) {
  297. var word = options.words[i];
  298. if (word.slice(0, token.string.length) == token.string)
  299. found.push(word);
  300. }
  301. if (found.length) return {
  302. list: found,
  303. from: CodeMirror.Pos(cur.line, token.start),
  304. to: CodeMirror.Pos(cur.line, token.end)
  305. };
  306. });
  307. CodeMirror.commands.autocomplete = CodeMirror.showHint;
  308. });