model/input.binding.js

  1. import { Binding } from "domodel"
  2. /**
  3. * @global
  4. */
  5. class InputBinding extends Binding {
  6. /**
  7. * @param {object} properties
  8. * @param {Editor} properties.editor
  9. * @param {Template} properties.template
  10. */
  11. constructor(properties) {
  12. super(properties)
  13. }
  14. onCreated() {
  15. const { editor, template } = this.properties
  16. this.listen(editor, "setHTMLMode", () => {
  17. this.root.innerHTML = template.toHTML(this.root.textContent)
  18. })
  19. this.listen(editor, "setRawMode", () => {
  20. this.root.textContent = template.toRaw(this.root.innerHTML)
  21. })
  22. this.listen(editor, "setRaw", (data) => {
  23. const html = template.toHTML(data)
  24. this.root.innerHTML = html
  25. editor.emit("inputChanged", { html, raw: data })
  26. })
  27. this.root.addEventListener("input", () => {
  28. editor.emit("inputChanged", { html: template.toHTML(this.root.textContent), raw: template.toRaw(this.root.innerHTML) })
  29. })
  30. this.root.addEventListener("keypress", event => {
  31. if (event.keyCode === 13) {
  32. event.preventDefault()
  33. const selection = this.root.ownerDocument.getSelection()
  34. const range = selection.getRangeAt(0)
  35. const brNode = document.createTextNode("\n")
  36. range.insertNode(brNode)
  37. range.setStartAfter(brNode)
  38. }
  39. })
  40. }
  41. }
  42. export default InputBinding