index.ts 1018 B

1234567891011121314151617181920212223242526272829303132
  1. import { EditorState } from 'prosemirror-state';
  2. import { type DirectEditorProps, EditorView } from 'prosemirror-view';
  3. import { Schema, DOMParser } from 'prosemirror-model';
  4. import { buildPlugins, type PluginOptions } from './plugins/index';
  5. import { schemaNodes, schemaMarks } from './schema/index';
  6. const schema = new Schema({
  7. nodes: schemaNodes,
  8. marks: schemaMarks,
  9. });
  10. export const createDocument = (content: string) => {
  11. const htmlString = `<div>${content}</div>`;
  12. const parser = new window.DOMParser();
  13. const element = parser.parseFromString(htmlString, 'text/html').body.firstElementChild;
  14. return DOMParser.fromSchema(schema).parse(element as Element);
  15. };
  16. export const initProsemirrorEditor = (
  17. dom: Element,
  18. content: string,
  19. props: Omit<DirectEditorProps, 'state'>,
  20. pluginOptions?: PluginOptions,
  21. ) => {
  22. return new EditorView(dom, {
  23. state: EditorState.create({
  24. doc: createDocument(content),
  25. plugins: buildPlugins(schema, pluginOptions),
  26. }),
  27. ...props,
  28. });
  29. };