You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

530 lines
20KB

  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.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) {
  252. var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
  253. if (curTop - height > 0) { // Fits above cursor
  254. hints.style.top = (top = pos.top - height - offsetTop) + "px";
  255. below = false;
  256. } else if (height > winH) {
  257. hints.style.height = (winH - 5) + "px";
  258. hints.style.top = (top = pos.bottom - box.top - offsetTop) + "px";
  259. var cursor = cm.getCursor();
  260. if (data.from.ch != cursor.ch) {
  261. pos = cm.cursorCoords(cursor);
  262. hints.style.left = (left = pos.left - offsetLeft) + "px";
  263. box = hints.getBoundingClientRect();
  264. }
  265. }
  266. }
  267. var overlapX = box.right - winW;
  268. if (scrolls) overlapX += cm.display.nativeBarWidth;
  269. if (overlapX > 0) {
  270. if (box.right - box.left > winW) {
  271. hints.style.width = (winW - 5) + "px";
  272. overlapX -= (box.right - box.left) - winW;
  273. }
  274. hints.style.left = (left = pos.left - overlapX - offsetLeft) + "px";
  275. }
  276. if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
  277. node.style.paddingRight = cm.display.nativeBarWidth + "px"
  278. cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
  279. moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
  280. setFocus: function(n) { widget.changeActive(n); },
  281. menuSize: function() { return widget.screenAmount(); },
  282. length: completions.length,
  283. close: function() { completion.close(); },
  284. pick: function() { widget.pick(); },
  285. data: data
  286. }));
  287. if (completion.options.closeOnUnfocus) {
  288. var closingOnBlur;
  289. cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
  290. cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
  291. }
  292. cm.on("scroll", this.onScroll = function() {
  293. var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
  294. if (!startScroll) startScroll = cm.getScrollInfo();
  295. var newTop = top + startScroll.top - curScroll.top;
  296. var point = newTop - (parentWindow.pageYOffset || (ownerDocument.documentElement || ownerDocument.body).scrollTop);
  297. if (!below) point += hints.offsetHeight;
  298. if (point <= editor.top || point >= editor.bottom) return completion.close();
  299. hints.style.top = newTop + "px";
  300. hints.style.left = (left + startScroll.left - curScroll.left) + "px";
  301. });
  302. CodeMirror.on(hints, "dblclick", function(e) {
  303. var t = getHintElement(hints, e.target || e.srcElement);
  304. if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
  305. });
  306. CodeMirror.on(hints, "click", function(e) {
  307. var t = getHintElement(hints, e.target || e.srcElement);
  308. if (t && t.hintId != null) {
  309. widget.changeActive(t.hintId);
  310. if (completion.options.completeOnSingleClick) widget.pick();
  311. }
  312. });
  313. CodeMirror.on(hints, "mousedown", function() {
  314. setTimeout(function(){cm.focus();}, 20);
  315. });
  316. // The first hint doesn't need to be scrolled to on init
  317. var selectedHintRange = this.getSelectedHintRange();
  318. if (selectedHintRange.from !== 0 || selectedHintRange.to !== 0) {
  319. this.scrollToActive();
  320. }
  321. CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]);
  322. return true;
  323. }
  324. Widget.prototype = {
  325. close: function() {
  326. if (this.completion.widget != this) return;
  327. this.completion.widget = null;
  328. if (this.hints.parentNode) this.hints.parentNode.removeChild(this.hints);
  329. this.completion.cm.removeKeyMap(this.keyMap);
  330. var input = this.completion.cm.getInputField()
  331. input.removeAttribute("aria-activedescendant")
  332. input.removeAttribute("aria-owns")
  333. var cm = this.completion.cm;
  334. if (this.completion.options.closeOnUnfocus) {
  335. cm.off("blur", this.onBlur);
  336. cm.off("focus", this.onFocus);
  337. }
  338. cm.off("scroll", this.onScroll);
  339. },
  340. disable: function() {
  341. this.completion.cm.removeKeyMap(this.keyMap);
  342. var widget = this;
  343. this.keyMap = {Enter: function() { widget.picked = true; }};
  344. this.completion.cm.addKeyMap(this.keyMap);
  345. },
  346. pick: function() {
  347. this.completion.pick(this.data, this.selectedHint);
  348. },
  349. changeActive: function(i, avoidWrap) {
  350. if (i >= this.data.list.length)
  351. i = avoidWrap ? this.data.list.length - 1 : 0;
  352. else if (i < 0)
  353. i = avoidWrap ? 0 : this.data.list.length - 1;
  354. if (this.selectedHint == i) return;
  355. var node = this.hints.childNodes[this.selectedHint];
  356. if (node) {
  357. node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
  358. node.removeAttribute("aria-selected")
  359. }
  360. node = this.hints.childNodes[this.selectedHint = i];
  361. node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
  362. node.setAttribute("aria-selected", "true")
  363. this.completion.cm.getInputField().setAttribute("aria-activedescendant", node.id)
  364. this.scrollToActive()
  365. CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
  366. },
  367. scrollToActive: function() {
  368. var selectedHintRange = this.getSelectedHintRange();
  369. var node1 = this.hints.childNodes[selectedHintRange.from];
  370. var node2 = this.hints.childNodes[selectedHintRange.to];
  371. var firstNode = this.hints.firstChild;
  372. if (node1.offsetTop < this.hints.scrollTop)
  373. this.hints.scrollTop = node1.offsetTop - firstNode.offsetTop;
  374. else if (node2.offsetTop + node2.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
  375. this.hints.scrollTop = node2.offsetTop + node2.offsetHeight - this.hints.clientHeight + firstNode.offsetTop;
  376. },
  377. screenAmount: function() {
  378. return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
  379. },
  380. getSelectedHintRange: function() {
  381. var margin = this.completion.options.scrollMargin || 0;
  382. return {
  383. from: Math.max(0, this.selectedHint - margin),
  384. to: Math.min(this.data.list.length - 1, this.selectedHint + margin),
  385. };
  386. }
  387. };
  388. function applicableHelpers(cm, helpers) {
  389. if (!cm.somethingSelected()) return helpers
  390. var result = []
  391. for (var i = 0; i < helpers.length; i++)
  392. if (helpers[i].supportsSelection) result.push(helpers[i])
  393. return result
  394. }
  395. function fetchHints(hint, cm, options, callback) {
  396. if (hint.async) {
  397. hint(cm, callback, options)
  398. } else {
  399. var result = hint(cm, options)
  400. if (result && result.then) result.then(callback)
  401. else callback(result)
  402. }
  403. }
  404. function resolveAutoHints(cm, pos) {
  405. var helpers = cm.getHelpers(pos, "hint"), words
  406. if (helpers.length) {
  407. var resolved = function(cm, callback, options) {
  408. var app = applicableHelpers(cm, helpers);
  409. function run(i) {
  410. if (i == app.length) return callback(null)
  411. fetchHints(app[i], cm, options, function(result) {
  412. if (result && result.list.length > 0) callback(result)
  413. else run(i + 1)
  414. })
  415. }
  416. run(0)
  417. }
  418. resolved.async = true
  419. resolved.supportsSelection = true
  420. return resolved
  421. } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
  422. return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
  423. } else if (CodeMirror.hint.anyword) {
  424. return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
  425. } else {
  426. return function() {}
  427. }
  428. }
  429. CodeMirror.registerHelper("hint", "auto", {
  430. resolve: resolveAutoHints
  431. });
  432. CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
  433. var cur = cm.getCursor(), token = cm.getTokenAt(cur)
  434. var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
  435. if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
  436. term = token.string.substr(0, cur.ch - token.start)
  437. } else {
  438. term = ""
  439. from = cur
  440. }
  441. var found = [];
  442. for (var i = 0; i < options.words.length; i++) {
  443. var word = options.words[i];
  444. if (word.slice(0, term.length) == term)
  445. found.push(word);
  446. }
  447. if (found.length) return {list: found, from: from, to: to};
  448. });
  449. CodeMirror.commands.autocomplete = CodeMirror.showHint;
  450. var defaultOptions = {
  451. hint: CodeMirror.hint.auto,
  452. completeSingle: true,
  453. alignWithWord: true,
  454. closeCharacters: /[\s()\[\]{};:>,]/,
  455. closeOnPick: true,
  456. closeOnUnfocus: true,
  457. updateOnCursorActivity: true,
  458. completeOnSingleClick: true,
  459. container: null,
  460. customKeys: null,
  461. extraKeys: null,
  462. paddingForScrollbar: true,
  463. moveOnOverlap: true,
  464. };
  465. CodeMirror.defineOption("hintOptions", null);
  466. });