-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathmenu.ts
233 lines (191 loc) · 6.1 KB
/
menu.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
import * as vscode from "vscode";
import { Context } from "./context";
import { keypress, promptLocked, promptOne } from "./prompt";
export interface Menu {
readonly title?: string;
readonly items: Menu.Items;
}
export declare namespace Menu {
export interface Items {
[keys: string]: Item;
}
export interface Item {
readonly text: string;
readonly command: string;
readonly args?: any[];
}
}
/**
* Validates the given menu and returns a list of strings representing errors
* with the given menu. If that list is empty, the menu is valid and can be
* used.
*/
export function validateMenu(menu: Menu) {
if (typeof menu !== "object" || menu === null) {
return ["menu must be an object"];
}
if (typeof menu.items !== "object" || Object.keys(menu.items ?? {}).length === 0) {
return ['menu must have an subobject "items" with at least two entries.'];
}
const seenKeyCodes = new Map<number, string>(),
errors = [] as string[];
if (menu.title !== undefined && typeof menu.title !== "string") {
errors.push("menu title must be a string");
}
for (const key in menu.items) {
const item = menu.items[key],
itemDisplay = JSON.stringify(key);
if (typeof item !== "object" || item === null) {
errors.push(`item ${itemDisplay} must be an object.`);
continue;
}
if (typeof item.text !== "string" || item.text.length === 0) {
errors.push(`item ${itemDisplay} must have a non-empty "text" property.`);
continue;
}
if (typeof item.command !== "string" || item.command.length === 0) {
errors.push(`item ${itemDisplay} must have a non-empty "command" property.`);
continue;
}
if (key.length === 0) {
errors.push(`item ${itemDisplay} must be a non-empty string key.`);
continue;
}
for (let i = 0; i < key.length; i++) {
const keyCode = key.charCodeAt(i),
prevKey = seenKeyCodes.get(keyCode);
if (prevKey) {
errors.push(`menu has duplicate key '${key[i]}' (specified by '${prevKey}' and '${key}').`);
continue;
}
seenKeyCodes.set(keyCode, key);
}
}
return errors;
}
/**
* Returns the menu with the given name. If no such menu exists, an exception
* will be thrown.
*/
export function findMenu(menuName: string, context = Context.WithoutActiveEditor.current) {
const menu = context.extension.menus.get(menuName);
if (menu === undefined) {
throw new Error(`menu ${JSON.stringify(menuName)} does not exist`);
}
return menu;
}
/**
* Shows the given menu to the user, awaiting a choice.
*/
export async function showMenu(
menu: Menu,
additionalArgs: readonly any[] = [],
prefix?: string,
) {
const entries = Object.entries(menu.items);
const items = entries.map((x) => [x[0], x[1].text] as const);
const choice = await promptOne(items, (quickPick) => quickPick.title = menu.title);
if (typeof choice === "string") {
if (prefix !== undefined) {
await vscode.commands.executeCommand("default:type", { text: prefix + choice });
}
return;
}
const pickedItem = entries[choice][1],
args = mergeArgs(pickedItem.args, additionalArgs);
return Context.WithoutActiveEditor.wrap(
vscode.commands.executeCommand(pickedItem.command, ...args),
);
}
/**
* Shows the menu with the given name.
*/
export function showMenuByName(
menuName: string,
additionalArgs: readonly any[] = [],
prefix?: string,
) {
return showMenu(findMenu(menuName), additionalArgs, prefix);
}
/**
* Same as {@link showMenu}, but only displays the menu after a specified delay.
*/
export async function showMenuAfterDelay(
delayMs: number,
menu: Menu,
additionalArgs: readonly any[] = [],
prefix?: string,
) {
const cancellationTokenSource = new vscode.CancellationTokenSource(),
currentContext = Context.current;
currentContext.cancellationToken.onCancellationRequested(() =>
cancellationTokenSource.cancel());
const keypressContext = currentContext.withCancellationToken(cancellationTokenSource.token),
timeout = setTimeout(() => cancellationTokenSource.cancel(), delayMs);
try {
const key = await keypress(keypressContext);
clearTimeout(timeout);
for (const itemKeys in menu.items) {
if (!itemKeys.includes(key)) {
continue;
}
const pickedItem = menu.items[itemKeys],
args = mergeArgs(pickedItem.args, additionalArgs);
return Context.WithoutActiveEditor.wrap(
vscode.commands.executeCommand(pickedItem.command, ...args),
);
}
if (prefix !== undefined) {
await vscode.commands.executeCommand("default:type", { text: prefix + key });
}
} catch (e) {
if (!currentContext.cancellationToken.isCancellationRequested) {
return showMenu(menu, additionalArgs, prefix);
}
throw e;
} finally {
cancellationTokenSource.dispose();
}
}
/**
* Shows the given menu to the user, not dismissing it when a key is pressed.
*/
export async function showLockedMenu(
menu: Menu,
additionalArgs: readonly any[] = [],
) {
const entries = Object.entries(menu.items),
items = entries.map(([keys, item]) =>
[keys, item.text, () =>
vscode.commands.executeCommand(
item.command, ...mergeArgs(item.args, additionalArgs))] as const);
await promptLocked(items, (quickPick) => quickPick.title = menu.title);
}
/**
* Shows the menu with the given name.
*/
export function showLockedMenyByName(
menuName: string,
additionalArgs: readonly any[] = [],
) {
return showLockedMenu(findMenu(menuName), additionalArgs);
}
function mergeArgs(args: readonly any[] | undefined, additionalArgs: readonly any[]) {
if (args == null) {
return additionalArgs;
}
if (!Array.isArray(args)) {
args = [args];
}
if (additionalArgs.length > 0) {
return args.length > additionalArgs.length
? args.map((arg, i) =>
i < additionalArgs.length && additionalArgs[i]
? Object.assign({}, additionalArgs[i], arg)
: arg)
: additionalArgs.map((arg, i) =>
i < args!.length ? Object.assign({}, arg, args![i]) : arg);
} else {
return args;
}
}