/
widget.tsx
371 lines (346 loc) · 9.81 KB
/
widget.tsx
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
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import { ActivityMonitor } from '@jupyterlab/coreutils';
import {
ABCWidgetFactory,
DocumentRegistry,
DocumentWidget,
IDocumentWidget
} from '@jupyterlab/docregistry';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import {
IFrame,
ReactWidget,
refreshIcon,
ToolbarButton,
ToolbarButtonComponent,
UseSignal
} from '@jupyterlab/ui-components';
import { ISignal, Signal } from '@lumino/signaling';
import { Widget } from '@lumino/widgets';
import * as React from 'react';
/**
* The timeout to wait for change activity to have ceased before rendering.
*/
const RENDER_TIMEOUT = 1000;
/**
* The CSS class to add to the HTMLViewer Widget.
*/
const CSS_CLASS = 'jp-HTMLViewer';
const UNTRUSTED_LINK_STYLE = (options: { warning: string }) => `<style>
a[target="_blank"],
area[target="_blank"],
form[target="_blank"],
button[formtarget="_blank"],
input[formtarget="_blank"][type="image"],
input[formtarget="_blank"][type="submit"] {
cursor: not-allowed !important;
}
a[target="_blank"]:hover::after,
area[target="_blank"]:hover::after,
form[target="_blank"]:hover::after,
button[formtarget="_blank"]:hover::after,
input[formtarget="_blank"][type="image"]:hover::after,
input[formtarget="_blank"][type="submit"]:hover::after {
content: "${options.warning}";
box-sizing: border-box;
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 1000;
border: 2px solid #e65100;
background-color: #ffb74d;
color: black;
font-family: system-ui, -apple-system, blinkmacsystemfont, 'Segoe UI', helvetica, arial, sans-serif;
text-align: center;
}
</style>`;
/**
* A viewer widget for HTML documents.
*
* #### Notes
* The iframed HTML document can pose a potential security risk,
* since it can execute Javascript, and make same-origin requests
* to the server, thereby executing arbitrary Javascript.
*
* Here, we sandbox the iframe so that it can't execute Javascript
* or launch any popups. We allow one exception: 'allow-same-origin'
* requests, so that local HTML documents can access CSS, images,
* etc from the files system.
*/
export class HTMLViewer
extends DocumentWidget<IFrame>
implements IDocumentWidget<IFrame>
{
/**
* Create a new widget for rendering HTML.
*/
constructor(options: DocumentWidget.IOptionsOptionalContent) {
super({
...options,
content: new IFrame({ sandbox: ['allow-same-origin'] })
});
this.translator = options.translator || nullTranslator;
this.content.addClass(CSS_CLASS);
void this.context.ready.then(() => {
this.update();
// Throttle the rendering rate of the widget.
this._monitor = new ActivityMonitor({
signal: this.context.model.contentChanged,
timeout: RENDER_TIMEOUT
});
this._monitor.activityStopped.connect(this.update, this);
});
}
/**
* Whether the HTML document is trusted. If trusted,
* it can execute Javascript in the iframe sandbox.
*/
get trusted(): boolean {
return this.content.sandbox.indexOf('allow-scripts') !== -1;
}
set trusted(value: boolean) {
if (this.trusted === value) {
return;
}
if (value) {
this.content.sandbox = Private.trusted;
} else {
this.content.sandbox = Private.untrusted;
}
this.update(); // Force a refresh.
this._trustedChanged.emit(value);
}
/**
* Emitted when the trust state of the document changes.
*/
get trustedChanged(): ISignal<this, boolean> {
return this._trustedChanged;
}
/**
* Dispose of resources held by the html viewer.
*/
dispose(): void {
if (this._objectUrl) {
try {
URL.revokeObjectURL(this._objectUrl);
} catch (error) {
/* no-op */
}
}
super.dispose();
}
/**
* Handle and update request.
*/
protected onUpdateRequest(): void {
if (this._renderPending) {
return;
}
this._renderPending = true;
void this._renderModel().then(() => (this._renderPending = false));
}
/**
* Render HTML in IFrame into this widget's node.
*/
private async _renderModel(): Promise<void> {
let data = this.context.model.toString();
data = await this._setupDocument(data);
// Set the new iframe url.
const blob = new Blob([data], { type: 'text/html' });
const oldUrl = this._objectUrl;
this._objectUrl = URL.createObjectURL(blob);
this.content.url = this._objectUrl;
// Release reference to any previous object url.
if (oldUrl) {
try {
URL.revokeObjectURL(oldUrl);
} catch (error) {
/* no-op */
}
}
return;
}
/**
* Set a <base> element in the HTML string so that the iframe
* can correctly dereference relative links.
*/
private async _setupDocument(data: string): Promise<string> {
const doc = this._parser.parseFromString(data, 'text/html');
let base = doc.querySelector('base');
if (!base) {
base = doc.createElement('base');
doc.head.insertBefore(base, doc.head.firstChild);
}
const path = this.context.path;
const baseUrl = await this.context.urlResolver.getDownloadUrl(path);
// Set the base href, plus a fake name for the url of this
// document. The fake name doesn't really matter, as long
// as the document can dereference relative links to resources
// (e.g. CSS and scripts).
base.href = baseUrl;
base.target = '_self';
// Inject dynamic style for links if the document is not trusted
if (!this.trusted) {
const trans = this.translator.load('jupyterlab');
const warning = trans.__('Action disabled as the file is not trusted.');
doc.body.insertAdjacentHTML(
'beforeend',
UNTRUSTED_LINK_STYLE({ warning })
);
}
return doc.documentElement.innerHTML;
}
protected translator: ITranslator;
private _renderPending = false;
private _parser = new DOMParser();
private _monitor: ActivityMonitor<DocumentRegistry.IModel, void> | null =
null;
private _objectUrl: string = '';
private _trustedChanged = new Signal<this, boolean>(this);
}
/**
* A widget factory for HTMLViewers.
*/
export class HTMLViewerFactory extends ABCWidgetFactory<HTMLViewer> {
/**
* Create a new widget given a context.
*/
protected createNewWidget(context: DocumentRegistry.Context): HTMLViewer {
return new HTMLViewer({ context });
}
/**
* Default factory for toolbar items to be added after the widget is created.
*/
protected defaultToolbarFactory(
widget: HTMLViewer
): DocumentRegistry.IToolbarItem[] {
return [
// Make a refresh button for the toolbar.
{
name: 'refresh',
widget: ToolbarItems.createRefreshButton(widget, this.translator)
},
// Make a trust button for the toolbar.
{
name: 'trust',
widget: ToolbarItems.createTrustButton(widget, this.translator)
}
];
}
}
/**
* A namespace for toolbar items generator
*/
export namespace ToolbarItems {
/**
* Create the refresh button
*
* @param widget HTML viewer widget
* @param translator Application translator object
* @returns Toolbar item button
*/
export function createRefreshButton(
widget: HTMLViewer,
translator?: ITranslator
): Widget {
const trans = (translator ?? nullTranslator).load('jupyterlab');
return new ToolbarButton({
icon: refreshIcon,
onClick: async () => {
if (!widget.context.model.dirty) {
await widget.context.revert();
widget.update();
}
},
tooltip: trans.__('Rerender HTML Document')
});
}
/**
* Create the trust button
*
* @param document HTML viewer widget
* @param translator Application translator object
* @returns Toolbar item button
*/
export function createTrustButton(
document: HTMLViewer,
translator: ITranslator
): Widget {
return ReactWidget.create(
<Private.TrustButtonComponent
htmlDocument={document}
translator={translator}
/>
);
}
}
/**
* A namespace for private data.
*/
namespace Private {
/**
* Sandbox exceptions for untrusted HTML.
*/
export const untrusted: IFrame.SandboxExceptions[] = [];
/**
* Sandbox exceptions for trusted HTML.
*/
export const trusted: IFrame.SandboxExceptions[] = [
'allow-scripts',
'allow-popups'
];
/**
* Namespace for TrustedButton.
*/
export namespace TrustButtonComponent {
/**
* Interface for TrustedButton props.
*/
export interface IProps {
htmlDocument: HTMLViewer;
/**
* Language translator.
*/
translator?: ITranslator;
}
}
/**
* React component for a trusted button.
*
* This wraps the ToolbarButtonComponent and watches for trust changes.
*/
export function TrustButtonComponent(
props: TrustButtonComponent.IProps
): JSX.Element {
const translator = props.translator || nullTranslator;
const trans = translator.load('jupyterlab');
return (
<UseSignal
signal={props.htmlDocument.trustedChanged}
initialSender={props.htmlDocument}
>
{() => (
<ToolbarButtonComponent
className=""
onClick={() =>
(props.htmlDocument.trusted = !props.htmlDocument.trusted)
}
tooltip={trans.__(`Whether the HTML file is trusted.
Trusting the file allows opening pop-ups and running scripts
which may result in security risks.
Only enable for files you trust.`)}
label={
props.htmlDocument.trusted
? trans.__('Distrust HTML')
: trans.__('Trust HTML')
}
/>
)}
</UseSignal>
);
}
}