-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
workspacesplugin.ts
319 lines (292 loc) · 9.09 KB
/
workspacesplugin.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
IRouter,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { Dialog, IWindowResolver, showDialog } from '@jupyterlab/apputils';
import { URLExt } from '@jupyterlab/coreutils';
import {
ABCWidgetFactory,
DocumentRegistry,
DocumentWidget,
IDocumentWidget
} from '@jupyterlab/docregistry';
import { FileBrowser, IFileBrowserFactory } from '@jupyterlab/filebrowser';
import {
ContentsManager,
Workspace,
WorkspaceManager
} from '@jupyterlab/services';
import { IStateDB } from '@jupyterlab/statedb';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import { Widget } from '@lumino/widgets';
namespace CommandIDs {
export const saveWorkspace = 'workspace-ui:save';
export const saveWorkspaceAs = 'workspace-ui:save-as';
}
const WORKSPACE_NAME = 'jupyterlab-workspace';
const WORKSPACE_EXT = '.' + WORKSPACE_NAME;
const LAST_SAVE_ID = 'workspace-ui:lastSave';
const ICON_NAME = 'jp-JupyterIcon';
/**
* The workspace MIME renderer and save plugin.
*/
export const workspacesPlugin: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/apputils-extension:workspaces',
autoStart: true,
requires: [
IFileBrowserFactory,
IWindowResolver,
IStateDB,
ITranslator,
JupyterFrontEnd.IPaths
],
optional: [IRouter],
activate: (
app: JupyterFrontEnd,
fbf: IFileBrowserFactory,
resolver: IWindowResolver,
state: IStateDB,
translator: ITranslator,
paths: JupyterFrontEnd.IPaths,
router: IRouter | null
): void => {
// The workspace factory creates dummy widgets to load a new workspace.
const factory = new Private.WorkspaceFactory({
workspaces: app.serviceManager.workspaces,
router,
state,
translator,
paths
});
const trans = translator.load('jupyterlab');
app.docRegistry.addFileType({
name: WORKSPACE_NAME,
contentType: 'file',
fileFormat: 'text',
displayName: trans.__('JupyterLab workspace File'),
extensions: [WORKSPACE_EXT],
mimeTypes: ['text/json'],
iconClass: ICON_NAME
});
app.docRegistry.addWidgetFactory(factory);
app.commands.addCommand(CommandIDs.saveWorkspaceAs, {
label: trans.__('Save Current Workspace As…'),
execute: async () => {
const data = app.serviceManager.workspaces.fetch(resolver.name);
await Private.saveAs(
fbf.defaultBrowser,
app.serviceManager.contents,
data,
state,
translator
);
}
});
app.commands.addCommand(CommandIDs.saveWorkspace, {
label: trans.__('Save Current Workspace'),
execute: async () => {
const { contents } = app.serviceManager;
const data = app.serviceManager.workspaces.fetch(resolver.name);
const lastSave = (await state.fetch(LAST_SAVE_ID)) as string;
if (lastSave === undefined) {
await Private.saveAs(
fbf.defaultBrowser,
contents,
data,
state,
translator
);
} else {
await Private.save(lastSave, contents, data, state);
}
}
});
}
};
namespace Private {
/**
* Save workspace to a user provided location
*/
export async function save(
userPath: string,
contents: ContentsManager,
data: Promise<Workspace.IWorkspace>,
state: IStateDB
): Promise<void> {
let name = userPath.split('/').pop();
// Add extension if not provided or remove extension from name if it was.
if (name !== undefined && name.includes('.')) {
name = name.split('.')[0];
} else {
userPath = userPath + WORKSPACE_EXT;
}
// Save last save location, for save button to work
await state.save(LAST_SAVE_ID, userPath);
const resolvedData = await data;
resolvedData.metadata.id = `${name}`;
await contents.save(userPath, {
type: 'file',
format: 'text',
content: JSON.stringify(resolvedData)
});
}
/**
* Ask user for location, and save workspace.
* Default location is the current directory in the file browser
*/
export async function saveAs(
browser: FileBrowser,
contents: ContentsManager,
data: Promise<Workspace.IWorkspace>,
state: IStateDB,
translator?: ITranslator
): Promise<void> {
translator = translator || nullTranslator;
const lastSave = await state.fetch(LAST_SAVE_ID);
let defaultName;
if (lastSave === undefined) {
defaultName = 'new-workspace';
} else {
defaultName = (lastSave as string).split('/').pop()?.split('.')[0];
}
const defaultPath = browser.model.path + '/' + defaultName + WORKSPACE_EXT;
const userPath = await getSavePath(defaultPath, translator);
if (userPath) {
await save(userPath, contents, data, state);
}
}
/**
* This widget factory is used to handle double click on workspace
*/
export class WorkspaceFactory extends ABCWidgetFactory<IDocumentWidget> {
/**
* Construct a widget factory that uploads a workspace and navigates to it.
*
* @param options - The instantiation options for a `WorkspaceFactory`.
*/
constructor(options: WorkspaceFactory.IOptions) {
const trans = (options.translator || nullTranslator).load('jupyterlab');
super({
name: trans.__('Workspace loader'),
fileTypes: [WORKSPACE_NAME],
defaultFor: [WORKSPACE_NAME],
readOnly: true
});
this._application = options.paths.urls.app;
this._router = options.router;
this._state = options.state;
this._workspaces = options.workspaces;
}
/**
* Loads the workspace into load, and jump to it
* @param context This is used queried to query the workspace content
*/
protected createNewWidget(
context: DocumentRegistry.Context
): IDocumentWidget {
// Save a file's contents as a workspace and navigate to that workspace.
void context.ready.then(async () => {
const file = context.model;
const workspace = (file.toJSON() as unknown) as Workspace.IWorkspace;
const path = context.path;
const id = workspace.metadata.id;
// Save the file contents as a workspace.
await this._workspaces.save(id, workspace);
// Save last save location for the save command.
await this._state.save(LAST_SAVE_ID, path);
// Navigate to new workspace.
const workspacesBase = URLExt.join(this._application, 'workspaces');
const url = URLExt.join(workspacesBase, id);
if (!workspacesBase.startsWith(url)) {
throw new Error('Can only be used for workspaces');
}
if (this._router) {
this._router.navigate(url, { hard: true });
} else {
document.location.href = url;
}
});
return dummyWidget(context);
}
private _application: string;
private _router: IRouter | null;
private _state: IStateDB;
private _workspaces: WorkspaceManager;
}
/**
* A namespace for `WorkspaceFactory`
*/
export namespace WorkspaceFactory {
/**
* Instantiation options for a `WorkspaceFactory`
*/
export interface IOptions {
paths: JupyterFrontEnd.IPaths;
router: IRouter | null;
state: IStateDB;
translator: ITranslator;
workspaces: WorkspaceManager;
}
}
/**
* Returns a dummy widget with disposed content that doesn't render in the UI.
*
* @param context - The file context.
*/
function dummyWidget(context: DocumentRegistry.Context): IDocumentWidget {
const widget = new DocumentWidget({ content: new Widget(), context });
widget.content.dispose();
return widget;
}
/**
* Ask user for a path to save to.
* @param defaultPath Path already present when the dialog is shown
*/
async function getSavePath(
defaultPath: string,
translator?: ITranslator
): Promise<string | null> {
translator = translator || nullTranslator;
const trans = translator.load('jupyterlab');
const saveBtn = Dialog.okButton({ label: trans.__('Save') });
const result = await showDialog({
title: trans.__('Save Current Workspace As…'),
body: new SaveWidget(defaultPath),
buttons: [Dialog.cancelButton({ label: trans.__('Cancel') }), saveBtn]
});
if (result.button.label === trans.__('Save')) {
return result.value;
} else {
return null;
}
}
/**
* A widget that gets a file path from a user.
*/
class SaveWidget extends Widget {
/**
* Gets a modal node for getting save location. Will have a default to the current opened directory
* @param path Default location
*/
constructor(path: string) {
super({ node: createSaveNode(path) });
}
/**
* Gets the save path entered by the user
*/
getValue(): string {
return (this.node as HTMLInputElement).value;
}
}
/**
* Create the node for a save widget.
*/
function createSaveNode(path: string): HTMLElement {
const input = document.createElement('input');
input.value = path;
return input;
}
}