Notifications in Visual Studio Code are trivial for your extensions to notify the user when something happens or a process completes. A downside of these notifications is that they cannot be dismissed programmatically; they require manual user interaction.
As in my current extension, I wanted to be able to have a notification that can do the following:
- Show notification with an undo button;
- Hide the notification after 10 seconds;
- If you click on the undo action, hide the notification needs to be removed.
You might think it should be easy, but unfortunately, it is not the case. In the above requirements, there are two issues.
- Cannot dismiss the notification programmatically;
- Cannot dismiss it after a given time.
To better understand the problem(s), I will go into more detail and provide you with a solution.
The problems
There is no dismiss method for notifications
First, the window.showInformationMessage
, window.showWarningMessage
, and window.showErrorMessage
methods do not provide a way to dismiss these programmatically.
Luckily, I found a solution to use a progress notification (window.withProgress
) to overcome this. It is a pretty neat solution, but it has another issue. Progress notifications do not allow you to provide additional actions. For this problem, I decided to use a link with a command URI which will trigger the undo functionality and dismisses the progress notification.
Dismiss the progress notification after a given time
The last issue is when a user clicks on the hyperlink/command action in the progress notification, it will not automatically dismiss.
Additional logic is required to solve the dismiss issue in progress notifications.
infoI wrote about this logic in the Cancel progress programmatically in Visual Studio Code extensions article.
The solution
The whole solution looks as follows:
|
|
The code from the above snippet shows a progress notification for 10 seconds with a undo link that uses a command URI.
When the user clicks on the link, it triggers the undo command.