show-hint.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // declare global: DOMRect
  4. (function(mod) {
  5. if (typeof exports == "object" && typeof module == "object") // CommonJS
  6. mod(require("../../lib/codemirror"));
  7. else if (typeof define == "function" && define.amd) // AMD
  8. define(["../../lib/codemirror"], mod);
  9. else // Plain browser env
  10. mod(CodeMirror);
  11. })(function(CodeMirror) {
  12. "use strict";
  13. var HINT_ELEMENT_CLASS = "CodeMirror-hint";
  14. var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
  15. // This is the old interface, kept around for now to stay
  16. // backwards-compatible.
  17. CodeMirror.showHint = function(cm, getHints, options) {
  18. if (!getHints) return cm.showHint(options);
  19. if (options && options.async) getHints.async = true;
  20. var newOpts = {hint: getHints};
  21. if (options) for (var prop in options) newOpts[prop] = options[prop];
  22. return cm.showHint(newOpts);
  23. };
  24. CodeMirror.defineExtension("showHint", function(options) {
  25. options = parseOptions(this, this.getCursor("start"), options);
  26. var selections = this.listSelections()
  27. if (selections.length > 1) return;
  28. // By default, don't allow completion when something is selected.
  29. // A hint function can have a `supportsSelection` property to
  30. // indicate that it can handle selections.
  31. if (this.somethingSelected()) {
  32. if (!options.hint.supportsSelection) return;
  33. // Don't try with cross-line selections
  34. for (var i = 0; i < selections.length; i++)
  35. if (selections[i].head.line != selections[i].anchor.line) return;
  36. }
  37. if (this.state.completionActive) this.state.completionActive.close();
  38. var completion = this.state.completionActive = new Completion(this, options);
  39. if (!completion.options.hint) return;
  40. CodeMirror.signal(this, "startCompletion", this);
  41. completion.update(true);
  42. });
  43. CodeMirror.defineExtension("closeHint", function() {
  44. if (this.state.completionActive) this.state.completionActive.close()
  45. })
  46. function Completion(cm, options) {
  47. this.cm = cm;
  48. this.options = options;
  49. this.widget = null;
  50. this.debounce = 0;
  51. this.tick = 0;
  52. this.startPos = this.cm.getCursor("start");
  53. this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
  54. if (this.options.updateOnCursorActivity) {
  55. var self = this;
  56. cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
  57. }
  58. }
  59. var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
  60. return setTimeout(fn, 1000/60);
  61. };
  62. var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
  63. Completion.prototype = {
  64. close: function() {
  65. if (!this.active()) return;
  66. this.cm.state.completionActive = null;
  67. this.tick = null;
  68. if (this.options.updateOnCursorActivity) {
  69. this.cm.off("cursorActivity", this.activityFunc);
  70. }
  71. if (this.widget && this.data) CodeMirror.signal(this.data, "close");
  72. if (this.widget) this.widget.close();
  73. CodeMirror.signal(this.cm, "endCompletion", this.cm);
  74. },
  75. active: function() {
  76. return this.cm.state.completionActive == this;
  77. },
  78. pick: function(data, i) {
  79. var completion = data.list[i], self = this;
  80. this.cm.operation(function() {
  81. if (completion.hint)
  82. completion.hint(self.cm, data, completion);
  83. else
  84. self.cm.replaceRange(getText(completion), completion.from || data.from,
  85. completion.to || data.to, "complete");
  86. CodeMirror.signal(data, "pick", completion);
  87. self.cm.scrollIntoView();
  88. });
  89. if (this.options.closeOnPick) {
  90. this.close();
  91. }
  92. },
  93. cursorActivity: function() {
  94. if (this.debounce) {
  95. cancelAnimationFrame(this.debounce);
  96. this.debounce = 0;
  97. }
  98. var identStart = this.startPos;
  99. if(this.data) {
  100. identStart = this.data.from;
  101. }
  102. var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
  103. if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
  104. pos.ch < identStart.ch || this.cm.somethingSelected() ||
  105. (!pos.ch || this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
  106. this.close();
  107. } else {
  108. var self = this;
  109. this.debounce = requestAnimationFrame(function() {self.update();});
  110. if (this.widget) this.widget.disable();
  111. }
  112. },
  113. update: function(first) {
  114. if (this.tick == null) return
  115. var self = this, myTick = ++this.tick
  116. fetchHints(this.options.hint, this.cm, this.options, function(data) {
  117. if (self.tick == myTick) self.finishUpdate(data, first)
  118. })
  119. },
  120. finishUpdate: function(data, first) {
  121. if (this.data) CodeMirror.signal(this.data, "update");
  122. var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
  123. if (this.widget) this.widget.close();
  124. this.data = data;
  125. if (data && data.list.length) {
  126. if (picked && data.list.length == 1) {
  127. this.pick(data, 0);
  128. } else {
  129. this.widget = new Widget(this, data);
  130. CodeMirror.signal(data, "shown");
  131. }
  132. }
  133. }
  134. };
  135. function parseOptions(cm, pos, options) {
  136. var editor = cm.options.hintOptions;
  137. var out = {};
  138. for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
  139. if (editor) for (var prop in editor)
  140. if (editor[prop] !== undefined) out[prop] = editor[prop];
  141. if (options) for (var prop in options)
  142. if (options[prop] !== undefined) out[prop] = options[prop];
  143. if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
  144. return out;
  145. }
  146. function getText(completion) {
  147. if (typeof completion == "string") return completion;
  148. else return completion.text;
  149. }
  150. function buildKeyMap(completion, handle) {
  151. var baseMap = {
  152. Up: function() {handle.moveFocus(-1);},
  153. Down: function() {handle.moveFocus(1);},
  154. PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
  155. PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
  156. Home: function() {handle.setFocus(0);},
  157. End: function() {handle.setFocus(handle.length - 1);},
  158. Enter: handle.pick,
  159. Tab: handle.pick,
  160. Esc: handle.close
  161. };
  162. var mac = /Mac/.test(navigator.platform);
  163. if (mac) {
  164. baseMap["Ctrl-P"] = function() {handle.moveFocus(-1);};
  165. baseMap["Ctrl-N"] = function() {handle.moveFocus(1);};
  166. }
  167. var custom = completion.options.customKeys;
  168. var ourMap = custom ? {} : baseMap;
  169. function addBinding(key, val) {
  170. var bound;
  171. if (typeof val != "string")
  172. bound = function(cm) { return val(cm, handle); };
  173. // This mechanism is deprecated
  174. else if (baseMap.hasOwnProperty(val))
  175. bound = baseMap[val];
  176. else
  177. bound = val;
  178. ourMap[key] = bound;
  179. }
  180. if (custom)
  181. for (var key in custom) if (custom.hasOwnProperty(key))
  182. addBinding(key, custom[key]);
  183. var extra = completion.options.extraKeys;
  184. if (extra)
  185. for (var key in extra) if (extra.hasOwnProperty(key))
  186. addBinding(key, extra[key]);
  187. return ourMap;
  188. }
  189. function getHintElement(hintsElement, el) {
  190. while (el && el != hintsElement) {
  191. if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
  192. el = el.parentNode;
  193. }
  194. }
  195. function Widget(completion, data) {
  196. this.completion = completion;
  197. this.data = data;
  198. this.picked = false;
  199. var widget = this, cm = completion.cm;
  200. var ownerDocument = cm.getInputField().ownerDocument;
  201. var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow;
  202. var hints = this.hints = ownerDocument.createElement("ul");
  203. var theme = completion.cm.options.theme;
  204. hints.className = "CodeMirror-hints " + theme;
  205. this.selectedHint = data.selectedHint || 0;
  206. var completions = data.list;
  207. for (var i = 0; i < completions.length; ++i) {
  208. var elt = hints.appendChild(ownerDocument.createElement("li")), cur = completions[i];
  209. var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
  210. if (cur.className != null) className = cur.className + " " + className;
  211. elt.className = className;
  212. if (cur.render) cur.render(elt, data, cur);
  213. else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur)));
  214. elt.hintId = i;
  215. }
  216. var container = completion.options.container || ownerDocument.body;
  217. var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
  218. var left = pos.left, top = pos.bottom, below = true;
  219. var offsetLeft = 0, offsetTop = 0;
  220. if (container !== ownerDocument.body) {
  221. // We offset the cursor position because left and top are relative to the offsetParent's top left corner.
  222. var isContainerPositioned = ['absolute', 'relative', 'fixed'].indexOf(parentWindow.getComputedStyle(container).position) !== -1;
  223. var offsetParent = isContainerPositioned ? container : container.offsetParent;
  224. var offsetParentPosition = offsetParent.getBoundingClientRect();
  225. var bodyPosition = ownerDocument.body.getBoundingClientRect();
  226. offsetLeft = (offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft);
  227. offsetTop = (offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop);
  228. }
  229. hints.style.left = (left - offsetLeft) + "px";
  230. hints.style.top = (top - offsetTop) + "px";
  231. // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
  232. var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth);
  233. var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight);
  234. container.appendChild(hints);
  235. var box = completion.options.moveOnOverlap ? hints.getBoundingClientRect() : new DOMRect();
  236. var scrolls = completion.options.paddingForScrollbar ? hints.scrollHeight > hints.clientHeight + 1 : false;
  237. // Compute in the timeout to avoid reflow on init
  238. var startScroll;
  239. setTimeout(function() { startScroll = cm.getScrollInfo(); });
  240. var overlapY = box.bottom - winH;
  241. if (overlapY > 0) {
  242. var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
  243. if (curTop - height > 0) { // Fits above cursor
  244. hints.style.top = (top = pos.top - height - offsetTop) + "px";
  245. below = false;
  246. } else if (height > winH) {
  247. hints.style.height = (winH - 5) + "px";
  248. hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px";
  249. var cursor = cm.getCursor();
  250. if (data.from.ch != cursor.ch) {
  251. pos = cm.cursorCoords(cursor);
  252. hints.style.left = (left = pos.left - offsetLeft) + "px";
  253. box = hints.getBoundingClientRect();
  254. }
  255. }
  256. }
  257. var overlapX = box.right - winW;
  258. if (overlapX > 0) {
  259. if (box.right - box.left > winW) {
  260. hints.style.width = (winW - 5) + "px";
  261. overlapX -= (box.right - box.left) - winW;
  262. }
  263. hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px";
  264. }
  265. if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
  266. node.style.paddingRight = cm.display.nativeBarWidth + "px"
  267. cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
  268. moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
  269. setFocus: function(n) { widget.changeActive(n); },
  270. menuSize: function() { return widget.screenAmount(); },
  271. length: completions.length,
  272. close: function() { completion.close(); },
  273. pick: function() { widget.pick(); },
  274. data: data
  275. }));
  276. if (completion.options.closeOnUnfocus) {
  277. var closingOnBlur;
  278. cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
  279. cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
  280. }
  281. cm.on("scroll", this.onScroll = function() {
  282. var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
  283. var newTop = top + startScroll.top - curScroll.top;
  284. var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop);
  285. if (!below) point += hints.offsetHeight;
  286. if (point <= editor.top || point >= editor.bottom) return completion.close();
  287. hints.style.top = newTop + "px";
  288. hints.style.left = (left + startScroll.left - curScroll.left) + "px";
  289. });
  290. CodeMirror.on(hints, "dblclick", function(e) {
  291. var t = getHintElement(hints, e.target || e.srcElement);
  292. if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
  293. });
  294. CodeMirror.on(hints, "click", function(e) {
  295. var t = getHintElement(hints, e.target || e.srcElement);
  296. if (t && t.hintId != null) {
  297. widget.changeActive(t.hintId);
  298. if (completion.options.completeOnSingleClick) widget.pick();
  299. }
  300. });
  301. CodeMirror.on(hints, "mousedown", function() {
  302. setTimeout(function(){cm.focus();}, 20);
  303. });
  304. // The first hint doesn't need to be scrolled to on init
  305. var selectedHintRange = this.getSelectedHintRange();
  306. if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) {
  307. this.scrollToActive();
  308. }
  309. CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]);
  310. return true;
  311. }
  312. Widget.prototype = {
  313. close: function() {
  314. if (this.completion.widget != this) return;
  315. this.completion.widget = null;
  316. if (this.hints.parentNode) this.hints.parentNode.removeChild(this.hints);
  317. this.completion.cm.removeKeyMap(this.keyMap);
  318. var cm = this.completion.cm;
  319. if (this.completion.options.closeOnUnfocus) {
  320. cm.off("blur", this.onBlur);
  321. cm.off("focus", this.onFocus);
  322. }
  323. cm.off("scroll", this.onScroll);
  324. },
  325. disable: function() {
  326. this.completion.cm.removeKeyMap(this.keyMap);
  327. var widget = this;
  328. this.keyMap = {Enter: function() { widget.picked = true; }};
  329. this.completion.cm.addKeyMap(this.keyMap);
  330. },
  331. pick: function() {
  332. this.completion.pick(this.data, this.selectedHint);
  333. },
  334. changeActive: function(i, avoidWrap) {
  335. if (i >= this.data.list.length)
  336. i = avoidWrap ? this.data.list.length - 1 : 0;
  337. else if (i < 0)
  338. i = avoidWrap ? 0 : this.data.list.length - 1;
  339. if (this.selectedHint == i) return;
  340. var node = this.hints.childNodes[this.selectedHint];
  341. if (node) node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
  342. node = this.hints.childNodes[this.selectedHint = i];
  343. node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
  344. this.scrollToActive()
  345. CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
  346. },
  347. scrollToActive: function() {
  348. var selectedHintRange = this.getSelectedHintRange();
  349. var node1 = this.hints.childNodes[selectedHintRange.from];
  350. var node2 = this.hints.childNodes[selectedHintRange.to];
  351. var firstNode = this.hints.firstChild;
  352. if (node1.offsetTop < this.hints.scrollTop)
  353. this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;
  354. else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
  355. this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop;
  356. },
  357. screenAmount: function() {
  358. return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
  359. },
  360. getSelectedHintRange: function() {
  361. var margin = this.completion.options.scrollMargin || 0;
  362. return {
  363. from: Math.max(0, this.selectedHint - margin),
  364. to: Math.min(this.data.list.length - 1, this.selectedHint + margin),
  365. };
  366. }
  367. };
  368. function applicableHelpers(cm, helpers) {
  369. if (!cm.somethingSelected()) return helpers
  370. var result = []
  371. for (var i = 0; i < helpers.length; i++)
  372. if (helpers[i].supportsSelection) result.push(helpers[i])
  373. return result
  374. }
  375. function fetchHints(hint, cm, options, callback) {
  376. if (hint.async) {
  377. hint(cm, callback, options)
  378. } else {
  379. var result = hint(cm, options)
  380. if (result && result.then) result.then(callback)
  381. else callback(result)
  382. }
  383. }
  384. function resolveAutoHints(cm, pos) {
  385. var helpers = cm.getHelpers(pos, "hint"), words
  386. if (helpers.length) {
  387. var resolved = function(cm, callback, options) {
  388. var app = applicableHelpers(cm, helpers);
  389. function run(i) {
  390. if (i == app.length) return callback(null)
  391. fetchHints(app[i], cm, options, function(result) {
  392. if (result && result.list.length > 0) callback(result)
  393. else run(i + 1)
  394. })
  395. }
  396. run(0)
  397. }
  398. resolved.async = true
  399. resolved.supportsSelection = true
  400. return resolved
  401. } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
  402. return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
  403. } else if (CodeMirror.hint.anyword) {
  404. return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
  405. } else {
  406. return function() {}
  407. }
  408. }
  409. CodeMirror.registerHelper("hint", "auto", {
  410. resolve: resolveAutoHints
  411. });
  412. CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
  413. var cur = cm.getCursor(), token = cm.getTokenAt(cur)
  414. var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
  415. if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
  416. term = token.string.substr(0, cur.ch - token.start)
  417. } else {
  418. term = ""
  419. from = cur
  420. }
  421. var found = [];
  422. for (var i = 0; i < options.words.length; i++) {
  423. var word = options.words[i];
  424. if (word.slice(0, term.length) == term)
  425. found.push(word);
  426. }
  427. if (found.length) return {list: found, from: from, to: to};
  428. });
  429. CodeMirror.commands.autocomplete = CodeMirror.showHint;
  430. var defaultOptions = {
  431. hint: CodeMirror.hint.auto,
  432. completeSingle: true,
  433. alignWithWord: true,
  434. closeCharacters: /[\s()\[\]{};:>,]/,
  435. closeOnPick: true,
  436. closeOnUnfocus: true,
  437. updateOnCursorActivity: true,
  438. completeOnSingleClick: true,
  439. container: null,
  440. customKeys: null,
  441. extraKeys: null,
  442. paddingForScrollbar: true,
  443. moveOnOverlap: true,
  444. };
  445. CodeMirror.defineOption("hintOptions", null);
  446. });