prosemirror: converting JSON output into HTML

Viewed 3117

I'm trying to convert ProseMirror's JSON output back to HTML (to save it from one db to another). I am new with ProseMirror and I'm not sure I fully understand the relation between model, state and schema.

Judging from what I have read https://github.com/ProseMirror/prosemirror/issues/455 and https://discuss.prosemirror.net/t/example-of-converting-between-formats-for-the-purpose-of-saving/424,

I should first create a new state based on a basic schema, then use the DOMSerializer and attach the output to a temporary element (then get innerHtml). Does that sound about right? Any help would be greatly appreciated.

1 Answers

After some digging, here's how I got this to work:

  1. Create a node using .fromJSON
  2. Make a DOMSerializer based on the schema used by the editor
  3. Pass the node to the serializer

My code is below.

const { schema } = require("prosemirror-schema-basic")
const { Node, DOMSerializer } = require("prosemirror-model")
const jsdom = require("jsdom").JSDOM

let dom = new jsdom('<!DOCTYPE html><div id="content"></div>')
let doc = dom.window.document
let target = doc.querySelector("div")
//Demo JSON output from ProseMirror
let content = {
  "doc": {
    "type": "doc",
    "content": [{
      "type": "paragraph",
      "attrs": {
        "align": "left"
      },
      "content": [{
        "type": "text",
        "text": "My sample text"
      }]
    }]
  },
  "selection": {
    "type": "text",
    "anchor": 16,
    "head": 16
  }
}

let contentNode = Node.fromJSON(schema, content.doc)

DOMSerializer
  .fromSchema(schema)
  .serializeFragment(contentNode.content, {
    "document": doc
  }, target)

console.log(doc.getElementById("content").innerHTML)
//<p>My sample text</p>

Related