-
Notifications
You must be signed in to change notification settings - Fork 664
/
Copy pathshow.ts
324 lines (296 loc) · 12.5 KB
/
show.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Copyright (c) jdneo. All rights reserved.
// Licensed under the MIT license.
import * as _ from "lodash";
import * as path from "path";
import * as unescapeJS from "unescape-js";
import * as vscode from "vscode";
import { explorerNodeManager } from "../explorer/explorerNodeManager";
import { LeetCodeNode } from "../explorer/LeetCodeNode";
import { leetCodeChannel } from "../leetCodeChannel";
import { leetCodeExecutor } from "../leetCodeExecutor";
import { leetCodeManager } from "../leetCodeManager";
import { Endpoint, IProblem, IQuickItemEx, languages, PREMIUM_URL_CN, PREMIUM_URL_GLOBAL, ProblemState } from "../shared";
import { genFileExt, genFileName, getNodeIdFromFile } from "../utils/problemUtils";
import * as settingUtils from "../utils/settingUtils";
import { IDescriptionConfiguration } from "../utils/settingUtils";
import {
DialogOptions,
DialogType,
openSettingsEditor,
openUrl,
promptForOpenOutputChannel,
promptForSignIn,
promptHintMessage,
} from "../utils/uiUtils";
import { getActiveFilePath, selectWorkspaceFolder } from "../utils/workspaceUtils";
import * as wsl from "../utils/wslUtils";
import { leetCodePreviewProvider } from "../webview/leetCodePreviewProvider";
import { leetCodeSolutionProvider } from "../webview/leetCodeSolutionProvider";
import * as list from "./list";
import { getLeetCodeEndpoint } from "./plugin";
import { globalState } from "../globalState";
import { queryDailyProblem } from "../request/query-daily-problem";
export async function previewProblem(input: IProblem | vscode.Uri, isSideMode: boolean = false): Promise<void> {
let node: IProblem;
if (input instanceof vscode.Uri) {
const activeFilePath: string = input.fsPath;
const id: string = await getNodeIdFromFile(activeFilePath);
if (!id) {
vscode.window.showErrorMessage(`Failed to resolve the problem id from file: ${activeFilePath}.`);
return;
}
const cachedNode: IProblem | undefined = explorerNodeManager.getNodeById(id);
if (!cachedNode) {
vscode.window.showErrorMessage(`Failed to resolve the problem with id: ${id}.`);
return;
}
node = cachedNode;
// Move the preview page aside if it's triggered from Code Lens
isSideMode = true;
} else {
node = input;
const { isPremium } = globalState.getUserStatus() ?? {};
if (input.locked && !isPremium) {
const url = getLeetCodeEndpoint() === Endpoint.LeetCode ? PREMIUM_URL_GLOBAL : PREMIUM_URL_CN;
openUrl(url);
return;
}
}
const needTranslation: boolean = settingUtils.shouldUseEndpointTranslation();
const descString: string = await leetCodeExecutor.getDescription(node.id, needTranslation);
leetCodePreviewProvider.show(descString, node, isSideMode);
}
export async function pickOne(): Promise<void> {
const problems: IProblem[] = await list.listProblems();
const randomProblem: IProblem = problems[Math.floor(Math.random() * problems.length)];
await showProblemInternal(randomProblem);
}
export async function pickDaily(): Promise<void> {
const dailyProblemID: string = await queryDailyProblem();
const node: IProblem | undefined = explorerNodeManager.getNodeById(dailyProblemID);
if (!node) {
vscode.window.showErrorMessage(`Failed to resolve the problem with id: ${dailyProblemID}.`);
return;
}
await showProblemInternal(node);
}
export async function showProblem(node?: LeetCodeNode): Promise<void> {
if (!node) {
return;
}
await showProblemInternal(node);
}
export async function searchProblem(): Promise<void> {
if (!leetCodeManager.getUser()) {
promptForSignIn();
return;
}
const choice: IQuickItemEx<IProblem> | undefined = await vscode.window.showQuickPick(parseProblemsToPicks(list.listProblems()), {
matchOnDetail: true,
placeHolder: "Select one problem",
});
if (!choice) {
return;
}
await showProblemInternal(choice.value);
}
export async function showSolution(input: LeetCodeNode | vscode.Uri): Promise<void> {
let problemInput: string | undefined;
if (input instanceof LeetCodeNode) {
// Triggerred from explorer
problemInput = input.id;
} else if (input instanceof vscode.Uri) {
// Triggerred from Code Lens/context menu
problemInput = `"${input.fsPath}"`;
} else if (!input) {
// Triggerred from command
problemInput = await getActiveFilePath();
}
if (!problemInput) {
vscode.window.showErrorMessage("Invalid input to fetch the solution data.");
return;
}
const language: string | undefined = await fetchProblemLanguage();
if (!language) {
return;
}
try {
const needTranslation: boolean = settingUtils.shouldUseEndpointTranslation();
const solution: string = await leetCodeExecutor.showSolution(problemInput, language, needTranslation);
leetCodeSolutionProvider.show(unescapeJS(solution));
} catch (error) {
leetCodeChannel.appendLine(error.toString());
await promptForOpenOutputChannel("Failed to fetch the top voted solution. Please open the output channel for details.", DialogType.error);
}
}
async function fetchProblemLanguage(): Promise<string | undefined> {
const leetCodeConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("leetcode");
let defaultLanguage: string | undefined = leetCodeConfig.get<string>("defaultLanguage");
if (defaultLanguage && languages.indexOf(defaultLanguage) < 0) {
defaultLanguage = undefined;
}
const language: string | undefined =
defaultLanguage ||
(await vscode.window.showQuickPick(languages, {
placeHolder: "Select the language you want to use",
ignoreFocusOut: true,
}));
// fire-and-forget default language query
(async (): Promise<void> => {
if (language && !defaultLanguage && leetCodeConfig.get<boolean>("hint.setDefaultLanguage")) {
const choice: vscode.MessageItem | undefined = await vscode.window.showInformationMessage(
`Would you like to set '${language}' as your default language?`,
DialogOptions.yes,
DialogOptions.no,
DialogOptions.never
);
if (choice === DialogOptions.yes) {
leetCodeConfig.update("defaultLanguage", language, true /* UserSetting */);
} else if (choice === DialogOptions.never) {
leetCodeConfig.update("hint.setDefaultLanguage", false, true /* UserSetting */);
}
}
})();
return language;
}
async function showProblemInternal(node: IProblem): Promise<void> {
try {
const language: string | undefined = await fetchProblemLanguage();
if (!language) {
return;
}
const leetCodeConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("leetcode");
const workspaceFolder: string = await selectWorkspaceFolder();
if (!workspaceFolder) {
return;
}
const fileFolder: string = leetCodeConfig
.get<string>(`filePath.${language}.folder`, leetCodeConfig.get<string>(`filePath.default.folder`, ""))
.trim();
const fileName: string = leetCodeConfig
.get<string>(`filePath.${language}.filename`, leetCodeConfig.get<string>(`filePath.default.filename`) || genFileName(node, language))
.trim();
let finalPath: string = path.join(workspaceFolder, fileFolder, fileName);
if (finalPath) {
finalPath = await resolveRelativePath(finalPath, node, language);
if (!finalPath) {
leetCodeChannel.appendLine("Showing problem canceled by user.");
return;
}
}
finalPath = wsl.useWsl() ? await wsl.toWinPath(finalPath) : finalPath;
const descriptionConfig: IDescriptionConfiguration = settingUtils.getDescriptionConfiguration();
const needTranslation: boolean = settingUtils.shouldUseEndpointTranslation();
await leetCodeExecutor.showProblem(node, language, finalPath, descriptionConfig.showInComment, needTranslation);
const promises: any[] = [
vscode.window.showTextDocument(vscode.Uri.file(finalPath), {
preview: false,
viewColumn: vscode.ViewColumn.One,
}),
promptHintMessage(
"hint.commentDescription",
'You can config how to show the problem description through "leetcode.showDescription".',
"Open settings",
(): Promise<any> => openSettingsEditor("leetcode.showDescription")
),
];
if (descriptionConfig.showInWebview) {
promises.push(showDescriptionView(node));
}
await Promise.all(promises);
} catch (error) {
await promptForOpenOutputChannel(`${error} Please open the output channel for details.`, DialogType.error);
}
}
async function showDescriptionView(node: IProblem): Promise<void> {
return previewProblem(node, vscode.workspace.getConfiguration("leetcode").get<boolean>("enableSideMode", true));
}
async function parseProblemsToPicks(p: Promise<IProblem[]>): Promise<Array<IQuickItemEx<IProblem>>> {
return new Promise(async (resolve: (res: Array<IQuickItemEx<IProblem>>) => void): Promise<void> => {
const picks: Array<IQuickItemEx<IProblem>> = (await p).map((problem: IProblem) =>
Object.assign(
{},
{
label: `${parseProblemDecorator(problem.state, problem.locked)}${problem.id}.${problem.name}`,
description: "",
detail: `AC rate: ${problem.passRate}, Difficulty: ${problem.difficulty}`,
value: problem,
}
)
);
resolve(picks);
});
}
function parseProblemDecorator(state: ProblemState, locked: boolean): string {
switch (state) {
case ProblemState.AC:
return "$(check) ";
case ProblemState.NotAC:
return "$(x) ";
default:
return locked ? "$(lock) " : "";
}
}
async function resolveRelativePath(relativePath: string, node: IProblem, selectedLanguage: string): Promise<string> {
let tag: string = "";
if (/\$\{tag\}/i.test(relativePath)) {
tag = (await resolveTagForProblem(node)) || "";
}
let company: string = "";
if (/\$\{company\}/i.test(relativePath)) {
company = (await resolveCompanyForProblem(node)) || "";
}
return relativePath.replace(/\$\{(.*?)\}/g, (_substring: string, ...args: string[]) => {
const placeholder: string = args[0].toLowerCase().trim();
switch (placeholder) {
case "id":
return node.id;
case "name":
return node.name;
case "camelcasename":
return _.camelCase(node.name);
case "pascalcasename":
return _.upperFirst(_.camelCase(node.name));
case "kebabcasename":
case "kebab-case-name":
return _.kebabCase(node.name);
case "snakecasename":
case "snake_case_name":
return _.snakeCase(node.name);
case "ext":
return genFileExt(selectedLanguage);
case "language":
return selectedLanguage;
case "difficulty":
return node.difficulty.toLocaleLowerCase();
case "tag":
return tag;
case "company":
return company;
default:
const errorMsg: string = `The config '${placeholder}' is not supported.`;
leetCodeChannel.appendLine(errorMsg);
throw new Error(errorMsg);
}
});
}
async function resolveTagForProblem(problem: IProblem): Promise<string | undefined> {
if (problem.tags.length === 1) {
return problem.tags[0];
}
return await vscode.window.showQuickPick(problem.tags, {
matchOnDetail: true,
placeHolder: "Multiple tags available, please select one",
ignoreFocusOut: true,
});
}
async function resolveCompanyForProblem(problem: IProblem): Promise<string | undefined> {
if (problem.companies.length === 1) {
return problem.companies[0];
}
return await vscode.window.showQuickPick(problem.companies, {
matchOnDetail: true,
placeHolder: "Multiple tags available, please select one",
ignoreFocusOut: true,
});
}