-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMessageBuilder.ts
executable file
·92 lines (78 loc) · 2.49 KB
/
MessageBuilder.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
import * as vscode from "vscode";
import Logger from "../../../log/Logger";
import MessageType from "./MessageType";
type Option = {
name: string;
action?: Action;
};
type Action = () => void;
/**
* Builder for showing VS Code Message.
*/
export default class MessageBuilder {
private type: MessageType = MessageType.Error;
private options: Option[] = [];
private modal = false;
private constructor(private message: string) { }
/**
* Initializes a message builder with a message.
* @param message A message to be shown.
*/
public static with(message: string): MessageBuilder {
return new MessageBuilder(message);
}
/**
* Show message using VS Code's built-in message function.
*/
private showMessage(message: string, options: vscode.MessageOptions, ...items: string[]):
Thenable<string | undefined> {
switch (this.type) {
case MessageType.Warning:
return vscode.window.showWarningMessage(message, options, ...items);
case MessageType.Error:
return vscode.window.showErrorMessage(message, options, ...items);
case MessageType.Info:
default:
return vscode.window.showInformationMessage(message, options, ...items);
}
}
/**
* Adds a button to the message.
* @param name A button text.
* @param action A button action.
*/
public addOption(name: string, action?: Action): MessageBuilder {
this.options.push({
name,
action
});
return this;
}
/**
* Sets type of message.
* @param type Message type.
*/
public setType(type: MessageType): MessageBuilder {
this.type = type;
return this;
}
/**
* Sets modality of message.
* @param modal Modal.
*/
public setModal(modal: boolean): MessageBuilder {
this.modal = modal;
return this;
}
/**
* Shows message with VS Code's built-in message feature.
*/
public async show(): Promise<string | undefined> {
const optionNames = this.options.map(option => option.name);
Logger.log(`Message shown: ${this.message}`);
const result = await this.showMessage(this.message, { modal: this.modal }, ...optionNames);
Logger.log(`Message answered: Answer: ${result}, Message: ${this.message}`);
this.options.find(option => option.name === result)?.action?.();
return result;
}
}