UNPKG

5.34 kBJavaScriptView Raw
1(function () {
2
3 if (typeof Prism === 'undefined' || typeof document === 'undefined') {
4 return;
5 }
6
7 // https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
8 if (!Element.prototype.matches) {
9 Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
10 }
11
12 var LOADING_MESSAGE = 'Loading…';
13 var FAILURE_MESSAGE = function (status, message) {
14 return '✖ Error ' + status + ' while fetching file: ' + message;
15 };
16 var FAILURE_EMPTY_MESSAGE = '✖ Error: File does not exist or is empty';
17
18 var EXTENSIONS = {
19 'js': 'javascript',
20 'py': 'python',
21 'rb': 'ruby',
22 'ps1': 'powershell',
23 'psm1': 'powershell',
24 'sh': 'bash',
25 'bat': 'batch',
26 'h': 'c',
27 'tex': 'latex'
28 };
29
30 var STATUS_ATTR = 'data-src-status';
31 var STATUS_LOADING = 'loading';
32 var STATUS_LOADED = 'loaded';
33 var STATUS_FAILED = 'failed';
34
35 var SELECTOR = 'pre[data-src]:not([' + STATUS_ATTR + '="' + STATUS_LOADED + '"])'
36 + ':not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
37
38 /**
39 * Loads the given file.
40 *
41 * @param {string} src The URL or path of the source file to load.
42 * @param {(result: string) => void} success
43 * @param {(reason: string) => void} error
44 */
45 function loadFile(src, success, error) {
46 var xhr = new XMLHttpRequest();
47 xhr.open('GET', src, true);
48 xhr.onreadystatechange = function () {
49 if (xhr.readyState == 4) {
50 if (xhr.status < 400 && xhr.responseText) {
51 success(xhr.responseText);
52 } else {
53 if (xhr.status >= 400) {
54 error(FAILURE_MESSAGE(xhr.status, xhr.statusText));
55 } else {
56 error(FAILURE_EMPTY_MESSAGE);
57 }
58 }
59 }
60 };
61 xhr.send(null);
62 }
63
64 /**
65 * Parses the given range.
66 *
67 * This returns a range with inclusive ends.
68 *
69 * @param {string | null | undefined} range
70 * @returns {[number, number | undefined] | undefined}
71 */
72 function parseRange(range) {
73 var m = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(range || '');
74 if (m) {
75 var start = Number(m[1]);
76 var comma = m[2];
77 var end = m[3];
78
79 if (!comma) {
80 return [start, start];
81 }
82 if (!end) {
83 return [start, undefined];
84 }
85 return [start, Number(end)];
86 }
87 return undefined;
88 }
89
90 Prism.hooks.add('before-highlightall', function (env) {
91 env.selector += ', ' + SELECTOR;
92 });
93
94 Prism.hooks.add('before-sanity-check', function (env) {
95 var pre = /** @type {HTMLPreElement} */ (env.element);
96 if (pre.matches(SELECTOR)) {
97 env.code = ''; // fast-path the whole thing and go to complete
98
99 pre.setAttribute(STATUS_ATTR, STATUS_LOADING); // mark as loading
100
101 // add code element with loading message
102 var code = pre.appendChild(document.createElement('CODE'));
103 code.textContent = LOADING_MESSAGE;
104
105 var src = pre.getAttribute('data-src');
106
107 var language = env.language;
108 if (language === 'none') {
109 // the language might be 'none' because there is no language set;
110 // in this case, we want to use the extension as the language
111 var extension = (/\.(\w+)$/.exec(src) || [, 'none'])[1];
112 language = EXTENSIONS[extension] || extension;
113 }
114
115 // set language classes
116 Prism.util.setLanguage(code, language);
117 Prism.util.setLanguage(pre, language);
118
119 // preload the language
120 var autoloader = Prism.plugins.autoloader;
121 if (autoloader) {
122 autoloader.loadLanguages(language);
123 }
124
125 // load file
126 loadFile(
127 src,
128 function (text) {
129 // mark as loaded
130 pre.setAttribute(STATUS_ATTR, STATUS_LOADED);
131
132 // handle data-range
133 var range = parseRange(pre.getAttribute('data-range'));
134 if (range) {
135 var lines = text.split(/\r\n?|\n/g);
136
137 // the range is one-based and inclusive on both ends
138 var start = range[0];
139 var end = range[1] == null ? lines.length : range[1];
140
141 if (start < 0) { start += lines.length; }
142 start = Math.max(0, Math.min(start - 1, lines.length));
143 if (end < 0) { end += lines.length; }
144 end = Math.max(0, Math.min(end, lines.length));
145
146 text = lines.slice(start, end).join('\n');
147
148 // add data-start for line numbers
149 if (!pre.hasAttribute('data-start')) {
150 pre.setAttribute('data-start', String(start + 1));
151 }
152 }
153
154 // highlight code
155 code.textContent = text;
156 Prism.highlightElement(code);
157 },
158 function (error) {
159 // mark as failed
160 pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
161
162 code.textContent = error;
163 }
164 );
165 }
166 });
167
168 Prism.plugins.fileHighlight = {
169 /**
170 * Executes the File Highlight plugin for all matching `pre` elements under the given container.
171 *
172 * Note: Elements which are already loaded or currently loading will not be touched by this method.
173 *
174 * @param {ParentNode} [container=document]
175 */
176 highlight: function highlight(container) {
177 var elements = (container || document).querySelectorAll(SELECTOR);
178
179 for (var i = 0, element; (element = elements[i++]);) {
180 Prism.highlightElement(element);
181 }
182 }
183 };
184
185 var logged = false;
186 /** @deprecated Use `Prism.plugins.fileHighlight.highlight` instead. */
187 Prism.fileHighlight = function () {
188 if (!logged) {
189 console.warn('Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.');
190 logged = true;
191 }
192 Prism.plugins.fileHighlight.highlight.apply(this, arguments);
193 };
194
195}());