This repository has been archived by the owner on Apr 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
markdown-viewer.js
174 lines (146 loc) · 6.24 KB
/
markdown-viewer.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
/* globals Components, markdownit, hljs, gContextMenu */
window.addEventListener('load', function load(event) {
window.removeEventListener('load', load, false);
MarkdownViewer.init();
}, false);
function BrowserSetForcedCharacterSet(aCharset) {
var wnd = (gContextMenu ? document.commandDispatcher.focusedWindow : window);
if (window === wnd || wnd === null) {
wnd = window.content;
}
var webNav = wnd.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIWebNavigation);
var docShell = webNav.QueryInterface(Components.interfaces.nsIDocShell);
docShell.QueryInterface(Components.interfaces.nsIDocCharset).charset = aCharset;
webNav.reload(0);
}
if (!MarkdownViewer) {
var MarkdownViewer = {
init: function() {
const appcontent = document.getElementById('appcontent');
if (appcontent) {
appcontent.addEventListener('DOMContentLoaded', this.onPageLoad, true);
}
},
onPageLoad: function(aEvent) {
if (aEvent.originalTarget.documentURI.indexOf('about:neterror') === 0) {
return;
}
const document = aEvent.originalTarget;
const markdownFileExtension = /\.m(arkdown|kdn?|d(o?wn)?)(\?.*)?(#.*)?$/i;
if (document.location.protocol !== "view-source:" &&
markdownFileExtension.test(document.location.href) &&
document.contentType !== "text/html") {
var textContent = document.body.textContent;
// Empty the body
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
// Change the charset
if (document.characterSet.toLowerCase() !== 'utf-8') {
BrowserSetForcedCharacterSet('utf-8');
return;
}
// Parse the content Markdown => HTML
var md = markdownit({
html: true,
linkify: true,
// Shameless copypasta https://github.com/markdown-it/markdown-it#syntax-highlighting
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(lang, str).value;
} catch (__) {}
}
try {
return hljs.highlightAuto(str).value;
} catch (__) {}
return ''; // use external default escaping
}
});
var html = md.render(textContent);
// For links, copy href attribute to data-original-href, for sanitizing later. Do
// that for both href="...", either generated by markdown-it, which uses escape(),
// or from the original .md file, and also for HTML5-style href='...' which can
// come from the original .md file. Assume that HTML from the original .md file is
// well-formed. Pass any attributes left of href unchanged; allow attribute names
// without value (e.g. xxx in <a xxx href='...'>).
html = html.replace( /<a((\s+(?!href)[a-zA-Z-_0-9]+(=("[^"]*"|'[^']'))?)*)\s+href="([^"]*)"/gi, '<a$1 href="$5" data-original-href="$5"' );
html = html.replace( /<a((\s+(?!href)[a-zA-Z-_0-9]+(=("[^"]*"|'[^']'))?)*)\s+href='([^']*)'/gi, "<a$1 href='$5' data-original-href='$5'" );
// Sanitize the HTML
// See https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIParserUtils
var fragment = Components.classes["@mozilla.org/parserutils;1"]
.getService(Components.interfaces.nsIParserUtils)
.parseFragment(html, Components.interfaces.nsIParserUtils.SanitizerAllowStyle, false, null, document.body);
// Add the content
document.body.appendChild(fragment);
// Give the page some styles
const mdvStyle = document.createElement('link');
mdvStyle.rel = 'stylesheet';
mdvStyle.type = 'text/css';
mdvStyle.href = 'resource://mdvlib/sss/sss.css';
document.head.appendChild(mdvStyle);
const printStyle = document.createElement('link');
printStyle.rel = 'stylesheet';
printStyle.setAttribute('media', 'print');
printStyle.type = 'text/css';
printStyle.href = 'resource://mdvlib/sss/sss.print.css';
document.head.appendChild(printStyle);
const hljsStyle = document.createElement('link');
hljsStyle.rel = 'stylesheet';
hljsStyle.type = 'text/css';
hljsStyle.href = 'resource://mdvlib/highlightjs/styles/default.css';
document.head.appendChild(hljsStyle);
// Adding this is considered a good practice for mobiles
const viewport = document.createElement('meta');
viewport.name = 'viewport';
viewport.content = 'width=device-width, initial-scale=1';
document.head.appendChild(viewport);
// Generate a title
var title = document.body.querySelector('h1'); // first h1
if (title) {
title = title.textContent;
}
else {
title = document.body.textContent.trim().split("\n")[0]; // first line
}
title = title.trim().substr(0, 50).replace('<', '<').replace('>', '>');
document.title = title;
// Restore the links
var links = document.getElementsByTagName('a');
// Files in the same folder: "fileNameRegardlessOfExtension",
// "./fileNameRegardlessOfExtension", "." or "./". Allow any #hash-part, too.
// Also, allow for relative (#hash-part-only) URLs within the same document.
var linkInTheSameFolderWithHash = /^(\.|(\.\/)?[^#/\\]*)(#.*)?$/;
// Like linkInTheSameFolderWithHash, but without extension and exluding any #hash-part.
var linkWithNoExtension = /^(\.|(\.\/)?[^#/\\.]*)$/;
for (var i=0; i < links.length; i++) {
var link = links[i];
if (!link.getAttribute('href')) {
var originalHref = link.getAttribute('data-original-href');
// linkInTheSameFolderWithHash also matches an empty string, so check that URL is non-empty
if (originalHref !== '') {
// Sanitize: Only allow links in the same folder.
var match = linkInTheSameFolderWithHash.exec(originalHref);
if (match) {
var url = match[1];
// Handling links with no extension, as used on Github pages:
// replacing PageName with PageName.md. Also, replacing ./ with ./index.md.
// If url is empty, then it's a #hash-part-only relative link.
if (url !== '' && linkWithNoExtension.test(url)) {
if (url === '.' || url === './') {
url = 'index';
}
url += '.md';
}
if (match[3]) {
url += match[3];
}
link.setAttribute('href', url);
}
}
}
}
}
}
};
}