|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Copyright (c) Red Hat, Inc. All rights reserved. |
| 3 | + * Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | + *--------------------------------------------------------------------------------------------*/ |
| 5 | + |
| 6 | +'use strict'; |
| 7 | + |
| 8 | +import * as vscode from 'vscode'; |
| 9 | +import { IHandler } from './handler'; |
| 10 | + |
| 11 | +const KEY_RECOMMENDATION_USER_CHOICE_MAP = 'recommendationUserChoice'; |
| 12 | + |
| 13 | +async function installExtensionCmdHandler(extensionName: string, displayName: string): Promise<unknown> { |
| 14 | + return vscode.window |
| 15 | + .withProgress( |
| 16 | + { location: vscode.ProgressLocation.Notification, title: `Installing ${displayName || extensionName}...` }, |
| 17 | + () => { |
| 18 | + return vscode.commands.executeCommand('workbench.extensions.installExtension', extensionName); |
| 19 | + } |
| 20 | + ) |
| 21 | + .then(() => { |
| 22 | + vscode.window.showInformationMessage(`Successfully installed ${displayName || extensionName}.`); |
| 23 | + }); |
| 24 | +} |
| 25 | + |
| 26 | +enum UserChoice { |
| 27 | + install = 'Install', |
| 28 | + never = 'Never', |
| 29 | + later = 'Later', |
| 30 | +} |
| 31 | + |
| 32 | +export class HandlerImpl implements IHandler { |
| 33 | + userChoice: () => unknown; |
| 34 | + storeUserChoice: (choice: unknown) => void; |
| 35 | + constructor(context: vscode.ExtensionContext) { |
| 36 | + this.userChoice = () => { |
| 37 | + return context.globalState.get(KEY_RECOMMENDATION_USER_CHOICE_MAP, {}); |
| 38 | + }; |
| 39 | + |
| 40 | + this.storeUserChoice = (choice: unknown) => { |
| 41 | + context.globalState.update(KEY_RECOMMENDATION_USER_CHOICE_MAP, choice); |
| 42 | + }; |
| 43 | + } |
| 44 | + |
| 45 | + isExtensionInstalled(extName: string): boolean { |
| 46 | + return !!vscode.extensions.getExtension(extName); |
| 47 | + } |
| 48 | + |
| 49 | + canRecommendExtension(extName: string): boolean { |
| 50 | + return this.userChoice()[extName] !== UserChoice.never && !this.isExtensionInstalled(extName); |
| 51 | + } |
| 52 | + |
| 53 | + async handle(extName: string, message: string): Promise<void> { |
| 54 | + if (this.isExtensionInstalled(extName)) { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + const choice = this.userChoice(); |
| 59 | + if (choice[extName] === UserChoice.never) { |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + const actions: Array<string> = Object.values(UserChoice); |
| 64 | + const answer = await vscode.window.showInformationMessage(message, ...actions); |
| 65 | + if (answer === UserChoice.install) { |
| 66 | + await installExtensionCmdHandler(extName, extName); |
| 67 | + } |
| 68 | + |
| 69 | + choice[extName] = answer; |
| 70 | + this.storeUserChoice(choice); |
| 71 | + } |
| 72 | +} |
0 commit comments