fromTextArea.js (1951B)
1 import { CodeMirror } from "./CodeMirror.js" 2 import { activeElt } from "../util/dom.js" 3 import { off, on } from "../util/event.js" 4 import { copyObj } from "../util/misc.js" 5 6 export function fromTextArea(textarea, options) { 7 options = options ? copyObj(options) : {} 8 options.value = textarea.value 9 if (!options.tabindex && textarea.tabIndex) 10 options.tabindex = textarea.tabIndex 11 if (!options.placeholder && textarea.placeholder) 12 options.placeholder = textarea.placeholder 13 // Set autofocus to true if this textarea is focused, or if it has 14 // autofocus and no other element is focused. 15 if (options.autofocus == null) { 16 let hasFocus = activeElt() 17 options.autofocus = hasFocus == textarea || 18 textarea.getAttribute("autofocus") != null && hasFocus == document.body 19 } 20 21 function save() {textarea.value = cm.getValue()} 22 23 let realSubmit 24 if (textarea.form) { 25 on(textarea.form, "submit", save) 26 // Deplorable hack to make the submit method do the right thing. 27 if (!options.leaveSubmitMethodAlone) { 28 let form = textarea.form 29 realSubmit = form.submit 30 try { 31 let wrappedSubmit = form.submit = () => { 32 save() 33 form.submit = realSubmit 34 form.submit() 35 form.submit = wrappedSubmit 36 } 37 } catch(e) {} 38 } 39 } 40 41 options.finishInit = cm => { 42 cm.save = save 43 cm.getTextArea = () => textarea 44 cm.toTextArea = () => { 45 cm.toTextArea = isNaN // Prevent this from being ran twice 46 save() 47 textarea.parentNode.removeChild(cm.getWrapperElement()) 48 textarea.style.display = "" 49 if (textarea.form) { 50 off(textarea.form, "submit", save) 51 if (typeof textarea.form.submit == "function") 52 textarea.form.submit = realSubmit 53 } 54 } 55 } 56 57 textarea.style.display = "none" 58 let cm = CodeMirror(node => textarea.parentNode.insertBefore(node, textarea.nextSibling), 59 options) 60 return cm 61 }