replaceText.ts 816 B

123456789101112131415161718192021222324252627282930313233
  1. import { EditorView } from 'prosemirror-view';
  2. import { Mark, NodeType, Node } from 'prosemirror-model';
  3. export const replaceText = (view: EditorView, newText: string) => {
  4. const { state } = view;
  5. const { schema, doc } = state;
  6. let marks: Mark[] = [];
  7. let nodeType: NodeType = schema.nodes.paragraph;
  8. if (doc.content.size > 2) {
  9. const firstCharPos = doc.resolve(1);
  10. marks = [...firstCharPos.marks()];
  11. nodeType = firstCharPos.parent.type;
  12. }
  13. const lines = newText.split('\n');
  14. const newNodes: Node[] = lines.map((line: string) => {
  15. if (line.trim() === '') return nodeType.create();
  16. const textNode = schema.text(line, marks);
  17. return nodeType.create(null, textNode);
  18. });
  19. const tr = state.tr;
  20. tr.replaceWith(0, doc.content.size, newNodes);
  21. view.dispatch(tr);
  22. };