-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathdocumentPicker.ts
More file actions
464 lines (453 loc) · 16 KB
/
documentPicker.ts
File metadata and controls
464 lines (453 loc) · 16 KB
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
import * as vscode from "vscode";
import { AtelierAPI } from "../api";
import { cspAppsForApi, handleError } from ".";
interface DocumentPickerItem extends vscode.QuickPickItem {
/** The full name of this item, including its parent(s). */
fullName: string;
}
function createMultiSelectItem(
item: { Name: string; Type: number },
parent?: string,
parentPad?: number
): DocumentPickerItem {
const result: DocumentPickerItem = { label: item.Name, fullName: item.Name };
// Add the icon
if (item.Type == 0) {
if (item.Name.endsWith(".inc")) {
result.label = "$(file-symlink-file) " + result.label;
} else if (item.Name.endsWith(".int") || item.Name.endsWith(".mac")) {
result.label = "$(note) " + result.label;
} else {
result.label = "$(symbol-misc) " + result.label;
}
} else if (item.Type == 10) {
result.label = "$(folder) " + result.label;
} else if (item.Type == 9) {
result.label = "$(package) " + result.label;
} else if (item.Type == 4) {
result.label = "$(symbol-class) " + result.label;
} else {
result.label = "$(symbol-file) " + result.label;
}
if (parent) {
// Update the full name and label padding if this is a nested item
let delim = ".";
if (parent.includes("/")) {
delim = "/";
}
result.fullName = parent + delim + item.Name;
result.label = " ".repeat(parentPad + 2) + result.label;
result.description = result.fullName;
}
if (item.Type == 9 || item.Type == 10) {
// Add the expand button if this is a package or directory
result.buttons = [
{
iconPath: new vscode.ThemeIcon("chevron-right"),
tooltip: "Expand",
},
];
}
return result;
}
function createSingleSelectItem(
item: { Name: string; Type: number },
parent?: string,
delimiter?: string
): DocumentPickerItem {
const result: DocumentPickerItem = { label: item.Name, fullName: item.Name };
// Add the icon
if (item.Type == 0) {
if (item.Name.endsWith(".inc")) {
result.label = "$(file-symlink-file) " + result.label;
} else if (item.Name.endsWith(".int") || item.Name.endsWith(".mac")) {
result.label = "$(note) " + result.label;
} else {
result.label = "$(symbol-misc) " + result.label;
}
} else if (item.Type == 4) {
result.label = "$(symbol-class) " + result.label;
} else if (![9, 10].includes(item.Type)) {
result.label = "$(symbol-file) " + result.label;
}
if (parent) {
// Update the full name if this is a nested item
result.fullName = parent + delimiter + item.Name;
}
return result;
}
/**
* Prompts the user to select documents in server-namespace `api`
* using a custom multi-select QuickPick. An optional prompt will customize the title.
*/
export async function pickDocuments(api: AtelierAPI, prompt?: string): Promise<string[]> {
let sys: "0" | "1" = "0";
let gen: "0" | "1" = "0";
let map: "0" | "1" = "1";
const query = "SELECT Name, Type FROM %Library.RoutineMgr_StudioOpenDialog(?,1,1,?,0,0,?,,0,?)";
const webApps = cspAppsForApi(api);
const webAppRootItems = webApps.map((app: string) => {
return {
label: "$(folder) " + app,
fullName: app,
buttons: [
{
iconPath: new vscode.ThemeIcon("chevron-right"),
tooltip: "Expand",
},
],
};
});
return new Promise<string[]>((resolve) => {
let result: string[] = [];
const quickPick = vscode.window.createQuickPick<DocumentPickerItem>();
quickPick.title = `Select documents in namespace '${api.ns}' on server '${api.serverId}'${
prompt ? " " + prompt : ""
}`;
quickPick.ignoreFocusOut = true;
quickPick.canSelectMany = true;
quickPick.keepScrollPosition = true;
quickPick.matchOnDescription = true;
quickPick.buttons = [
{
iconPath: new vscode.ThemeIcon("library"),
tooltip: "System",
location: vscode.QuickInputButtonLocation.Input,
toggle: { checked: false },
},
{
iconPath: new vscode.ThemeIcon("server-process"),
tooltip: "Generated",
location: vscode.QuickInputButtonLocation.Input,
toggle: { checked: false },
},
{
iconPath: new vscode.ThemeIcon("references"),
tooltip: "Mapped",
location: vscode.QuickInputButtonLocation.Input,
toggle: { checked: true },
},
];
const getRootItems = (): Promise<void> => {
return api
.actionQuery(`${query} WHERE Type != 5 AND Type != 10`, ["*", sys, gen, map])
.then((data) => {
const rootitems: DocumentPickerItem[] = data.result.content.map((i) => createMultiSelectItem(i));
const findLastIndex = (): number => {
let l = rootitems.length;
while (l--) {
if (rootitems[l].buttons) return l;
}
return -1;
};
rootitems.splice(findLastIndex() + 1, 0, ...webAppRootItems);
return rootitems;
})
.then((items) => {
quickPick.items = items;
quickPick.busy = false;
quickPick.enabled = true;
})
.catch((error) => {
quickPick.hide();
handleError(error, "Failed to get namespace contents.");
});
};
const expandItem = (itemIdx: number): Promise<void> => {
const selected = quickPick.selectedItems;
const item = quickPick.items[itemIdx];
quickPick.items[itemIdx].buttons = [
{
iconPath: new vscode.ThemeIcon("chevron-down"),
tooltip: "Collapse",
},
];
return api
.actionQuery(query, [`${item.fullName}/*`, sys, gen, map])
.then((data) => {
const insertItems: DocumentPickerItem[] = data.result.content.map((i) =>
createMultiSelectItem(i, item.fullName, item.label.search(/\S/))
);
const newItems = [...quickPick.items];
newItems.splice(itemIdx + 1, 0, ...insertItems);
quickPick.items = newItems;
quickPick.selectedItems = selected;
quickPick.busy = false;
quickPick.enabled = true;
})
.catch((error) => {
quickPick.hide();
handleError(error, "Failed to get namespace contents.");
});
};
quickPick.onDidChangeSelection((items) => {
result = items.map((item) =>
item.buttons && item.buttons.length
? item.fullName.includes("/")
? item.fullName + "/*"
: item.fullName + ".*"
: item.fullName
);
});
quickPick.onDidTriggerButton((button) => {
quickPick.busy = true;
quickPick.enabled = false;
if (button.tooltip == "System") {
sys = button.toggle.checked ? "1" : "0";
} else if (button.tooltip == "Generated") {
gen = button.toggle.checked ? "1" : "0";
} else {
map = button.toggle.checked ? "1" : "0";
}
// Refresh the items list
getRootItems();
});
quickPick.onDidTriggerItemButton((event) => {
quickPick.busy = true;
quickPick.enabled = false;
const itemIdx = quickPick.items.findIndex((i) => i.fullName === event.item.fullName);
if (event.button.tooltip.charAt(0) == "E") {
// Expand this item
expandItem(itemIdx);
} else {
// Collapse this item
const selected = quickPick.selectedItems;
quickPick.items[itemIdx].buttons = [
{
iconPath: new vscode.ThemeIcon("chevron-right"),
tooltip: "Expand",
},
];
quickPick.items = quickPick.items.filter(
(i) => !i.fullName.startsWith(event.item.fullName + (event.item.fullName.includes("/") ? "/" : "."))
);
quickPick.selectedItems = selected;
quickPick.busy = false;
quickPick.enabled = true;
}
});
quickPick.onDidChangeValue((filter: string) => {
if (filter.endsWith(".") || filter.endsWith("/")) {
const itemIdx = quickPick.items.findIndex(
(i) => i.fullName.toLowerCase() === filter.slice(0, -1).toLowerCase()
);
if (
itemIdx != -1 &&
quickPick.items[itemIdx].buttons.length &&
quickPick.items[itemIdx].buttons[0].tooltip.charAt(0) == "E"
) {
// Expand this item
quickPick.busy = true;
quickPick.enabled = false;
expandItem(itemIdx);
}
}
});
quickPick.onDidAccept(async () => {
quickPick.busy = true;
quickPick.enabled = false;
const pkgDir = result.filter((e) => e.endsWith("*"));
if (pkgDir.length) {
// Expand packages/folders
const resolved: string[] = await api
.actionQuery(
"SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,1,1,?,1,0,?,,0,?) WHERE Name %PATTERN ?",
["*", sys, gen, map, `1(${pkgDir.map((e) => `1"${e.slice(0, -1)}"`).join(",")}).E`]
)
.then((data) => data.result.content.map((e) => e.Name))
.catch((error) => {
quickPick.hide();
handleError(error, "Failed to resolve documents in selected packages or folders.");
});
// Remove duplicates
result = [...new Set(resolved.concat(result.filter((e) => !e.endsWith("*"))))];
}
resolve(result);
quickPick.hide();
});
quickPick.onDidHide(() => {
resolve([]);
quickPick.dispose();
});
quickPick.busy = true;
quickPick.enabled = false;
quickPick.show();
getRootItems();
});
}
/**
* Prompts the user to select a single document in server-namespace `api`
* using a custom QuickPick. An optional `prompt` will customize the title.
* `typeSuffix` can be provided to filter for specific types of documents (e.g. "cls").
* If `step` is provided and greater than 1, a back button will be included that resolves to an empty string when pressed.
* If `numberOfSteps` is provided, the title will be suffixed with the current step and total number of steps (e.g. "(2/4)") instead of the namespace and server information.
*/
export async function pickDocument(
api: AtelierAPI,
prompt?: string,
typeSuffix?: string,
step?: number,
numberOfSteps?: number
): Promise<string> {
let sys: "0" | "1" = "0";
let gen: "0" | "1" = "0";
let map: "0" | "1" = "1";
const query = "SELECT Name, Type FROM %Library.RoutineMgr_StudioOpenDialog(?,1,1,?,0,0,?,,0,?)";
const webApps = (typeSuffix ?? "csp") == "csp" ? cspAppsForApi(api) : [];
const webAppRootItems = webApps.map((app: string) => {
return {
label: app,
fullName: app,
};
});
return new Promise<string>((resolve) => {
const quickPick = vscode.window.createQuickPick<DocumentPickerItem>();
quickPick.title = `${prompt ? prompt : "Select a document"} ${numberOfSteps ? `(${step}/${numberOfSteps})` : `in namespace '${api.ns}' on server '${api.serverId}'`}`;
quickPick.ignoreFocusOut = true;
quickPick.buttons = [
...((step ?? 0) > 1 ? [vscode.QuickInputButtons.Back] : []),
{
iconPath: new vscode.ThemeIcon("library"),
tooltip: "System",
location: vscode.QuickInputButtonLocation.Input,
toggle: { checked: false },
},
{
iconPath: new vscode.ThemeIcon("server-process"),
tooltip: "Generated",
location: vscode.QuickInputButtonLocation.Input,
toggle: { checked: false },
},
{
iconPath: new vscode.ThemeIcon("references"),
tooltip: "Mapped",
location: vscode.QuickInputButtonLocation.Input,
toggle: { checked: true },
},
];
const getRootItems = (): Promise<void> => {
return api
.actionQuery(`${query} WHERE Type != 5 AND Type != 10`, [
typeSuffix ? `*.${typeSuffix}` : "*,'*.prj",
sys,
gen,
map,
])
.then((data) => {
const rootitems: DocumentPickerItem[] = data.result.content.map((i) => createSingleSelectItem(i));
const findLastIndex = (): number => {
let l = rootitems.length;
while (l--) {
if (!rootitems[l].label.startsWith("$(")) return l;
}
return -1;
};
rootitems.splice(findLastIndex() + 1, 0, ...webAppRootItems);
return rootitems;
})
.then((items) => {
quickPick.items = items;
quickPick.selectedItems = [];
quickPick.value = "";
quickPick.busy = false;
quickPick.enabled = true;
})
.catch((error) => {
quickPick.hide();
handleError(error, "Failed to get namespace contents.");
});
};
quickPick.onDidTriggerButton((button) => {
quickPick.busy = true;
quickPick.enabled = false;
if (button === vscode.QuickInputButtons.Back) {
resolve(""); // signal "go back" to the caller
quickPick.hide();
}
if (button.tooltip == "System") {
sys = button.toggle.checked ? "1" : "0";
} else if (button.tooltip == "Generated") {
gen = button.toggle.checked ? "1" : "0";
} else {
map = button.toggle.checked ? "1" : "0";
}
// Refresh the items list
getRootItems();
});
quickPick.onDidAccept(() => {
quickPick.busy = true;
quickPick.enabled = false;
const item = quickPick.selectedItems[0];
if (!item || item.label.startsWith("$(")) {
let doc = item?.fullName ?? quickPick.value.trim();
if (!item) {
// The document name came from the value text, so validate it first
// Normalize the file extension case for classes and routines
doc = [".cls", ".mac", ".int", ".inc"].includes(doc.slice(-4).toLowerCase())
? doc.slice(0, -3) + doc.slice(-3).toLowerCase()
: doc;
// Expand the short form of %Library classes to the long form
doc =
doc.startsWith("%") && doc.split(".").length == 2 && doc.slice(-4) == ".cls"
? `%Library.${doc.slice(1)}`
: doc;
api
.headDoc(doc)
.then(() => resolve(doc))
.catch((error) => {
vscode.window.showErrorMessage(
error?.statusCode == 400
? `'${doc}' is an invalid document name.`
: error?.statusCode == 404
? `Document '${doc}' does not exist.`
: `Internal Server Error encountered trying to validate document '${doc}'.`,
"Dismiss"
);
resolve(undefined);
})
.finally(() => quickPick.hide());
} else {
// The document name came from an item so no validation is required
resolve(doc);
quickPick.hide();
}
} else {
// Replace the items with the folder's contents
if (item.fullName == "") {
getRootItems();
} else {
api
.actionQuery(query, [`${item.fullName}/*${typeSuffix ? `.${typeSuffix}` : ""}`, sys, gen, map])
.then((data) => {
const delim = item.fullName.includes("/") ? "/" : ".";
const newItems: DocumentPickerItem[] = data.result.content.map((i) =>
createSingleSelectItem(i, item.fullName, delim)
);
let parentFullName =
delim == "/" && webApps.includes(item.fullName)
? ""
: item.fullName.split(delim).slice(0, -1).join(delim);
if (parentFullName == "/") parentFullName = "";
quickPick.items = [{ label: "..", fullName: parentFullName }].concat(newItems);
quickPick.value = "";
quickPick.selectedItems = [];
quickPick.busy = false;
quickPick.enabled = true;
})
.catch((error) => {
quickPick.hide();
handleError(error, "Failed to get namespace contents.");
});
}
}
});
quickPick.onDidHide(() => {
resolve(undefined);
quickPick.dispose();
});
quickPick.busy = true;
quickPick.enabled = false;
quickPick.show();
getRootItems();
});
}