code.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import Block from '../blots/block';
  2. import Break from '../blots/break';
  3. import Cursor from '../blots/cursor';
  4. import Inline from '../blots/inline';
  5. import TextBlot, { escapeText } from '../blots/text';
  6. import Container from '../blots/container';
  7. import Quill from '../core/quill';
  8. class CodeBlockContainer extends Container {
  9. static create(value) {
  10. const domNode = super.create(value);
  11. domNode.setAttribute('spellcheck', false);
  12. return domNode;
  13. }
  14. code(index, length) {
  15. const text = this.children
  16. .map(child => (child.length() <= 1 ? '' : child.domNode.innerText))
  17. .join('\n')
  18. .slice(index, index + length);
  19. return escapeText(text);
  20. }
  21. html(index, length) {
  22. // `\n`s are needed in order to support empty lines at the beginning and the end.
  23. // https://html.spec.whatwg.org/multipage/syntax.html#element-restrictions
  24. return `<pre>\n${this.code(index, length)}\n</pre>`;
  25. }
  26. }
  27. class CodeBlock extends Block {
  28. static register(options) {
  29. Quill.register(CodeBlockContainer, options);
  30. }
  31. }
  32. class Code extends Inline {}
  33. Code.blotName = 'code';
  34. Code.tagName = 'CODE';
  35. CodeBlock.blotName = 'code-block';
  36. CodeBlock.className = 'ql-code-block';
  37. CodeBlock.tagName = 'DIV';
  38. CodeBlockContainer.blotName = 'code-block-container';
  39. CodeBlockContainer.className = 'ql-code-block-container';
  40. CodeBlockContainer.tagName = 'DIV';
  41. CodeBlockContainer.allowedChildren = [CodeBlock];
  42. CodeBlock.allowedChildren = [TextBlot, Break, Cursor];
  43. CodeBlock.requiredContainer = CodeBlockContainer;
  44. CodeBlock.TAB = ' ';
  45. export { Code, CodeBlockContainer, CodeBlock as default };