From 3dcd2852b109edbc0b7c52fec83594472b8332b2 Mon Sep 17 00:00:00 2001 From: Owen Young Date: Tue, 15 Nov 2022 18:03:33 +0800 Subject: [PATCH] remove selected text translation --- CHANGELOG.md | 7 + gulpfile.js | 2 +- readme.md | 14 +- src/_locales/zh_CN/messages.json | 7 +- src/_locales/zh_TW/messages.json | 4 + src/background/background.js | 100 +-- src/background/chrome_background.js | 97 +-- src/background/textToSpeech.js | 201 ----- src/chrome_manifest.json | 42 +- src/contentScript/enhance.js | 24 +- src/contentScript/popupMobile.js | 17 - src/lib/config.js | 20 +- src/lib/specialRules.js | 53 +- src/manifest.json | 49 +- src/options/options.html | 1136 ++------------------------ src/options/options.js | 220 +---- src/popup/old-popup.js | 9 +- src/popup/popup-change-language.html | 133 --- src/popup/popup-change-language.js | 97 --- src/popup/popup-translate-text.html | 139 ---- src/popup/popup-translate-text.js | 305 ------- 21 files changed, 181 insertions(+), 2495 deletions(-) delete mode 100644 src/background/textToSpeech.js delete mode 100644 src/popup/popup-change-language.html delete mode 100644 src/popup/popup-change-language.js delete mode 100644 src/popup/popup-translate-text.html delete mode 100644 src/popup/popup-translate-text.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fa99e3c..826c7f7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ ## 0.0.25 - Support gist.github.com +- Support slack.com +- Fix 1paragraph.app epub adapt + +### Break Changes + +- Remove select text to translate, now the extension is focus on web page translate +- Better for Options ## 0.0.24 diff --git a/gulpfile.js b/gulpfile.js index 7c02f748..a03b1445 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -65,7 +65,7 @@ gulp.task("chrome-babel", () => { }); gulp.task("chrome-concat-background",()=>{ - return gulp.src(["/lib/languages.js", "/lib/config.js", "/lib/platformInfo.js","/lib/util.js", "/background/translationCache.js", "/background/translationService.js", "/background/textToSpeech.js", "/background/chrome_background.js"].map(item=>"dist/chrome"+item)) + return gulp.src(["/lib/languages.js", "/lib/config.js", "/lib/platformInfo.js","/lib/util.js", "/background/translationCache.js", "/background/translationService.js", "/background/chrome_background.js"].map(item=>"dist/chrome"+item)) .pipe(concat('background-entry.js')) .pipe(gulp.dest('dist/chrome/background')); }) diff --git a/readme.md b/readme.md index d8d90387..9a2685e4 100644 --- a/readme.md +++ b/readme.md @@ -17,6 +17,8 @@ Let's experience immersive web translation, with bilingual simultaneous display - 支持PDF文件双语对照翻译(pdf文件翻译需要点击浏览器右上角的该扩展图标,弹出提示框后按提示框操作) - 配合epub在线阅读网站 即可实现双语阅读国外电子书 +> 已删除原扩展选中文本翻译功能,此扩展现在仅 Focus 网页翻译。划词翻译功能请使用其他同类产品~ + **视频介绍** [![Demo](https://img.youtube.com/vi/9TzX0xEBmyw/0.jpg)](https://www.youtube.com/watch?v=9TzX0xEBmyw) @@ -32,7 +34,7 @@ Let's experience immersive web translation, with bilingual simultaneous display - 希望同时显示双语,以平衡部分机器翻译的不知所云 - 希望尽快摆脱这个扩展,直接习惯看原文的用户的过渡助手 -该扩展同时支持(依赖)谷歌翻译引擎或Yandex翻译引擎,同时也支持使用Bing,Deepl进行文本选中翻译,完全免费,希望我们都能尽可能平等的获取知识,不要让语言成为障碍,感谢[原作者](https://github.com/FilipePS/Traduzir-paginas-web)为这个项目付出的巨大努力。 +该扩展同时支持(依赖)谷歌翻译引擎或Yandex翻译引擎,完全免费,希望我们都能尽可能平等的获取知识,不要让语言成为障碍,感谢[原作者](https://github.com/FilipePS/Traduzir-paginas-web)为这个项目付出的巨大努力。 本项目的[Wiki页面](https://github.com/immersive-translate/immersive-translate/wiki)下有更多使用帮助信息。 @@ -86,7 +88,7 @@ Google翻译会调用该接口: `https://translate.googleapis.com/translate_a/ 目前已有的规则见[这里](https://github.com/immersive-translate/immersive-translate/blob/main/src/lib/specialRules.js) -你可以点击浏览器该扩展图标 -> 选项(进入扩展配置页面) -> 网站配置 -> 特殊页面翻译规则 来进入页面规则配置, +你可以点击浏览器该扩展图标 -> 选项(进入扩展配置), 滑动到最后,即可看到特殊页面规则配置, 一个基本的配置规则如下: @@ -105,7 +107,7 @@ Google翻译会调用该接口: `https://translate.googleapis.com/translate_a/ ### 双语显示样式配置 -默认的双语显示没有添加任何样式,但是我们提供了内置的几种样式可供选择,你可以从`配置->样式->双语显示主题配置`来更改样式,比如下划线样式长这样: +默认的双语显示没有添加任何样式,但是我们提供了内置的几种样式可供选择,你可以从`配置->常用配置->双语显示主题配置`来更改样式,比如下划线样式长这样: ![twitter](assets/twitter.png) @@ -215,9 +217,9 @@ Some pages like [support.mozilla.org](https://support.mozilla.org/) and [addons. - [x] - adapt for Github - [x] - backup默认文件名还是TWP -- [ ] - option页面从extension中打开的显示问题 +- [x] - option页面从extension中打开的显示问题 - [x] - 版本号自动添加 - [x] - youtube comments - [x] - better for github -- [ ] - check is target language, if so ,do not translate -- [ ] - read mode +- [x] - check is target language, if so ,do not translate +- [x] - read mode diff --git a/src/_locales/zh_CN/messages.json b/src/_locales/zh_CN/messages.json index d52e25c1..40c94726 100644 --- a/src/_locales/zh_CN/messages.json +++ b/src/_locales/zh_CN/messages.json @@ -372,7 +372,7 @@ "message": "翻译页面为目标语言" }, "lblTranslateTag_pre": { - "message": "启用对 $HTML_TAG_NAME$ 标签的翻译", + "message": "启用对 $HTML_TAG_NAME$ 标签(常用于代码块)的翻译", "placeholders": { "HTML_TAG_NAME": { "content": "
"
@@ -383,7 +383,7 @@
     "message": "不对 Google 翻译结果进行排序"
   },
   "lbltranslatedynamicallycreatedcontent": {
-    "message": "翻译动态创建的内容"
+    "message": "是否翻译加载更多后的内容"
   },
   "calculatestorage": {
     "message": "计算"
@@ -525,6 +525,9 @@
   },
   "lblTelegram":{
     "message": "加Telegram群"
+  },
+  "msgCommon":{
+    "message":"常用配置"
   }
  
 }
diff --git a/src/_locales/zh_TW/messages.json b/src/_locales/zh_TW/messages.json
index e778961e..ac76a162 100644
--- a/src/_locales/zh_TW/messages.json
+++ b/src/_locales/zh_TW/messages.json
@@ -522,6 +522,10 @@
   },
     "lblTelegram":{
     "message": "加Telegram群"
+  },
+"msgCommon":{
+    "message":"常用設置"
   }
 
+
 }
diff --git a/src/background/background.js b/src/background/background.js
index 3ee18c9b..8365f8b7 100644
--- a/src/background/background.js
+++ b/src/background/background.js
@@ -97,18 +97,6 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
     }
 })
 
-function updateTranslateSelectedContextMenu() {
-    if (typeof chrome.contextMenus !== "undefined") {
-        chrome.contextMenus.remove("translate-selected-text", checkedLastError)
-        if (twpConfig.get("showTranslateSelectedContextMenu") === "yes") {
-            chrome.contextMenus.create({
-                id: "translate-selected-text",
-                title: chrome.i18n.getMessage("msgTranslateSelectedText"),
-                contexts: ["selection"]
-            })
-        }
-    }
-}
 
 function updateContextMenu(pageLanguageState = "original") {
     let contextMenuTitle
@@ -249,22 +237,6 @@ if (typeof chrome.contextMenus !== "undefined") {
                   action: "toggle-translation"
               }, checkedLastError)
             }
-        } else if (info.menuItemId == "translate-selected-text") {
-            if (chrome.pageAction && chrome.pageAction.openPopup && (!tabHasContentScript[tab.id] || tab.isInReaderMode)) {
-                chrome.pageAction.setPopup({
-                    popup: "popup/popup-translate-text.html#text=" + encodeURIComponent(info.selectionText),
-                    tabId: tab.id
-                })
-                chrome.pageAction.openPopup()
-
-                resetPageAction(tab.id)
-            } else {
-                // a merda do chrome não suporte openPopup
-                chrome.tabs.sendMessage(tab.id, {
-                    action: "TranslateSelectedText",
-                    selectionText: info.selectionText
-                }, checkedLastError)
-            }
         } else if (info.menuItemId == "browserAction-showPopup") {
             resetBrowserAction(true)
 
@@ -525,6 +497,7 @@ twpConfig.onReady(() => {
 
 if (typeof chrome.commands !== "undefined") {
     chrome.commands.onCommand.addListener(command => {
+        console.log("command", command)
         if (command === "hotkey-toggle-translation") {
             chrome.tabs.query({
                 currentWindow: true,
@@ -534,14 +507,6 @@ if (typeof chrome.commands !== "undefined") {
                     action: "toggle-translation"
                 }, checkedLastError)
             })
-        } else if (command === "hotkey-translate-selected-text") {
-            chrome.tabs.query({
-                currentWindow: true,
-                active: true
-            }, tabs =>
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "TranslateSelectedText"
-                }, checkedLastError))
         } else if (command === "hotkey-swap-page-translation-service") {
             chrome.tabs.query({
                 active: true,
@@ -559,72 +524,15 @@ if (typeof chrome.commands !== "undefined") {
             }
 
             twpConfig.set("pageTranslatorService", currentPageTranslatorService)
-        } else if (command === "hotkey-show-original") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs =>
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "translatePage",
-                    targetLanguage: "original"
-                }, checkedLastError))
-        } else if (command === "hotkey-translate-page-1") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs => {
-                twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[0])
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "translatePage",
-                    targetLanguage: twpConfig.get("targetLanguages")[0]
-                }, checkedLastError)
-            })
-        } else if (command === "hotkey-translate-page-2") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs => {
-                twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[1])
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "translatePage",
-                    targetLanguage: twpConfig.get("targetLanguages")[1]
-                }, checkedLastError)
-            })
-        } else if (command === "hotkey-translate-page-3") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs => {
-                twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[2])
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "translatePage",
-                    targetLanguage: twpConfig.get("targetLanguages")[2]
-                }, checkedLastError)
-            })
-        } else if (command === "hotkey-hot-translate-selected-text") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs => {
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "hotTranslateSelectedText"
-                }, checkedLastError)
-            })
-        }
+        } 
+
     })
 }
 
 twpConfig.onReady(async () => {
     updateContextMenu()
-    updateTranslateSelectedContextMenu()
-
-    twpConfig.onChanged((name, newvalue) => {
-        if (name === "showTranslateSelectedContextMenu") {
-            updateTranslateSelectedContextMenu()
-        }
-    })
 
-    if (!twpConfig.get("installDateTime")) {
+     if (!twpConfig.get("installDateTime")) {
         twpConfig.set("installDateTime", Date.now())
     }
 })
diff --git a/src/background/chrome_background.js b/src/background/chrome_background.js
index 5b27a687..84852b57 100644
--- a/src/background/chrome_background.js
+++ b/src/background/chrome_background.js
@@ -98,18 +98,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
 
 })
 
-function updateTranslateSelectedContextMenu() {
-    if (typeof chrome.contextMenus !== "undefined") {
-        chrome.contextMenus.remove("translate-selected-text", checkedLastError)
-        if (twpConfig.get("showTranslateSelectedContextMenu") === "yes") {
-            chrome.contextMenus.create({
-                id: "translate-selected-text",
-                title: chrome.i18n.getMessage("msgTranslateSelectedText"),
-                contexts: ["selection"]
-            })
-        }
-    }
-}
+
 
 function updateContextMenu(pageLanguageState = "original") {
     let contextMenuTitle
@@ -249,23 +238,6 @@ if (typeof chrome.contextMenus !== "undefined") {
                   action: "toggle-translation"
               }, checkedLastError)
             }
-        } else if (info.menuItemId == "translate-selected-text") {
-            if (chrome.action && chrome.action.openPopup && (!tabHasContentScript[tab.id] || tab.isInReaderMode)) {
-
-                chrome.action.setPopup({
-                    popup: "popup/popup-translate-text.html#text=" + encodeURIComponent(info.selectionText),
-                    tabId: tab.id
-                })
-                chrome.action.openPopup()
-
-                resetPageAction(tab.id)
-            } else {
-                // a merda do chrome não suporte openPopup
-                chrome.tabs.sendMessage(tab.id, {
-                    action: "TranslateSelectedText",
-                    selectionText: info.selectionText
-                }, checkedLastError)
-            }
         } else if (info.menuItemId == "browserAction-showPopup") {
             resetBrowserAction(true)
 
@@ -535,14 +507,6 @@ if (typeof chrome.commands !== "undefined") {
                     action: "toggle-translation"
                 }, checkedLastError)
             })
-        } else if (command === "hotkey-translate-selected-text") {
-            chrome.tabs.query({
-                currentWindow: true,
-                active: true
-            }, tabs =>
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "TranslateSelectedText"
-                }, checkedLastError))
         } else if (command === "hotkey-swap-page-translation-service") {
             chrome.tabs.query({
                 active: true,
@@ -560,70 +524,13 @@ if (typeof chrome.commands !== "undefined") {
             }
 
             twpConfig.set("pageTranslatorService", currentPageTranslatorService)
-        } else if (command === "hotkey-show-original") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs =>
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "translatePage",
-                    targetLanguage: "original"
-                }, checkedLastError))
-        } else if (command === "hotkey-translate-page-1") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs => {
-                twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[0])
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "translatePage",
-                    targetLanguage: twpConfig.get("targetLanguages")[0]
-                }, checkedLastError)
-            })
-        } else if (command === "hotkey-translate-page-2") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs => {
-                twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[1])
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "translatePage",
-                    targetLanguage: twpConfig.get("targetLanguages")[1]
-                }, checkedLastError)
-            })
-        } else if (command === "hotkey-translate-page-3") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs => {
-                twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[2])
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "translatePage",
-                    targetLanguage: twpConfig.get("targetLanguages")[2]
-                }, checkedLastError)
-            })
-        } else if (command === "hotkey-hot-translate-selected-text") {
-            chrome.tabs.query({
-                active: true,
-                currentWindow: true
-            }, tabs => {
-                chrome.tabs.sendMessage(tabs[0].id, {
-                    action: "hotTranslateSelectedText"
-                }, checkedLastError)
-            })
-        }
+        } 
     })
 }
 
 twpConfig.onReady(async () => {
     updateContextMenu()
-    updateTranslateSelectedContextMenu()
 
-    twpConfig.onChanged((name, newvalue) => {
-        if (name === "showTranslateSelectedContextMenu") {
-            updateTranslateSelectedContextMenu()
-        }
-    })
 
     if (!twpConfig.get("installDateTime")) {
         twpConfig.set("installDateTime", Date.now())
diff --git a/src/background/textToSpeech.js b/src/background/textToSpeech.js
deleted file mode 100644
index fefbbbe5..00000000
--- a/src/background/textToSpeech.js
+++ /dev/null
@@ -1,201 +0,0 @@
-"use strict";
-
-const textToSpeech = (function () {
-  const textToSpeech = {};
-
-  /**
-   * @callback Callback_Speech_cbGetExtraParameters
-   * @param {string} text
-   * @param {string} targetLanguage
-   * @return {string} urlParamsString
-   */
-
-  class Service {
-    /**
-     * Defines the Service class for the text-to-speech service.
-     * @param {string} serviceName
-     * @param {string} baseURL
-     * @param {"GET" | "POST"} xhrMethod
-     * @param {Callback_Speech_cbGetExtraParameters} cbGetExtraParameters
-     */
-    constructor(serviceName, baseURL, xhrMethod, cbGetExtraParameters) {
-      this.serviceName = serviceName;
-      this.baseURL = baseURL;
-      this.xhrMethod = xhrMethod;
-      this.cbGetExtraParameters = cbGetExtraParameters;
-      /** @type {Map} */
-      this.audios = new Map();
-      this.audioSpeed = 1.0;
-    }
-
-    /**
-     * Takes a long text and splits the text into an array of strings. Each string will be less than 170 characters.
-     *
-     * The goal is not to exceed the quota for text-to-speech services.
-     * @param {string} fullText
-     * @returns {string[]} requestStrings
-     */
-    getRequests(fullText) {
-      /** @type {string[]} */
-      const fullTextSplitted = [];
-      fullText
-        .trim()
-        .split(" ")
-        .forEach((word) => {
-          if (word.length > 160) {
-            while (word.length > 160) {
-              fullTextSplitted.push(word.slice(0, 160));
-              word = word.slice(160);
-            }
-            if (word.trim().length > 0) {
-              fullTextSplitted.push(word);
-            }
-          } else if (word.trim().length > 0) {
-            fullTextSplitted.push(word);
-          }
-        });
-
-      /** @type {string[]} */
-      const requests = [];
-      let requestString = "";
-      for (let text of fullTextSplitted) {
-        text += " ";
-        if (requestString.length + text.length < 170) {
-          requestString += text;
-        } else {
-          requests.push(requestString);
-          requestString = text;
-        }
-      }
-      if (requestString.trim().length > 0) {
-        requests.push(requestString);
-        requestString = "";
-      }
-
-      return requests;
-    }
-
-    /**
-     * Makes the request to the text-to-speech service and returns a promise that resolves with the result of the request.
-     *
-     * The promise is rejected if there is an error.
-     * @param {string} text
-     * @param {string} targetLanguage
-     * @returns {Promise} Promise\
-     */
-    async makeRequest(text, targetLanguage) {
-      return await new Promise(async (resolve, reject) => {
-        const response = await fetch(this.baseURL + this.cbGetExtraParameters(text, targetLanguage), {
-          method: this.xhrMethod,
-        });
-        const blob = await response.blob();
-
-          const reader = new FileReader();
-          reader.onloadend = () => resolve(reader.result);
-          reader.onerror = () => reject();
-          reader.readAsDataURL(blob);
-      });
-    }
-
-    /**
-     * Transform text into audio and play then.
-     * @param {string} fullText
-     * @param {string} targetLanguage
-     * @returns {Promise} Promise\
-     */
-    async textToSpeech(fullText, targetLanguage) {
-      const requests = this.getRequests(fullText);
-      const promises = [];
-
-      const resultObj = {};
-
-      for (const requestText of requests) {
-        const audioKey = [targetLanguage, requestText].join(", ");
-        if (!this.audios.get(audioKey)) {
-          promises.push(
-            this.makeRequest(requestText, targetLanguage)
-              .then(
-                /** @type {string} */ (response) => {
-                  resultObj[audioKey] = response;
-                  this.audios.set(audioKey,response);
-                  return response;
-                }
-              )
-              .catch((e) => {
-                console.error(e);
-                return null;
-              })
-          );
-        }else{
-          resultObj[audioKey] = this.audios.get(audioKey);
-        }
-      }
-      await Promise.all(promises);
-      return resultObj;
-    }
-
-
-    /**
-     * Sets the audio speed
-     * @param {number} speed
-     */
-    setAudioSpeed(speed) {
-      this.audioSpeed = speed;
-      this.audios.forEach((audio) => {
-        audio.playbackRate = this.audioSpeed;
-      });
-    }
-
-    /**
-     * Pause all audio and reset audio time to start
-     */
-    stopAll() {
-      this.audios.forEach((audio) => {
-        audio.pause();
-        audio.currentTime = 0;
-      });
-    }
-  }
-
-  // Create a Service instance based on google's text-to-speech service.
-  const googleService = new Service(
-    "google",
-    "https://translate.google.com/translate_tts?ie=UTF-8",
-    "GET",
-    function getExtraParameters(text, targetLanguage) {
-      return `&tl=${targetLanguage}&client=dict-chrome-ex&ttsspeed=0.5&q=${encodeURIComponent(
-        text
-      )}`;
-    }
-  );
-
-  // Listen for messages coming from contentScript or other scripts.
-  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
-    if (request.action === "getAudioURLs") {
-      googleService
-        .textToSpeech(request.text, request.targetLanguage)
-        .then((response) => {
-          sendResponse(response);
-        }).catch(e=>{
-          console.warn('fetch audios error',e)
-          sendResponse({})
-
-        });
-    
-
-      return true;
-    }  });
-
-  // Listen for changes to the audio speed setting and apply it immediately.
-  twpConfig.onReady(async () => {
-    twpConfig.onChanged((name, newvalue) => {
-      if (name === "ttsSpeed") {
-        googleService.setAudioSpeed(newvalue);
-      }
-    });
-  });
-
-  textToSpeech.google = googleService;
-
-  return textToSpeech;
-})();
diff --git a/src/chrome_manifest.json b/src/chrome_manifest.json
index 9b2073c7..2589ddd4 100644
--- a/src/chrome_manifest.json
+++ b/src/chrome_manifest.json
@@ -3,42 +3,16 @@
     "default_locale": "en",
     "name": "Immersive Translate",
     "description": "Let's experience immersive web translation, with bilingual simultaneous display and translation of only the important content.",
-    "version": "0.0.24.2",
+    "version": "0.0.25",
     "homepage_url": "https://github.com/immersive-translate/immersive-translate",
 
     "commands": {
         "hotkey-toggle-translation": {
             "suggested_key": {
-                "default": "Alt+T"
+                "default": "Ctrl+T",
+                "mac": "MacCtrl+T"
             },
             "description": "__MSG_lblSwitchTranslatedAndOriginal__"
-        },
-        "hotkey-translate-selected-text": {
-            "suggested_key": {
-                "default": "Alt+S"
-            },
-            "description": "__MSG_msgTranslateSelectedText__"
-        },
-        "hotkey-swap-page-translation-service": {
-            "suggested_key": {
-                "default": "Alt+Q"
-            },
-            "description": "__MSG_swapTranslationService__"
-        },
-        "hotkey-show-original": {
-            "description": "__MSG_lblRestorePageToOriginal__"
-        },
-        "hotkey-translate-page-1": {
-            "description": "__MSG_lblTranslatePageToTargetLanguage__ 1"
-        },
-        "hotkey-translate-page-2": {
-            "description": "__MSG_lblTranslatePageToTargetLanguage__ 2"
-        },
-        "hotkey-translate-page-3": {
-            "description": "__MSG_lblTranslatePageToTargetLanguage__ 3"
-        },
-        "hotkey-hot-translate-selected-text": {
-            "description": "__MSG_lblHotTranslatedSelectedText__"
         }
     },
 
@@ -73,7 +47,7 @@
 
     "options_ui": {
         "page": "/options/options.html",
-        "open_in_tab": false,
+        "open_in_tab": true,
         "browser_style": false
     },
 
@@ -101,19 +75,13 @@
             "run_at": "document_end",
             "all_frames": true,
             "match_about_blank": true,
-            "js": ["/lib/i18n.js", "/contentScript/showOriginal.js", "/lib/specialRules.js", "/contentScript/enhance.js", "/contentScript/pageTranslator.js","/contentScript/play.js", "/contentScript/translateSelected.js", "/contentScript/showTranslated.js"]
+            "js": ["/lib/i18n.js", "/contentScript/showOriginal.js", "/lib/specialRules.js", "/contentScript/enhance.js", "/contentScript/pageTranslator.js"]
         },
         {
             "matches": [""],
             "run_at": "document_end",
             "all_frames": false,
             "js": ["/contentScript/popupMobile.js"]
-        },
-        {
-            "matches": ["https://www.deepl.com/translator*"],
-            "run_at": "document_end",
-            "all_frames": false,
-            "js": ["/contentScript/deepl.js"]
         }
     ],
     "background": {
diff --git a/src/contentScript/enhance.js b/src/contentScript/enhance.js
index c4362622..1e6bf03d 100644
--- a/src/contentScript/enhance.js
+++ b/src/contentScript/enhance.js
@@ -299,18 +299,26 @@ async function getNodesThatNeedToTranslate(root,ctx,options){
   // check node language is target language, if yes, remove it
 
   let newAllNodes = [];
-  for(const node of allNodes){
-    const nodeText = node.innerText;
-    if(nodeText && nodeText.trim().length>0){
-      const lang = await detectLanguage(nodeText);
-      if(lang && !checkIsSameLanguage(lang,currentTargetLanguage,ctx)){
-        // only translate the clearly language
-        newAllNodes.push(node);
+
+  if((pageSpecialConfig && pageSpecialConfig.detectLanguage===true)){
+    // only check when detectLanguage is not false
+    if(allNodes.length<500){
+      for(const node of allNodes){
+        const nodeText = node.innerText;
+        if(nodeText && nodeText.trim().length>0){
+            const lang = await detectLanguage(nodeText);
+            if(lang && !checkIsSameLanguage(lang,currentTargetLanguage,ctx)){
+              // only translate the clearly language
+              newAllNodes.push(node);
+            }
+
+        }
       }
+      allNodes = newAllNodes;
     }
   }
 
-  allNodes = newAllNodes;
+
 
   if(!isShowDualLanguage){
       return allNodes;
diff --git a/src/contentScript/popupMobile.js b/src/contentScript/popupMobile.js
index 39e404af..fbd10494 100644
--- a/src/contentScript/popupMobile.js
+++ b/src/contentScript/popupMobile.js
@@ -26,7 +26,6 @@ Promise.all([twpConfig.onReady(), getTabHostName()])
             
- Languages - Sites + Common Translations - Style Hotkeys Storage Others @@ -30,6 +27,8 @@

Immersive Translate

class="w3-bar-item w3-button w3-padding" data-i18n="lblReport">Report a problem Telegram Group + Github @@ -55,30 +54,25 @@

Immersive Translate

-
-

Target languages

-
    -
  • -

    Target language 1

    - -
  • -
  • -

    Target language 2

    - -
  • -
  • -

    Target language 3

    - -
  • -
-
+
+
+
+

Target language

+
+
+
+ +
+
+
+

Never translate these languages

- @@ -103,41 +97,20 @@

Immersive Translate

-
    -
    -
    -
    -
    -
    -

    Show translated text when hovering over sites - with these languages

    -
    -
    -
    - - -
    -
    -
    -
      +
        -
        - -
        +

        Always translate these sites

        -
        -
          +

            @@ -145,40 +118,50 @@

            Immersive Translate

            Never translate these sites

            -
            -
              -
              -
              -
              -
              -

              Show translated text when hovering on these - sites

              -
              -
              - -
              +
                +
                +
                +
                +

                Is show dual language?

                +
                +
                +
                +
                -
                  +
                  -
                  -
                  -
                  -
                  -

                  add to custom dictionary (This allows you to skip certain words during web page translation)

                  -
                  -
                  - -
                  -
                  -
                    +
                    + +
                    +
                    +

                    Bilingual display effect theme options

                    +
                    +
                    +
                    + +
                    +
                    +
                    + +

                    Custom bilingual display CSS style (advanced, will override the default theme)

                    +   
                    +
                    Exmaple:  border-bottom: 2px solid #72ECE9;
                    +

                    Special Rules (Advanced)

                    @@ -198,55 +181,26 @@

                    Immersive Translate


                    -

                    Text Translation Service

                    - -
                    -

                    Text-to-speech audio speed

                    - - 1.0 -

                    Translate dynamically created content


                    -

                    Show the button to translate the selected text

                    - -
                    - - -
                    - - -
                    - - -
                    - - -

                    -

                    Show original text when hovering

                    - +
                    +
                    +

                    add to custom dictionary (This allows you to skip certain words during web page translation)

                    +
                    +
                    + +
                    +
                    +
                      -

                      Automatically translate when clicking on a link that takes you to the same domain as the current site

                      -
                      -
                      -

                      Enable DeepL as a text translation service

                      - -
                      -
                      - -
                      - -

                      Is show dual language?

                      - - - -

                      Bilingual display effect theme options

                      - - -

                      Custom bilingual display CSS style (advanced, will override the default theme)

                      -    -
                      -
                      Exmaple:  border-bottom: 2px solid #72ECE9;
                      - - - -

                      Dark mode

                      - - -
                      -

                      Make the pop-up icon blue when the site is - translated

                      - -
                      - -

                      Special keyboard shortcuts

                      -
                        -
                      • -
                      • -
                      -

                      Keyboard shortcuts

                        @@ -346,14 +243,6 @@

                        Immersive Translate

                        -
                        -

                        Show release notes when updating

                        - -
                        -

                        Show the mobile popup


                        -

                        Show the option to translate the selected text in - the context menu

                        - -
                        +

                        Translate the page by clicking once on the button in the address bar. (To see the popup, right-click)

                        - - - - - - -
                        - - - - - - - - diff --git a/src/popup/popup-change-language.js b/src/popup/popup-change-language.js deleted file mode 100644 index 9c16d4ce..00000000 --- a/src/popup/popup-change-language.js +++ /dev/null @@ -1,97 +0,0 @@ -"use strict"; - -let $ = document.querySelector.bind(document); - -const selectTargetLanguage = $("select") - -$("#btnClose").addEventListener("click", () => { - window.location = "popup.html" -}) - -$("#btnApply").addEventListener("click", () => { - twpConfig.setTargetLanguage(selectTargetLanguage.value, true) - window.location = "popup.html" -}) - -twpConfig.onReady(function () { - let langs = twpLang.getLanguageList() - - const langsSorted = [] - - for (const i in langs) { - langsSorted.push([i, langs[i]]) - } - - langsSorted.sort(function (a, b) { - return a[1].localeCompare(b[1]); - }) - - const eAllLangs = selectTargetLanguage.querySelector('[name="all"]') - langsSorted.forEach(value => { - const option = document.createElement("option") - option.value = value[0] - option.textContent = value[1] - eAllLangs.appendChild(option) - }) - - const eRecentsLangs = selectTargetLanguage.querySelector('[name="targets"]') - for (const value of twpConfig.get("targetLanguages")) { - const option = document.createElement("option") - option.value = value - option.textContent = langs[value] - eRecentsLangs.appendChild(option) - } - selectTargetLanguage.value = twpConfig.get("targetLanguages")[0] - - function disableDarkMode() { - if (!$("#lightModeElement")) { - const el = document.createElement("style") - el.setAttribute("id", "lightModeElement") - el.setAttribute("rel", "stylesheet") - el.textContent = ` - body { - color: rgb(0, 0, 0); - background-color: rgb(224, 224, 224); - } - - .select, #btnApply { - color: black; - background-color: rgba(0, 0, 0, 0.2); - } - - .select:hover, #btnApply:hover { - background-color: rgba(0, 0, 0, 0.4); - } - - .mdiv, .md { - background-color: rgb(0, 0, 0); - } - ` - document.head.appendChild(el) - } - } - - function enableDarkMode() { - if ($("#lightModeElement")) { - $("#lightModeElement").remove() - } - } - - switch (twpConfig.get("darkMode")) { - case "auto": - if (matchMedia("(prefers-color-scheme: dark)").matches) { - enableDarkMode() - } else { - disableDarkMode() - } - break - case "yes": - enableDarkMode() - break - case "no": - disableDarkMode() - break - default: - break - } -}) diff --git a/src/popup/popup-translate-text.html b/src/popup/popup-translate-text.html deleted file mode 100644 index e997a962..00000000 --- a/src/popup/popup-translate-text.html +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - - - - - - - -
                        -
                        -
                        -
                        -
                        -
                        -
                        -
                          -
                        • en
                        • -
                        • es
                        • -
                        • de
                        • -
                        -
                          -
                        • g
                        • -
                        • y
                        • -
                        • b
                        • - -
                        -
                          -
                        • - - - - - - -
                        • -
                        • - - - - - -
                        • -
                        -
                        -
                        - - - - - - - - - diff --git a/src/popup/popup-translate-text.js b/src/popup/popup-translate-text.js deleted file mode 100644 index dcf62d44..00000000 --- a/src/popup/popup-translate-text.js +++ /dev/null @@ -1,305 +0,0 @@ -"use strict"; - -let $ = document.querySelector.bind(document); - -twpConfig.onReady(function () { - function backgroundTranslateSingleText(translationService, targetLanguage, source) { - return new Promise((resolve, reject) => { - chrome.runtime.sendMessage({ - action: "translateSingleText", - translationService, - targetLanguage, - source - }, response => { - resolve(response) - }) - }) - } - - let currentTargetLanguages = twpConfig.get("targetLanguages") - let currentTargetLanguage = twpConfig.get("targetLanguageTextTranslation") - let currentTextTranslatorService = twpConfig.get("textTranslatorService") - - function disableDarkMode() { - if (!document.getElementById("lightModeElement")) { - const el = document.createElement("style") - el.setAttribute("id", "lightModeElement") - el.setAttribute("rel", "stylesheet") - el.textContent = ` - body { - color: rgb(0, 0, 0) !important; - background-color: rgb(215, 215, 215) !important; - } - .selected { - background-color: rgba(0, 0, 0, 0.6) !important; - } - hr { - width: 95%; - border: 1px rgba(0, 0, 0, 0.75) solid; - } - ` - document.body.appendChild(el) - document.querySelector("#listen svg").style = "fill: rgb(0, 0, 0)" - } - } - - function enableDarkMode() { - if (document.getElementById("#lightModeElement")) { - document.getElementById("#lightModeElement").remove() - document.querySelector("#listen svg").style = "fill: black" - } - } - - switch (twpConfig.get("darkMode")) { - case "auto": - if (matchMedia("(prefers-color-scheme: dark)").matches) { - enableDarkMode() - } else { - disableDarkMode() - } - break - case "yes": - enableDarkMode() - break - case "no": - disableDarkMode() - break - default: - break - } - - let isPlayingAudio = false - - function playAudio(text, targetLanguage, cbOnEnded=() => {}) { - isPlayingAudio = true - audioPlayer.textToSpeech(text, targetLanguage).then(()=>{ - isPlayingAudio = false - cbOnEnded() - }) - // chrome.runtime.sendMessage({ - // action: "textToSpeech", - // text, - // targetLanguage - // }, () => { - // isPlayingAudio = false - // cbOnEnded() - // }) - } - - function stopAudio() { - if (isPlayingAudio) { - chrome.runtime.sendMessage({ - action: "stopAudio" - }) - } - isPlayingAudio = false - } - - function stopAudio() { - if (isPlayingAudio) { - audioPlayer.stopAll() - // chrome.runtime.sendMessage({ - // action: "stopAudio" - // }) - } - isPlayingAudio = false - } - - - const eOrigText = document.getElementById("eOrigText") - const eOrigTextDiv = document.getElementById("eOrigTextDiv") - const eTextTranslated = document.getElementById("eTextTranslated") - - const sGoogle = document.getElementById("sGoogle") - const sYandex = document.getElementById("sYandex") - const sBing = document.getElementById("sBing") - const sDeepL = document.getElementById("sDeepL") - const eCopy = document.getElementById("copy") - const eListen = document.getElementById("listen") - - eCopy.onclick = () => { - navigator.clipboard.writeText(eTextTranslated.textContent).then(async () => { - eCopy.style.backgroundColor = "rgba(0, 255, 0, 0.4)" - setTimeout(() => { - eCopy.style.backgroundColor = "rgba(0, 0, 0, 0.4)" - }, 500) - }) - } - - function setCaretAtEnd() { - const el = eOrigText - const range = document.createRange() - const sel = window.getSelection() - range.setStart(el, 1) - range.collapse(true) - sel.removeAllRanges() - sel.addRange(range) - el.focus() - } - - let translateNewInputTimerHandler - eOrigText.oninput = () => { - clearTimeout(translateNewInputTimerHandler) - translateNewInputTimerHandler = setTimeout(translateText, 800) - } - - sGoogle.onclick = () => { - currentTextTranslatorService = "google" - twpConfig.set("textTranslatorService", "google") - translateText() - - sGoogle.classList.remove("selected") - sYandex.classList.remove("selected") - sBing.classList.remove("selected") - sDeepL.classList.remove("selected") - - sGoogle.classList.add("selected") - } - sYandex.onclick = () => { - currentTextTranslatorService = "yandex" - twpConfig.set("textTranslatorService", "yandex") - translateText() - - sGoogle.classList.remove("selected") - sYandex.classList.remove("selected") - sBing.classList.remove("selected") - sDeepL.classList.remove("selected") - - sYandex.classList.add("selected") - } - sBing.onclick = () => { - currentTextTranslatorService = "bing" - twpConfig.set("textTranslatorService", "bing") - translateText() - - sGoogle.classList.remove("selected") - sYandex.classList.remove("selected") - sBing.classList.remove("selected") - sDeepL.classList.remove("selected") - - sBing.classList.add("selected") - } - sDeepL.onclick = () => { - currentTextTranslatorService = "deepl" - twpConfig.set("textTranslatorService", "deepl") - translateText() - - sGoogle.classList.remove("selected") - sYandex.classList.remove("selected") - sBing.classList.remove("selected") - sDeepL.classList.remove("selected") - - sDeepL.classList.add("selected") - } - - const setTargetLanguage = document.getElementById("setTargetLanguage") - setTargetLanguage.onclick = e => { - if (e.target.getAttribute("value")) { - const langCode = twpLang.fixTLanguageCode(e.target.getAttribute("value")) - if (langCode) { - currentTargetLanguage = langCode - twpConfig.setTargetLanguageTextTranslation(langCode) - translateText() - } - - document.querySelectorAll("#setTargetLanguage li").forEach(li => { - li.classList.remove("selected") - }) - - e.target.classList.add("selected") - } - } - - eListen.classList.remove("selected") - eListen.onclick = () => { - const msgListen = chrome.i18n.getMessage("btnListen") - const msgStopListening = chrome.i18n.getMessage("btnStopListening") - - eListen.classList.remove("selected") - eListen.setAttribute("title", msgStopListening) - - if (isPlayingAudio) { - stopAudio() - eListen.classList.remove("selected") - } else { - playAudio(eTextTranslated.textContent, currentTargetLanguage, () => { - eListen.classList.remove("selected") - eListen.setAttribute("title", msgListen) - }) - eListen.classList.add("selected") - } - } - - const targetLanguageButtons = document.querySelectorAll("#setTargetLanguage li") - - for (let i = 0; i < 3; i++) { - if (currentTargetLanguages[i] == currentTargetLanguage) { - targetLanguageButtons[i].classList.add("selected") - } - targetLanguageButtons[i].textContent = currentTargetLanguages[i] - targetLanguageButtons[i].setAttribute("value", currentTargetLanguages[i]) - targetLanguageButtons[i].setAttribute("title", twpLang.codeToLanguage(currentTargetLanguages[i])) - } - - switch (currentTextTranslatorService) { - case "yandex": - sYandex.classList.add("selected") - break - case "deepl": - sDeepL.classList.add("selected") - break - case "bing": - sBing.classList.add("selected") - break - case "google": - sGoogle.classList.add("selected") - break - default: - sGoogle.classList.add("selected") - break - } - - if (twpConfig.get("enableDeepL") === "yes") { - sDeepL.removeAttribute("hidden") - } else { - sDeepL.setAttribute("hidden", "") - } - twpConfig.onChanged((name, newvalue) => { - switch (name) { - case "enableDeepL": - if (newvalue === "yes") { - sDeepL.removeAttribute("hidden") - } else { - sDeepL.setAttribute("hidden", "") - } - break - } - }) - - - function translateText() { - stopAudio() - - backgroundTranslateSingleText(currentTextTranslatorService, currentTargetLanguage, eOrigText.textContent) - .then(result => { - if (twpLang.isRtlLanguage(currentTargetLanguage)) { - eTextTranslated.setAttribute("dir", "rtl") - } else { - eTextTranslated.setAttribute("dir", "ltr") - } - eTextTranslated.textContent = result - }) - } - - let params = location.hash.substring(1).split("&").reduce((a, b) => { - const splited = b.split("=") - a[decodeURIComponent(splited[0])] = decodeURIComponent(splited[1]) - return a - }, {}) - - if (params["text"]) { - eOrigText.textContent = params["text"] - setCaretAtEnd() - translateText() - } -})