This repository has been archived by the owner on Feb 16, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
index.ts
388 lines (340 loc) · 10.9 KB
/
index.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { ISessionContext, DOMUtils } from '@jupyterlab/apputils';
import { CodeCell } from '@jupyterlab/cells';
import { Text, Time } from '@jupyterlab/coreutils';
import { IDocumentManager } from '@jupyterlab/docmanager';
import { IMainMenu } from '@jupyterlab/mainmenu';
import { NotebookPanel, INotebookTracker } from '@jupyterlab/notebook';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { ITranslator } from '@jupyterlab/translation';
import { IRetroShell } from '@retrolab/application';
import { Poll } from '@lumino/polling';
import { Menu, Widget } from '@lumino/widgets';
/**
* The class for kernel status errors.
*/
const KERNEL_STATUS_ERROR_CLASS = 'jp-RetroKernelStatus-error';
/**
* The class for kernel status warnings.
*/
const KERNEL_STATUS_WARN_CLASS = 'jp-RetroKernelStatus-warn';
/**
* The class for kernel status infos.
*/
const KERNEL_STATUS_INFO_CLASS = 'jp-RetroKernelStatus-info';
/**
* The class to fade out the kernel status.
*/
const KERNEL_STATUS_FADE_OUT_CLASS = 'jp-RetroKernelStatus-fade';
/**
* The class for scrolled outputs
*/
const SCROLLED_OUTPUTS_CLASS = 'jp-mod-outputsScrolled';
/**
* A plugin for the checkpoint indicator
*/
const checkpoints: JupyterFrontEndPlugin<void> = {
id: '@retrolab/notebook-extension:checkpoints',
autoStart: true,
requires: [IDocumentManager, ITranslator],
optional: [IRetroShell],
activate: (
app: JupyterFrontEnd,
docManager: IDocumentManager,
translator: ITranslator,
retroShell: IRetroShell | null
) => {
const { shell } = app;
const trans = translator.load('retrolab');
const widget = new Widget();
widget.id = DOMUtils.createDomID();
widget.addClass('jp-RetroCheckpoint');
app.shell.add(widget, 'top', { rank: 100 });
const onChange = async () => {
const current = shell.currentWidget;
if (!current) {
return;
}
const context = docManager.contextForWidget(current);
context?.fileChanged.disconnect(onChange);
context?.fileChanged.connect(onChange);
const checkpoints = await context?.listCheckpoints();
if (!checkpoints) {
return;
}
const checkpoint = checkpoints[checkpoints.length - 1];
widget.node.textContent = trans.__(
'Last Checkpoint: %1',
Time.formatHuman(new Date(checkpoint.last_modified))
);
};
if (retroShell) {
retroShell.currentChanged.connect(onChange);
}
new Poll({
auto: true,
factory: () => onChange(),
frequency: {
interval: 2000,
backoff: false
},
standby: 'when-hidden'
});
}
};
/**
* The kernel logo plugin.
*/
const kernelLogo: JupyterFrontEndPlugin<void> = {
id: '@retrolab/notebook-extension:kernel-logo',
autoStart: true,
requires: [IRetroShell],
activate: (app: JupyterFrontEnd, shell: IRetroShell) => {
const { serviceManager } = app;
let widget: Widget;
const onChange = async () => {
if (widget) {
widget.dispose();
widget.parent = null;
}
const current = shell.currentWidget;
if (!(current instanceof NotebookPanel)) {
return;
}
await current.sessionContext.ready;
current.sessionContext.kernelChanged.disconnect(onChange);
current.sessionContext.kernelChanged.connect(onChange);
const name = current.sessionContext.session?.kernel?.name ?? '';
const spec = serviceManager.kernelspecs?.specs?.kernelspecs[name];
if (!spec) {
return;
}
const kernelIconUrl = spec.resources['logo-64x64'];
if (!kernelIconUrl) {
return;
}
const node = document.createElement('div');
const img = document.createElement('img');
img.src = kernelIconUrl;
img.title = spec.display_name;
node.appendChild(img);
widget = new Widget({ node });
widget.addClass('jp-RetroKernelLogo');
app.shell.add(widget, 'top', { rank: 10_010 });
};
app.started.then(() => {
shell.currentChanged.connect(onChange);
});
}
};
/**
* A plugin to display the kernel status;
*/
const kernelStatus: JupyterFrontEndPlugin<void> = {
id: '@retrolab/notebook-extension:kernel-status',
autoStart: true,
requires: [IRetroShell, ITranslator],
activate: (
app: JupyterFrontEnd,
shell: IRetroShell,
translator: ITranslator
) => {
const trans = translator.load('retrolab');
const widget = new Widget();
widget.addClass('jp-RetroKernelStatus');
app.shell.add(widget, 'menu', { rank: 10_010 });
const removeClasses = () => {
widget.removeClass(KERNEL_STATUS_ERROR_CLASS);
widget.removeClass(KERNEL_STATUS_WARN_CLASS);
widget.removeClass(KERNEL_STATUS_INFO_CLASS);
widget.removeClass(KERNEL_STATUS_FADE_OUT_CLASS);
};
const onStatusChanged = (sessionContext: ISessionContext) => {
const status = sessionContext.kernelDisplayStatus;
let text = `Kernel ${Text.titleCase(status)}`;
removeClasses();
switch (status) {
case 'busy':
case 'idle':
text = '';
widget.addClass(KERNEL_STATUS_FADE_OUT_CLASS);
break;
case 'dead':
case 'terminating':
widget.addClass(KERNEL_STATUS_ERROR_CLASS);
break;
case 'unknown':
widget.addClass(KERNEL_STATUS_WARN_CLASS);
break;
default:
widget.addClass(KERNEL_STATUS_INFO_CLASS);
widget.addClass(KERNEL_STATUS_FADE_OUT_CLASS);
break;
}
widget.node.textContent = trans.__(text);
};
const onChange = async () => {
const current = shell.currentWidget;
if (!(current instanceof NotebookPanel)) {
return;
}
const sessionContext = current.sessionContext;
sessionContext.statusChanged.connect(onStatusChanged);
};
shell.currentChanged.connect(onChange);
}
};
/**
* A plugin to customize notebook related menu entries
* TODO: switch to settings define menus when fixed upstream: https://github.com/jupyterlab/jupyterlab/issues/11754
*/
const menuPlugin: JupyterFrontEndPlugin<void> = {
id: '@retrolab/notebook-extension:menu-plugin',
autoStart: true,
requires: [IMainMenu, ITranslator],
activate: (
app: JupyterFrontEnd,
mainMenu: IMainMenu,
translator: ITranslator
) => {
const { commands } = app;
const trans = translator.load('retrolab');
const cellTypeSubmenu = new Menu({ commands });
cellTypeSubmenu.title.label = trans._p('menu', 'Cell Type');
[
'notebook:change-cell-to-code',
'notebook:change-cell-to-markdown',
'notebook:change-cell-to-raw'
].forEach(command => {
cellTypeSubmenu.addItem({
command
});
});
mainMenu.runMenu.addItem({ type: 'separator', rank: 1000 });
mainMenu.runMenu.addItem({
type: 'submenu',
submenu: cellTypeSubmenu,
rank: 1010
});
}
};
/**
* A plugin to add an extra shortcut to execute a cell in place via Cmd-Enter on Mac.
* TODO: switch to settings define menus when fixed upstream: https://github.com/jupyterlab/jupyterlab/issues/11754
*/
const runShortcut: JupyterFrontEndPlugin<void> = {
id: '@retrolab/notebook-extension:run-shortcut',
autoStart: true,
activate: (app: JupyterFrontEnd) => {
app.commands.addKeyBinding({
command: 'notebook:run-cell',
keys: ['Accel Enter'],
selector: '.jp-Notebook:focus'
});
app.commands.addKeyBinding({
command: 'notebook:run-cell',
keys: ['Accel Enter'],
selector: '.jp-Notebook.jp-mod-editMode'
});
}
};
/**
* A plugin to enable scrolling for outputs by default.
* Mimic the logic from the classic notebook, as found here:
* https://github.com/jupyter/notebook/blob/a9a31c096eeffe1bff4e9164c6a0442e0e13cdb3/notebook/static/notebook/js/outputarea.js#L96-L120
*/
const scrollOutput: JupyterFrontEndPlugin<void> = {
id: '@retrolab/notebook-extension:scroll-output',
autoStart: true,
requires: [INotebookTracker],
optional: [ISettingRegistry],
activate: async (
app: JupyterFrontEnd,
tracker: INotebookTracker,
settingRegistry: ISettingRegistry | null
) => {
const autoScrollThreshold = 100;
let autoScrollOutputs = true;
// decide whether to scroll the output of the cell based on some heuristics
const autoScroll = (cell: CodeCell) => {
if (!autoScrollOutputs) {
// bail if disabled via the settings
return;
}
const { outputArea } = cell;
// respect cells with an explicit scrolled state
const scrolled = cell.model.metadata.get('scrolled');
if (scrolled !== undefined) {
return;
}
const { node } = outputArea;
const height = node.scrollHeight;
const fontSize = parseFloat(node.style.fontSize.replace('px', ''));
const lineHeight = (fontSize || 14) * 1.3;
// do not set via cell.outputScrolled = true, as this would
// otherwise synchronize the scrolled state to the notebook metadata
const scroll = height > lineHeight * autoScrollThreshold;
cell.toggleClass(SCROLLED_OUTPUTS_CLASS, scroll);
};
tracker.widgetAdded.connect((sender, notebook) => {
notebook.model?.cells.changed.connect((sender, changed) => {
// process new cells only
if (!(changed.type === 'add')) {
return;
}
const [cellModel] = changed.newValues;
notebook.content.widgets.forEach(cell => {
if (cell.model.id === cellModel.id && cell.model.type === 'code') {
const codeCell = cell as CodeCell;
codeCell.outputArea.model.changed.connect(() =>
autoScroll(codeCell)
);
}
});
});
// when the notebook widget is created, process all the cells
// TODO: investigate why notebook.content.fullyRendered is not enough
notebook.sessionContext.ready.then(() => {
notebook.content.widgets.forEach(cell => {
if (cell.model.type === 'code') {
autoScroll(cell as CodeCell);
}
});
});
});
if (settingRegistry) {
const loadSettings = settingRegistry.load(scrollOutput.id);
const updateSettings = (settings: ISettingRegistry.ISettings): void => {
autoScrollOutputs = settings.get('autoScrollOutputs')
.composite as boolean;
};
Promise.all([loadSettings, app.restored])
.then(([settings]) => {
updateSettings(settings);
settings.changed.connect(settings => {
updateSettings(settings);
});
})
.catch((reason: Error) => {
console.error(reason.message);
});
}
}
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [
checkpoints,
kernelLogo,
kernelStatus,
menuPlugin,
runShortcut,
scrollOutput
];
export default plugins;