newline.ts 742 B

1234567891011121314151617181920212223242526272829303132333435
  1. function getIndent(text) {
  2. let offset = text.length - text.trimLeft().length;
  3. if (offset) {
  4. let indent = text[0];
  5. while (--offset) {
  6. indent += text[0];
  7. }
  8. return indent;
  9. }
  10. return '';
  11. }
  12. export default function NewlinePlugin() {
  13. return {
  14. onKeyDown(event, change) {
  15. const { value } = change;
  16. if (!value.isCollapsed) {
  17. return undefined;
  18. }
  19. if (event.key === 'Enter' && !event.shiftKey) {
  20. event.preventDefault();
  21. const { startBlock } = value;
  22. const currentLineText = startBlock.text;
  23. const indent = getIndent(currentLineText);
  24. return change
  25. .splitBlock()
  26. .insertText(indent)
  27. .focus();
  28. }
  29. },
  30. };
  31. }