-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
80 lines (75 loc) · 2.3 KB
/
index.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { Schema, DOMParser } from "prosemirror-model";
import { marks, nodes } from "nib-schema";
const schema = new Schema({
nodes,
marks
});
const getHTMLString = node => {
const { type, text } = node;
if (text) {
let strContent = text;
for (let i = 0; i < node.marks.length; i += 1) {
const mark = node.marks[i];
const { type: markType } = mark;
const domDetails = markType.spec.toDOM(mark);
const htmlAttrs = Object.keys(domDetails[1]).reduce(
(str, key) => `${str}${key}="${domDetails[1][key]}"`,
""
);
const htmlTag = domDetails[0];
strContent = `<${htmlTag} ${htmlAttrs}>${strContent}</${htmlTag}>`;
}
return strContent;
}
let strContent = "";
for (let i = 0; i < node.childCount; i += 1) {
const childNode = node.child(i);
strContent += getHTMLString(childNode);
}
if (type.spec.toDOM) {
const domDetails = type.spec.toDOM(node);
if (node.type.name === "embed") {
strContent = `<p style="display:flex;justify-content:center;">${
domDetails[1]["data-nib-embed"]
}</p>`;
return strContent;
}
let htmlAttrs = "";
if (domDetails.length > 1)
htmlAttrs = Object.keys(domDetails[1]).reduce(
(str, key) => `${str} ${key}="${domDetails[1][key]}"`,
htmlAttrs
);
const htmlTag = domDetails[0];
strContent = `<${htmlTag} ${htmlAttrs}>${strContent ||
"<br>"}</${htmlTag}>`;
if (node.type.name === "image") {
strContent = `<p style="text-align: center;">${strContent}<br></p>`;
}
}
return strContent;
};
const convertToHTML = content => {
if (JSON.stringify(content) === "{}") return "";
const node = schema.nodeFromJSON(content);
return getHTMLString(node);
};
const convertFromHTML = (html = "<p></p>") => {
if (!document)
throw new Error("Document object is required to convert from html.");
const contentWrapper = document.createElement("div");
document.body.appendChild(contentWrapper);
contentWrapper.innerHTML = html;
const parser = DOMParser.fromSchema(schema);
const content = parser.parse(contentWrapper);
document.body.removeChild(contentWrapper);
return {
doc: content.toJSON(),
selection: {
type: "text",
anchor: 0,
head: 0
}
};
};
export default { convertToHTML, convertFromHTML };