Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Code Snippets and Daily Challenge Selection Features #982

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -141,6 +141,11 @@
"title": "Sort Problems",
"category": "LeetCode",
"icon": "$(sort-precedence)"
},
{
"command": "leetcode.pickDaily",
"title": "Pick Daily Chanllenge",
"category": "LeetCode"
}
],
"viewsContainers": {
@@ -223,6 +228,11 @@
"command": "leetcode.removeFavorite",
"when": "view == leetCodeExplorer && viewItem == problem-favorite",
"group": "inline"
},
{
"command": "leetcode.pickDaily",
"when": "view == leetCodeExplorer",
"group": "leetcode@4"
}
],
"commandPalette": [
@@ -705,6 +715,12 @@
"default": true,
"scope": "application",
"description": "Allow LeetCode to report anonymous usage data to improve the product."
},
"leetcode.codeSnippets": {
"type": "string",
"default": "",
"scope": "application",
"description": "Custom code snippets for LeetCode problems."
}
}
}
5 changes: 2 additions & 3 deletions src/commands/plugin.ts
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@
import * as vscode from "vscode";
import { leetCodeTreeDataProvider } from "../explorer/LeetCodeTreeDataProvider";
import { leetCodeExecutor } from "../leetCodeExecutor";
import { IQuickItemEx } from "../shared";
import { getEndpoint, IQuickItemEx } from "../shared";
import { Endpoint, SortingStrategy } from "../shared";
import { DialogType, promptForOpenOutputChannel, promptForSignIn } from "../utils/uiUtils";
import { deleteCache } from "./cache";
@@ -50,8 +50,7 @@ export async function switchEndpoint(): Promise<void> {
}

export function getLeetCodeEndpoint(): string {
const leetCodeConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("leetcode");
return leetCodeConfig.get<string>("endpoint", Endpoint.LeetCode);
return getEndpoint();
}

const SORT_ORDER: SortingStrategy[] = [
11 changes: 11 additions & 0 deletions src/commands/show.ts
Original file line number Diff line number Diff line change
@@ -30,6 +30,7 @@ import { leetCodeSolutionProvider } from "../webview/leetCodeSolutionProvider";
import * as list from "./list";
import { getLeetCodeEndpoint } from "./plugin";
import { globalState } from "../globalState";
import { queryDailyChallenge } from "../request/query-daily-challange";

export async function previewProblem(input: IProblem | vscode.Uri, isSideMode: boolean = false): Promise<void> {
let node: IProblem;
@@ -70,6 +71,16 @@ export async function pickOne(): Promise<void> {
await showProblemInternal(randomProblem);
}

export async function pickDailyChallenge(): Promise<void> {
const dailyChallengeID: string = await queryDailyChallenge();
const node: IProblem | undefined = explorerNodeManager.getNodeById(dailyChallengeID);
if (!node) {
vscode.window.showErrorMessage(`No daily challenge found for today.`);
return;
}
await showProblemInternal(node);
}

export async function showProblem(node?: LeetCodeNode): Promise<void> {
if (!node) {
return;
2 changes: 2 additions & 0 deletions src/explorer/LeetCodeTreeDataProvider.ts
Original file line number Diff line number Diff line change
@@ -85,6 +85,8 @@ export class LeetCodeTreeDataProvider implements vscode.TreeDataProvider<LeetCod
return explorerNodeManager.getAllTagNodes();
case Category.Company:
return explorerNodeManager.getAllCompanyNodes();
case Category.Daily:
return explorerNodeManager.getDailyChallengeNode();
default:
if (element.isProblem) {
return [];
10 changes: 10 additions & 0 deletions src/explorer/explorerNodeManager.ts
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@ import { getSortingStrategy } from "../commands/plugin";
import { Category, defaultProblem, ProblemState, SortingStrategy } from "../shared";
import { shouldHideSolvedProblem } from "../utils/settingUtils";
import { LeetCodeNode } from "./LeetCodeNode";
import { queryDailyChallenge } from "../request/query-daily-challange";

class ExplorerNodeManager implements Disposable {
private explorerNodeMap: Map<string, LeetCodeNode> = new Map<string, LeetCodeNode>();
@@ -53,6 +54,10 @@ class ExplorerNodeManager implements Disposable {
id: Category.Favorite,
name: Category.Favorite,
}), false),
new LeetCodeNode(Object.assign({}, defaultProblem, {
id: Category.Daily,
name: Category.Daily,
}), false)
];
}

@@ -148,6 +153,11 @@ class ExplorerNodeManager implements Disposable {
return this.applySortingStrategy(res);
}

public async getDailyChallengeNode(): Promise<LeetCodeNode[]> {
const dailyChallengeID: string = await queryDailyChallenge();
return this.getNodeById(dailyChallengeID) ? [this.getNodeById(dailyChallengeID)!] : [];
}

public dispose(): void {
this.explorerNodeMap.clear();
this.companySet.clear();
3 changes: 2 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
@@ -97,7 +97,8 @@ export async function activate(context: vscode.ExtensionContext): Promise<void>
vscode.commands.registerCommand("leetcode.switchDefaultLanguage", () => switchDefaultLanguage()),
vscode.commands.registerCommand("leetcode.addFavorite", (node: LeetCodeNode) => star.addFavorite(node)),
vscode.commands.registerCommand("leetcode.removeFavorite", (node: LeetCodeNode) => star.removeFavorite(node)),
vscode.commands.registerCommand("leetcode.problems.sort", () => plugin.switchSortingStrategy())
vscode.commands.registerCommand("leetcode.problems.sort", () => plugin.switchSortingStrategy()),
vscode.commands.registerCommand("leetcode.pickDaily", () => show.pickDailyChallenge())
);

await leetCodeExecutor.switchEndpoint(plugin.getLeetCodeEndpoint());
15 changes: 14 additions & 1 deletion src/leetCodeExecutor.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) jdneo. All rights reserved.
// Licensed under the MIT license.

import * as vscode from "vscode";
import * as cp from "child_process";
import * as fse from "fs-extra";
import * as os from "os";
@@ -110,7 +111,19 @@ class LeetCodeExecutor implements Disposable {

if (!await fse.pathExists(filePath)) {
await fse.createFile(filePath);
const codeTemplate: string = await this.executeCommandWithProgressEx("Fetching problem data...", this.nodeExecutable, cmd);
let codeTemplate: string = await this.executeCommandWithProgressEx("Fetching problem data...", this.nodeExecutable, cmd);
const lines = codeTemplate.split(/\r?\n/);
const targetIndex = lines.findIndex(line => line.includes('// @lc code=start'));
const codeSnippet: string = vscode.workspace.getConfiguration('leetcode').get<string>('codeSnippets', '');
if (targetIndex !== -1 && codeSnippet.trim() !== '') {
let insertIndex = targetIndex;
while (insertIndex - 1 >= 0 && lines[insertIndex - 1].trim() === '') {
lines.splice(insertIndex - 1, 1);
insertIndex--;
}
lines.splice(insertIndex, 0, codeSnippet);
}
codeTemplate = lines.join('\n');
await fse.writeFile(filePath, codeTemplate);
}
}
57 changes: 57 additions & 0 deletions src/request/query-daily-challange.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {getUrl, getEndpoint, Endpoint} from "../shared";
import {LcAxios} from "../utils/httpUtils";
import {AxiosResponse} from "axios";


export const getDailyQueryStr = (): string => {
const dailyQueryStrs = {
LeetCode: `
query questionOfToday {
activeDailyCodingChallengeQuestion {
question {
frontendQuestionId: questionFrontendId
}
}
}
`,
LeetCodeCN: `
query questionOfToday {
todayRecord {
question {
frontendQuestionId: questionFrontendId
}
}
}
`
}
const point: string = getEndpoint();
switch (point) {
case Endpoint.LeetCodeCN:
return dailyQueryStrs.LeetCodeCN;
case Endpoint.LeetCode:
return dailyQueryStrs.LeetCode;
}
return "";
}

export const getDailyProblemID = (res: AxiosResponse<any, any>): string => {
const point = getEndpoint();
switch (point) {
case Endpoint.LeetCodeCN:
return res.data.data.todayRecord[0].question.frontendQuestionId;
case Endpoint.LeetCode:
return res.data.data.todayRecord[0].question.frontendQuestionId;
}
return "";
}

export const queryDailyChallenge = async (): Promise<string> => {
return LcAxios(getUrl("graphql"), {
method: "POST",
data: {
query: getDailyQueryStr(),
variables: {},
operationName: 'questionOfToday'
},
}).then((res) => getDailyProblemID(res));
};
9 changes: 7 additions & 2 deletions src/shared.ts
Original file line number Diff line number Diff line change
@@ -101,6 +101,7 @@ export enum Category {
Tag = "Tag",
Company = "Company",
Favorite = "Favorite",
Daily = "Daily Challenge"
}

export const supportedPlugins: string[] = ["company", "solution.discuss", "leetcode.cn"];
@@ -146,8 +147,7 @@ export const urlsCn = {
};

export const getUrl = (key: string) => {
const leetCodeConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("leetcode");
const point = leetCodeConfig.get<string>("endpoint", Endpoint.LeetCode);
const point = getEndpoint();
switch (point) {
case Endpoint.LeetCodeCN:
return urlsCn[key];
@@ -156,3 +156,8 @@ export const getUrl = (key: string) => {
return urls[key];
}
};

export const getEndpoint = (): string => {
const leetCodeConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("leetcode");
return leetCodeConfig.get<string>("endpoint", Endpoint.LeetCode);
}