showhint.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/5/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.id = "cm-complete-" + Math.floor(Math.random(1e6))
  197. this.completion = completion;
  198. this.data = data;
  199. this.picked = false;
  200. var widget = this, cm = completion.cm;
  201. var ownerDocument = cm.getInputField().ownerDocument;
  202. var parentWindow = ownerDocument.defaultView || ownerDocument.parentWindow;
  203. var hints = this.hints = ownerDocument.createElement("ul");
  204. hints.setAttribute("role", "listbox")
  205. hints.setAttribute("aria-expanded", "true")
  206. hints.id = this.id
  207. var theme = completion.cm.options.theme;
  208. hints.className = "CodeMirror-hints " + theme;
  209. this.selectedHint = data.selectedHint || 0;
  210. var completions = data.list;
  211. for (var i = 0; i < completions.length; ++i) {
  212. var elt = hints.appendChild(ownerDocument.createElement("li")), cur = completions[i];
  213. var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
  214. if (cur.className != null) className = cur.className + " " + className;
  215. elt.className = className;
  216. if (i == this.selectedHint) elt.setAttribute("aria-selected", "true")
  217. elt.id = this.id + "-" + i
  218. elt.setAttribute("role", "option")
  219. if (cur.render) cur.render(elt, data, cur);
  220. else elt.appendChild(ownerDocument.createTextNode(cur.displayText || getText(cur)));
  221. elt.hintId = i;
  222. }
  223. var container = completion.options.container || ownerDocument.body;
  224. var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
  225. var left = pos.left, top = pos.bottom, below = true;
  226. var offsetLeft = 0, offsetTop = 0;
  227. if (container !== ownerDocument.body) {
  228. // We offset the cursor position because left and top are relative to the offsetParent's top left corner.
  229. var isContainerPositioned = ['absolute', 'relative', 'fixed'].indexOf(parentWindow.getComputedStyle(container).position) !== -1;
  230. var offsetParent = isContainerPositioned ? container : container.offsetParent;
  231. var offsetParentPosition = offsetParent.getBoundingClientRect();
  232. var bodyPosition = ownerDocument.body.getBoundingClientRect();
  233. offsetLeft = (offsetParentPosition.left - bodyPosition.left - offsetParent.scrollLeft);
  234. offsetTop = (offsetParentPosition.top - bodyPosition.top - offsetParent.scrollTop);
  235. }
  236. hints.style.left = (left - offsetLeft) + "px";
  237. hints.style.top = (top - offsetTop) + "px";
  238. // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
  239. var winW = parentWindow.innerWidth || Math.max(ownerDocument.body.offsetWidth, ownerDocument.documentElement.offsetWidth);
  240. var winH = parentWindow.innerHeight || Math.max(ownerDocument.body.offsetHeight, ownerDocument.documentElement.offsetHeight);
  241. container.appendChild(hints);
  242. cm.getInputField().setAttribute("aria-autocomplete", "list")
  243. cm.getInputField().setAttribute("aria-owns", this.id)
  244. cm.getInputField().setAttribute("aria-activedescendant", this.id + "-" + this.selectedHint)
  245. var box = completion.options.moveOnOverlap ? hints.getBoundingClientRect() : new DOMRect();
  246. var scrolls = completion.options.paddingForScrollbar ? hints.scrollHeight > hints.clientHeight + 1 : false;
  247. // Compute in the timeout to avoid reflow on init
  248. var startScroll;
  249. setTimeout(function() { startScroll = cm.getScrollInfo(); });
  250. var overlapY = box.bottom - winH;
  251. if (overlapY > 0) { // Does not fit below
  252. var height = box.bottom - box.top, spaceAbove = box.top - (pos.bottom - pos.top) - 2
  253. if (winH - box.top < spaceAbove) { // More room at the top
  254. if (height > spaceAbove) hints.style.height = (height = spaceAbove) + "px";
  255. hints.style.top = ((top = pos.top - height) + offsetTop) + "px";
  256. below = false;
  257. } else {
  258. hints.style.height = (winH - box.top - 2) + "px";
  259. }
  260. }
  261. var overlapX = box.right - winW;
  262. if (scrolls) overlapX += cm.display.nativeBarWidth;
  263. if (overlapX > 0) {
  264. if (box.right - box.left > winW) {
  265. hints.style.width = (winW - 5) + "px";
  266. overlapX -= (box.right - box.left) - winW;
  267. }
  268. hints.style.left = (left = Math.max(pos.left - overlapX - offsetLeft, 0)) + "px";
  269. }
  270. if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
  271. node.style.paddingRight = cm.display.nativeBarWidth + "px"
  272. cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
  273. moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
  274. setFocus: function(n) { widget.changeActive(n); },
  275. menuSize: function() { return widget.screenAmount(); },
  276. length: completions.length,
  277. close: function() { completion.close(); },
  278. pick: function() { widget.pick(); },
  279. data: data
  280. }));
  281. if (completion.options.closeOnUnfocus) {
  282. var closingOnBlur;
  283. cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
  284. cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
  285. }
  286. cm.on("scroll", this.onScroll = function() {
  287. var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
  288. if (!startScroll) startScroll = cm.getScrollInfo();
  289. var newTop = top + startScroll.top - curScroll.top;
  290. var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop);
  291. if (!below) point += hints.offsetHeight;
  292. if (point <= editor.top || point >= editor.bottom) return completion.close();
  293. hints.style.top = newTop + "px";
  294. hints.style.left = (left + startScroll.left - curScroll.left) + "px";
  295. });
  296. CodeMirror.on(hints, "dblclick", function(e) {
  297. var t = getHintElement(hints, e.target || e.srcElement);
  298. if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
  299. });
  300. CodeMirror.on(hints, "click", function(e) {
  301. var t = getHintElement(hints, e.target || e.srcElement);
  302. if (t && t.hintId != null) {
  303. widget.changeActive(t.hintId);
  304. if (completion.options.completeOnSingleClick) widget.pick();
  305. }
  306. });
  307. CodeMirror.on(hints, "mousedown", function() {
  308. setTimeout(function(){cm.focus();}, 20);
  309. });
  310. // The first hint doesn't need to be scrolled to on init
  311. var selectedHintRange = this.getSelectedHintRange();
  312. if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) {
  313. this.scrollToActive();
  314. }
  315. CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]);
  316. return true;
  317. }
  318. Widget.prototype = {
  319. close: function() {
  320. if (this.completion.widget != this) return;
  321. this.completion.widget = null;
  322. if (this.hints.parentNode) this.hints.parentNode.removeChild(this.hints);
  323. this.completion.cm.removeKeyMap(this.keyMap);
  324. var input = this.completion.cm.getInputField()
  325. input.removeAttribute("aria-activedescendant")
  326. input.removeAttribute("aria-owns")
  327. var cm = this.completion.cm;
  328. if (this.completion.options.closeOnUnfocus) {
  329. cm.off("blur", this.onBlur);
  330. cm.off("focus", this.onFocus);
  331. }
  332. cm.off("scroll", this.onScroll);
  333. },
  334. disable: function() {
  335. this.completion.cm.removeKeyMap(this.keyMap);
  336. var widget = this;
  337. this.keyMap = {Enter: function() { widget.picked = true; }};
  338. this.completion.cm.addKeyMap(this.keyMap);
  339. },
  340. pick: function() {
  341. this.completion.pick(this.data, this.selectedHint);
  342. },
  343. changeActive: function(i, avoidWrap) {
  344. if (i >= this.data.list.length)
  345. i = avoidWrap ? this.data.list.length - 1 : 0;
  346. else if (i < 0)
  347. i = avoidWrap ? 0 : this.data.list.length - 1;
  348. if (this.selectedHint == i) return;
  349. var node = this.hints.childNodes[this.selectedHint];
  350. if (node) {
  351. node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
  352. node.removeAttribute("aria-selected")
  353. }
  354. node = this.hints.childNodes[this.selectedHint = i];
  355. node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
  356. node.setAttribute("aria-selected", "true")
  357. this.completion.cm.getInputField().setAttribute("aria-activedescendant", node.id)
  358. this.scrollToActive()
  359. CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
  360. },
  361. scrollToActive: function() {
  362. var selectedHintRange = this.getSelectedHintRange();
  363. var node1 = this.hints.childNodes[selectedHintRange.from];
  364. var node2 = this.hints.childNodes[selectedHintRange.to];
  365. var firstNode = this.hints.firstChild;
  366. if (node1.offsetTop < this.hints.scrollTop)
  367. this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;
  368. else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
  369. this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop;
  370. },
  371. screenAmount: function() {
  372. return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
  373. },
  374. getSelectedHintRange: function() {
  375. var margin = this.completion.options.scrollMargin || 0;
  376. return {
  377. from: Math.max(0, this.selectedHint - margin),
  378. to: Math.min(this.data.list.length - 1, this.selectedHint + margin),
  379. };
  380. }
  381. };
  382. function applicableHelpers(cm, helpers) {
  383. if (!cm.somethingSelected()) return helpers
  384. var result = []
  385. for (var i = 0; i < helpers.length; i++)
  386. if (helpers[i].supportsSelection) result.push(helpers[i])
  387. return result
  388. }
  389. function fetchHints(hint, cm, options, callback) {
  390. if (hint.async) {
  391. hint(cm, callback, options)
  392. } else {
  393. var result = hint(cm, options)
  394. if (result && result.then) result.then(callback)
  395. else callback(result)
  396. }
  397. }
  398. function resolveAutoHints(cm, pos) {
  399. var helpers = cm.getHelpers(pos, "hint"), words
  400. if (helpers.length) {
  401. var resolved = function(cm, callback, options) {
  402. var app = applicableHelpers(cm, helpers);
  403. function run(i) {
  404. if (i == app.length) return callback(null)
  405. fetchHints(app[i], cm, options, function(result) {
  406. if (result && result.list.length > 0) callback(result)
  407. else run(i + 1)
  408. })
  409. }
  410. run(0)
  411. }
  412. resolved.async = true
  413. resolved.supportsSelection = true
  414. return resolved
  415. } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
  416. return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
  417. } else if (CodeMirror.hint.anyword) {
  418. return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
  419. } else {
  420. return function() {}
  421. }
  422. }
  423. CodeMirror.registerHelper("hint", "auto", {
  424. resolve: resolveAutoHints
  425. });
  426. CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
  427. var cur = cm.getCursor(), token = cm.getTokenAt(cur)
  428. var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
  429. if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
  430. term = token.string.substr(0, cur.ch - token.start)
  431. } else {
  432. term = ""
  433. from = cur
  434. }
  435. var found = [];
  436. for (var i = 0; i < options.words.length; i++) {
  437. var word = options.words[i];
  438. if (word.slice(0, term.length) == term)
  439. found.push(word);
  440. }
  441. if (found.length) return {list: found, from: from, to: to};
  442. });
  443. CodeMirror.commands.autocomplete = CodeMirror.showHint;
  444. var defaultOptions = {
  445. hint: CodeMirror.hint.auto,
  446. completeSingle: true,
  447. alignWithWord: true,
  448. closeCharacters: /[\s()\[\]{};:>,]/,
  449. closeOnPick: true,
  450. closeOnUnfocus: true,
  451. updateOnCursorActivity: true,
  452. completeOnSingleClick: true,
  453. container: null,
  454. customKeys: null,
  455. extraKeys: null,
  456. paddingForScrollbar: true,
  457. moveOnOverlap: true,
  458. };
  459. CodeMirror.defineOption("hintOptions", null);
  460. });