|
| 1 | +import * as vscode from "vscode"; |
| 2 | +import { |
| 3 | + QuickPickOptions, |
| 4 | + UnknownValuesOptions, |
| 5 | +} from "../../libs/common/ide/types/QuickPickOptions"; |
| 6 | + |
| 7 | +export async function vscodeShowQuickPick( |
| 8 | + items: readonly string[], |
| 9 | + options: QuickPickOptions | undefined, |
| 10 | +) { |
| 11 | + if (options?.unknownValues == null) { |
| 12 | + return await vscode.window.showQuickPick(items, options); |
| 13 | + } |
| 14 | + |
| 15 | + const { unknownValues, ...rest } = options; |
| 16 | + return await showQuickPickAllowingUnknown(items, unknownValues, rest); |
| 17 | +} |
| 18 | + |
| 19 | +interface CustomQuickPickItem extends vscode.QuickPickItem { |
| 20 | + value: string; |
| 21 | +} |
| 22 | + |
| 23 | +const DEFAULT_NEW_VALUE_TEMPLATE = "Add new value '{}' →"; |
| 24 | + |
| 25 | +/** |
| 26 | + * Show a quick pick that allows the user to enter a new value. We do this by |
| 27 | + * adding a new dummy item to the list as the user is typing. If they select |
| 28 | + * the dummy item, we return the value they typed. It is up to the client to |
| 29 | + * detect that it is an unknown value and handle that case. |
| 30 | + * |
| 31 | + * Based on https://stackoverflow.com/a/69842249 |
| 32 | + * @param items |
| 33 | + * @param options |
| 34 | + */ |
| 35 | +function showQuickPickAllowingUnknown( |
| 36 | + choices: readonly string[], |
| 37 | + unknownValues: UnknownValuesOptions, |
| 38 | + options: vscode.QuickPickOptions, |
| 39 | +) { |
| 40 | + return new Promise<string | undefined>((resolve, _reject) => { |
| 41 | + const quickPick = vscode.window.createQuickPick<CustomQuickPickItem>(); |
| 42 | + const quickPickItems = choices.map((choice) => ({ |
| 43 | + label: choice, |
| 44 | + value: choice, |
| 45 | + })); |
| 46 | + quickPick.items = quickPickItems; |
| 47 | + |
| 48 | + if (options.title != null) { |
| 49 | + quickPick.title = options.title; |
| 50 | + } |
| 51 | + |
| 52 | + const { newValueTemplate = DEFAULT_NEW_VALUE_TEMPLATE } = unknownValues; |
| 53 | + |
| 54 | + quickPick.onDidChangeValue(() => { |
| 55 | + quickPick.items = [ |
| 56 | + ...quickPickItems, |
| 57 | + |
| 58 | + // INJECT user values into proposed values |
| 59 | + ...(choices.includes(quickPick.value) |
| 60 | + ? [] |
| 61 | + : [ |
| 62 | + { |
| 63 | + label: newValueTemplate.replace("{}", quickPick.value), |
| 64 | + value: quickPick.value, |
| 65 | + }, |
| 66 | + ]), |
| 67 | + ]; |
| 68 | + }); |
| 69 | + |
| 70 | + quickPick.onDidAccept(() => { |
| 71 | + const selection = quickPick.activeItems[0]; |
| 72 | + resolve(selection.value); |
| 73 | + quickPick.hide(); |
| 74 | + }); |
| 75 | + |
| 76 | + quickPick.onDidHide(() => { |
| 77 | + resolve(undefined); |
| 78 | + }); |
| 79 | + |
| 80 | + quickPick.show(); |
| 81 | + }); |
| 82 | +} |
0 commit comments