index.ts 875 B

12345678910111213141516171819202122232425262728
  1. import { EditorState } from 'prosemirror-state'
  2. import { EditorView } from 'prosemirror-view'
  3. import { Schema, DOMParser } from 'prosemirror-model'
  4. import { buildPlugins } 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 = (dom: Element, content: string, props = {}) => {
  17. return new EditorView(dom, {
  18. state: EditorState.create({
  19. doc: createDocument(content),
  20. plugins: buildPlugins(schema),
  21. }),
  22. ...props,
  23. })
  24. }