Skip to content

Instantly share code, notes, and snippets.

@vpontis
Created June 7, 2021 04:38
Show Gist options
  • Save vpontis/e5e373ea9950b413c18c867a5aedf352 to your computer and use it in GitHub Desktop.
Save vpontis/e5e373ea9950b413c18c867a5aedf352 to your computer and use it in GitHub Desktop.
import { DOMParser } from "prosemirror-model";
import React from "react";
import ReactDOMServer from "react-dom/server";
import { MirrorDocumentValue, mirrorSchema } from "./mirror-schema";
import { MirrorNodeValue, MirrorReactView } from "./MirrorReactView";
export const getHtmlContentFromMirror = ({
mirrorValue,
}: {
mirrorValue: MirrorDocumentValue;
}): { html: string | null; text: string | null } => {
if (!mirrorValue) {
return { html: null, text: null };
}
const html = ReactDOMServer.renderToString(
<MirrorReactView docValue={mirrorValue} />
);
const text = getTextFromMirrorDocument(mirrorValue);
return { html, text };
};
export const getMirrorJsonFromHtml = ({
domNode,
}: {
domNode: HTMLElement;
}): { mirror_value: MirrorDocumentValue } => {
const serializer = DOMParser.fromSchema(mirrorSchema);
const mirrorNode = serializer.parse(domNode);
return { mirror_value: mirrorNode.toJSON() as MirrorDocumentValue };
};
const getTextFromMirrorDocument = (
mirrorValue: MirrorDocumentValue
): string => {
const { content } = mirrorValue;
if (!content || content.length === 0) {
return "";
}
let out = "";
for (const node of content) {
out += getTextFromMirrorNode(node) + "\n";
}
out = out.trim();
return out;
};
const getTextFromMirrorNode = (mirrorNode: MirrorNodeValue): string => {
if (!mirrorNode) {
return "";
}
switch (mirrorNode.type) {
case "text":
// TODO: if this is a link do we want to show the URL?
return mirrorNode.text || "";
case "button":
return mirrorNode?.attrs?.text || "";
case "hard_break":
return "\n";
case "image":
return "";
case "bullet_list":
case "ordered_list":
if (!mirrorNode.content) {
return "";
}
return mirrorNode.content
.map((subNode) => getTextFromMirrorNode(subNode))
.join("\n");
case "list_item":
case "paragraph":
case "code_block":
case "heading":
if (!mirrorNode.content) {
return "";
}
return mirrorNode.content
.map((subNode) => getTextFromMirrorNode(subNode))
.join(" ");
}
return "";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment