ContentEditableInput.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. import { operation, runInOp } from "../display/operations.js"
  2. import { prepareSelection } from "../display/selection.js"
  3. import { regChange } from "../display/view_tracking.js"
  4. import { applyTextInput, copyableRanges, disableBrowserMagic, handlePaste, hiddenTextarea, lastCopied, setLastCopied } from "./input.js"
  5. import { cmp, maxPos, minPos, Pos } from "../line/pos.js"
  6. import { getBetween, getLine, lineNo } from "../line/utils_line.js"
  7. import { findViewForLine, findViewIndex, mapFromLineView, nodeAndOffsetInLineMap } from "../measurement/position_measurement.js"
  8. import { replaceRange } from "../model/changes.js"
  9. import { simpleSelection } from "../model/selection.js"
  10. import { setSelection } from "../model/selection_updates.js"
  11. import { getBidiPartAt, getOrder } from "../util/bidi.js"
  12. import { android, chrome, gecko, ie_version } from "../util/browser.js"
  13. import { contains, range, removeChildrenAndAdd, selectInput } from "../util/dom.js"
  14. import { on, signalDOMEvent } from "../util/event.js"
  15. import { Delayed, lst, sel_dontScroll } from "../util/misc.js"
  16. // CONTENTEDITABLE INPUT STYLE
  17. export default class ContentEditableInput {
  18. constructor(cm) {
  19. this.cm = cm
  20. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  21. this.polling = new Delayed()
  22. this.composing = null
  23. this.gracePeriod = false
  24. this.readDOMTimeout = null
  25. }
  26. init(display) {
  27. let input = this, cm = input.cm
  28. let div = input.div = display.lineDiv
  29. disableBrowserMagic(div, cm.options.spellcheck)
  30. on(div, "paste", e => {
  31. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  32. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  33. if (ie_version <= 11) setTimeout(operation(cm, () => this.updateFromDOM()), 20)
  34. })
  35. on(div, "compositionstart", e => {
  36. this.composing = {data: e.data, done: false}
  37. })
  38. on(div, "compositionupdate", e => {
  39. if (!this.composing) this.composing = {data: e.data, done: false}
  40. })
  41. on(div, "compositionend", e => {
  42. if (this.composing) {
  43. if (e.data != this.composing.data) this.readFromDOMSoon()
  44. this.composing.done = true
  45. }
  46. })
  47. on(div, "touchstart", () => input.forceCompositionEnd())
  48. on(div, "input", () => {
  49. if (!this.composing) this.readFromDOMSoon()
  50. })
  51. function onCopyCut(e) {
  52. if (signalDOMEvent(cm, e)) return
  53. if (cm.somethingSelected()) {
  54. setLastCopied({lineWise: false, text: cm.getSelections()})
  55. if (e.type == "cut") cm.replaceSelection("", null, "cut")
  56. } else if (!cm.options.lineWiseCopyCut) {
  57. return
  58. } else {
  59. let ranges = copyableRanges(cm)
  60. setLastCopied({lineWise: true, text: ranges.text})
  61. if (e.type == "cut") {
  62. cm.operation(() => {
  63. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  64. cm.replaceSelection("", null, "cut")
  65. })
  66. }
  67. }
  68. if (e.clipboardData) {
  69. e.clipboardData.clearData()
  70. let content = lastCopied.text.join("\n")
  71. // iOS exposes the clipboard API, but seems to discard content inserted into it
  72. e.clipboardData.setData("Text", content)
  73. if (e.clipboardData.getData("Text") == content) {
  74. e.preventDefault()
  75. return
  76. }
  77. }
  78. // Old-fashioned briefly-focus-a-textarea hack
  79. let kludge = hiddenTextarea(), te = kludge.firstChild
  80. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  81. te.value = lastCopied.text.join("\n")
  82. let hadFocus = document.activeElement
  83. selectInput(te)
  84. setTimeout(() => {
  85. cm.display.lineSpace.removeChild(kludge)
  86. hadFocus.focus()
  87. if (hadFocus == div) input.showPrimarySelection()
  88. }, 50)
  89. }
  90. on(div, "copy", onCopyCut)
  91. on(div, "cut", onCopyCut)
  92. }
  93. prepareSelection() {
  94. let result = prepareSelection(this.cm, false)
  95. result.focus = this.cm.state.focused
  96. return result
  97. }
  98. showSelection(info, takeFocus) {
  99. if (!info || !this.cm.display.view.length) return
  100. if (info.focus || takeFocus) this.showPrimarySelection()
  101. this.showMultipleSelections(info)
  102. }
  103. getSelection() {
  104. return this.cm.display.wrapper.ownerDocument.getSelection()
  105. }
  106. showPrimarySelection() {
  107. let sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary()
  108. let from = prim.from(), to = prim.to()
  109. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  110. sel.removeAllRanges()
  111. return
  112. }
  113. let curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  114. let curFocus = domToPos(cm, sel.focusNode, sel.focusOffset)
  115. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  116. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  117. cmp(maxPos(curAnchor, curFocus), to) == 0)
  118. return
  119. let view = cm.display.view
  120. let start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  121. {node: view[0].measure.map[2], offset: 0}
  122. let end = to.line < cm.display.viewTo && posToDOM(cm, to)
  123. if (!end) {
  124. let measure = view[view.length - 1].measure
  125. let map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  126. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}
  127. }
  128. if (!start || !end) {
  129. sel.removeAllRanges()
  130. return
  131. }
  132. let old = sel.rangeCount && sel.getRangeAt(0), rng
  133. try { rng = range(start.node, start.offset, end.offset, end.node) }
  134. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  135. if (rng) {
  136. if (!gecko && cm.state.focused) {
  137. sel.collapse(start.node, start.offset)
  138. if (!rng.collapsed) {
  139. sel.removeAllRanges()
  140. sel.addRange(rng)
  141. }
  142. } else {
  143. sel.removeAllRanges()
  144. sel.addRange(rng)
  145. }
  146. if (old && sel.anchorNode == null) sel.addRange(old)
  147. else if (gecko) this.startGracePeriod()
  148. }
  149. this.rememberSelection()
  150. }
  151. startGracePeriod() {
  152. clearTimeout(this.gracePeriod)
  153. this.gracePeriod = setTimeout(() => {
  154. this.gracePeriod = false
  155. if (this.selectionChanged())
  156. this.cm.operation(() => this.cm.curOp.selectionChanged = true)
  157. }, 20)
  158. }
  159. showMultipleSelections(info) {
  160. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  161. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  162. }
  163. rememberSelection() {
  164. let sel = this.getSelection()
  165. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
  166. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
  167. }
  168. selectionInEditor() {
  169. let sel = this.getSelection()
  170. if (!sel.rangeCount) return false
  171. let node = sel.getRangeAt(0).commonAncestorContainer
  172. return contains(this.div, node)
  173. }
  174. focus() {
  175. if (this.cm.options.readOnly != "nocursor") {
  176. if (!this.selectionInEditor())
  177. this.showSelection(this.prepareSelection(), true)
  178. this.div.focus()
  179. }
  180. }
  181. blur() { this.div.blur() }
  182. getField() { return this.div }
  183. supportsTouch() { return true }
  184. receivedFocus() {
  185. let input = this
  186. if (this.selectionInEditor())
  187. this.pollSelection()
  188. else
  189. runInOp(this.cm, () => input.cm.curOp.selectionChanged = true)
  190. function poll() {
  191. if (input.cm.state.focused) {
  192. input.pollSelection()
  193. input.polling.set(input.cm.options.pollInterval, poll)
  194. }
  195. }
  196. this.polling.set(this.cm.options.pollInterval, poll)
  197. }
  198. selectionChanged() {
  199. let sel = this.getSelection()
  200. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  201. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  202. }
  203. pollSelection() {
  204. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) return
  205. let sel = this.getSelection(), cm = this.cm
  206. // On Android Chrome (version 56, at least), backspacing into an
  207. // uneditable block element will put the cursor in that element,
  208. // and then, because it's not editable, hide the virtual keyboard.
  209. // Because Android doesn't allow us to actually detect backspace
  210. // presses in a sane way, this code checks for when that happens
  211. // and simulates a backspace press in this case.
  212. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  213. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs})
  214. this.blur()
  215. this.focus()
  216. return
  217. }
  218. if (this.composing) return
  219. this.rememberSelection()
  220. let anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  221. let head = domToPos(cm, sel.focusNode, sel.focusOffset)
  222. if (anchor && head) runInOp(cm, () => {
  223. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  224. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true
  225. })
  226. }
  227. pollContent() {
  228. if (this.readDOMTimeout != null) {
  229. clearTimeout(this.readDOMTimeout)
  230. this.readDOMTimeout = null
  231. }
  232. let cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
  233. let from = sel.from(), to = sel.to()
  234. if (from.ch == 0 && from.line > cm.firstLine())
  235. from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length)
  236. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  237. to = Pos(to.line + 1, 0)
  238. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false
  239. let fromIndex, fromLine, fromNode
  240. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  241. fromLine = lineNo(display.view[0].line)
  242. fromNode = display.view[0].node
  243. } else {
  244. fromLine = lineNo(display.view[fromIndex].line)
  245. fromNode = display.view[fromIndex - 1].node.nextSibling
  246. }
  247. let toIndex = findViewIndex(cm, to.line)
  248. let toLine, toNode
  249. if (toIndex == display.view.length - 1) {
  250. toLine = display.viewTo - 1
  251. toNode = display.lineDiv.lastChild
  252. } else {
  253. toLine = lineNo(display.view[toIndex + 1].line) - 1
  254. toNode = display.view[toIndex + 1].node.previousSibling
  255. }
  256. if (!fromNode) return false
  257. let newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  258. let oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  259. while (newText.length > 1 && oldText.length > 1) {
  260. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
  261. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
  262. else break
  263. }
  264. let cutFront = 0, cutEnd = 0
  265. let newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
  266. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  267. ++cutFront
  268. let newBot = lst(newText), oldBot = lst(oldText)
  269. let maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  270. oldBot.length - (oldText.length == 1 ? cutFront : 0))
  271. while (cutEnd < maxCutEnd &&
  272. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  273. ++cutEnd
  274. // Try to move start of change to start of selection if ambiguous
  275. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  276. while (cutFront && cutFront > from.ch &&
  277. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  278. cutFront--
  279. cutEnd++
  280. }
  281. }
  282. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "")
  283. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "")
  284. let chFrom = Pos(fromLine, cutFront)
  285. let chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  286. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  287. replaceRange(cm.doc, newText, chFrom, chTo, "+input")
  288. return true
  289. }
  290. }
  291. ensurePolled() {
  292. this.forceCompositionEnd()
  293. }
  294. reset() {
  295. this.forceCompositionEnd()
  296. }
  297. forceCompositionEnd() {
  298. if (!this.composing) return
  299. clearTimeout(this.readDOMTimeout)
  300. this.composing = null
  301. this.updateFromDOM()
  302. this.div.blur()
  303. this.div.focus()
  304. }
  305. readFromDOMSoon() {
  306. if (this.readDOMTimeout != null) return
  307. this.readDOMTimeout = setTimeout(() => {
  308. this.readDOMTimeout = null
  309. if (this.composing) {
  310. if (this.composing.done) this.composing = null
  311. else return
  312. }
  313. this.updateFromDOM()
  314. }, 80)
  315. }
  316. updateFromDOM() {
  317. if (this.cm.isReadOnly() || !this.pollContent())
  318. runInOp(this.cm, () => regChange(this.cm))
  319. }
  320. setUneditable(node) {
  321. node.contentEditable = "false"
  322. }
  323. onKeyPress(e) {
  324. if (e.charCode == 0 || this.composing) return
  325. e.preventDefault()
  326. if (!this.cm.isReadOnly())
  327. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0)
  328. }
  329. readOnlyChanged(val) {
  330. this.div.contentEditable = String(val != "nocursor")
  331. }
  332. onContextMenu() {}
  333. resetPosition() {}
  334. }
  335. ContentEditableInput.prototype.needsContentAttribute = true
  336. function posToDOM(cm, pos) {
  337. let view = findViewForLine(cm, pos.line)
  338. if (!view || view.hidden) return null
  339. let line = getLine(cm.doc, pos.line)
  340. let info = mapFromLineView(view, line, pos.line)
  341. let order = getOrder(line, cm.doc.direction), side = "left"
  342. if (order) {
  343. let partPos = getBidiPartAt(order, pos.ch)
  344. side = partPos % 2 ? "right" : "left"
  345. }
  346. let result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  347. result.offset = result.collapse == "right" ? result.end : result.start
  348. return result
  349. }
  350. function isInGutter(node) {
  351. for (let scan = node; scan; scan = scan.parentNode)
  352. if (/CodeMirror-gutter-wrapper/.test(scan.className)) return true
  353. return false
  354. }
  355. function badPos(pos, bad) { if (bad) pos.bad = true; return pos }
  356. function domTextBetween(cm, from, to, fromLine, toLine) {
  357. let text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false
  358. function recognizeMarker(id) { return marker => marker.id == id }
  359. function close() {
  360. if (closing) {
  361. text += lineSep
  362. if (extraLinebreak) text += lineSep
  363. closing = extraLinebreak = false
  364. }
  365. }
  366. function addText(str) {
  367. if (str) {
  368. close()
  369. text += str
  370. }
  371. }
  372. function walk(node) {
  373. if (node.nodeType == 1) {
  374. let cmText = node.getAttribute("cm-text")
  375. if (cmText) {
  376. addText(cmText)
  377. return
  378. }
  379. let markerID = node.getAttribute("cm-marker"), range
  380. if (markerID) {
  381. let found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  382. if (found.length && (range = found[0].find(0)))
  383. addText(getBetween(cm.doc, range.from, range.to).join(lineSep))
  384. return
  385. }
  386. if (node.getAttribute("contenteditable") == "false") return
  387. let isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName)
  388. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) return
  389. if (isBlock) close()
  390. for (let i = 0; i < node.childNodes.length; i++)
  391. walk(node.childNodes[i])
  392. if (/^(pre|p)$/i.test(node.nodeName)) extraLinebreak = true
  393. if (isBlock) closing = true
  394. } else if (node.nodeType == 3) {
  395. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "))
  396. }
  397. }
  398. for (;;) {
  399. walk(from)
  400. if (from == to) break
  401. from = from.nextSibling
  402. extraLinebreak = false
  403. }
  404. return text
  405. }
  406. function domToPos(cm, node, offset) {
  407. let lineNode
  408. if (node == cm.display.lineDiv) {
  409. lineNode = cm.display.lineDiv.childNodes[offset]
  410. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true)
  411. node = null; offset = 0
  412. } else {
  413. for (lineNode = node;; lineNode = lineNode.parentNode) {
  414. if (!lineNode || lineNode == cm.display.lineDiv) return null
  415. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break
  416. }
  417. }
  418. for (let i = 0; i < cm.display.view.length; i++) {
  419. let lineView = cm.display.view[i]
  420. if (lineView.node == lineNode)
  421. return locateNodeInLineView(lineView, node, offset)
  422. }
  423. }
  424. function locateNodeInLineView(lineView, node, offset) {
  425. let wrapper = lineView.text.firstChild, bad = false
  426. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true)
  427. if (node == wrapper) {
  428. bad = true
  429. node = wrapper.childNodes[offset]
  430. offset = 0
  431. if (!node) {
  432. let line = lineView.rest ? lst(lineView.rest) : lineView.line
  433. return badPos(Pos(lineNo(line), line.text.length), bad)
  434. }
  435. }
  436. let textNode = node.nodeType == 3 ? node : null, topNode = node
  437. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  438. textNode = node.firstChild
  439. if (offset) offset = textNode.nodeValue.length
  440. }
  441. while (topNode.parentNode != wrapper) topNode = topNode.parentNode
  442. let measure = lineView.measure, maps = measure.maps
  443. function find(textNode, topNode, offset) {
  444. for (let i = -1; i < (maps ? maps.length : 0); i++) {
  445. let map = i < 0 ? measure.map : maps[i]
  446. for (let j = 0; j < map.length; j += 3) {
  447. let curNode = map[j + 2]
  448. if (curNode == textNode || curNode == topNode) {
  449. let line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  450. let ch = map[j] + offset
  451. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]
  452. return Pos(line, ch)
  453. }
  454. }
  455. }
  456. }
  457. let found = find(textNode, topNode, offset)
  458. if (found) return badPos(found, bad)
  459. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  460. for (let after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  461. found = find(after, after.firstChild, 0)
  462. if (found)
  463. return badPos(Pos(found.line, found.ch - dist), bad)
  464. else
  465. dist += after.textContent.length
  466. }
  467. for (let before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  468. found = find(before, before.firstChild, -1)
  469. if (found)
  470. return badPos(Pos(found.line, found.ch + dist), bad)
  471. else
  472. dist += before.textContent.length
  473. }
  474. }