From 35c3dfe0081c228d80f84d38205dc39184d2f922 Mon Sep 17 00:00:00 2001
From: Renkin <906155099@qq.com>
Date: Tue, 31 Oct 2023 14:13:25 +0800
Subject: [PATCH 1/7] feat: support insert button on en website
---
src/contentScript.js | 68 ++++++++++++-----------
src/locales/en.js | 101 ++++++++++++++++++++---------------
src/locales/index.js | 19 ++++---
src/locales/{cn.js => zh.js} | 16 +++++-
4 files changed, 120 insertions(+), 84 deletions(-)
rename src/locales/{cn.js => zh.js} (58%)
diff --git a/src/contentScript.js b/src/contentScript.js
index e018861..64c257d 100644
--- a/src/contentScript.js
+++ b/src/contentScript.js
@@ -13,7 +13,11 @@ import {
} from "./utils";
import zenAble from "./zen/zenMode";
import hideFailCases from "./submission/hideFailCases";
-
+import { t as tt, lang } from "./locales";
+let documentLang = document.documentElement.lang;
+const t = (keypath, slotText) => tt(keypath, slotText, documentLang);
+// console.log("lang", lang);
+// lang = document.documentElement.lang
// WTF! ant message didn't go well with chrome extension?
const message = {
success({ content }) {
@@ -222,7 +226,7 @@ function goToVisDebug() {
};
const prefixMap = {
Python3: `
- # 如何你在调试链表题目,手动生成链表很麻烦,想快速生成链表可以注释如下方法,并使用如下方法,输入一个数组,返回一个链表
+ # ${t("app.linkedListCommnet")}
# eg:head = ListNodes([4,2,1,3]).head
# class ListNodes:
# def __init__(self, vals)->ListNode:
@@ -234,7 +238,7 @@ function goToVisDebug() {
# self.head = dummy.next
`,
JavaScript: `
-// 如何你在调试链表题目,手动生成链表很麻烦,想快速生成链表可以注释如下方法,并使用如下方法,输入一个数组,返回一个链表
+// ${t("app.linkedListCommnet")}
// eg:head = ListNodes([4,2,1,3]).head
// function ListNodes(vals) {
// let cur = new ListNode()
@@ -310,18 +314,18 @@ using namespace std;
};
const suffixMap = {
Python3: `
-# 替换下方的 xxx 为主函数名, yyy 为测试用例参数开启调试
+# ${t("app.visualDebugComment")}
Solution().xxx(yyy)
`,
JavaScript: `
-// 替换下方的 xxx 为主函数名, yyy 为测试用例参数开启调试
+// ${t("app.visualDebugComment")}
xxx(yyy)
`,
"C++": `
int main()
{
Solution s;
- // 替换下方的 xxx 为主函数名, yyy 为测试用例参数开启调试
+ // ${t("app.visualDebugComment")}
s.xxx(yyy);
return 0;
}
@@ -331,7 +335,7 @@ int main()
};
if (!supportedLanguages.includes(language))
return message.warn({
- content: `当前仅支持 ${supportedLanguages.join(",")}`,
+ content: `${t("app.visualDebugSupport")} ${supportedLanguages.join(",")}`,
});
const code =
(prefixMap[language] || "") +
@@ -348,17 +352,17 @@ int main()
function getCodeLanguage() {
const langMap = {
- "cpp": "C++",
- "python3": "Python3",
- "java": "Java",
- "c": "C",
- "javascript": "JavaScript",
- }
- const l =window?.monaco?.editor?.getModels()[0]?.getLanguageId() ||
- localStorage.getItem("global_lang")
-
- return langMap[l.toLowerCase()]
+ cpp: "C++",
+ python3: "Python3",
+ java: "Java",
+ c: "C",
+ javascript: "JavaScript",
+ };
+ const l =
+ window?.monaco?.editor?.getModels()[0]?.getLanguageId() ||
+ localStorage.getItem("global_lang");
+ return langMap[l.toLowerCase()];
}
function insertButton() {
const customBtnStyle = {
@@ -369,10 +373,7 @@ function insertButton() {
const buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; ++i) {
- if (buttons[i].innerText.includes("运行")) {
-
- // 停止观察器
- // observer.disconnect();
+ if (buttons[i].innerText.includes(t("Locale.app.run"))) {
// const container = document.createElement("div");
@@ -400,7 +401,7 @@ function insertButton() {
// };
// buttons[i].parentElement.prepend(copyButton);
const writeSolutionButton = document.createElement("a");
- writeSolutionButton.innerText = "写题解";
+ writeSolutionButton.innerText = t("Locale.app.wirteSolution");
Object.assign(writeSolutionButton.style, customBtnStyle);
writeSolutionButton.className = buttons[i].className;
@@ -413,7 +414,7 @@ function insertButton() {
if (!desc) {
return message.warn({
- content: "获取题目描述失败,请先切换到题目描述标签",
+ content: t("app.getProblemError"),
});
}
const title = document.title;
@@ -426,7 +427,7 @@ function insertButton() {
// const desc = document.querySelector("#question-detail-main-tabs")?.children[1]?.children[0]?.children[1]?.innerText;
- const hide = message.loading("正在存储题目信息,请稍后~", 0);
+ const hide = message.loading(t("app.savingProblem"), 0);
writeSolutionButton.setAttribute("disabled", true);
// Dismiss manually and asynchronously
setTimeout(() => {
@@ -466,8 +467,7 @@ function insertButton() {
);
} else {
message.warn({
- content:
- "使用 Github API 失败,已为您切换为普通模式,普通模式仅可自动带入题目名称,题目地址以及题解语言。",
+ content: t("app.githubAPIError"),
});
setTimeout(() => {
window.open(
@@ -484,20 +484,24 @@ function insertButton() {
};
// ReactDOM.render(, writeSolutionButton);
-
- buttons[i].parentElement.parentElement.prepend(writeSolutionButton);
// ele.appendChild(writeSolutionButton);
const visDebugButton = document.createElement("a");
- visDebugButton.innerText = "可视化调试";
+ visDebugButton.innerText = t("Locale.app.visualizationDebug");
Object.assign(visDebugButton.style, customBtnStyle);
visDebugButton.className = buttons[i].className;
visDebugButton.onclick = goToVisDebug;
+ if (documentLang === "en") {
+ buttons[i].parentElement.prepend(visDebugButton);
+ buttons[i].parentElement.prepend(writeSolutionButton);
+ } else {
+ buttons[i].parentElement.parentElement.prepend(writeSolutionButton);
- buttons[i].parentElement.parentElement.prepend(visDebugButton);
+ buttons[i].parentElement.parentElement.prepend(visDebugButton);
+ }
inserted = true;
- } else if (buttons[i].innerText.includes("提交")) {
+ } else if (buttons[i].innerText.includes(t("app.submit"))) {
const click = buttons[i].onclick;
buttons[i].onclick = (...args) => {
click.call(buttons[i], ...args);
@@ -536,7 +540,7 @@ const timerId = setInterval(() => {
if (inserted && submitProxied) return clearInterval(timerId);
if (retried > MAX_TRY) {
clearInterval(timerId);
- return console.error("初始化 chrome 插件 content script 失败");
+ return console.error(t("app.initializeContentScriptFailed"));
}
insertButton();
diff --git a/src/locales/en.js b/src/locales/en.js
index 8e28b42..856d91f 100644
--- a/src/locales/en.js
+++ b/src/locales/en.js
@@ -1,46 +1,61 @@
export const en = {
- app: {
- back: "Back to Home page",
- viewSolution: "View solution",
- viewInHandpickCollection:"This question has been collected in the handpick collection《{slotText}》Click to view",
- notCollected: "This question has not been collected by LeetCode Plus, click to view all collected questions",
- allCollected: "All collected questions",
- writingExplanation: "Writing explanation",
- goToTheWebsiteToUse: "Go to the website to use",
- checkTips:
- "Generally, as long as you turn on automatic updates, chrome will automatically update within five hours after the plug-in is updated. If you want to update as soon as possible, or if you disable automatic updates, you can check the latest version here.",
- checkBtn: "Check for updates",
- selfIntroduction:
- "The author is a front-end architect with 40K stars on Github, the author of the leetcode-cheatsheet leetcode plugin, master all kinds of algorithm routines, and wrote hundreds of thousands of words of algorithm brushing e-books. Reply to the public account [电子书] to get.",
- allSolutions: {
- columns: {
- title: "Title",
- tag: "Tag",
- },
+ app: {
+ back: "Back to Home page",
+ viewSolution: "View solution",
+ viewInHandpickCollection:
+ "This question has been collected in the handpick collection《{slotText}》Click to view",
+ notCollected:
+ "This question has not been collected by LeetCode Plus, click to view all collected questions",
+ allCollected: "All collected questions",
+ writingExplanation: "Writing explanation",
+ goToTheWebsiteToUse: "Go to the website to use",
+ checkTips:
+ "Generally, as long as you turn on automatic updates, chrome will automatically update within five hours after the plug-in is updated. If you want to update as soon as possible, or if you disable automatic updates, you can check the latest version here.",
+ checkBtn: "Check for updates",
+ selfIntroduction:
+ "The author is a front-end architect with 40K stars on Github, the author of the leetcode-cheatsheet leetcode plugin, master all kinds of algorithm routines, and wrote hundreds of thousands of words of algorithm brushing e-books. Reply to the public account [电子书] to get.",
+ allSolutions: {
+ columns: {
+ title: "Title",
+ tag: "Tag",
},
},
- codeTemplate: {
- name: "Code Template",
- },
- dataStructureVisualization: {
- name: "Data Structure Visualization",
- },
-
- explanationTemplate: {
- name: "Explanation Template",
- },
- complexityQuickCheck: {
- name: "Complexity Quick Check",
- },
- learningRoute: {
- name: "Learning Route",
- },
- checkForUpdates: {
- name: "Check for Updates",
- },
- aboutMe: {
- name: "About Me",
- },
- };
- export default en;
-
\ No newline at end of file
+ initializeContentScriptFailed:"Failed to initialize the chrome plugin content script",
+ run: "Run",
+ submit: "Submit",
+ wirteSolution: "Write Solution",
+ visualizationDebug: "Visualization Debug",
+ linkedListCommnet:
+ "If you are debugging linked list questions, it is very troublesome to generate linked lists manually. If you want to quickly generate linked lists, you can comment out the following method and use the following method to enter an array and return a linked list.",
+ visualDebugComment:
+ "Replace xxx below with the main function name, yyy with the test case parameter, and turn on debugging",
+ getProblemError:
+ "Failed to get the problem description, please switch to the problem description tab first",
+ savingProblem: "Saving problem information, please wait~",
+ githubAPIError:
+ "Failed to use Github API, has been switched to normal mode, normal mode can only automatically bring in the problem name, problem address and solution language.",
+ },
+ codeTemplate: {
+ name: "Code Template",
+ },
+ dataStructureVisualization: {
+ name: "Data Structure Visualization",
+ },
+
+ explanationTemplate: {
+ name: "Explanation Template",
+ },
+ complexityQuickCheck: {
+ name: "Complexity Quick Check",
+ },
+ learningRoute: {
+ name: "Learning Route",
+ },
+ checkForUpdates: {
+ name: "Check for Updates",
+ },
+ aboutMe: {
+ name: "About Me",
+ },
+};
+export default en;
diff --git a/src/locales/index.js b/src/locales/index.js
index cbf34c4..c7d99a9 100644
--- a/src/locales/index.js
+++ b/src/locales/index.js
@@ -1,20 +1,20 @@
-import cn from "./cn";
+import zh from "./zh";
import en from "./en";
// import { getStorage, setStorage } from "../utils";
// const STORAGE_LANG_KEY = "LEETCODE_CHEAT_LANG";
const LEETCODE_URL_CN = "https://leetcode.cn";
const LEETCODE_URL_EN = "https://leetcode.com";
-const DEFAULT_LANG = "cn";
+const DEFAULT_LANG = "zh";
-let lang = DEFAULT_LANG;
+export let lang = DEFAULT_LANG;
const ALL_LANGS = {
- cn,
+ zh,
en,
};
export const ALL_LANG_OPTIONS = {
- cn: "简体中文",
+ zh: "简体中文",
en: "English",
};
@@ -22,7 +22,7 @@ export const AllLangs = Object.keys(ALL_LANGS);
export const initLang = async (currentUrl) => {
const isCnHref = currentUrl.includes(LEETCODE_URL_CN);
- setLang(isCnHref ? "cn" : "en");
+ setLang(isCnHref ? "zh" : "en");
};
export const setLang = (_lang) => {
@@ -38,9 +38,12 @@ const getForPath = (obj, path) => {
return result;
};
-export const t = (keypath, slotText) => {
- const langData ={ Locale: ALL_LANGS[lang] }
+export const t = (keypath, slotText,l) => {
+ const langData ={ Locale: ALL_LANGS[l||lang] }
if (!keypath) return "";
+ if (!keypath.includes("Locale")) {
+ keypath = "Locale." + keypath
+ }
let content = getForPath(langData, keypath);
if (slotText) {
if (Array.isArray(slotText)) {
diff --git a/src/locales/cn.js b/src/locales/zh.js
similarity index 58%
rename from src/locales/cn.js
rename to src/locales/zh.js
index 6ca8fed..d8f3b57 100644
--- a/src/locales/cn.js
+++ b/src/locales/zh.js
@@ -2,7 +2,7 @@ export const cn = {
app: {
back: "返回主页",
viewSolution: "查看本题题解",
- viewInHandpickCollection:"该题已被收录到精选合集《{slotText}》点击查看",
+ viewInHandpickCollection: "该题已被收录到精选合集《{slotText}》点击查看",
notCollected: "本题暂未被力扣加加收录,点击查看所有已收录题目~",
allCollected: "所有已收录的题目",
writingExplanation: "正在撰写题解...",
@@ -18,6 +18,20 @@ export const cn = {
tag: "标签",
},
},
+ initializeContentScriptFailed:"初始化 chrome 插件 content script 失败",
+ run: "运行",
+ submit: "提交",
+ wirteSolution: "写题解",
+ visualizationDebug: "可视化调试",
+ linkedListCommnet:
+ "如果你在调试链表题目,手动生成链表很麻烦,想快速生成链表可以注释如下方法,并使用如下方法,输入一个数组,返回一个链表",
+ visualDebugComment:
+ "替换下方的 xxx 为主函数名, yyy 为测试用例参数开启调试",
+ visualDebugSupport: "当前仅支持",
+ getProblemError: "获取题目描述失败,请先切换到题目描述标签页",
+ savingProblem: "正在存储题目信息,请稍后~",
+ githubAPIError:
+ "使用 Github API 失败,已为您切换为普通模式,普通模式仅可自动带入题目名称,题目地址以及题解语言。",
},
codeTemplate: {
name: "代码模板",
From 4087ea4eb4614e179e33d6ec7e20c5026955f07a Mon Sep 17 00:00:00 2001
From: Renkin <906155099@qq.com>
Date: Tue, 31 Oct 2023 14:14:37 +0800
Subject: [PATCH 2/7] chore: delete comment
---
src/contentScript.js | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/src/contentScript.js b/src/contentScript.js
index 64c257d..6bb8c29 100644
--- a/src/contentScript.js
+++ b/src/contentScript.js
@@ -13,11 +13,10 @@ import {
} from "./utils";
import zenAble from "./zen/zenMode";
import hideFailCases from "./submission/hideFailCases";
-import { t as tt, lang } from "./locales";
+import { t as tt } from "./locales";
let documentLang = document.documentElement.lang;
const t = (keypath, slotText) => tt(keypath, slotText, documentLang);
-// console.log("lang", lang);
-// lang = document.documentElement.lang
+
// WTF! ant message didn't go well with chrome extension?
const message = {
success({ content }) {
From 8671341cd508a41b49b86369227463017a1e75b1 Mon Sep 17 00:00:00 2001
From: Renkin <906155099@qq.com>
Date: Tue, 31 Oct 2023 18:04:38 +0800
Subject: [PATCH 3/7] feat: support change language; supplement i18n
---
src/App.js | 287 +++++++++++++++-------------
src/codeTemplates/backtrack.js | 7 +-
src/codeTemplates/bfs.js | 4 +-
src/codeTemplates/binarySearch.js | 11 +-
src/codeTemplates/codeTemplate.jsx | 47 +++--
src/codeTemplates/grapth.js | 27 +--
src/codeTemplates/hand-writing.js | 4 +-
src/codeTemplates/heap.js | 4 +-
src/codeTemplates/index.js | 8 +-
src/codeTemplates/preSum.js | 24 +--
src/codeTemplates/prime.js | 44 ++---
src/codeTemplates/rotate.js | 4 +-
src/codeTemplates/segmentTree.js | 40 ++--
src/codeTemplates/sliding-window.js | 7 +-
src/codeTemplates/suffix_array.js | 4 +-
src/codeTemplates/trie.js | 7 +-
src/codeTemplates/uf.js | 7 +-
src/components/codes.jsx | 5 +-
src/constant/index.js | 2 +-
src/locales/en.js | 40 +++-
src/locales/index.js | 60 +++---
src/locales/zh.js | 38 ++++
src/utils.js | 28 +++
23 files changed, 430 insertions(+), 279 deletions(-)
diff --git a/src/App.js b/src/App.js
index ba8d1eb..2b4a1bf 100644
--- a/src/App.js
+++ b/src/App.js
@@ -1,4 +1,4 @@
-import React, { useState, Suspense } from "react";
+import React, { useState, Suspense, useEffect } from "react";
import { Button, Table, Empty, Tabs, Image } from "antd";
import "highlight.js/styles/github.css";
@@ -12,7 +12,7 @@ import { LEETCODE_CN_URL } from "./constant/index";
import ProblemDetail from "./Detail";
import Roadmap from "./roadmap/roadmap.jsx";
import TagOrLink from "./components/TagOrLink";
-import tempaltes from "./codeTemplates/index";
+import templates from "./codeTemplates/index";
import checkUpdate from "./checkUpdates";
import { isInExtension, getUrlParameter } from "./utils";
@@ -22,7 +22,7 @@ import "./App.css";
import CodeTemplates from "./codeTemplates/codeTemplate";
import ComplexityRating from "./complexityRating/index";
import SolutionTemplate from "./solutionTemplate/index";
-import { t, initLang } from "./locales";
+import { t, initLang, setLang, lang } from "./locales";
// import { data as a } from "./db/binary-tree";
const DataStrutureVis = isInExtension()
@@ -106,6 +106,7 @@ function App() {
// setHasSolution(!!problems[problemId]);
// }, 1000);
+ const [langReady, setLangReady] = useState(false);
const [problemId, setProblemId] = useState("");
const [hasSolution, setHasSolution] = useState(false);
@@ -113,6 +114,12 @@ function App() {
const [page, setPage] = useState("");
const [tab, setTab] = useState(initialTab);
+ useEffect(() => {
+ process.env.NODE_ENV === "development" && initLang();
+ setLangReady(true);
+ }, []);
+
+
// const [inLeetCode, setInLeetCode] = useState(true);
// if (!inLeetCode) return window.open(LEETCODE_CN_URL + "/problemset/all/");
@@ -124,152 +131,168 @@ function App() {
// }, 1000);
// console.log(a);
- return (
-
-
- {isInExtension() && (
- <>
-
-
- {page !== "" ? (
-
- ) : (
- ""
- )}
- {hasSolution && page === "" ? (
-
- ) : (
- ""
- )}
+ const changeLang = async () => {
+ await setLangReady(false);
+ setLang(lang === "zh" ? "en" : "zh");
+ setLangReady(true);
+ };
- {!hasSolution &&
- page !== "allSolutions" &&
- (inSelected ? (
-
}>
+
+
+ )}
+
+ {!isInExtension() && (
+
- {t("Locale.app.goToTheWebsiteToUse")}
-
- ) : (
- Loading...}>
-
-
+
+
)}
-
- {!isInExtension() && (
+
-
+
- )}
+
+
+
+ {isInExtension() && (
+
+ {t("Locale.app.checkTips")}
+
+ {t("Locale.app.checkBtn")}
+
+
+ )}
-
-
-
-
-
-
- {isInExtension() && (
-
- {t("Locale.app.checkTips")}
-
- {t("Locale.app.checkBtn")}
+
+
+
{t("Locale.app.selfIntroduction")}
+
+
+
+
+
+ {t("app.changeLang")}
- )}
-
-
-
-
{t("Locale.app.selfIntroduction")}
-
-
-
-
- )}
-
+
+ )}
+
+ )
);
}
diff --git a/src/codeTemplates/backtrack.js b/src/codeTemplates/backtrack.js
index 3a6713f..34a19dd 100644
--- a/src/codeTemplates/backtrack.js
+++ b/src/codeTemplates/backtrack.js
@@ -1,4 +1,4 @@
-module.exports = {
+module.exports = () => ({
logo: require("../imgs/backtrack.svg"),
title: "回溯",
list: [
@@ -107,6 +107,5 @@ class Solution:
],
},
],
- link:
- "https://github.com/azl397985856/leetcode/blob/master/thinkings/backtrack.md",
-};
+ link: "https://github.com/azl397985856/leetcode/blob/master/thinkings/backtrack.md",
+});
diff --git a/src/codeTemplates/bfs.js b/src/codeTemplates/bfs.js
index f3be181..ad175d3 100644
--- a/src/codeTemplates/bfs.js
+++ b/src/codeTemplates/bfs.js
@@ -1,6 +1,6 @@
import bfsLogo from "../imgs/bfs.svg";
-export default {
+export default () => ({
title: "BFS",
logo: bfsLogo,
list: [
@@ -82,4 +82,4 @@ export default {
},
],
link: "https://github.com/azl397985856/leetcode/blob/master/thinkings/tree.md",
-};
+});
diff --git a/src/codeTemplates/binarySearch.js b/src/codeTemplates/binarySearch.js
index d44a5b6..7efd787 100644
--- a/src/codeTemplates/binarySearch.js
+++ b/src/codeTemplates/binarySearch.js
@@ -1,8 +1,6 @@
-import halfLogo from "../imgs/half.svg";
-
-export default {
+module.exports = () => ({
title: "二分法",
- logo: halfLogo,
+ logo: require("../imgs/half.svg"),
list: [
{
text: "查找一个数",
@@ -402,6 +400,5 @@ function searchInsertRight(nums, x) {
],
},
],
- link:
- "https://github.com/azl397985856/leetcode/blob/master/91/binary-search.md",
-};
+ link: "https://github.com/azl397985856/leetcode/blob/master/91/binary-search.md",
+});
diff --git a/src/codeTemplates/codeTemplate.jsx b/src/codeTemplates/codeTemplate.jsx
index f46f47a..a5233ab 100644
--- a/src/codeTemplates/codeTemplate.jsx
+++ b/src/codeTemplates/codeTemplate.jsx
@@ -1,11 +1,8 @@
-import React from "react";
+import React, { useEffect, useState } from "react";
import { Button, Collapse, Tabs } from "antd";
import Codes from "../components/codes";
-
-import {
- LEETCODE_CN_URL,
- CONTRIBUTE_PROGRAMMING_LANGUAGE_URL,
-} from "../constant/index";
+import { t, getLeetcodeUrlForLang } from "../locales";
+import { CONTRIBUTE_PROGRAMMING_LANGUAGE_URL } from "../constant/index";
const { TabPane } = Tabs;
const { Panel } = Collapse;
@@ -13,14 +10,26 @@ const { Panel } = Collapse;
function computedURL(problem) {
if (problem.id.startsWith("https://") || problem.id.startsWith("https://"))
return problem.id;
- return `${LEETCODE_CN_URL}/problems/${problem.id}`;
+
+ return `${getLeetcodeUrlForLang()}/problems/${problem.id}`;
}
-export default function CodeTemplate({ tempaltes }) {
+export default function CodeTemplate({ templates }) {
+ const [tab, setTab] = useState("");
+ const [tempaltesState, setTempaltesState] = useState([]);
+
+ useEffect(() => {
+ setTempaltesState(templates.map((c) => c?.call()));
+ }, [templates]);
+
+ useEffect(() => {
+ tempaltesState[0] && setTab(tempaltesState[0].title);
+ }, [tempaltesState]);
+
return (
-
- {tempaltes.map((tempalte) => (
+
+ {tempaltesState.map((tempalte) => (
@@ -41,18 +50,18 @@ export default function CodeTemplate({ tempaltes }) {
>
{tempalte.link && (
- 建议先学会之后再用模板。 如果你还不会的话,可以看看这篇
+ {t("Locale.codeTemplate.perSum.tips")}
- 文章
+ {t("Locale.app.article")}
- 哦~
+ ~
)}
{tempalte.list.map(({ text, problems, codes }) => (
{text}} key={text}>
0 ? {} : { display: "none" }}>
- 推荐题目:
+ {t("Locale.app.recommendedQuestions")}
{problems.map((problem) => (
-
@@ -65,7 +74,7 @@ export default function CodeTemplate({ tempaltes }) {
size="small"
style={{ marginLeft: "10px" }}
>
- 去默写
+ {t("Locale.app.toWriteSilently")}
))}
@@ -76,7 +85,7 @@ export default function CodeTemplate({ tempaltes }) {
type="link"
href={CONTRIBUTE_PROGRAMMING_LANGUAGE_URL}
>
- 纠错 or 贡献其他语言
+ {t("Locale.app.contribution")}
@@ -84,7 +93,11 @@ export default function CodeTemplate({ tempaltes }) {
))}
-
+
);
diff --git a/src/codeTemplates/grapth.js b/src/codeTemplates/grapth.js
index 62b7ae7..20f39b7 100644
--- a/src/codeTemplates/grapth.js
+++ b/src/codeTemplates/grapth.js
@@ -1,13 +1,14 @@
-module.exports = {
- title: "图",
+const t = require("../locales").t;
+module.exports = () => ({
+ title: t("Locale.codeTemplate.graph.title"),
logo: require("../imgs/grapth.svg"),
list: [
{
- text: "dijkstra(单源贪心最短路径)",
+ text: t("Locale.codeTemplate.graph.item1"),
problems: [
{
id: "network-delay-time",
- title: "743. 网络延迟时间",
+ title: t("Locale.problem.743"),
},
],
codes: [
@@ -66,11 +67,11 @@ def dijkstra(graph, start, end):
],
},
{
- text: "floyd_warshall(多源动态规划最短路径)",
+ text: t("Locale.codeTemplate.graph.item2"),
problems: [
{
id: "course-schedule-iv",
- title: "1462. 课程表 IV",
+ title: t("Locale.problem.1462"),
},
],
codes: [
@@ -104,7 +105,7 @@ def floyd_warshall(graph, n):
],
},
{
- text: "Bellman–Ford(单源动态规划最短路径)",
+ text: t("Locale.codeTemplate.graph.item3"),
problems: [
{
id: "https://binarysearch.com/problems/Best-Currency-Path",
@@ -135,11 +136,11 @@ def bell_man(edges, s):
],
},
{
- text: "Kruskal(又称加边法,是一种最小生成树算法)",
+ text: t("Locale.codeTemplate.graph.item4"),
problems: [
{
id: "min-cost-to-connect-all-points",
- title: "1584. 连接所有点的最小费用",
+ title: t("Locale.problem.1584"),
},
],
codes: [
@@ -198,11 +199,11 @@ if __name__ == "__main__": # pragma: no cover
],
},
{
- text: "Prim(又称加点法,是一种最小生成树算法)",
+ text: t("Locale.codeTemplate.graph.item5"),
problems: [
{
id: "min-cost-to-connect-all-points",
- title: "1584. 连接所有点的最小费用",
+ title: t("Locale.problem.1584"),
},
],
codes: [
@@ -330,7 +331,7 @@ if __name__ == "__main__": # pragma: no cover
],
},
{
- text: "Kahn(基于BFS的拓扑排序)",
+ text: t("Locale.codeTemplate.graph.item6"),
problems: [],
codes: [
{
@@ -378,4 +379,4 @@ topologicalSort(graph)
},
],
link: "",
-};
+});
diff --git a/src/codeTemplates/hand-writing.js b/src/codeTemplates/hand-writing.js
index 6164159..fe2bbb7 100644
--- a/src/codeTemplates/hand-writing.js
+++ b/src/codeTemplates/hand-writing.js
@@ -1,4 +1,4 @@
-module.exports = {
+module.exports = () => ({
logo: require("../imgs/hand-writing.svg"),
title: "手撕算法",
list: [
@@ -296,4 +296,4 @@ class Solution:
},
],
// link: "",
-};
+});
diff --git a/src/codeTemplates/heap.js b/src/codeTemplates/heap.js
index 4a972a0..81cce23 100644
--- a/src/codeTemplates/heap.js
+++ b/src/codeTemplates/heap.js
@@ -235,7 +235,7 @@ public class MinHeap {
`;
-module.exports = {
+module.exports = () => ({
logo: require("../imgs/heap.svg"),
title: "堆",
list: [
@@ -264,4 +264,4 @@ module.exports = {
},
],
link: "https://leetcode-solution.cn/solutionDetail?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fapi.github.com%2Frepos%2Fazl397985856%2Fleetcode%2Fcontents%2Fthinkings%2Fheap.md&type=1",
-};
+});
diff --git a/src/codeTemplates/index.js b/src/codeTemplates/index.js
index aee5761..6f265be 100644
--- a/src/codeTemplates/index.js
+++ b/src/codeTemplates/index.js
@@ -10,8 +10,9 @@ import preSum from "./preSum";
import handWriting from "./hand-writing";
import rotate from "./rotate";
import grapth from "./grapth";
-import prime from './prime'
-export default [
+import prime from "./prime";
+console.log(binarySearch,"123");
+const templates = [
preSum,
grapth,
binarySearch,
@@ -24,5 +25,6 @@ export default [
segmemntTree,
handWriting,
rotate,
- prime
+ prime,
];
+export default templates;
diff --git a/src/codeTemplates/preSum.js b/src/codeTemplates/preSum.js
index b6c84b2..b4a6042 100644
--- a/src/codeTemplates/preSum.js
+++ b/src/codeTemplates/preSum.js
@@ -1,3 +1,5 @@
+// import { t } from "../locales";
+const { t } = require("../locales");
const pre1dJSCode = `
// 建立
const pre = [0]
@@ -63,15 +65,15 @@ const diff2dPythonCode = `
`;
-module.exports = {
- title: "前缀和",
+module.exports = () => ({
+ title: t("Locale.codeTemplate.perSum.title"),
logo: require("../imgs/preSum.svg"),
list: [
{
- text: "一维前缀和",
+ text: t("Locale.codeTemplate.perSum.item1"),
problems: [
{
- title: "1480. 一维数组的动态和",
+ title: t("Locale.problem.1480"),
id: "running-sum-of-1d-array",
},
],
@@ -87,10 +89,10 @@ module.exports = {
],
},
{
- text: "二维前缀和",
+ text: t("Locale.codeTemplate.perSum.item2"),
problems: [
{
- title: "1314. 矩阵区域和",
+ title: t("Locale.problem.1314"),
id: "matrix-block-sum",
},
],
@@ -102,10 +104,10 @@ module.exports = {
],
},
{
- text: "一维差分数组",
+ text: t("Locale.codeTemplate.perSum.item3"),
problems: [
{
- title: "1109. 航班预订统计",
+ title: t("Locale.problem.1109"),
id: "corporate-flight-bookings",
},
],
@@ -117,10 +119,10 @@ module.exports = {
],
},
{
- text: "二维差分数组",
+ text: t("Locale.codeTemplate.perSum.item4"),
problems: [
{
- title: "6292. 子矩阵元素加 1",
+ title: t("Locale.problem.2536"),
id: "increment-submatrices-by-one",
},
],
@@ -133,4 +135,4 @@ module.exports = {
},
],
link: "https://lucifer.ren/blog/2020/09/27/atMostK/",
-};
+});
diff --git a/src/codeTemplates/prime.js b/src/codeTemplates/prime.js
index a554cd4..4ba1a59 100644
--- a/src/codeTemplates/prime.js
+++ b/src/codeTemplates/prime.js
@@ -6,26 +6,26 @@ for i in range(2, int(MAXN ** 0.5) + 1):
if flag[i]:
for j in range(i * 2, MAXN + 1, i):
flag[j] = False
-`
+`;
-module.exports = {
- title: "求质数",
- // logo: require("../imgs/preSum.svg"),
- list: [
- {
- text: "质数筛选法",
- problems: [
- {
- title: "2867. 统计树中的合法路径数目",
- id: "count-valid-paths-in-a-tree",
- },
- ],
- codes: [
- {
- language: "py",
- text: pyCode,
- },
- ],
- },
- ]
- };
\ No newline at end of file
+module.exports = () => ({
+ title: "求质数",
+ // logo: require("../imgs/preSum.svg"),
+ list: [
+ {
+ text: "质数筛选法",
+ problems: [
+ {
+ title: "2867. 统计树中的合法路径数目",
+ id: "count-valid-paths-in-a-tree",
+ },
+ ],
+ codes: [
+ {
+ language: "py",
+ text: pyCode,
+ },
+ ],
+ },
+ ],
+});
diff --git a/src/codeTemplates/rotate.js b/src/codeTemplates/rotate.js
index bd92a84..c74f846 100644
--- a/src/codeTemplates/rotate.js
+++ b/src/codeTemplates/rotate.js
@@ -1,4 +1,4 @@
-module.exports = {
+module.exports = () => ({
title: "矩阵旋转",
logo: require("../imgs/rotate.svg"),
list: [
@@ -41,4 +41,4 @@ def rotate(mat):
},
],
link: "",
-};
+});
diff --git a/src/codeTemplates/segmentTree.js b/src/codeTemplates/segmentTree.js
index ccb8a0f..06d41e5 100644
--- a/src/codeTemplates/segmentTree.js
+++ b/src/codeTemplates/segmentTree.js
@@ -85,7 +85,7 @@ class SegmentTree:
self.tree[tree_index] = self.tree[left] + self.tree[right]
`;
-export default {
+export default () => ({
title: "线段树",
logo: segmentLogo,
link: "https://oi-wiki.org/ds/seg/",
@@ -114,8 +114,8 @@ export default {
problems: [
{
id: "handling-sum-queries-after-update",
- title: "2569. 更新数组后处理求和查询"
- }
+ title: "2569. 更新数组后处理求和查询",
+ },
],
codes: [
{
@@ -188,9 +188,9 @@ export default {
if qr <= mid: return self.query(left, l, mid, ql, qr)
if ql > mid: return self.query(right, mid+1, r, ql, qr)
return self.query(left, l, mid, ql, mid) + self.query(right, mid+1, r, mid+1, qr)
- `
- }
- ]
+ `,
+ },
+ ],
},
{
text: "计数线段树",
@@ -261,14 +261,17 @@ class SegmentTree:
],
},
{
- text: '动态开点',
- problems: [{
- id: 'maximum-sum-queries',
- title: '2736. 最大和查询'
- }],
- codes: [{
- language: 'py',
- text: `
+ text: "动态开点",
+ problems: [
+ {
+ id: "maximum-sum-queries",
+ title: "2736. 最大和查询",
+ },
+ ],
+ codes: [
+ {
+ language: "py",
+ text: `
class Node:
def __init__(self, l, r):
self.left = None # 左孩子的指针
@@ -324,8 +327,9 @@ class SegmentTree:
def querySum(self,left,right):
return self.query(left,right,self.root)
- `
- }]
- }
+ `,
+ },
+ ],
+ },
],
-};
+});
diff --git a/src/codeTemplates/sliding-window.js b/src/codeTemplates/sliding-window.js
index 1147dc6..16431ef 100644
--- a/src/codeTemplates/sliding-window.js
+++ b/src/codeTemplates/sliding-window.js
@@ -1,5 +1,5 @@
import windowLogo from "../imgs/window.svg";
-export default {
+export default () => ({
title: "滑动窗口",
logo: windowLogo,
list: [
@@ -87,6 +87,5 @@ export default {
],
},
],
- link:
- "https://github.com/azl397985856/leetcode/blob/master/thinkings/slide-window.md",
-};
+ link: "https://github.com/azl397985856/leetcode/blob/master/thinkings/slide-window.md",
+});
diff --git a/src/codeTemplates/suffix_array.js b/src/codeTemplates/suffix_array.js
index a7ce82d..ea37f22 100644
--- a/src/codeTemplates/suffix_array.js
+++ b/src/codeTemplates/suffix_array.js
@@ -1,4 +1,4 @@
-export default {
+export default () => ({
title: "后缀树组",
logo: "",
list: [
@@ -116,4 +116,4 @@ export default {
},
],
link: "",
-};
+});
diff --git a/src/codeTemplates/trie.js b/src/codeTemplates/trie.js
index 79d0ed8..8a3923d 100644
--- a/src/codeTemplates/trie.js
+++ b/src/codeTemplates/trie.js
@@ -215,7 +215,7 @@ class Trie {
}
}
`;
-export default {
+export default () => ({
title: "前缀树",
logo: treeLogo,
list: [
@@ -345,6 +345,5 @@ class Trie:
],
},
],
- link:
- "https://github.com/azl397985856/leetcode/blob/master/thinkings/trie.md",
-};
+ link: "https://github.com/azl397985856/leetcode/blob/master/thinkings/trie.md",
+});
diff --git a/src/codeTemplates/uf.js b/src/codeTemplates/uf.js
index 49e0cf6..f9a3b00 100644
--- a/src/codeTemplates/uf.js
+++ b/src/codeTemplates/uf.js
@@ -1,6 +1,6 @@
import ufLogo from "../imgs/uf.svg";
-export default {
+export default () => ({
title: "并查集",
logo: ufLogo,
list: [
@@ -94,6 +94,5 @@ class UF:
],
},
],
- link:
- "https://github.com/azl397985856/leetcode/blob/master/thinkings/union-find.md",
-};
+ link: "https://github.com/azl397985856/leetcode/blob/master/thinkings/union-find.md",
+});
diff --git a/src/components/codes.jsx b/src/components/codes.jsx
index 68c7ab9..5778c71 100644
--- a/src/components/codes.jsx
+++ b/src/components/codes.jsx
@@ -4,6 +4,7 @@ import { Button, message, Collapse } from "antd";
import CodeBlock from "./CodeBlock";
import { copy } from "../utils";
+import { t } from "../locales";
const { Panel } = Collapse;
@@ -22,11 +23,11 @@ export default function Codes({ codes, renderHeader }) {
onClick={(e) => {
e.stopPropagation();
copy(c.text, () => {
- message.success("复制成功~");
+ message.success(t("Locale.app.copySuccess"));
});
}}
>
- 复制
+ {t("Locale.app.copy")}
{renderHeader && renderHeader()}
diff --git a/src/constant/index.js b/src/constant/index.js
index 4890c96..e63d1ad 100644
--- a/src/constant/index.js
+++ b/src/constant/index.js
@@ -1,4 +1,4 @@
-export const LEETCODE_CN_URL = "https://leetcode-cn.com";
+export const LEETCODE_CN_URL = "https://leetcode.cn";
export const LEETCODE_URL = "https://leetcode.com";
export const ISSUES_URL =
"https://github.com/azl397985856/leetcode-cheat/issues";
diff --git a/src/locales/en.js b/src/locales/en.js
index 856d91f..cae4471 100644
--- a/src/locales/en.js
+++ b/src/locales/en.js
@@ -1,5 +1,13 @@
export const en = {
app: {
+ setLang: "Set Language",
+ changeLang: "Switch to Chinese",
+ copy: "copy",
+ copySuccess: "Copy successfully~",
+ article: "article",
+ recommendedQuestions: "Recommended Questions:",
+ toWriteSilently: "To write silently",
+ contribution: "Correction or contribution to other languages",
back: "Back to Home page",
viewSolution: "View solution",
viewInHandpickCollection:
@@ -20,7 +28,8 @@ export const en = {
tag: "Tag",
},
},
- initializeContentScriptFailed:"Failed to initialize the chrome plugin content script",
+ initializeContentScriptFailed:
+ "Failed to initialize the chrome plugin content script",
run: "Run",
submit: "Submit",
wirteSolution: "Write Solution",
@@ -35,8 +44,37 @@ export const en = {
githubAPIError:
"Failed to use Github API, has been switched to normal mode, normal mode can only automatically bring in the problem name, problem address and solution language.",
},
+ problem: {
+ 743: "743. Network Delay Time",
+ 1109: "1109. Corporate Flight Bookings",
+ 1314: "1314. Matrix Block Sum",
+ 1462: "1462. Course Schedule IV",
+ 1480: "1480. Running Sum of 1d Array",
+ 1584: "1584. Min Cost to Connect All Points",
+ 2536: "2536. Increment Submatrices by One",
+ },
codeTemplate: {
name: "Code Template",
+ perSum: {
+ title: "Prefix Sum",
+ tips: "It is recommended to learn it first and then use the template. If you don't know it yet, you can take a look at this article",
+ item1: "One-dimensional prefix sum",
+ item2: "Two-dimensional prefix sum",
+ item3: "One-dimensional difference array",
+ item4: "Two-dimensional difference array",
+ },
+ graph: {
+ title: "Graph",
+ item1: "dijkstra(single-source greedy shortest path)",
+ item2: "floyd_warshall(multi-source dynamic programming shortest path)",
+ item3: "Bellman–Ford(single-source dynamic programming shortest path)",
+ item4:
+ "Kruskal(also known as adding edge method, is a minimum spanning tree algorithm)",
+ item5:
+ "Prim(also known as adding point method, is a minimum spanning tree algorithm)",
+ item6: "Kahn(topological sorting based on BFS)",
+ },
+ moreTemplate: "More templates will be updated one after another~",
},
dataStructureVisualization: {
name: "Data Structure Visualization",
diff --git a/src/locales/index.js b/src/locales/index.js
index 8edb279..9711797 100644
--- a/src/locales/index.js
+++ b/src/locales/index.js
@@ -1,10 +1,10 @@
+import { getUrlParams, getForPath, } from "../utils";
+import { LEETCODE_CN_URL, LEETCODE_URL } from "../constant";
import zh from "./zh";
import en from "./en";
-// import { getStorage, setStorage } from "../utils";
-// const STORAGE_LANG_KEY = "LEETCODE_CHEAT_LANG";
-const LEETCODE_URL_CN = "https://leetcode.cn";
-const LEETCODE_URL_EN = "https://leetcode.com";
+
const DEFAULT_LANG = "zh";
+let isInit = false;
export let lang = DEFAULT_LANG;
@@ -13,43 +13,51 @@ const ALL_LANGS = {
en,
};
-export const ALL_LANG_OPTIONS = {
- zh: "简体中文",
- en: "English",
-};
-
-export const AllLangs = Object.keys(ALL_LANGS);
-
-export const initLang = async (currentUrl) => {
- const isCnHref = currentUrl.includes(LEETCODE_URL_CN);
- setLang(isCnHref ? "zh" : "en");
-};
+// export const ALL_LANG_OPTIONS = {
+// zh: "简体中文",
+// en: "English",
+// };
export const setLang = (_lang) => {
lang = _lang || DEFAULT_LANG;
};
-const getForPath = (obj, path) => {
- const pathArr = path.split(".");
- let result = obj;
- for (const key of pathArr) {
- result = result[key];
+export const initLang = async (currentUrl) => {
+ if (isInit) return;
+ // 开发环境,可以通过url参数来切换语言
+ if (process.env.NODE_ENV === "development") {
+ const urlLang = getUrlParams(window.location.href)?.lang;
+ urlLang && setLang(urlLang);
+ return;
}
- return result;
+
+ const isCnHref = currentUrl.includes(LEETCODE_CN_URL);
+ setLang(isCnHref ? "zh" : "en");
+ isInit = true;
+};
+
+export const getLeetcodeUrlForLang = () => {
+ return lang === "zh" ? LEETCODE_CN_URL : LEETCODE_URL;
};
-export const t = (keypath, slotText,l) => {
- const langData ={ Locale: ALL_LANGS[l||lang] }
+/**
+ * @param {string} keypath
+ * @param {string | string[]} slotText
+ * @param {string} l lang
+ * @returns {string}
+ */
+export const t = (keypath, slotText, l) => {
+ const langData = { Locale: ALL_LANGS[l || lang] };
if (!keypath) return "";
- if (!keypath.includes("Locale")) {
- keypath = "Locale." + keypath
+ if (!keypath.includes("Locale")) {
+ keypath = "Locale." + keypath;
}
let content = getForPath(langData, keypath);
if (slotText) {
if (Array.isArray(slotText)) {
slotText.forEach((item, idx) => {
content = content.replace(`{${idx}}`, item);
- })
+ });
} else {
content = content.replace("{slotText}", slotText);
}
diff --git a/src/locales/zh.js b/src/locales/zh.js
index d8f3b57..f645ef3 100644
--- a/src/locales/zh.js
+++ b/src/locales/zh.js
@@ -1,5 +1,14 @@
export const cn = {
+
app: {
+ setLang: "设置语言",
+ changeLang: "切换为英文",
+ copy: "复制",
+ copySuccess: "复制成功~",
+ article: "文章",
+ recommendedQuestions: "推荐题目:",
+ toWriteSilently: "去默写",
+ contribution:"纠错 or 贡献其他语言",
back: "返回主页",
viewSolution: "查看本题题解",
viewInHandpickCollection: "该题已被收录到精选合集《{slotText}》点击查看",
@@ -33,8 +42,37 @@ export const cn = {
githubAPIError:
"使用 Github API 失败,已为您切换为普通模式,普通模式仅可自动带入题目名称,题目地址以及题解语言。",
},
+ problem: {
+ "743": "743. 网络延迟时间",
+ "1109": "1109. 航班预订统计",
+ "1314": "1314. 矩阵区域和",
+ "1462":"1462. 课程表 IV",
+ "1480": "1480. 一维数组的动态和",
+ "1584":"1584. 连接所有点的最小费用",
+ "2536": "2536. 子矩阵元素加 1",
+ },
codeTemplate: {
name: "代码模板",
+ perSum: {
+ title: "前缀和",
+ tips: "建议先学会之后再用模板。 如果你还不会的话,可以看看这篇",
+ item1: "一维前缀和",
+ item2: "二维前缀和",
+ item3: "一维差分数组",
+ item4: "二维差分数组",
+ },
+ graph: {
+ title: "图",
+ item1: "dijkstra(单源贪心最短路径)",
+ item2: "floyd_warshall(多源动态规划最短路径)",
+ item3: "Bellman–Ford(单源动态规划最短路径)",
+ item4: "Kruskal(又称加边法,是一种最小生成树算法)",
+ item5: "Prim(又称加点法,是一种最小生成树算法)",
+ item6: "Kahn(基于BFS的拓扑排序)",
+
+ },
+
+ moreTemplate:"更多模板后续陆续更新~"
},
dataStructureVisualization: {
name: "数据结构可视化",
diff --git a/src/utils.js b/src/utils.js
index 4a2f36a..3471ba2 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -343,3 +343,31 @@ export const addStyle = (css) => {
const head = document.getElementsByTagName("head")[0];
head.appendChild(style);
};
+
+/**
+ * 获取url参数
+ * @param {string} url
+ * @returns object
+ */
+export const getUrlParams = (url) => {
+ let urlStr = url.split("?")[1];
+ const urlSearchParams = new URLSearchParams(urlStr);
+ const result = Object.fromEntries(urlSearchParams.entries());
+ return result;
+};
+
+
+/**
+ * 获取对象指定路径的值
+ * @param {object} obj
+ * @param {string} path
+ * @returns any
+ */
+export const getForPath = (obj, path) => {
+ const pathArr = path.split(".");
+ let result = obj;
+ for (const key of pathArr) {
+ result = result[key];
+ }
+ return result;
+};
\ No newline at end of file
From 5f93f6cc1c2c341522d2a3d28a72b51616b7909e Mon Sep 17 00:00:00 2001
From: Renkin <906155099@qq.com>
Date: Tue, 31 Oct 2023 18:26:14 +0800
Subject: [PATCH 4/7] fix: button was inserted into the plugin
---
src/contentScript.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/contentScript.js b/src/contentScript.js
index 68ef2b1..ba774ae 100644
--- a/src/contentScript.js
+++ b/src/contentScript.js
@@ -541,6 +541,7 @@ const timerId = setInterval(() => {
clearInterval(timerId);
return console.error(t("app.initializeContentScriptFailed"));
}
+ if(document.title.includes("力扣加加")) return
insertButton();
// if (inserted && submitProxied) {
From 79260408d66411a189e75fe5c552558f5b08f03f Mon Sep 17 00:00:00 2001
From: Renkin <906155099@qq.com>
Date: Wed, 1 Nov 2023 11:34:29 +0800
Subject: [PATCH 5/7] chore: add comment
---
src/contentScript.js | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/src/contentScript.js b/src/contentScript.js
index ba774ae..853ea79 100644
--- a/src/contentScript.js
+++ b/src/contentScript.js
@@ -541,7 +541,10 @@ const timerId = setInterval(() => {
clearInterval(timerId);
return console.error(t("app.initializeContentScriptFailed"));
}
- if(document.title.includes("力扣加加")) return
+
+ // 防止 insertButton 在本插件应用中执行,会匹配到题目中包含 "Run" 的情况,例如:“1480. Running Sum of 1d Array”
+ if (document.title.includes("力扣加加")) return
+
insertButton();
// if (inserted && submitProxied) {
From 60130b837d89c7200330cd610129eb57a14f9cd9 Mon Sep 17 00:00:00 2001
From: Renkin <906155099@qq.com>
Date: Wed, 1 Nov 2023 11:35:48 +0800
Subject: [PATCH 6/7] feat: Adjust lang button position
---
src/App.css | 2 +-
src/App.js | 27 ++++++++++++++-------------
src/locales/en.js | 2 +-
src/locales/zh.js | 2 +-
4 files changed, 17 insertions(+), 16 deletions(-)
diff --git a/src/App.css b/src/App.css
index 75aafef..8849a09 100644
--- a/src/App.css
+++ b/src/App.css
@@ -35,7 +35,7 @@
height: 30px;
}
.guide-wrapper {
- display: flex;
+ display: inline-flex;
}
.ant-layout-sider {
background: none;
diff --git a/src/App.js b/src/App.js
index 2b4a1bf..1967262 100644
--- a/src/App.js
+++ b/src/App.js
@@ -1,4 +1,4 @@
-import React, { useState, Suspense, useEffect } from "react";
+import React, { useState, Suspense } from "react";
import { Button, Table, Empty, Tabs, Image } from "antd";
import "highlight.js/styles/github.css";
@@ -23,6 +23,7 @@ import CodeTemplates from "./codeTemplates/codeTemplate";
import ComplexityRating from "./complexityRating/index";
import SolutionTemplate from "./solutionTemplate/index";
import { t, initLang, setLang, lang } from "./locales";
+
// import { data as a } from "./db/binary-tree";
const DataStrutureVis = isInExtension()
@@ -82,6 +83,7 @@ const columns = [
},
];
const initialTab = getUrlParameter("tab") || "code-template";
+const isDev = process.env.NODE_ENV === "development";
function App() {
// eslint-disable-next-line
chrome &&
@@ -91,6 +93,7 @@ function App() {
console.log("[leetcode 插件打印]:chrome.tabs.query", tabs);
const currentUrl = tabs[0].url;
initLang(currentUrl);
+ setLangReady(true);
const match = currentUrl.match(/problems\/(.+?)\//);
const problemId = match && match[1];
setProblemId(problemId);
@@ -106,7 +109,8 @@ function App() {
// setHasSolution(!!problems[problemId]);
// }, 1000);
- const [langReady, setLangReady] = useState(false);
+ // 开发环境不需要依赖 chrome 插件 query 函数
+ const [langReady, setLangReady] = useState(isDev);
const [problemId, setProblemId] = useState("");
const [hasSolution, setHasSolution] = useState(false);
@@ -114,12 +118,6 @@ function App() {
const [page, setPage] = useState("");
const [tab, setTab] = useState(initialTab);
- useEffect(() => {
- process.env.NODE_ENV === "development" && initLang();
- setLangReady(true);
- }, []);
-
-
// const [inLeetCode, setInLeetCode] = useState(true);
// if (!inLeetCode) return window.open(LEETCODE_CN_URL + "/problemset/all/");
@@ -156,6 +154,14 @@ function App() {
+
+ {t("app.changeLang")}
+
{isInExtension() && (
<>
@@ -284,11 +290,6 @@ function App() {
-
-
- {t("app.changeLang")}
-
-
)}
diff --git a/src/locales/en.js b/src/locales/en.js
index cae4471..12db0b7 100644
--- a/src/locales/en.js
+++ b/src/locales/en.js
@@ -1,7 +1,7 @@
export const en = {
app: {
setLang: "Set Language",
- changeLang: "Switch to Chinese",
+ changeLang: "中文",
copy: "copy",
copySuccess: "Copy successfully~",
article: "article",
diff --git a/src/locales/zh.js b/src/locales/zh.js
index f645ef3..4dee4a9 100644
--- a/src/locales/zh.js
+++ b/src/locales/zh.js
@@ -2,7 +2,7 @@ export const cn = {
app: {
setLang: "设置语言",
- changeLang: "切换为英文",
+ changeLang: "English",
copy: "复制",
copySuccess: "复制成功~",
article: "文章",
From 546d794c5d2ec4e35ce894749656095cd5ecb60b Mon Sep 17 00:00:00 2001
From: Renkin <906155099@qq.com>
Date: Wed, 1 Nov 2023 11:36:47 +0800
Subject: [PATCH 7/7] feat: Optimize the language configuration logic
---
src/locales/index.js | 17 +++++++++--------
1 file changed, 9 insertions(+), 8 deletions(-)
diff --git a/src/locales/index.js b/src/locales/index.js
index 9711797..a5d0da2 100644
--- a/src/locales/index.js
+++ b/src/locales/index.js
@@ -1,9 +1,16 @@
-import { getUrlParams, getForPath, } from "../utils";
+import { getUrlParams, getForPath } from "../utils";
import { LEETCODE_CN_URL, LEETCODE_URL } from "../constant";
import zh from "./zh";
import en from "./en";
-const DEFAULT_LANG = "zh";
+const DEV_URL_LANG =
+ process.env.NODE_ENV === "development"
+ ? getUrlParams(window.location.href)?.lang
+ : undefined;
+
+// 支持在 url 中传入 lang 参数,否则本地开发刷新页面后会恢复为默认语言
+const DEFAULT_LANG = DEV_URL_LANG || "zh";
+
let isInit = false;
export let lang = DEFAULT_LANG;
@@ -24,12 +31,6 @@ export const setLang = (_lang) => {
export const initLang = async (currentUrl) => {
if (isInit) return;
- // 开发环境,可以通过url参数来切换语言
- if (process.env.NODE_ENV === "development") {
- const urlLang = getUrlParams(window.location.href)?.lang;
- urlLang && setLang(urlLang);
- return;
- }
const isCnHref = currentUrl.includes(LEETCODE_CN_URL);
setLang(isCnHref ? "zh" : "en");