-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
factory.ts
450 lines (411 loc) · 13.6 KB
/
factory.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
/*
* Copyright (c) Jupyter Development Team.
* Distributed under the terms of the Modified BSD License.
*/
import { IObservableList, ObservableList } from '@jupyterlab/observables';
import { ISettingRegistry, SettingRegistry } from '@jupyterlab/settingregistry';
import { ITranslator, TranslationBundle } from '@jupyterlab/translation';
import { Toolbar } from '@jupyterlab/ui-components';
import { findIndex } from '@lumino/algorithm';
import { JSONExt, PartialJSONObject } from '@lumino/coreutils';
import { Widget } from '@lumino/widgets';
import { Dialog, showDialog } from '../dialog';
import { IToolbarWidgetRegistry, ToolbarRegistry } from '../tokens';
/**
* Default toolbar item rank
*
* #### Notes
* This will place item just before the white spacer item in the notebook toolbar.
*/
const DEFAULT_TOOLBAR_ITEM_RANK = 50;
const TOOLBAR_KEY = 'jupyter.lab.toolbars';
/**
* Display warning when the toolbar definition have been modified.
*
* @param trans Translation bundle
*/
async function displayInformation(trans: TranslationBundle): Promise<void> {
const result = await showDialog({
title: trans.__('Information'),
body: trans.__(
'Toolbar customization has changed. You will need to reload JupyterLab to see the changes.'
),
buttons: [
Dialog.cancelButton(),
Dialog.okButton({ label: trans.__('Reload') })
]
});
if (result.button.accept) {
location.reload();
}
}
/**
* Set the toolbar definition by accumulating all settings definition.
*
* The list will be populated only with the enabled items.
*
* @param toolbarItems Observable list to populate
* @param registry Application settings registry
* @param factoryName Widget factory name that needs a toolbar
* @param pluginId Settings plugin id
* @param translator Translator object
* @param propertyId Property holding the toolbar definition in the settings; default 'toolbar'
* @returns List of toolbar items
*/
async function setToolbarItems(
toolbarItems: IObservableList<ISettingRegistry.IToolbarItem>,
registry: ISettingRegistry,
factoryName: string,
pluginId: string,
translator: ITranslator,
propertyId: string = 'toolbar'
): Promise<void> {
const trans = translator.load('jupyterlab');
let canonical: ISettingRegistry.ISchema | null = null;
let loaded: { [name: string]: ISettingRegistry.IToolbarItem[] } = {};
let listenPlugin = true;
try {
/**
* Populate the plugin's schema defaults.
*
* We keep track of disabled entries in case the plugin is loaded
* after the toolbar initialization.
*/
function populate(schema: ISettingRegistry.ISchema) {
loaded = {};
const pluginDefaults = Object.keys(registry.plugins)
// Filter out the current plugin (will be listed when reloading)
// because we control its addition after the mapping step
.filter(plugin => plugin !== pluginId)
.map(plugin => {
const items =
(registry.plugins[plugin]!.schema[TOOLBAR_KEY] ?? {})[
factoryName
] ?? [];
loaded[plugin] = items;
return items;
})
.concat([(schema[TOOLBAR_KEY] ?? {})[factoryName] ?? []])
.reduceRight(
(acc, val) => SettingRegistry.reconcileToolbarItems(acc, val, true),
[]
)!;
// Apply default value as last step to take into account overrides.json
// The standard toolbars default is [] as the plugin must use
// `jupyter.lab.toolbars.<factory>` to define its default value.
schema.properties![propertyId].default =
SettingRegistry.reconcileToolbarItems(
pluginDefaults,
schema.properties![propertyId].default as any[],
true
)!.sort(
(a, b) =>
(a.rank ?? DEFAULT_TOOLBAR_ITEM_RANK) -
(b.rank ?? DEFAULT_TOOLBAR_ITEM_RANK)
);
}
// Transform the plugin object to return different schema than the default.
registry.transform(pluginId, {
compose: plugin => {
// Only override the canonical schema the first time.
if (!canonical) {
canonical = JSONExt.deepCopy(plugin.schema);
populate(canonical);
}
const defaults =
((canonical.properties ?? {})[propertyId] ?? {}).default ?? [];
// Initialize the settings
const user: PartialJSONObject = plugin.data.user;
const composite: PartialJSONObject = plugin.data.composite;
// Overrides the value with using the aggregated default for the toolbar property
user[propertyId] =
(plugin.data.user[propertyId] as ISettingRegistry.IToolbarItem[]) ??
[];
composite[propertyId] = (
SettingRegistry.reconcileToolbarItems(
defaults as ISettingRegistry.IToolbarItem[],
user[propertyId] as ISettingRegistry.IToolbarItem[],
false
) ?? []
).sort(
(a, b) =>
(a.rank ?? DEFAULT_TOOLBAR_ITEM_RANK) -
(b.rank ?? DEFAULT_TOOLBAR_ITEM_RANK)
);
plugin.data = { composite, user };
return plugin;
},
fetch: plugin => {
// Only override the canonical schema the first time.
if (!canonical) {
canonical = JSONExt.deepCopy(plugin.schema);
populate(canonical);
}
return {
data: plugin.data,
id: plugin.id,
raw: plugin.raw,
schema: canonical,
version: plugin.version
};
}
});
} catch (error) {
if (error.name === 'TransformError') {
// Assume the existing transformer is the toolbar builder transformer
// from another factory set up.
listenPlugin = false;
} else {
throw error;
}
}
// Repopulate the canonical variable after the setting registry has
// preloaded all initial plugins.
const settings = await registry.load(pluginId);
// React to customization by the user
settings.changed.connect(() => {
const newItems: ISettingRegistry.IToolbarItem[] =
(settings.composite[propertyId] as any) ?? [];
transferSettings(newItems);
});
const transferSettings = (newItems: ISettingRegistry.IToolbarItem[]) => {
// This is not optimal but safer because a toolbar item with the same
// name cannot be inserted (it will be a no-op). But that could happen
// if the settings are changing the items order.
toolbarItems.clear();
toolbarItems.pushAll(newItems.filter(item => !item.disabled));
};
// Initialize the toolbar
transferSettings((settings.composite[propertyId] as any) ?? []);
// React to plugin changes if no other transformer exists, otherwise bail.
if (!listenPlugin) {
return;
}
registry.pluginChanged.connect(async (sender, plugin) => {
// Since the plugin storing the toolbar definition is transformed above,
// if it has changed, it means that a request to reload was triggered.
// Hence the toolbar definitions from the other plugins have been
// automatically reset during the transform step.
if (plugin === pluginId) {
return;
}
// If a plugin changed its toolbar items
const oldItems = loaded[plugin] ?? [];
const newItems =
(registry.plugins[plugin]!.schema[TOOLBAR_KEY] ?? {})[factoryName] ?? [];
if (!JSONExt.deepEqual(oldItems, newItems)) {
if (loaded[plugin]) {
// The plugin has changed, request the user to reload the UI
await displayInformation(trans);
} else {
if (newItems.length > 0) {
// Empty the default values to avoid toolbar settings collisions.
canonical = null;
const schema = registry.plugins[pluginId]!.schema;
schema.properties!.toolbar.default = [];
// Run again the transformations.
await registry.load(pluginId, true);
}
}
}
});
}
/**
* Create the toolbar factory for a given container widget based
* on a data description stored in settings
*
* @param toolbarRegistry Toolbar widgets registry
* @param settingsRegistry Settings registry
* @param factoryName Toolbar container factory name
* @param pluginId Settings plugin id
* @param translator Translator
* @param propertyId Toolbar definition key in the settings plugin
* @returns List of toolbar widgets factory
*/
export function createToolbarFactory(
toolbarRegistry: IToolbarWidgetRegistry,
settingsRegistry: ISettingRegistry,
factoryName: string,
pluginId: string,
translator: ITranslator,
propertyId: string = 'toolbar'
): (widget: Widget) => IObservableList<ToolbarRegistry.IToolbarItem> {
const items = new ObservableList<ISettingRegistry.IToolbarItem>({
itemCmp: (a, b) => JSONExt.deepEqual(a as any, b as any)
});
// Get toolbar definition from the settings
setToolbarItems(
items,
settingsRegistry,
factoryName,
pluginId,
translator,
propertyId
).catch(reason => {
console.error(
`Failed to load toolbar items for factory ${factoryName} from ${pluginId}`,
reason
);
});
return (widget: Widget) => {
const updateToolbar = (
list: IObservableList<ToolbarRegistry.IWidget>,
change: IObservableList.IChangedArgs<ToolbarRegistry.IWidget>
) => {
switch (change.type) {
case 'move':
toolbar.move(change.oldIndex, change.newIndex);
break;
case 'add':
change.newValues.forEach(item =>
toolbar.push({
name: item.name,
widget: toolbarRegistry.createWidget(factoryName, widget, item)
})
);
break;
case 'remove':
change.oldValues.forEach(() => toolbar.remove(change.oldIndex));
break;
case 'set':
change.newValues.forEach(item =>
toolbar.set(change.newIndex, {
name: item.name,
widget: toolbarRegistry.createWidget(factoryName, widget, item)
})
);
break;
}
};
const updateWidget = (
registry: IToolbarWidgetRegistry,
itemName: string
) => {
const itemIndex = Array.from(items).findIndex(
item => item.name === itemName
);
if (itemIndex >= 0) {
toolbar.set(itemIndex, {
name: itemName,
widget: toolbarRegistry.createWidget(
factoryName,
widget,
items.get(itemIndex)
)
});
}
};
const toolbar = new ObservableList<ToolbarRegistry.IToolbarItem>({
values: Array.from(items).map(item => {
return {
name: item.name,
widget: toolbarRegistry.createWidget(factoryName, widget, item)
};
})
});
// Re-render the widget if a new factory has been added.
toolbarRegistry.factoryAdded.connect(updateWidget);
items.changed.connect(updateToolbar);
widget.disposed.connect(() => {
items.changed.disconnect(updateToolbar);
toolbarRegistry.factoryAdded.disconnect(updateWidget);
});
return toolbar;
};
}
/**
* Set the toolbar items of a widget from a factory
*
* @param widget Widget with the toolbar to set
* @param factory Toolbar items factory
* @param toolbar Separated toolbar if widget is a raw widget
*/
export function setToolbar(
widget: Toolbar.IWidgetToolbar | Widget,
factory: (
widget: Widget
) =>
| IObservableList<ToolbarRegistry.IToolbarItem>
| ToolbarRegistry.IToolbarItem[],
toolbar?: Toolbar
): void {
// @ts-expect-error Widget has no toolbar
if (!widget.toolbar && !toolbar) {
console.log(
`Widget ${widget.id} has no 'toolbar' and no explicit toolbar was provided.`
);
return;
}
// @ts-expect-error Widget has no toolbar
const toolbar_ = (widget.toolbar as Toolbar) ?? toolbar;
const items = factory(widget);
if (Array.isArray(items)) {
items.forEach(({ name, widget: item }) => {
toolbar_.addItem(name, item);
});
} else {
const updateToolbar = (
list: IObservableList<ToolbarRegistry.IToolbarItem>,
changes: IObservableList.IChangedArgs<ToolbarRegistry.IToolbarItem>
) => {
switch (changes.type) {
case 'add':
changes.newValues.forEach((item, index) => {
toolbar_.insertItem(
changes.newIndex + index,
item.name,
item.widget
);
});
break;
case 'move':
changes.oldValues.forEach(item => {
item.widget.parent = null;
});
changes.newValues.forEach((item, index) => {
toolbar_.insertItem(
changes.newIndex + index,
item.name,
item.widget
);
});
break;
case 'remove':
changes.oldValues.forEach(item => {
item.widget.parent = null;
});
break;
case 'set':
changes.oldValues.forEach(item => {
item.widget.parent = null;
});
changes.newValues.forEach((item, index) => {
const existingIndex = findIndex(
toolbar_.names(),
name => item.name === name
);
if (existingIndex >= 0) {
Array.from(toolbar_.children())[existingIndex].parent = null;
}
toolbar_.insertItem(
changes.newIndex + index,
item.name,
item.widget
);
});
break;
}
};
updateToolbar(items, {
newIndex: 0,
newValues: Array.from(items),
oldIndex: 0,
oldValues: [],
type: 'add'
});
items.changed.connect(updateToolbar);
widget.disposed.connect(() => {
items.changed.disconnect(updateToolbar);
});
}
}