forked from jupyterlab/jupyterlab
/
mimedocument.ts
351 lines (305 loc) · 8.69 KB
/
mimedocument.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { showErrorMessage, Printing } from '@jupyterlab/apputils';
import { ActivityMonitor } from '@jupyterlab/coreutils';
import {
IRenderMime,
IRenderMimeRegistry,
MimeModel
} from '@jupyterlab/rendermime';
import { PromiseDelegate, JSONExt, PartialJSONObject } from '@lumino/coreutils';
import { Message, MessageLoop } from '@lumino/messaging';
import { StackedLayout, Widget } from '@lumino/widgets';
import { ABCWidgetFactory, DocumentWidget } from './default';
import { DocumentRegistry } from './registry';
/**
* A content widget for a rendered mimetype document.
*/
export class MimeContent extends Widget {
/**
* Construct a new widget.
*/
constructor(options: MimeContent.IOptions) {
super();
this.addClass('jp-MimeDocument');
this.mimeType = options.mimeType;
this._dataType = options.dataType || 'string';
this._context = options.context;
this.renderer = options.renderer;
const layout = (this.layout = new StackedLayout());
layout.addWidget(this.renderer);
this._context.ready
.then(() => {
return this._render();
})
.then(() => {
// After rendering for the first time, send an activation request if we
// are currently focused.
if (this.node === document.activeElement) {
// We want to synchronously send (not post) the activate message, while
// we know this node still has focus.
MessageLoop.sendMessage(this.renderer, Widget.Msg.ActivateRequest);
}
// Throttle the rendering rate of the widget.
this._monitor = new ActivityMonitor({
signal: this._context.model.contentChanged,
timeout: options.renderTimeout
});
this._monitor.activityStopped.connect(this.update, this);
this._ready.resolve(undefined);
})
.catch(reason => {
// Dispose the document if rendering fails.
requestAnimationFrame(() => {
this.dispose();
});
void showErrorMessage(
`Renderer Failure: ${this._context.path}`,
reason
);
});
}
/**
* The mimetype for this rendered content.
*/
readonly mimeType: string;
/**
* Print method. Defered to the renderer.
*/
[Printing.symbol]() {
return Printing.getPrintFunction(this.renderer);
}
/**
* A promise that resolves when the widget is ready.
*/
get ready(): Promise<void> {
return this._ready.promise;
}
/**
* Set URI fragment identifier.
*/
setFragment(fragment: string) {
this._fragment = fragment;
this.update();
}
/**
* Dispose of the resources held by the widget.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
if (this._monitor) {
this._monitor.dispose();
}
this._monitor = null;
super.dispose();
}
/**
* Handle an `update-request` message to the widget.
*/
protected onUpdateRequest(msg: Message): void {
if (this._context.isReady) {
void this._render();
this._fragment = '';
}
}
/**
* Render the mime content.
*/
private async _render(): Promise<void> {
if (this.isDisposed) {
return;
}
// Since rendering is async, we note render requests that happen while we
// actually are rendering for a future rendering.
if (this._isRendering) {
this._renderRequested = true;
return;
}
// Set up for this rendering pass.
this._renderRequested = false;
let context = this._context;
let model = context.model;
let data: PartialJSONObject = {};
if (this._dataType === 'string') {
data[this.mimeType] = model.toString();
} else {
data[this.mimeType] = model.toJSON();
}
let mimeModel = new MimeModel({
data,
callback: this._changeCallback,
metadata: { fragment: this._fragment }
});
try {
// Do the rendering asynchronously.
this._isRendering = true;
await this.renderer.renderModel(mimeModel);
this._isRendering = false;
// If there is an outstanding request to render, go ahead and render
if (this._renderRequested) {
return this._render();
}
} catch (reason) {
// Dispose the document if rendering fails.
requestAnimationFrame(() => {
this.dispose();
});
void showErrorMessage(`Renderer Failure: ${context.path}`, reason);
}
}
/**
* A bound change callback.
*/
private _changeCallback = (
options: IRenderMime.IMimeModel.ISetDataOptions
) => {
if (!options.data || !options.data[this.mimeType]) {
return;
}
let data = options.data[this.mimeType];
if (typeof data === 'string') {
if (data !== this._context.model.toString()) {
this._context.model.fromString(data);
}
} else if (
data !== null &&
data !== undefined &&
!JSONExt.deepEqual(data, this._context.model.toJSON())
) {
this._context.model.fromJSON(data);
}
};
readonly renderer: IRenderMime.IRenderer;
private _context: DocumentRegistry.IContext<DocumentRegistry.IModel>;
private _fragment = '';
private _monitor: ActivityMonitor<DocumentRegistry.IModel, void> | null;
private _ready = new PromiseDelegate<void>();
private _dataType: 'string' | 'json';
private _isRendering = false;
private _renderRequested = false;
}
/**
* The namespace for MimeDocument class statics.
*/
export namespace MimeContent {
/**
* The options used to initialize a MimeDocument.
*/
export interface IOptions {
/**
* Context
*/
context: DocumentRegistry.IContext<DocumentRegistry.IModel>;
/**
* The renderer instance.
*/
renderer: IRenderMime.IRenderer;
/**
* The mime type.
*/
mimeType: string;
/**
* The render timeout.
*/
renderTimeout: number;
/**
* Preferred data type from the model.
*/
dataType?: 'string' | 'json';
}
}
/**
* A document widget for mime content.
*/
export class MimeDocument extends DocumentWidget<MimeContent> {
setFragment(fragment: string): void {
this.content.setFragment(fragment);
}
}
/**
* An implementation of a widget factory for a rendered mimetype document.
*/
export class MimeDocumentFactory extends ABCWidgetFactory<MimeDocument> {
/**
* Construct a new mimetype widget factory.
*/
constructor(options: MimeDocumentFactory.IOptions<MimeDocument>) {
super(Private.createRegistryOptions(options));
this._rendermime = options.rendermime;
this._renderTimeout = options.renderTimeout || 1000;
this._dataType = options.dataType || 'string';
this._fileType = options.primaryFileType;
}
/**
* Create a new widget given a context.
*/
protected createNewWidget(context: DocumentRegistry.Context): MimeDocument {
const ft = this._fileType;
const mimeType = ft?.mimeTypes.length ? ft.mimeTypes[0] : 'text/plain';
const rendermime = this._rendermime.clone({
resolver: context.urlResolver
});
const renderer = rendermime.createRenderer(mimeType);
const content = new MimeContent({
context,
renderer,
mimeType,
renderTimeout: this._renderTimeout,
dataType: this._dataType
});
content.title.iconClass = ft?.iconClass ?? '';
content.title.iconLabel = ft?.iconLabel ?? '';
content.title.iconRenderer = ft?.icon!;
const widget = new MimeDocument({ content, context });
return widget;
}
private _rendermime: IRenderMimeRegistry;
private _renderTimeout: number;
private _dataType: 'string' | 'json';
private _fileType: DocumentRegistry.IFileType | undefined;
}
/**
* The namespace for MimeDocumentFactory class statics.
*/
export namespace MimeDocumentFactory {
/**
* The options used to initialize a MimeDocumentFactory.
*/
export interface IOptions<T extends MimeDocument>
extends DocumentRegistry.IWidgetFactoryOptions<T> {
/**
* The primary file type associated with the document.
*/
primaryFileType: DocumentRegistry.IFileType | undefined;
/**
* The rendermime instance.
*/
rendermime: IRenderMimeRegistry;
/**
* The render timeout.
*/
renderTimeout?: number;
/**
* Preferred data type from the model.
*/
dataType?: 'string' | 'json';
}
}
/**
* The namespace for the module implementation details.
*/
namespace Private {
/**
* Create the document registry options.
*/
export function createRegistryOptions(
options: MimeDocumentFactory.IOptions<MimeDocument>
): DocumentRegistry.IWidgetFactoryOptions<MimeDocument> {
return {
...options,
readOnly: true
} as DocumentRegistry.IWidgetFactoryOptions<MimeDocument>;
}
}