summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/content_editor/services/gl_api_markdown_deserializer.js
blob: e65644d2c5c5b451eea075b5bf46dd062f651268 (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
34
35
36
import { DOMParser as ProseMirrorDOMParser } from '@tiptap/pm/model';
import { replaceCommentsWith } from '~/lib/utils/dom_utils';

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, markdown }) => {
      const html = await render(markdown);

      if (!html) return {};

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

      replaceCommentsWith(body, 'comment');

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

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