summaryrefslogtreecommitdiff
path: root/spec/frontend/content_editor/render_html_and_json_for_all_examples.js
blob: 5df901e0f15fbd7e14efb2027a40faa7d3f813fe (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
37
38
39
40
41
42
43
44
45
46
import { DOMSerializer } from 'prosemirror-model';
import createMarkdownDeserializer from '~/content_editor/services/remark_markdown_deserializer';
import { createTiptapEditor } from 'jest/content_editor/test_utils';

const tiptapEditor = createTiptapEditor();

export const IMPLEMENTATION_ERROR_MSG = 'Error - check implementation';

async function renderMarkdownToHTMLAndJSON(markdown, schema, deserializer) {
  let prosemirrorDocument;
  try {
    const { document } = await deserializer.deserialize({ schema, markdown });
    prosemirrorDocument = document;
  } catch (e) {
    const errorMsg = `${IMPLEMENTATION_ERROR_MSG}:\n${e.message}`;
    return {
      html: errorMsg,
      json: errorMsg,
    };
  }

  const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(
    prosemirrorDocument.content,
  );
  const htmlString = Array.from(documentFragment.children)
    .map((el) => el.outerHTML)
    .join('\n');

  const json = prosemirrorDocument.toJSON();
  const jsonString = JSON.stringify(json, null, 2);
  return { html: htmlString, json: jsonString };
}

export function renderHtmlAndJsonForAllExamples(markdownExamples) {
  const { schema } = tiptapEditor;
  const deserializer = createMarkdownDeserializer();
  const exampleNames = Object.keys(markdownExamples);

  return exampleNames.reduce(async (promisedExamples, exampleName) => {
    const markdown = markdownExamples[exampleName];
    const htmlAndJson = await renderMarkdownToHTMLAndJSON(markdown, schema, deserializer);
    const examples = await promisedExamples;
    examples[exampleName] = htmlAndJson;
    return examples;
  }, Promise.resolve({}));
}