show-hint.js 23 KB

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