/
widget.ts
369 lines (323 loc) · 8.79 KB
/
widget.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { showErrorMessage } from '@jupyterlab/apputils';
import { ActivityMonitor } from '@jupyterlab/coreutils';
import {
ABCWidgetFactory,
DocumentRegistry,
DocumentWidget
} from '@jupyterlab/docregistry';
import {
IRenderMime,
IRenderMimeRegistry,
MimeModel
} from '@jupyterlab/rendermime';
import { PromiseDelegate } from '@lumino/coreutils';
import { Message } from '@lumino/messaging';
import { JSONObject } from '@lumino/coreutils';
import { StackedLayout, Widget } from '@lumino/widgets';
/**
* The class name added to a markdown viewer.
*/
const MARKDOWNVIEWER_CLASS = 'jp-MarkdownViewer';
/**
* The markdown MIME type.
*/
const MIMETYPE = 'text/markdown';
/**
* A widget for markdown documents.
*/
export class MarkdownViewer extends Widget {
/**
* Construct a new markdown viewer widget.
*/
constructor(options: MarkdownViewer.IOptions) {
super();
this.context = options.context;
this.renderer = options.renderer;
this.node.tabIndex = -1;
this.addClass(MARKDOWNVIEWER_CLASS);
const layout = (this.layout = new StackedLayout());
layout.addWidget(this.renderer);
void this.context.ready.then(async () => {
await this._render();
// Throttle the rendering rate of the widget.
this._monitor = new ActivityMonitor({
signal: this.context.model.contentChanged,
timeout: this._config.renderTimeout
});
this._monitor.activityStopped.connect(this.update, this);
this._ready.resolve(undefined);
});
}
/**
* A promise that resolves when the markdown viewer is ready.
*/
get ready(): Promise<void> {
return this._ready.promise;
}
/**
* Set URI fragment identifier.
*/
setFragment(fragment: string) {
this._fragment = fragment;
this.update();
}
/**
* Set a config option for the markdown viewer.
*/
setOption<K extends keyof MarkdownViewer.IConfig>(
option: K,
value: MarkdownViewer.IConfig[K]
): void {
if (this._config[option] === value) {
return;
}
this._config[option] = value;
const { style } = this.renderer.node;
switch (option) {
case 'fontFamily':
style.fontFamily = value as string | null;
break;
case 'fontSize':
style.fontSize = value ? value + 'px' : null;
break;
case 'hideFrontMatter':
this.update();
break;
case 'lineHeight':
style.lineHeight = value ? value.toString() : null;
break;
case 'lineWidth':
const padding = value ? `calc(50% - ${(value as number) / 2}ch)` : null;
style.paddingLeft = padding;
style.paddingRight = padding;
break;
case 'renderTimeout':
this._monitor.timeout = value as number;
break;
default:
break;
}
}
/**
* 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 && !this.isDisposed) {
void this._render();
this._fragment = '';
}
}
/**
* Handle `'activate-request'` messages.
*/
protected onActivateRequest(msg: Message): void {
this.node.focus();
}
/**
* 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;
const { context } = this;
const { model } = context;
const source = model.toString();
const data: JSONObject = {};
// If `hideFrontMatter`is true remove front matter.
data[MIMETYPE] = this._config.hideFrontMatter
? Private.removeFrontMatter(source)
: source;
const mimeModel = new MimeModel({
data,
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);
}
}
readonly context: DocumentRegistry.Context;
readonly renderer: IRenderMime.IRenderer;
private _config = { ...MarkdownViewer.defaultConfig };
private _fragment = '';
private _monitor: ActivityMonitor<DocumentRegistry.IModel, void> | null;
private _ready = new PromiseDelegate<void>();
private _isRendering = false;
private _renderRequested = false;
}
/**
* The namespace for MarkdownViewer class statics.
*/
export namespace MarkdownViewer {
/**
* The options used to initialize a MarkdownViewer.
*/
export interface IOptions {
/**
* Context
*/
context: DocumentRegistry.IContext<DocumentRegistry.IModel>;
/**
* The renderer instance.
*/
renderer: IRenderMime.IRenderer;
}
export interface IConfig {
/**
* User preferred font family for markdown viewer.
*/
fontFamily: string | null;
/**
* User preferred size in pixel of the font used in markdown viewer.
*/
fontSize: number | null;
/**
* User preferred text line height, as a multiplier of font size.
*/
lineHeight: number | null;
/**
* User preferred text line width expressed in CSS ch units.
*/
lineWidth: number | null;
/**
* Whether to hide the YALM front matter.
*/
hideFrontMatter: boolean;
/**
* The render timeout.
*/
renderTimeout: number;
}
/**
* The default configuration options for an editor.
*/
export const defaultConfig: MarkdownViewer.IConfig = {
fontFamily: null,
fontSize: null,
lineHeight: null,
lineWidth: null,
hideFrontMatter: true,
renderTimeout: 1000
};
}
/**
* A document widget for markdown content.
*/
export class MarkdownDocument extends DocumentWidget<MarkdownViewer> {
setFragment(fragment: string): void {
this.content.setFragment(fragment);
}
}
/**
* A widget factory for markdown viewers.
*/
export class MarkdownViewerFactory extends ABCWidgetFactory<MarkdownDocument> {
/**
* Construct a new markdown viewer widget factory.
*/
constructor(options: MarkdownViewerFactory.IOptions) {
super(Private.createRegistryOptions(options));
this._fileType = options.primaryFileType;
this._rendermime = options.rendermime;
}
/**
* Create a new widget given a context.
*/
protected createNewWidget(
context: DocumentRegistry.Context
): MarkdownDocument {
const rendermime = this._rendermime.clone({
resolver: context.urlResolver
});
const renderer = rendermime.createRenderer(MIMETYPE);
const content = new MarkdownViewer({ context, renderer });
content.title.iconClass = this._fileType.iconClass;
content.title.iconLabel = this._fileType.iconLabel;
const widget = new MarkdownDocument({ content, context });
return widget;
}
private _fileType: DocumentRegistry.IFileType;
private _rendermime: IRenderMimeRegistry;
}
/**
* The namespace for MarkdownViewerFactory class statics.
*/
export namespace MarkdownViewerFactory {
/**
* The options used to initialize a MarkdownViewerFactory.
*/
export interface IOptions extends DocumentRegistry.IWidgetFactoryOptions {
/**
* The primary file type associated with the document.
*/
primaryFileType: DocumentRegistry.IFileType;
/**
* The rendermime instance.
*/
rendermime: IRenderMimeRegistry;
}
}
/**
* A namespace for markdown viewer widget private data.
*/
namespace Private {
/**
* Create the document registry options.
*/
export function createRegistryOptions(
options: MarkdownViewerFactory.IOptions
): DocumentRegistry.IWidgetFactoryOptions {
return {
...options,
readOnly: true
} as DocumentRegistry.IWidgetFactoryOptions;
}
/**
* Remove YALM front matter from source.
*/
export function removeFrontMatter(source: string): string {
const re = /^---\n[^]*?\n(---|...)\n/;
const match = source.match(re);
if (!match) {
return source;
}
const { length } = match[0];
return source.slice(length);
}
}