29c82137248800dac93b3b7898f16c50504d866e8b0ab781d71d20aa1761d3d50b5a809598ff70add874ceaf629c4abfeb0c18cd2d0a2356624f4350ef5992 2.0 KB

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