summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/content_editor/services/markdown_deserializer.js
blob: cd4863d8eacac6ab7f83d1edcb8a67d648de8475 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { DOMParser as ProseMirrorDOMParser } from 'prosemirror-model';

export default ({ render }) => {
  /**
   * Converts a Markdown string into a ProseMirror JSONDocument based
   * on a ProseMirror schema.
   *
   * @param {Object} options — The schema and content for deserialization
   * @param {ProseMirror.Schema} params.schema A ProseMirror schema that defines
   * the types of content supported in the document
   * @param {String} params.content An arbitrary markdown string
   *
   * @returns An object with the following properties:
   *  - document: A ProseMirror document object generated from the deserialized Markdown
   *  - dom: The Markdown Deserializer renders Markdown as HTML to generate the ProseMirror
   *    document. The dom property contains the HTML generated from the Markdown Source.
   */
  return {
    deserialize: async ({ schema, content }) => {
      const html = await render(content);

      if (!html) return {};

      const parser = new DOMParser();
      const { body } = parser.parseFromString(html, 'text/html');

      // append original source as a comment that nodes can access
      body.append(document.createComment(content));

      return { document: ProseMirrorDOMParser.fromSchema(schema).parse(body), dom: body };
    },
  };
};