/
layoutrestorer.ts
689 lines (608 loc) · 18.9 KB
/
layoutrestorer.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
/*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import { WidgetTracker } from '@jupyterlab/apputils';
import { IDataConnector, IRestorer } from '@jupyterlab/statedb';
import { CommandRegistry } from '@lumino/commands';
import {
JSONExt,
JSONObject,
PromiseDelegate,
PartialJSONObject,
ReadonlyPartialJSONValue,
ReadonlyPartialJSONObject,
Token
} from '@lumino/coreutils';
import { AttachedProperty } from '@lumino/properties';
import { DockPanel, Widget } from '@lumino/widgets';
import { ILabShell } from './shell';
/* tslint:disable */
/**
* The layout restorer token.
*/
export const ILayoutRestorer = new Token<ILayoutRestorer>(
'@jupyterlab/application:ILayoutRestorer'
);
/* tslint:enable */
/**
* A static class that restores the widgets of the application when it reloads.
*/
export interface ILayoutRestorer extends IRestorer {
/**
* A promise resolved when the layout restorer is ready to receive signals.
*/
restored: Promise<void>;
/**
* Add a widget to be tracked by the layout restorer.
*/
add(widget: Widget, name: string): void;
/**
* Restore the widgets of a particular widget tracker.
*
* @param tracker - The widget tracker whose widgets will be restored.
*
* @param options - The restoration options.
*/
restore<T extends Widget>(
tracker: WidgetTracker<T>,
options: IRestorer.IOptions<T>
): Promise<any>;
}
/**
* The data connector key for restorer data.
*/
const KEY = 'layout-restorer:data';
/**
* The default implementation of a layout restorer.
*
* #### Notes
* The lifecycle for state restoration is subtle. The sequence of events is:
*
* 1. The layout restorer plugin is instantiated and makes a `fetch` call to
* the data connector that stores the layout restoration data. The `fetch`
* call returns a promise that resolves in step 6, below.
*
* 2. Other plugins that care about state restoration require the layout
* restorer as a dependency.
*
* 3. As each load-time plugin initializes (which happens before the front-end
* application has `started`), it instructs the layout restorer whether
* the restorer ought to `restore` its widgets by passing in its widget
* tracker.
* Alternatively, a plugin that does not require its own widget tracker
* (because perhaps it only creates a single widget, like a command palette),
* can simply `add` its widget along with a persistent unique name to the
* layout restorer so that its layout state can be restored when the lab
* application restores.
*
* 4. After all the load-time plugins have finished initializing, the front-end
* application `started` promise will resolve. This is the `first`
* promise that the layout restorer waits for. By this point, all of the
* plugins that care about restoration will have instructed the layout
* restorer to `restore` their widget trackers.
*
* 5. The layout restorer will then instruct each plugin's widget tracker
* to restore its state and reinstantiate whichever widgets it wants. The
* tracker returns a promise to the layout restorer that resolves when it
* has completed restoring the tracked widgets it cares about.
*
* 6. As each widget tracker finishes restoring the widget instances it cares
* about, it resolves the promise that was returned to the layout restorer
* (in step 5). After all of the promises that the restorer is awaiting have
* settled, the restorer then resolves the outstanding `fetch` promise
* (from step 1) and hands off a layout state object to the application
* shell's `restoreLayout` method for restoration.
*
* 7. Once the application shell has finished restoring the layout, the
* JupyterLab application's `restored` promise is resolved.
*
* Of particular note are steps 5 and 6: since data restoration of plugins
* is accomplished by executing commands, the command that is used to restore
* the data of each plugin must return a promise that only resolves when the
* widget has been created and added to the plugin's widget tracker.
*/
export class LayoutRestorer implements ILayoutRestorer {
/**
* Create a layout restorer.
*/
constructor(options: LayoutRestorer.IOptions) {
this._connector = options.connector;
this._first = options.first;
this._registry = options.registry;
void this._first
.then(() => {
this._firstDone = true;
})
.then(() => Promise.all(this._promises))
.then(() => {
this._promisesDone = true;
// Release the tracker set.
this._trackers.clear();
})
.then(() => {
this._restored.resolve(void 0);
});
}
/**
* A promise resolved when the layout restorer is ready to receive signals.
*/
get restored(): Promise<void> {
return this._restored.promise;
}
/**
* Add a widget to be tracked by the layout restorer.
*/
add(widget: Widget, name: string): void {
Private.nameProperty.set(widget, name);
this._widgets.set(name, widget);
widget.disposed.connect(this._onWidgetDisposed, this);
}
/**
* Fetch the layout state for the application.
*
* #### Notes
* Fetching the layout relies on all widget restoration to be complete, so
* calls to `fetch` are guaranteed to return after restoration is complete.
*/
async fetch(): Promise<ILabShell.ILayout> {
const blank: ILabShell.ILayout = {
fresh: true,
mainArea: null,
leftArea: null,
rightArea: null
};
const layout = this._connector.fetch(KEY);
try {
const [data] = await Promise.all([layout, this.restored]);
if (!data) {
return blank;
}
const { main, left, right } = data as Private.ILayout;
// If any data exists, then this is not a fresh session.
const fresh = false;
// Rehydrate main area.
const mainArea = this._rehydrateMainArea(main);
// Rehydrate left area.
const leftArea = this._rehydrateSideArea(left);
// Rehydrate right area.
const rightArea = this._rehydrateSideArea(right);
return { fresh, mainArea, leftArea, rightArea };
} catch (error) {
return blank;
}
}
/**
* Restore the widgets of a particular widget tracker.
*
* @param tracker - The widget tracker whose widgets will be restored.
*
* @param options - The restoration options.
*/
restore(
tracker: WidgetTracker,
options: IRestorer.IOptions<Widget>
): Promise<any> {
const warning = 'restore() can only be called before `first` has resolved.';
if (this._firstDone) {
console.warn(warning);
return Promise.reject(warning);
}
const { namespace } = tracker;
if (this._trackers.has(namespace)) {
const warning = `A tracker namespaced ${namespace} was already restored.`;
console.warn(warning);
return Promise.reject(warning);
}
const { args, command, name, when } = options;
// Add the tracker to the private trackers collection.
this._trackers.add(namespace);
// Whenever a new widget is added to the tracker, record its name.
tracker.widgetAdded.connect((_, widget) => {
const widgetName = name(widget);
if (widgetName) {
this.add(widget, `${namespace}:${widgetName}`);
}
}, this);
// Whenever a widget is updated, get its new name.
tracker.widgetUpdated.connect((_, widget) => {
const widgetName = name(widget);
if (widgetName) {
const name = `${namespace}:${widgetName}`;
Private.nameProperty.set(widget, name);
this._widgets.set(name, widget);
}
});
const first = this._first;
const promise = tracker
.restore({
args: args || (() => JSONExt.emptyObject),
command,
connector: this._connector,
name,
registry: this._registry,
when: when ? [first].concat(when) : first
})
.catch(error => {
console.error(error);
});
this._promises.push(promise);
return promise;
}
/**
* Save the layout state for the application.
*/
save(data: ILabShell.ILayout): Promise<void> {
// If there are promises that are unresolved, bail.
if (!this._promisesDone) {
let warning = 'save() was called prematurely.';
console.warn(warning);
return Promise.reject(warning);
}
let dehydrated: Private.ILayout = {};
// Dehydrate main area.
dehydrated.main = this._dehydrateMainArea(data.mainArea);
// Dehydrate left area.
dehydrated.left = this._dehydrateSideArea(data.leftArea);
// Dehydrate right area.
dehydrated.right = this._dehydrateSideArea(data.rightArea);
return this._connector.save(KEY, dehydrated);
}
/**
* Dehydrate a main area description into a serializable object.
*/
private _dehydrateMainArea(
area: ILabShell.IMainArea | null
): Private.IMainArea | null {
if (!area) {
return null;
}
return Private.serializeMain(area);
}
/**
* Reydrate a serialized main area description object.
*
* #### Notes
* This function consumes data that can become corrupted, so it uses type
* coercion to guarantee the dehydrated object is safely processed.
*/
private _rehydrateMainArea(
area?: Private.IMainArea | null
): ILabShell.IMainArea | null {
if (!area) {
return null;
}
return Private.deserializeMain(area, this._widgets);
}
/**
* Dehydrate a side area description into a serializable object.
*/
private _dehydrateSideArea(
area?: ILabShell.ISideArea | null
): Private.ISideArea | null {
if (!area) {
return null;
}
let dehydrated: Private.ISideArea = { collapsed: area.collapsed };
if (area.currentWidget) {
let current = Private.nameProperty.get(area.currentWidget);
if (current) {
dehydrated.current = current;
}
}
if (area.widgets) {
dehydrated.widgets = area.widgets
.map(widget => Private.nameProperty.get(widget))
.filter(name => !!name);
}
return dehydrated;
}
/**
* Reydrate a serialized side area description object.
*
* #### Notes
* This function consumes data that can become corrupted, so it uses type
* coercion to guarantee the dehydrated object is safely processed.
*/
private _rehydrateSideArea(
area?: Private.ISideArea | null
): ILabShell.ISideArea {
if (!area) {
return { collapsed: true, currentWidget: null, widgets: null };
}
let internal = this._widgets;
const collapsed = area.hasOwnProperty('collapsed')
? !!area.collapsed
: false;
const currentWidget =
area.current && internal.has(`${area.current}`)
? internal.get(`${area.current}`)
: null;
const widgets = !Array.isArray(area.widgets)
? null
: area.widgets
.map(name =>
internal.has(`${name}`) ? internal.get(`${name}`) : null
)
.filter(widget => !!widget);
return {
collapsed,
currentWidget: currentWidget!,
widgets: widgets as Widget[] | null
};
}
/**
* Handle a widget disposal.
*/
private _onWidgetDisposed(widget: Widget): void {
let name = Private.nameProperty.get(widget);
this._widgets.delete(name);
}
private _connector: IDataConnector<ReadonlyPartialJSONValue>;
private _first: Promise<any>;
private _firstDone = false;
private _promisesDone = false;
private _promises: Promise<any>[] = [];
private _restored = new PromiseDelegate<void>();
private _registry: CommandRegistry;
private _trackers = new Set<string>();
private _widgets = new Map<string, Widget>();
}
/**
* A namespace for `LayoutRestorer` statics.
*/
export namespace LayoutRestorer {
/**
* The configuration options for layout restorer instantiation.
*/
export interface IOptions {
/**
* The data connector used for layout saving and fetching.
*/
connector: IDataConnector<ReadonlyPartialJSONValue>;
/**
* The initial promise that has to be resolved before restoration.
*
* #### Notes
* This promise should equal the JupyterLab application `started` notifier.
*/
first: Promise<any>;
/**
* The application command registry.
*/
registry: CommandRegistry;
}
}
/*
* A namespace for private data.
*/
namespace Private {
/**
* The dehydrated state of the application layout.
*
* #### Notes
* This format is JSON serializable and saved with the data connector.
* It is meant to be a data structure can translate into a `LabShell.ILayout`
* data structure for consumption by the application shell.
*/
export interface ILayout extends PartialJSONObject {
/**
* The main area of the user interface.
*/
main?: IMainArea | null;
/**
* The left area of the user interface.
*/
left?: ISideArea | null;
/**
* The right area of the user interface.
*/
right?: ISideArea | null;
}
/**
* The restorable description of the main application area.
*/
export interface IMainArea extends PartialJSONObject {
/**
* The current widget that has application focus.
*/
current?: string | null;
/**
* The main application dock panel.
*/
dock?: ISplitArea | ITabArea | null;
/**
* The document mode (i.e., multiple/single) of the main dock panel.
*/
mode?: DockPanel.Mode | null;
}
/**
* The restorable description of a sidebar in the user interface.
*/
export interface ISideArea extends PartialJSONObject {
/**
* A flag denoting whether the sidebar has been collapsed.
*/
collapsed?: boolean | null;
/**
* The current widget that has side area focus.
*/
current?: string | null;
/**
* The collection of widgets held by the sidebar.
*/
widgets?: Array<string> | null;
}
/**
* The restorable description of a tab area in the user interface.
*/
export interface ITabArea extends JSONObject {
/**
* The type indicator of the serialized tab area.
*/
type: 'tab-area';
/**
* The widgets in the tab area.
*/
widgets: Array<string> | null;
/**
* The index of the selected tab.
*/
currentIndex: number;
}
/**
* The restorable description of a split area in the user interface.
*/
export interface ISplitArea extends JSONObject {
/**
* The type indicator of the serialized split area.
*/
type: 'split-area';
/**
* The orientation of the split area.
*/
orientation: 'horizontal' | 'vertical';
/**
* The children in the split area.
*/
children: Array<ITabArea | ISplitArea> | null;
/**
* The sizes of the children.
*/
sizes: Array<number>;
}
/**
* An attached property for a widget's ID in the serialized restore data.
*/
export const nameProperty = new AttachedProperty<Widget, string>({
name: 'name',
create: owner => ''
});
/**
* Serialize individual areas within the main area.
*/
function serializeArea(
area: ILabShell.AreaConfig | null
): ITabArea | ISplitArea | null {
if (!area || !area.type) {
return null;
}
if (area.type === 'tab-area') {
return {
type: 'tab-area',
currentIndex: area.currentIndex,
widgets: area.widgets
.map(widget => nameProperty.get(widget))
.filter(name => !!name)
};
}
return {
type: 'split-area',
orientation: area.orientation,
sizes: area.sizes,
children: area.children
.map(serializeArea)
.filter(area => !!area) as Array<ITabArea | ISplitArea>
};
}
/**
* Return a dehydrated, serializable version of the main dock panel.
*/
export function serializeMain(area: ILabShell.IMainArea): IMainArea {
let dehydrated: IMainArea = {
dock: (area && area.dock && serializeArea(area.dock.main)) || null
};
if (area) {
dehydrated.mode = area.mode;
if (area.currentWidget) {
let current = Private.nameProperty.get(area.currentWidget);
if (current) {
dehydrated.current = current;
}
}
}
return dehydrated;
}
/**
* Deserialize individual areas within the main area.
*
* #### Notes
* Because this data comes from a potentially unreliable foreign source, it is
* typed as a `JSONObject`; but the actual expected type is:
* `ITabArea | ISplitArea`.
*
* For fault tolerance, types are manually checked in deserialization.
*/
function deserializeArea(
area: JSONObject,
names: Map<string, Widget>
): ILabShell.AreaConfig | null {
if (!area) {
return null;
}
// Because this data is saved to a foreign data source, its type safety is
// not guaranteed when it is retrieved, so exhaustive checks are necessary.
const type = ((area as any).type as string) || 'unknown';
if (type === 'unknown' || (type !== 'tab-area' && type !== 'split-area')) {
console.warn(`Attempted to deserialize unknown type: ${type}`);
return null;
}
if (type === 'tab-area') {
const { currentIndex, widgets } = area as ITabArea;
let hydrated: ILabShell.AreaConfig = {
type: 'tab-area',
currentIndex: currentIndex || 0,
widgets:
(widgets &&
(widgets
.map(widget => names.get(widget))
.filter(widget => !!widget) as Widget[])) ||
[]
};
// Make sure the current index is within bounds.
if (hydrated.currentIndex > hydrated.widgets.length - 1) {
hydrated.currentIndex = 0;
}
return hydrated;
}
const { orientation, sizes, children } = area as ISplitArea;
let hydrated: ILabShell.AreaConfig = {
type: 'split-area',
orientation: orientation,
sizes: sizes || [],
children:
(children &&
(children
.map(child => deserializeArea(child, names))
.filter(widget => !!widget) as ILabShell.AreaConfig[])) ||
[]
};
return hydrated;
}
/**
* Return the hydrated version of the main dock panel, ready to restore.
*
* #### Notes
* Because this data comes from a potentially unreliable foreign source, it is
* typed as a `JSONObject`; but the actual expected type is: `IMainArea`.
*
* For fault tolerance, types are manually checked in deserialization.
*/
export function deserializeMain(
area: ReadonlyPartialJSONObject,
names: Map<string, Widget>
): ILabShell.IMainArea | null {
if (!area) {
return null;
}
const name = (area as any).current || null;
const dock = (area as any).dock || null;
const mode = (area as any).mode || null;
return {
currentWidget: (name && names.has(name) && names.get(name)) || null,
dock: dock ? { main: deserializeArea(dock, names) } : null,
mode:
mode === 'multiple-document' || mode === 'single-document' ? mode : null
};
}
}