This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
forked from speced/respec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown.js
225 lines (210 loc) · 6.08 KB
/
markdown.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/**
* Module core/markdown
* Handles the optional markdown processing.
*
* Markdown support is optional. It is enabled by setting the `format`
* property of the configuration object to "markdown."
*
* We use marked for parsing Markdown:
* https://github.com/chjj/marked
*
* Note that the content of SECTION elements, and elements with a
* class name of "note", "issue" or "req" are also parsed.
*
* The HTML created by the Markdown parser is turned into a nested
* structure of SECTION elements, following the structure given by
* the headings. For example, the following markup:
*
* Title
* -----
*
* ### Subtitle ###
*
* Here's some text.
*
* ### Another subtitle ###
*
* More text.
*
* will be transformed into:
*
* <section>
* <h2>Title</h2>
* <section>
* <h3>Subtitle</h3>
* <p>Here's some text.</p>
* </section>
* <section>
* <h3>Another subtitle</h3>
* <p>More text.</p>
* </section>
* </section>
*
* The whitespace of pre elements are left alone.
**/
import { markdownToHtml } from "core/utils";
export const name = "core/markdown";
function processElements(selector) {
return element => {
const elements = Array.from(element.querySelectorAll(selector));
elements.reverse().forEach(element => {
element.innerHTML = markdownToHtml(element.innerHTML);
});
return elements;
};
}
class Builder {
constructor(doc) {
this.doc = doc;
this.root = doc.createDocumentFragment();
this.stack = [this.root];
this.current = this.root;
}
findPosition(header) {
return parseInt(header.tagName.charAt(1), 10);
}
findParent(position) {
let parent;
while (position > 0) {
position--;
parent = this.stack[position];
if (parent) return parent;
}
}
findHeader({ firstChild: node }) {
while (node) {
if (/H[1-6]/.test(node.tagName)) {
return node;
}
node = node.nextSibling;
}
return null;
}
addHeader(header) {
const section = this.doc.createElement("section");
const position = this.findPosition(header);
section.appendChild(header);
this.findParent(position).appendChild(section);
this.stack[position] = section;
this.stack.length = position + 1;
this.current = section;
}
addSection(node, process) {
const header = this.findHeader(node);
const position = header ? this.findPosition(header) : 1;
const parent = this.findParent(position);
if (header) {
node.removeChild(header);
}
node.appendChild(process(node));
if (header) {
node.insertBefore(header, node.firstChild);
}
parent.appendChild(node);
this.current = parent;
}
addElement(node) {
this.current.appendChild(node);
}
}
function structure(fragment, doc) {
function process(root) {
const stack = new Builder(doc);
while (root.firstChild) {
const node = root.firstChild;
if (node.nodeType !== Node.ELEMENT_NODE) {
root.removeChild(node);
continue;
}
switch (node.localName) {
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
stack.addHeader(node);
break;
case "section":
stack.addSection(node, process);
break;
default:
stack.addElement(node);
}
}
return stack.root;
}
return process(fragment);
}
function substituteWithTextNodes(elements) {
Array.from(elements).forEach(element => {
const textNode = element.ownerDocument.createTextNode(element.textContent);
element.parentElement.replaceChild(textNode, element);
});
}
const processMDSections = processElements("[data-format='markdown']:not(body)");
const processBlockLevelElements = processElements(
"[data-format=markdown]:not(body), section, div, address, article, aside, figure, header, main, body"
);
export function run(conf, doc, cb) {
const hasMDSections = !!doc.querySelector("[data-format=markdown]:not(body)");
const isMDFormat = conf.format === "markdown";
if (!isMDFormat && !hasMDSections) {
return cb(); // Nothing to be done
}
// Only has markdown-format sections
if (!isMDFormat) {
processMDSections(doc.body)
.map(elem => {
const structuredInternals = structure(elem, elem.ownerDocument);
return {
structuredInternals,
elem,
};
})
.forEach(({ elem, structuredInternals }) => {
elem.setAttribute("aria-busy", "true");
if (
structuredInternals.firstElementChild.localName === "section" &&
elem.localName === "section"
) {
const section = structuredInternals.firstElementChild;
section.remove();
while (section.hasChildNodes()) {
elem.appendChild(section.firstChild);
}
} else {
elem.innerHTML = "";
}
elem.appendChild(structuredInternals);
elem.setAttribute("aria-busy", "false");
});
return cb();
}
// We transplant the UI to do the markdown processing
const rsUI = doc.getElementById("respec-ui");
rsUI.remove();
// The new body will replace the old body
const newHTML = doc.createElement("html");
const newBody = doc.createElement("body");
newBody.innerHTML = doc.body.innerHTML;
// Marked expects markdown be flush against the left margin
// so we need to normalize the inner text of some block
// elements.
newHTML.appendChild(newBody);
processBlockLevelElements(newHTML);
// Process root level text nodes
const cleanHTML = newBody.innerHTML
// Markdown parsing sometimes inserts empty p tags
.replace(/<p>\s*<\/p>/gm, "");
newBody.innerHTML = cleanHTML;
// Remove links where class .nolinks
substituteWithTextNodes(newBody.querySelectorAll(".nolinks a[href]"));
// Restructure the document properly
var fragment = structure(newBody, doc);
// Frankenstein the whole thing back together
newBody.appendChild(fragment);
newBody.insertAdjacentElement("afterbegin", rsUI);
doc.body.parentNode.replaceChild(newBody, doc.body);
cb();
}