I’m writing a VS Code extension in TypeScript and need the user to select a Yes/No option. I want it to be character responsive so it returns when the user hits “Y”, “N”, or presses enter for the default (“Yes”).
I’ve written this extension in many code editors and have taken input of this option with a status bar prompt, by reading the keystrokes directly, and with a dialog box in a GUI editor. Neither of these options are readily available in VS Code. There is a way to do a modal dialog with buttons but it’s quite ugly and I can’t make it character responsive.
Anyone have any ideas?
I have managed to do it with a QuickPick. This function returns a promise resolved with the boolean response and rejected if the user hits ESC or moves focus out of the input:
function getFormatOption() {
const input = vscode.window.createQuickPick();
input.title = "Reformat Comment?";
input.items = [
{ label: "Yes", description: "Reformat paragraphs before commenting." },
{ label: "No", description: "Comment block without reformatting."}
];
return new Promise((resolve, reject) => {
input.onDidHide(reject);
input.onDidChangeSelection(items => resolve(items[0] === input.items[0]));
input.onDidChangeValue(value => {
input.value = "";
input.selectedItems = input.items.filter(i =>
value.toUpperCase() === i.label.substring(0, 1));
});
input.show();
})
.finally(() => input.dispose());
}
input.onDidHide()
rejects when the input loses focus before a selection is made.
input.onDidChangeSelection()
resolves with the boolean response when a selection is made.
input.onDidChangeValue()
is called with each keystroke when the filter value changes. If the character entered matches the first character of one of the options, that option is selected which will fire onDidChangeSelection
.