-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
renderers.ts
798 lines (682 loc) · 19.2 KB
/
renderers.ts
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import {
ansi_to_html, escape_for_html
} from 'ansi_up';
import * as marked
from 'marked';
import {
ISanitizer
} from '@jupyterlab/apputils';
import {
Mode, CodeMirrorEditor
} from '@jupyterlab/codemirror';
import {
URLExt
} from '@jupyterlab/coreutils';
import {
IRenderMime
} from '@jupyterlab/rendermime-interfaces';
import {
typeset, removeMath, replaceMath
} from './latex';
/**
* Render HTML into a host node.
*
* @params options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export
function renderHTML(options: renderHTML.IOptions): Promise<void> {
// Unpack the options.
let {
host, source, trusted, sanitizer, resolver, linkHandler, shouldTypeset
} = options;
// Bail early if the source is empty.
if (!source) {
host.textContent = '';
return Promise.resolve(undefined);
}
// Sanitize the source if it is not trusted. This removes all
// `<script>` tags as well as other potentially harmful HTML.
if (!trusted) {
source = sanitizer.sanitize(source);
}
// Set the inner HTML of the host.
host.innerHTML = source;
// TODO - arbitrary script execution is disabled for now.
// Eval any script tags contained in the HTML. This is not done
// automatically by the browser when script tags are created by
// setting `innerHTML`. The santizer should have removed all of
// the script tags for untrusted source, but this extra trusted
// check is just extra insurance.
// if (trusted) {
// // TODO do we really want to run scripts? Because if so, there
// // is really no difference between this and a JS mime renderer.
// Private.evalInnerHTMLScriptTags(host);
// }
// Patch the urls if a resolver is available.
let promise: Promise<void>;
if (resolver) {
promise = Private.handleUrls(host, resolver, linkHandler);
} else {
promise = Promise.resolve(undefined);
}
// Return the final rendered promise.
return promise.then(() => { if (shouldTypeset) { typeset(host); } });
}
/**
* The namespace for the `renderHTML` function statics.
*/
export
namespace renderHTML {
/**
* The options for the `renderHTML` function.
*/
export
interface IOptions {
/**
* The host node for the rendered HTML.
*/
host: HTMLElement;
/**
* The HTML source to render.
*/
source: string;
/**
* Whether the source is trusted.
*/
trusted: boolean;
/**
* The html sanitizer for untrusted source.
*/
sanitizer: ISanitizer;
/**
* An optional url resolver.
*/
resolver: IRenderMime.IResolver | null;
/**
* An optional link handler.
*/
linkHandler: IRenderMime.ILinkHandler | null;
/**
* Whether the node should be typeset.
*/
shouldTypeset: boolean;
}
}
/**
* Render an image into a host node.
*
* @params options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export
function renderImage(options: renderImage.IRenderOptions): Promise<void> {
// Unpack the options.
let { host, mimeType, source, width, height } = options;
// Clear the content in the host.
host.textContent = '';
// Create the image element.
let img = document.createElement('img');
// Set the source of the image.
img.src = `data:${mimeType};base64,${source}`;
// Set the size of the image if provided.
if (typeof height === 'number') {
img.height = height;
}
if (typeof width === 'number') {
img.width = width;
}
// Add the image to the host.
host.appendChild(img);
// Return the rendered promise.
return Promise.resolve(undefined);
}
/**
* The namespace for the `renderImage` function statics.
*/
export
namespace renderImage {
/**
* The options for the `renderImage` function.
*/
export
interface IRenderOptions {
/**
* The image node to update with the content.
*/
host: HTMLElement;
/**
* The mime type for the image.
*/
mimeType: string;
/**
* The base64 encoded source for the image.
*/
source: string;
/**
* The optional width for the image.
*/
width?: number;
/**
* The optional height for the image.
*/
height?: number;
}
}
/**
* Render LaTeX into a host node.
*
* @params options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export
function renderLatex(options: renderLatex.IRenderOptions): Promise<void> {
// Unpack the options.
let { host, source, shouldTypeset } = options;
// Set the source on the node.
host.textContent = source;
// Typeset the node if needed.
if (shouldTypeset) {
typeset(host);
}
// Return the rendered promise.
return Promise.resolve(undefined);
}
/**
* The namespace for the `renderLatex` function statics.
*/
export
namespace renderLatex {
/**
* The options for the `renderLatex` function.
*/
export
interface IRenderOptions {
/**
* The host node for the rendered LaTeX.
*/
host: HTMLElement;
/**
* The LaTeX source to render.
*/
source: string;
/**
* Whether the node should be typeset.
*/
shouldTypeset: boolean;
}
}
/**
* Render Markdown into a host node.
*
* @params options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export
function renderMarkdown(options: renderMarkdown.IRenderOptions): Promise<void> {
// Unpack the options.
let {
host, source, trusted, sanitizer, resolver, linkHandler, shouldTypeset
} = options;
// Clear the content if there is no source.
if (!source) {
host.textContent = '';
return Promise.resolve(undefined);
}
// Separate math from normal markdown text.
let parts = removeMath(source);
// Render the markdown and handle sanitization.
return Private.renderMarked(parts['text']).then(content => {
// Restore the math content in the rendered markdown.
content = replaceMath(content, parts['math']);
// Santize the content it is not trusted.
if (!trusted) {
content = sanitizer.sanitize(content);
}
// Set the inner HTML of the host.
host.innerHTML = content;
// TODO arbitrary script execution is disabled for now.
// Eval any script tags contained in the HTML. This is not done
// automatically by the browser when script tags are created by
// setting `innerHTML`. The santizer should have removed all of
// the script tags for untrusted source, but this extra trusted
// check is just extra insurance.
// if (trusted) {
// // TODO really want to run scripts?
// Private.evalInnerHTMLScriptTags(host);
// }
// Apply ids to the header nodes.
Private.headerAnchors(host);
// Patch the urls if a resolver is available.
let promise: Promise<void>;
if (resolver) {
promise = Private.handleUrls(host, resolver, linkHandler);
} else {
promise = Promise.resolve(undefined);
}
// Return the rendered promise.
return promise;
}).then(() => { if (shouldTypeset) { typeset(host) } });
}
/**
* The namespace for the `renderMarkdown` function statics.
*/
export
namespace renderMarkdown {
/**
* The options for the `renderMarkdown` function.
*/
export
interface IRenderOptions {
/**
* The host node for the rendered Markdown.
*/
host: HTMLElement;
/**
* The Markdown source to render.
*/
source: string;
/**
* Whether the source is trusted.
*/
trusted: boolean;
/**
* The html sanitizer for untrusted source.
*/
sanitizer: ISanitizer;
/**
* An optional url resolver.
*/
resolver: IRenderMime.IResolver | null;
/**
* An optional link handler.
*/
linkHandler: IRenderMime.ILinkHandler | null;
/**
* Whether the node should be typeset.
*/
shouldTypeset: boolean;
}
}
/**
* Render a PDF into a host node.
*
* @params options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export
function renderPDF(options: renderPDF.IRenderOptions): Promise<void> {
// Unpack the options.
let { host, source, trusted } = options;
// Clear the content if there is no source.
if (!source) {
host.textContent = '';
return Promise.resolve(undefined);
}
// Display a message if the source is not trusted.
if (!trusted) {
host.textContent = 'Cannot display an untrusted PDF. Maybe you need to run the cell?';
return Promise.resolve(undefined);
}
// Update the host with the display content.
let href = `data:application/pdf;base64,${source}`;
host.innerHTML = `<a target="_blank" href="${href}">View PDF</a>`;
// Return the final rendered promise.
return Promise.resolve(undefined);
}
/**
* The namespace for the `renderPDF` function statics.
*/
export
namespace renderPDF {
/**
* The options for the `renderPDF` function.
*/
export
interface IRenderOptions {
/**
* The host node for the rendered PDF.
*/
host: HTMLElement;
/**
* The base64 encoded source for the PDF.
*/
source: string;
/**
* Whether the source is trusted.
*/
trusted: boolean;
}
}
/**
* Render SVG into a host node.
*
* @params options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export
function renderSVG(options: renderSVG.IRenderOptions): Promise<void> {
// Unpack the options.
let {
host, source, trusted, resolver, linkHandler, shouldTypeset
} = options;
// Clear the content if there is no source.
if (!source) {
host.textContent = '';
return Promise.resolve(undefined);
}
// Display a message if the source is not trusted.
if (!trusted) {
host.textContent = 'Cannot display an untrusted SVG. Maybe you need to run the cell?';
return Promise.resolve(undefined);
}
// Set the inner HTML of the host.
host.innerHTML = source;
// TODO
// what about script tags inside the svg?
// Patch the urls if a resolver is available.
let promise: Promise<void>;
if (resolver) {
promise = Private.handleUrls(host, resolver, linkHandler);
} else {
promise = Promise.resolve(undefined);
}
// Return the final rendered promise.
return promise.then(() => { if (shouldTypeset) { typeset(host); } });
}
/**
* The namespace for the `renderSVG` function statics.
*/
export
namespace renderSVG {
/**
* The options for the `renderSVG` function.
*/
export
interface IRenderOptions {
/**
* The host node for the rendered SVG.
*/
host: HTMLElement;
/**
* The SVG source.
*/
source: string;
/**
* Whether the source is trusted.
*/
trusted: boolean;
/**
* An optional url resolver.
*/
resolver: IRenderMime.IResolver | null;
/**
* An optional link handler.
*/
linkHandler: IRenderMime.ILinkHandler | null;
/**
* Whether the node should be typeset.
*/
shouldTypeset: boolean;
}
}
/**
* Render text into a host node.
*
* @params options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export
function renderText(options: renderText.IRenderOptions): Promise<void> {
// Unpack the options.
let { host, source } = options;
// Escape the terminal codes and HTML tags.
let data = escape_for_html(source);
// Create the HTML content.
let content = ansi_to_html(data, { use_classes: true });
// Set the inner HTML for the host node.
host.innerHTML = `<pre>${content}</pre>`;
// Return the rendered promise.
return Promise.resolve(undefined);
}
/**
* The namespace for the `renderText` function statics.
*/
export
namespace renderText {
/**
* The options for the `renderText` function.
*/
export
interface IRenderOptions {
/**
* The host node for the text content.
*/
host: HTMLElement;
/**
* The source text to render.
*/
source: string;
}
}
/**
* The namespace for module implementation details.
*/
namespace Private {
// This is disabled for now until we decide we actually really
// truly want to allow arbitrary script execution.
/**
* Eval the script tags contained in a host populated by `innerHTML`.
*
* When script tags are created via `innerHTML`, the browser does not
* evaluate them when they are added to the page. This function works
* around that by creating new equivalent script nodes manually, and
* replacing the originals.
*/
// export
// function evalInnerHTMLScriptTags(host: HTMLElement): void {
// // Create a snapshot of the current script nodes.
// let scripts = toArray(host.getElementsByTagName('script'));
// // Loop over each script node.
// for (let script of scripts) {
// // Skip any scripts which no longer have a parent.
// if (!script.parentNode) {
// continue;
// }
// // Create a new script node which will be clone.
// let clone = document.createElement('script');
// // Copy the attributes into the clone.
// let attrs = script.attributes;
// for (let i = 0, n = attrs.length; i < n; ++i) {
// let { name, value } = attrs[i];
// clone.setAttribute(name, value);
// }
// // Copy the text content into the clone.
// clone.textContent = script.textContent;
// // Replace the old script in the parent.
// script.parentNode.replaceChild(clone, script);
// }
// }
/**
* Render markdown for the specified content.
*
* @param content - The string of markdown to render.
*
* @return A promise which resolves with the rendered content.
*/
export
function renderMarked(content: string): Promise<string> {
initializeMarked();
return new Promise<string>((resolve, reject) => {
marked(content, (err: any, content: string) => {
if (err) {
reject(err);
} else {
resolve(content);
}
});
});
}
/**
* Resolve the relative urls in element `src` and `href` attributes.
*
* @param node - The head html element.
*
* @param resolver - A url resolver.
*
* @param linkHandler - An optional link handler for nodes.
*
* @returns a promise fulfilled when the relative urls have been resolved.
*/
export
function handleUrls(node: HTMLElement, resolver: IRenderMime.IResolver, linkHandler: IRenderMime.ILinkHandler | null): Promise<void> {
// Set up an array to collect promises.
let promises: Promise<void>[] = [];
// Handle HTML Elements with src attributes.
let nodes = node.querySelectorAll('*[src]');
for (let i = 0; i < nodes.length; i++) {
promises.push(handleAttr(nodes[i] as HTMLElement, 'src', resolver));
}
// Handle achor elements.
let anchors = node.getElementsByTagName('a');
for (let i = 0; i < anchors.length; i++) {
promises.push(handleAnchor(anchors[i], resolver, linkHandler));
}
// Handle link elements.
let links = node.getElementsByTagName('link');
for (let i = 0; i < links.length; i++) {
promises.push(handleAttr(links[i], 'href', resolver));
}
// Wait on all promises.
return Promise.all(promises).then(() => undefined);
}
/**
* Apply ids to headers.
*/
export
function headerAnchors(node: HTMLElement): void {
let headerNames = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
for (let headerType of headerNames){
let headers = node.getElementsByTagName(headerType);
for (let i=0; i < headers.length; i++) {
let header = headers[i];
header.id = header.innerHTML.replace(/ /g, '-');
let anchor = document.createElement('a');
anchor.target = '_self';
anchor.textContent = '¶';
anchor.href = '#' + header.id;
anchor.classList.add('jp-InternalAnchorLink');
header.appendChild(anchor);
}
}
}
/**
* Handle a node with a `src` or `href` attribute.
*/
function handleAttr(node: HTMLElement, name: 'src' | 'href', resolver: IRenderMime.IResolver): Promise<void> {
let source = node.getAttribute(name);
if (!source) {
return Promise.resolve(undefined);
}
node.setAttribute(name, '');
return resolver.resolveUrl(source).then(path => {
return resolver.getDownloadUrl(path);
}).then(url => {
node.setAttribute(name, url);
});
}
/**
* Handle an anchor node.
*/
function handleAnchor(anchor: HTMLAnchorElement, resolver: IRenderMime.IResolver, linkHandler: IRenderMime.ILinkHandler | null): Promise<void> {
anchor.target = '_blank';
// Get the link path without the location prepended.
// (e.g. "./foo.md#Header 1" vs "http://localhost:8888/foo.md#Header 1")
let href = anchor.getAttribute('href');
// Bail if it is not a file-like url.
if (!href || href.indexOf('://') !== -1 && href.indexOf('//') === 0) {
return Promise.resolve(undefined);
}
// Remove the hash until we can handle it.
let hash = anchor.hash;
if (hash) {
// Handle internal link in the file.
if (hash === href) {
anchor.target = '_self';
return Promise.resolve(undefined);
}
// For external links, remove the hash until we have hash handling.
href = href.replace(hash, '');
}
// Get the appropriate file path.
return resolver.resolveUrl(href).then(path => {
// Handle the click override.
if (linkHandler && URLExt.isLocal(path)) {
linkHandler.handleLink(anchor, path);
}
// Get the appropriate file download path.
return resolver.getDownloadUrl(path);
}).then(url => {
// Set the visible anchor.
anchor.href = url + hash;
});
}
let markedInitialized = false;
/**
* Support GitHub flavored Markdown, leave sanitizing to external library.
*/
function initializeMarked(): void {
if (markedInitialized) {
return;
}
markedInitialized = true;
marked.setOptions({
gfm: true,
sanitize: false,
tables: true,
// breaks: true; We can't use GFM breaks as it causes problems with tables
langPrefix: `cm-s-${CodeMirrorEditor.defaultConfig.theme} language-`,
highlight: (code, lang, callback) => {
if (!lang) {
// no language, no highlight
if (callback) {
callback(null, code);
return;
} else {
return code;
}
}
Mode.ensure(lang).then(spec => {
let el = document.createElement('div');
if (!spec) {
console.log(`No CodeMirror mode: ${lang}`);
callback(null, code);
return;
}
try {
Mode.run(code, spec.mime, el);
callback(null, el.innerHTML);
} catch (err) {
console.log(`Failed to highlight ${lang} code`, err);
callback(err, code);
}
}).catch(err => {
console.log(`No CodeMirror mode: ${lang}`);
console.log(`Require CodeMirror mode error: ${err}`);
callback(null, code);
});
}
});
}
}