/
renderers.ts
1589 lines (1432 loc) · 41.8 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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import { URLExt } from '@jupyterlab/coreutils';
import { IRenderMime } from '@jupyterlab/rendermime-interfaces';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import escape from 'lodash.escape';
import { removeMath, replaceMath } from './latex';
/**
* Render HTML into a host node.
*
* @param 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,
latexTypesetter,
translator
} = options;
translator = translator || nullTranslator;
const trans = translator?.load('jupyterlab');
let originalSource = source;
// 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) {
originalSource = `${source}`;
source = sanitizer.sanitize(source);
}
// Set the inner HTML of the host.
host.innerHTML = source;
if (host.getElementsByTagName('script').length > 0) {
// If output it trusted, eval any script tags contained in the HTML.
// This is not done automatically by the browser when script tags are
// created by setting `innerHTML`.
if (trusted) {
Private.evalInnerHTMLScriptTags(host);
} else {
const container = document.createElement('div');
const warning = document.createElement('pre');
warning.textContent = trans.__(
'This HTML output contains inline scripts. Are you sure that you want to run arbitrary Javascript within your JupyterLab session?'
);
const runButton = document.createElement('button');
runButton.textContent = trans.__('Run');
runButton.onclick = event => {
host.innerHTML = originalSource;
Private.evalInnerHTMLScriptTags(host);
if (host.firstChild) {
host.removeChild(host.firstChild);
}
};
container.appendChild(warning);
container.appendChild(runButton);
host.insertBefore(container, host.firstChild);
}
}
// Handle default behavior of nodes.
Private.handleDefaults(host, resolver);
// 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 && latexTypesetter) {
latexTypesetter.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: IRenderMime.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;
/**
* The LaTeX typesetter for the application.
*/
latexTypesetter: IRenderMime.ILatexTypesetter | null;
/**
* The application language translator.
*/
translator?: ITranslator;
}
}
/**
* Render an image into a host node.
*
* @param 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.
const { host, mimeType, source, width, height, needsBackground, unconfined } =
options;
// Clear the content in the host.
host.textContent = '';
// Create the image element.
const 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;
}
if (needsBackground === 'light') {
img.classList.add('jp-needs-light-background');
} else if (needsBackground === 'dark') {
img.classList.add('jp-needs-dark-background');
}
if (unconfined === true) {
img.classList.add('jp-mod-unconfined');
}
// 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;
/**
* Whether an image requires a background for legibility.
*/
needsBackground?: string;
/**
* Whether the image should be unconfined.
*/
unconfined?: boolean;
}
}
/**
* Render LaTeX into a host node.
*
* @param 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.
const { host, source, shouldTypeset, latexTypesetter } = options;
// Set the source on the node.
host.textContent = source;
// Typeset the node if needed.
if (shouldTypeset && latexTypesetter) {
latexTypesetter.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;
/**
* The LaTeX typesetter for the application.
*/
latexTypesetter: IRenderMime.ILatexTypesetter | null;
}
}
/**
* Render Markdown into a host node.
*
* @param options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export async function renderMarkdown(
options: renderMarkdown.IRenderOptions
): Promise<void> {
// Unpack the options.
const { host, source, markdownParser, ...others } = options;
// Clear the content if there is no source.
if (!source) {
host.textContent = '';
return;
}
let html = '';
if (markdownParser) {
// Separate math from normal markdown text.
const parts = removeMath(source);
// Convert the markdown to HTML.
html = await markdownParser.render(parts['text']);
// Replace math.
html = replaceMath(html, parts['math']);
} else {
// Fallback if the application does not have any markdown parser.
html = `<pre>${source}</pre>`;
}
// Render HTML.
await renderHTML({
host,
source: html,
...others
});
// Apply ids to the header nodes.
Private.headerAnchors(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: IRenderMime.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;
/**
* The LaTeX typesetter for the application.
*/
latexTypesetter: IRenderMime.ILatexTypesetter | null;
/**
* The Markdown parser.
*/
markdownParser: IRenderMime.IMarkdownParser | null;
/**
* The application language translator.
*/
translator?: ITranslator;
}
/**
* Create a normalized id for a header element.
*
* @param header Header element
* @returns Normalized id
*/
export function createHeaderId(header: Element): string {
return (header.textContent ?? '').replace(/ /g, '-');
}
}
/**
* Render SVG into a host node.
*
* @param 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, unconfined } = 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);
}
// Add missing SVG namespace (if actually missing)
const patt = '<svg[^>]+xmlns=[^>]+svg';
if (source.search(patt) < 0) {
source = source.replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"');
}
// Render in img so that user can save it easily
const img = new Image();
img.src = `data:image/svg+xml,${encodeURIComponent(source)}`;
host.appendChild(img);
if (unconfined === true) {
host.classList.add('jp-mod-unconfined');
}
return Promise.resolve();
}
/**
* 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;
/**
* Whether the svg should be unconfined.
*/
unconfined?: boolean;
/**
* The application language translator.
*/
translator: ITranslator;
}
}
/**
* Options for auto linker.
*/
interface IAutoLinkOptions {
/**
* Whether to look for web URLs e.g. indicated by http schema or www prefix.
*/
checkWeb: boolean;
/**
* Whether to look for path URIs.
*/
checkPaths: boolean;
}
interface ILinker {
/**
* Regular expression capturing links in the group named `path`.
*
* Full match extend will be used as label for the link.
* Additional named groups represent locator fragments.
*/
regex: RegExp;
/**
* Create the anchor element.
*/
createAnchor: (
text: string,
label: string,
attributes?: Record<string, string>
) => HTMLAnchorElement;
/**
* Modify the path value if needed.
*/
processPath?: (text: string) => string;
/**
* Modify the label if needed.
*/
processLabel?: (text: string) => string;
}
namespace ILinker {
// Taken from Visual Studio Code:
// https://github.com/microsoft/vscode/blob/9f709d170b06e991502153f281ec3c012add2e42/src/vs/workbench/contrib/debug/browser/linkDetector.ts#L17-L18
const controlCodes = '\\u0000-\\u0020\\u007f-\\u009f';
export const webLinkRegex = new RegExp(
'(?<path>(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\\/\\/|data:|www\\.)[^\\s' +
controlCodes +
'"]{2,}[^\\s' +
controlCodes +
'"\'(){}\\[\\],:;.!?])',
'ug'
);
// Taken from Visual Studio Code:
// https://github.com/microsoft/vscode/blob/3e407526a1e2ff22cacb69c7e353e81a12f41029/extensions/notebook-renderers/src/linkify.ts#L9
const winAbsPathRegex = /(?:[a-zA-Z]:(?:(?:\\|\/)[\w\.-]*)+)/;
const winRelPathRegex = /(?:(?:\~|\.)(?:(?:\\|\/)[\w\.-]*)+)/;
const winPathRegex = new RegExp(
`(${winAbsPathRegex.source}|${winRelPathRegex.source})`
);
const posixPathRegex = /((?:\~|\.)?(?:\/[\w\.-]*)+)/;
const lineColumnRegex =
/(?:(?:\:|", line )(?<line>[\d]+))?(?:\:(?<column>[\d]+))?/;
// TODO: this ought to come from kernel (browser may be on a different OS).
const isWindows = navigator.userAgent.indexOf('Windows') >= 0;
export const pathLinkRegex = new RegExp(
`(?<path>${isWindows ? winPathRegex.source : posixPathRegex.source})${
lineColumnRegex.source
}`,
'g'
);
}
/**
* Linker for web URLs.
*/
class WebLinker implements ILinker {
regex = ILinker.webLinkRegex;
createAnchor(url: string, label: string) {
const anchor = document.createElement('a');
anchor.href = url.startsWith('www.') ? 'https://' + url : url;
anchor.rel = 'noopener';
anchor.target = '_blank';
anchor.appendChild(document.createTextNode(label));
return anchor;
}
processPath(url: string) {
// Special case when the URL ends with ">" or "<"
const lastChars = url.slice(-1);
const endsWithGtLt = ['>', '<'].indexOf(lastChars) !== -1;
const len = endsWithGtLt ? url.length - 1 : url.length;
url = url.slice(0, len);
return url;
}
processLabel(url: string) {
return this.processPath(url);
}
}
/**
* Linker for path URIs.
*/
class PathLinker implements ILinker {
regex = ILinker.pathLinkRegex;
createAnchor(path: string, label: string, locators: Record<string, string>) {
const anchor = document.createElement('a');
// Store the path in dataset.
// Do not set `href` - at this point we do not know if the path is valid and
// accessible for application (and we want rendering those as links).
anchor.dataset.path = path;
// Store line using RFC 5147 fragment locator for text/plain files.
// It could be expanded to other formats, e.g. based on file extension.
const line = parseInt(locators['line'], 10);
let locator: string = !isNaN(line) ? `line=${line - 1}` : '';
anchor.dataset.locator = locator;
anchor.appendChild(document.createTextNode(label));
return anchor;
}
}
function autolink(
content: string,
options: IAutoLinkOptions
): Array<HTMLAnchorElement | Text> {
const linkers: ILinker[] = [];
if (options.checkWeb) {
linkers.push(new WebLinker());
}
if (options.checkPaths) {
linkers.push(new PathLinker());
}
const nodes: Array<HTMLAnchorElement | Text> = [];
// There are two ways to implement competitive regexes:
// - two heads (which would need to resolve overlaps), or
// - (simpler) divide and recurse (implemented below)
const linkify = (content: string, regexIndex: number) => {
if (regexIndex >= linkers.length) {
nodes.push(document.createTextNode(content));
return;
}
const linker = linkers[regexIndex];
let match: RegExpExecArray | null;
let currentIndex = 0;
const regex = linker.regex;
// Reset regex
regex.lastIndex = 0;
while (null != (match = regex.exec(content))) {
const stringBeforeMatch = content.substring(currentIndex, match.index);
if (stringBeforeMatch) {
linkify(stringBeforeMatch, regexIndex + 1);
}
const { path, ...locators } = match.groups!;
const value = linker.processPath ? linker.processPath(path) : path;
const label = linker.processLabel
? linker.processLabel(match[0])
: match[0];
nodes.push(linker.createAnchor(value, label, locators));
currentIndex = match.index + label.length;
}
const stringAfterMatches = content.substring(currentIndex);
if (stringAfterMatches) {
linkify(stringAfterMatches, regexIndex + 1);
}
};
linkify(content, 0);
return nodes;
}
/**
* Split a shallow node (node without nested nodes inside) at a given text content position.
*
* @param node the shallow node to be split
* @param at the position in textContent at which the split should occur
*/
function splitShallowNode<T extends Node>(
node: T,
at: number
): { pre: T; post: T } {
const pre = node.cloneNode() as T;
pre.textContent = node.textContent?.slice(0, at) as string;
const post = node.cloneNode() as T;
post.textContent = node.textContent?.slice(at) as string;
return {
pre,
post
};
}
/**
* Iterate over some nodes, while tracking cumulative start and end position.
*/
function* nodeIter<T extends Node>(
nodes: T[]
): IterableIterator<{ node: T; start: number; end: number; isText: boolean }> {
let start = 0;
let end;
for (let node of nodes) {
end = start + (node.textContent?.length || 0);
yield {
node,
start,
end,
isText: node.nodeType === Node.TEXT_NODE
};
start = end;
}
}
/**
* Align two collections of nodes.
*
* If a text node in one collections spans an element in the other, yield the spanned elements.
* Otherwise, split the nodes such that yielded pair start and stop on the same position.
*/
function* alignedNodes<T extends Node, U extends Node>(
a: T[],
b: U[]
): IterableIterator<[T, null] | [null, U] | [T, U]> {
let iterA = nodeIter(a);
let iterB = nodeIter(b);
let nA = iterA.next();
let nB = iterB.next();
while (!nA.done && !nB.done) {
let A = nA.value;
let B = nB.value;
if (A.isText && A.start <= B.start && A.end >= B.end) {
// A is a text element that spans all of B, simply yield B
yield [null, B.node];
nB = iterB.next();
} else if (B.isText && B.start <= A.start && B.end >= A.end) {
// B is a text element that spans all of A, simply yield A
yield [A.node, null];
nA = iterA.next();
} else {
// There is some intersection, split one, unless they match exactly
if (A.end === B.end && A.start === B.start) {
yield [A.node, B.node];
nA = iterA.next();
nB = iterB.next();
} else if (A.end > B.end) {
/*
A |-----[======]---|
B |--[======]------|
| <- Split A here
| <- trim B to start from here if needed
*/
let { pre, post } = splitShallowNode(A.node, B.end - A.start);
if (B.start < A.start) {
// this node should not be yielded anywhere else, so ok to modify in-place
B.node.textContent = B.node.textContent?.slice(
A.start - B.start
) as string;
}
yield [pre, B.node];
// Modify iteration result in-place:
A.node = post;
A.start = B.end;
nB = iterB.next();
} else if (B.end > A.end) {
let { pre, post } = splitShallowNode(B.node, A.end - B.start);
if (A.start < B.start) {
// this node should not be yielded anywhere else, so ok to modify in-place
A.node.textContent = A.node.textContent?.slice(
B.start - A.start
) as string;
}
yield [A.node, pre];
// Modify iteration result in-place:
B.node = post;
B.start = A.end;
nA = iterA.next();
} else {
throw new Error(
`Unexpected intersection: ${JSON.stringify(A)} ${JSON.stringify(B)}`
);
}
}
}
}
/**
* Render text into a host node.
*
* @param 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.
const { host, sanitizer, source } = options;
// Create the HTML content.
const content = sanitizer.sanitize(Private.ansiSpan(source), {
allowedTags: ['span']
});
// Set the sanitized content for the host node.
const pre = document.createElement('pre');
pre.innerHTML = content;
const preTextContent = pre.textContent;
let ret: HTMLPreElement;
if (preTextContent) {
// Note: only text nodes and span elements should be present after sanitization in the `<pre>` element.
const linkedNodes =
sanitizer.getAutolink?.() ?? true
? autolink(preTextContent, {
checkWeb: true,
checkPaths: false
})
: [document.createTextNode(content)];
const preNodes = Array.from(pre.childNodes) as (Text | HTMLSpanElement)[];
ret = mergeNodes(preNodes, linkedNodes);
} else {
ret = document.createElement('pre');
}
host.appendChild(ret);
// 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 html sanitizer for untrusted source.
*/
sanitizer: IRenderMime.ISanitizer;
/**
* The source text to render.
*/
source: string;
/**
* The application language translator.
*/
translator?: ITranslator;
}
}
/**
* Render error into a host node.
*
* @param options - The options for rendering.
*
* @returns A promise which resolves when rendering is complete.
*/
export function renderError(
options: renderError.IRenderOptions
): Promise<void> {
// Unpack the options.
const { host, linkHandler, sanitizer, resolver, source } = options;
// Create the HTML content.
const content = sanitizer.sanitize(Private.ansiSpan(source), {
allowedTags: ['span']
});
// Set the sanitized content for the host node.
const pre = document.createElement('pre');
pre.innerHTML = content;
const preTextContent = pre.textContent;
let ret: HTMLPreElement;
if (preTextContent) {
// Note: only text nodes and span elements should be present after sanitization in the `<pre>` element.
const linkedNodes =
sanitizer.getAutolink?.() ?? true
? autolink(preTextContent, {
checkWeb: true,
checkPaths: true
})
: [document.createTextNode(content)];
const preNodes = Array.from(pre.childNodes) as (Text | HTMLSpanElement)[];
ret = mergeNodes(preNodes, linkedNodes);
} else {
ret = document.createElement('pre');
}
host.appendChild(ret);
// Patch the paths if a resolver is available.
let promise: Promise<void>;
if (resolver) {
promise = Private.handlePaths(host, resolver, linkHandler);
} else {
promise = Promise.resolve(undefined);
}
// Return the rendered promise.
return promise;
}
/**
* Merge `<span>` nodes from a `<pre>` element with `<a>` nodes from linker.
*/
function mergeNodes(
preNodes: (Text | HTMLSpanElement)[],
linkedNodes: (Text | HTMLAnchorElement)[]
): HTMLPreElement {
const ret = document.createElement('pre');
let inAnchorElement = false;
const combinedNodes: (HTMLAnchorElement | Text | HTMLSpanElement)[] = [];
for (let nodes of alignedNodes(preNodes, linkedNodes)) {
if (!nodes[0]) {
combinedNodes.push(nodes[1]);
inAnchorElement = nodes[1].nodeType !== Node.TEXT_NODE;
continue;
} else if (!nodes[1]) {
combinedNodes.push(nodes[0]);
inAnchorElement = false;
continue;
}
let [preNode, linkNode] = nodes;
const lastCombined = combinedNodes[combinedNodes.length - 1];
// If we are already in an anchor element and the anchor element did not change,
// we should insert the node from <pre> which is either Text node or coloured span Element
// into the anchor content as a child
if (
inAnchorElement &&
(linkNode as HTMLAnchorElement).href ===
(lastCombined as HTMLAnchorElement).href
) {
lastCombined.appendChild(preNode);
} else {
// the `linkNode` is either Text or AnchorElement;
const isAnchor = linkNode.nodeType !== Node.TEXT_NODE;
// if we are NOT about to start an anchor element, just add the pre Node
if (!isAnchor) {
combinedNodes.push(preNode);
inAnchorElement = false;
} else {
// otherwise start a new anchor; the contents of the `linkNode` and `preNode` should be the same,
// so we just put the neatly formatted `preNode` inside the anchor node (`linkNode`)
// and append that to combined nodes.
linkNode.textContent = '';
linkNode.appendChild(preNode);
combinedNodes.push(linkNode);
inAnchorElement = true;
}
}
}
// Do not reuse `pre` element. Clearing out previous children is too slow...
for (const child of combinedNodes) {
ret.appendChild(child);
}
return ret;
}
/**
* The namespace for the `renderError` function statics.
*/
export namespace renderError {
/**
* The options for the `renderError` function.
*/
export interface IRenderOptions {
/**
* The host node for the error content.
*/
host: HTMLElement;
/**
* The html sanitizer for untrusted source.
*/
sanitizer: IRenderMime.ISanitizer;
/**
* The source error to render.
*/
source: string;
/**
* An optional url resolver.
*/
resolver: IRenderMime.IResolver | null;
/**
* An optional link handler.