-
Notifications
You must be signed in to change notification settings - Fork 22
/
markdown-content.js
388 lines (353 loc) 路 14.8 KB
/
markdown-content.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/**
* DataFormsJS <markdown-content> JavaScript Control
*
* This control is designed for compatibility with the DataFormsJS Web Component
* [js/web-components/markdown-content.js].
*
* When [js/web-components/polyfill.js] is used for DataFormsJS Web Components
* this file will be downloaded and used if a <markdown-content> element
* is found on the page.
*
* See the Web Component source for additional comments and details of
* what Markdown Libraries are supported and how it works.
*/
/* Validates with both [jshint] and [eslint] */
/* global hljs, marked, markdownit, markdownitEmoji, remarkable, DOMPurify */
/* global app */
/* jshint strict: true */
/* eslint-env browser */
/* eslint quotes: ["error", "single", { "avoidEscape": true }] */
/* eslint strict: ["error", "function"] */
/* eslint spaced-comment: ["error", "always"] */
/* eslint no-console: ["error", { allow: ["log", "warn", "error"] }] */
(function() {
'use strict';
var returnCode = false;
function highlight(code, lang) {
if (window.hljs === undefined) {
return (returnCode ? code : '');
}
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(lang, code).value;
} catch (err) {
console.warn(err);
}
}
try {
return hljs.highlightAuto(code).value;
} catch (err) {
console.warn(err);
}
return (returnCode ? code : '');
}
/**
* Markdown Caching for when [load-only-once] is used.
*/
var markdownCache = [];
var maxCacheSize = 100;
function saveMarkdownToCache(url, content, errorMessage) {
if (markdownCache.length > maxCacheSize) {
markdownCache.length = 0; // Clear array
}
for (var n = 0, m = markdownCache.length; n < m; n++) {
if (url === markdownCache[n].url) {
return; // Already saved
}
}
markdownCache.push({ url:url, content:content, errorMessage:errorMessage });
}
function getMarkdownFromCache(url) {
for (var n = 0, m = markdownCache.length; n < m; n++) {
if (url === markdownCache[n].url) {
return markdownCache[n];
}
}
return null;
}
/**
* DataFormsJS <markdown-content> Control
*/
var markdownContent = {
/**
* Data for the control
*/
data: {
bind: null,
content: null,
url: null,
loadingSelector: null,
showSource: false,
errorMessage: null,
linkTarget: null,
linkRel: null,
linkRootUrl: null,
loadOnlyOnce: false,
useRootUrl: true,
},
/**
* Event that gets called when a <markdown-content> is rendered on screen
*
* @this markdownContent.data
* @param {object} element
*/
onLoad: function(element, model) {
// Modify the element the first time it is loaded so that it has an API
// that matches with the Web Components Version for common API calls.
if (Object.getOwnPropertyDescriptor(element, 'url') === undefined) {
Object.defineProperty(element, 'url', {
get: function() {
return this.getAttribute('data-url');
},
set: function(newValue) {
var existingValue = this.url;
if (existingValue !== newValue) {
this.setAttribute('data-url', newValue);
app.loadJsControl(this);
}
}
});
Object.defineProperty(element, 'showSource', {
get: function() {
return this.hasAttribute('data-show-source');
},
set: function(newValue) {
var existingValue = this.showSource;
if (existingValue !== newValue) {
if (newValue) {
this.setAttribute('data-show-source', '');
} else {
this.removeAttribute('data-show-source');
}
app.loadJsControl(this);
}
}
});
Object.defineProperty(element, 'value', {
get: function() {
return this.getAttribute('data-content');
},
set: function(newValue) {
var existingValue = this.value;
if (existingValue !== newValue) {
if (newValue === '') {
this.removeAttribute('data-content');
} else {
this.setAttribute('data-content', newValue);
}
app.loadJsControl(this);
}
}
});
element.clearContent = function() {
element.innerHTML = '';
markdownContent.dispatchRendered(element);
};
}
// Download Markdown if using [data-url] attribute
if (this.url) {
markdownContent.fetch.call(this, element);
return;
}
// Set content from source if defined on initial load
var sourceEl = element.querySelector('script[type="text/markdown"]');
if (sourceEl) {
this.content = sourceEl.innerHTML;
} else if (this.bind) {
// Get Table from Active Model or passed Model Object. If using format of "object.prop"
// then the [dataBind] plugin (if available) will used to get the data.
this.content = (model && model[this.bind] ? model[this.bind] : null);
if (this.content === null && app.plugins.dataBind !== undefined && typeof app.plugins.dataBind.getBindValue === 'function') {
this.content = app.plugins.dataBind.getBindValue(this.bind, model);
}
}
// Render markdown
markdownContent.render.call(this, element);
},
dispatchRendered: function(element) {
var event, eventName = 'app:markdownRendered';
if (typeof(Event) === 'function') {
event = new Event(eventName, { bubbles: true }); // Modern Browsers
} else {
event = document.createEvent('Event'); // IE 11
event.initEvent(eventName, true, false);
}
element.dispatchEvent(event);
},
fetch: function (element) {
// Option to load markdown from cache rather than fetching each time.
if (this.loadOnlyOnce) {
var cache = getMarkdownFromCache(this.url);
if (cache) {
this.content = cache.content;
this.errorMessage = cache.errorMessage;
markdownContent.render.call(this, element);
return;
}
}
// Show loading screen
if (this.loadingSelector) {
var loading = document.querySelector(this.loadingSelector);
if (loading) {
element.innerHTML = loading.innerHTML;
} else {
console.warn('Could not find template from <markdown-content [loading-selector="' + this.loadingSelector + '"]>.');
}
}
// Fetch content
var control = this;
var url = this.url;
app
.fetch(url, null, 'text/plain')
.then(function(text) {
control.content = text;
control.errorMessage = null;
markdownContent.render.call(control, element);
})
.catch(function(error) {
var errorMessage = 'Error loading markdown content from [' + url + ']. Error: ' + error;
control.errorMessage = errorMessage;
markdownContent.render.call(control, element);
})
.finally(function() {
if (control.loadOnlyOnce) {
saveMarkdownToCache(url, control.content, control.errorMessage);
}
});
},
render: function (element) {
// Error message (for example a failed fetch)
if (this.errorMessage) {
app.showError(element, this.errorMessage);
markdownContent.dispatchRendered(element);
return;
}
// Nothing to show
if (this.content === null) {
element.innerHTML = '';
return;
}
// If a source element exists then keep it in case the control get's loaded multiple times.
// This will be added back to the control after markdown is rendered.
var sourceEl = element.querySelector('script[type="text/markdown"]');
if (sourceEl) {
sourceEl.parentNode.removeChild(sourceEl);
}
// Shows as text rather than rendering source
if (this.showSource) {
element.innerHTML = '<pre></pre>';
element.querySelector('pre').textContent = this.content;
if (sourceEl) {
element.appendChild(sourceEl);
}
markdownContent.dispatchRendered(element);
return;
}
// Render Markdown to HTML using one of 3 libraries
var html;
var md;
returnCode = false;
if (window.marked) {
returnCode = true;
marked.setOptions({
highlight: highlight
});
if (marked.marked && marked.marked.parse) {
html = marked.marked.parse(this.content); // 4.#
} else {
html = marked(this.content); // 3.#
}
} else if (window.markdownit) {
md = markdownit({
html: true,
linkify: true,
typographer: true,
highlight: highlight
});
if (window.markdownitEmoji) {
md.use(markdownitEmoji);
}
html = md.render(this.content);
} else if (window.remarkable) {
md = new remarkable.Remarkable({
html: true,
typographer: true,
highlight: highlight
}).use(remarkable.linkify);
html = (md).render(this.content);
} else {
app.showError(element, 'Error - Unable to show Markdown content because a Markdown JavaScript library was not found on the page.');
markdownContent.dispatchRendered(element);
return;
}
// Clean/Sanitize the HTML for Security if DOMPurify is loaded
if (window.DOMPurify !== undefined) {
html = DOMPurify.sanitize(html);
}
// Set Content and add back <script type="text/markdown">
// if one was used for the source.
element.innerHTML = html;
if (sourceEl) {
element.appendChild(sourceEl);
}
// Update code blocks so they highlight with the
// correct theme if using [highlight.js].
if (window.hljs !== undefined) {
var codeBlocks = element.querySelectorAll('code[class*="language-"]');
Array.prototype.forEach.call(codeBlocks, function(code) {
code.classList.add('hljs');
});
}
// Update all [a.target] and [a.rel] attributes if specified.
// Example: [data-link-target="_blank"] and [data-link-rel="noopener"]
var linkTarget = this.linkTarget;
var linkRel = this.linkRel;
if (linkTarget || linkRel) {
var links = element.querySelectorAll('a');
Array.prototype.forEach.call(links, function(link) {
link.target = (linkTarget ? linkTarget : link.target);
link.rel = (linkRel ? linkRel : link.rel);
});
}
// Handle relative links and images by default
if (this.useRootUrl !== false) {
// Get the root URL of the document if using URL
var url = this.url;
var rootUrl;
if (url) {
var parts = url.split('/');
rootUrl = url.substring(0, url.length - parts[parts.length - 1].length);
}
// Update all local links if [data-link-root-url] is specified.
// For example Github readme docs would often point to links in the local repository.
// This feature can be used to specify the root URL so that all links work correctly,
// and link to the main source display page and not raw content.
var linkRootUrl = this.linkRootUrl;
linkRootUrl = (linkRootUrl ? linkRootUrl : rootUrl);
if (linkRootUrl) {
var localLinks = element.querySelectorAll('a:not([href^="http:"]):not([href^="https:"])');
Array.prototype.forEach.call(localLinks, function(link) {
var href = link.getAttribute('href');
link.setAttribute('data-original-href', href);
link.setAttribute('href', linkRootUrl + href);
});
}
// Update Images that use a relative URL based on the document
var images = element.querySelectorAll('img:not([src^="http:"]):not([src^="https:"])');
Array.prototype.forEach.call(images, function(img) {
var src = img.getAttribute('src');
img.setAttribute('data-original-src', src);
img.setAttribute('src', rootUrl + src);
});
}
// Run event to let app know content has been rendered
markdownContent.dispatchRendered(element);
},
};
/**
* Add control to app and add basic CSS to doc to prevent layout issues
*/
app
.addControl('markdown-content', markdownContent)
.loadCss('dataformsjs-control-markdown-content', 'markdown-content[data-control] { display:block; }');
})();