-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmd-block.js
304 lines (243 loc) · 6.25 KB
/
md-block.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/**
* <md-block> custom element
* @author Lea Verou
*/
let marked = window.marked;
let DOMPurify = window.DOMPurify;
let Prism = window.Prism;
export const URLs = {
marked: "https://cdn.jsdelivr.net/npm/marked/src/marked.min.js",
DOMPurify: "https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.es.min.js"
}
// Fix indentation
function deIndent(text) {
let indent = text.match(/^[\r\n]*([\t ]+)/);
if (indent) {
indent = indent[1];
text = text.replace(RegExp("^" + indent, "gm"), "");
}
return text;
}
export class MarkdownElement extends HTMLElement {
constructor() {
super();
this.renderer = Object.assign({}, this.constructor.renderer);
for (let property in this.renderer) {
this.renderer[property] = this.renderer[property].bind(this);
}
}
get rendered() {
return this.getAttribute("rendered");
}
get mdContent () {
return this._mdContent;
}
set mdContent (html) {
this._mdContent = html;
this._contentFromHTML = false;
this.render();
}
connectedCallback() {
Object.defineProperty(this, "untrusted", {
value: this.hasAttribute("untrusted"),
enumerable: true,
configurable: false,
writable: false
});
if (this._mdContent === undefined) {
this._contentFromHTML = true;
this._mdContent = deIndent(this.innerHTML);
// https://github.com/markedjs/marked/issues/874#issuecomment-339995375
// marked expects markdown quotes (>) to be un-escaped, otherwise they won't render correctly
this._mdContent = this._mdContent.replace(/>/g, '>');
}
this.render();
}
async render () {
if (!this.isConnected || this._mdContent === undefined) {
return;
}
if (!marked) {
marked = import(URLs.marked).then(m => m.marked);
}
marked = await marked;
marked.setOptions({
gfm: true,
smartypants: true,
langPrefix: "language-",
});
marked.use({renderer: this.renderer});
let html = this._parse();
if (this.untrusted) {
let mdContent = this._mdContent;
html = await MarkdownElement.sanitize(html);
if (this._mdContent !== mdContent) {
// While we were running this async call, the content changed
// We don’t want to overwrite with old data. Abort mission!
return;
}
}
this.innerHTML = html;
if (!Prism && URLs.Prism && this.querySelector("code")) {
Prism = import(URLs.Prism);
if (URLs.PrismCSS) {
let link = document.createElement("link");
link.rel = "stylesheet";
link.href = URLs.PrismCSS;
document.head.appendChild(link);
}
}
if (Prism) {
await Prism; // in case it's still loading
Prism.highlightAllUnder(this);
}
if (this.src) {
this.setAttribute("rendered", this._contentFromHTML? "fallback" : "remote");
}
else {
this.setAttribute("rendered", this._contentFromHTML? "content" : "property");
}
// Fire event
let event = new CustomEvent("md-render", {bubbles: true, composed: true});
this.dispatchEvent(event);
}
static async sanitize(html) {
if (!DOMPurify) {
DOMPurify = import(URLs.DOMPurify).then(m => m.default);
}
DOMPurify = await DOMPurify; // in case it's still loading
return DOMPurify.sanitize(html);
}
};
export class MarkdownSpan extends MarkdownElement {
constructor() {
super();
}
_parse () {
return marked.parseInline(this._mdContent);
}
static renderer = {
codespan (code) {
if (this._contentFromHTML) {
// Inline HTML code needs to be escaped to not be parsed as HTML by the browser
// This results in marked double-escaping it, so we need to unescape it
code = code.replace(/&(?=[lg]t;)/g, "&");
}
else {
// Remote code may include characters that need to be escaped to be visible in HTML
code = code.replace(/</g, "<");
}
return `<code>${code}</code>`;
}
}
}
export class MarkdownBlock extends MarkdownElement {
constructor() {
super();
}
get src() {
return this._src;
}
set src(value) {
this.setAttribute("src", value);
}
get hmin() {
return this._hmin || 1;
}
set hmin(value) {
this.setAttribute("hmin", value);
}
get hlinks() {
return this._hlinks ?? null;
}
set hlinks(value) {
this.setAttribute("hlinks", value);
}
_parse () {
return marked.parse(this._mdContent);
}
static renderer = Object.assign({
heading (text, level, _raw, slugger) {
level = Math.min(6, level + (this.hmin - 1));
const id = slugger.slug(text);
const hlinks = this.hlinks;
let content;
if (hlinks === null) {
// No heading links
content = text;
}
else {
content = `<a href="#${id}" class="anchor">`;
if (hlinks === "") {
// Heading content is the link
content += text + "</a>";
}
else {
// Headings are prepended with a linked symbol
content += hlinks + "</a>" + text;
}
}
return `
<h${level} id="${id}">
${content}
</h${level}>`;
},
code (code, language, escaped) {
if (this._contentFromHTML) {
// Inline HTML code needs to be escaped to not be parsed as HTML by the browser
// This results in marked double-escaping it, so we need to unescape it
code = code.replace(/&(?=[lg]t;)/g, "&");
}
else {
// Remote code may include characters that need to be escaped to be visible in HTML
code = code.replace(/</g, "<");
}
return `<pre class="language-${language}"><code>${code}</code></pre>`;
}
}, MarkdownSpan.renderer);
static get observedAttributes() {
return ["src", "hmin", "hlinks"];
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) {
return;
}
switch (name) {
case "src":
let url;
try {
url = new URL(newValue, location);
}
catch (e) {
return;
}
let prevSrc = this.src;
this._src = url;
if (this.src !== prevSrc) {
fetch(this.src)
.then(response => {
if (!response.ok) {
throw new Error(`Failed to fetch ${this.src}: ${response.status} ${response.statusText}`);
}
return response.text();
})
.then(text => {
this.mdContent = text;
})
.catch(e => {});
}
break;
case "hmin":
if (newValue > 0) {
this._hmin = +newValue;
this.render();
}
break;
case "hlinks":
this._hlinks = newValue;
this.render();
}
}
}
customElements.define("md-block", MarkdownBlock);
customElements.define("md-span", MarkdownSpan);