Change format rule

This commit is contained in:
sienori 2018-07-31 20:35:03 +09:00
parent a3bdaeca75
commit d3bcce91b6
13 changed files with 1399 additions and 1353 deletions

View file

@ -10,81 +10,80 @@ browser.runtime.onInstalled.addListener(function(){
browser.runtime.openOptionsPage(); browser.runtime.openOptionsPage();
}); });
*/ */
function settingsObj() {}; function settingsObj() {}
(function () { (function() {
//オプションページを書き換え,設定の初期化 //オプションページを書き換え,設定の初期化
//Rewrite option page, initialize setting //Rewrite option page, initialize setting
settingsObj.prototype.initOptionsPage = function () { settingsObj.prototype.initOptionsPage = function() {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
labelSet(); labelSet();
getSettingsByHtml(); getSettingsByHtml();
overRideSettingsByStorage().then(function () { overRideSettingsByStorage().then(function() {
overRideHtml(); overRideHtml();
saveSettings(); saveSettings();
resolve(); resolve();
}); });
}) });
}; };
//オプションページから設定を保存 //オプションページから設定を保存
//Save settings from options page //Save settings from options page
settingsObj.prototype.saveOptionsPage = function () { settingsObj.prototype.saveOptionsPage = function() {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
getSettingsByHtml(); getSettingsByHtml();
saveSettings().then(function () { saveSettings().then(function() {
resolve(); resolve();
}); });
}) });
}; };
//設定を初期化 //設定を初期化
//Initialize setting //Initialize setting
settingsObj.prototype.init = function () { settingsObj.prototype.init = function() {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
getSettings().then(function () { getSettings().then(function() {
resolve(Settings); resolve(Settings);
}) });
}) });
} };
//設定を返す //設定を返す
//return settings //return settings
settingsObj.prototype.get = function () { settingsObj.prototype.get = function() {
return Settings; return Settings;
}; };
//受け取ったオブジェクトを保存 //受け取ったオブジェクトを保存
//Save the received object //Save the received object
settingsObj.prototype.save = function (settings) { settingsObj.prototype.save = function(settings) {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
for (let i in settings) { for (let i in settings) {
Settings[i] = settings[i]; Settings[i] = settings[i];
} }
saveSettings().then(function () { saveSettings().then(function() {
resolve(); resolve();
}); });
}) });
}; };
//設定を削除 //設定を削除
//Delete settings //Delete settings
settingsObj.prototype.clear = function (setting) { settingsObj.prototype.clear = function(setting) {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
delete Settings[setting]; delete Settings[setting];
saveSettings().then(function () { saveSettings().then(function() {
resolve(); resolve();
}) });
}) });
} };
//全ての設定を削除 //全ての設定を削除
//Delete all settings //Delete all settings
settingsObj.prototype.clearAll = function () { settingsObj.prototype.clearAll = function() {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
Settings = new settingsObj(); Settings = new settingsObj();
saveSettings().then(function () { saveSettings().then(function() {
resolve(); resolve();
}) });
}) });
} };
settingsObj.prototype.labelSet = function () { settingsObj.prototype.labelSet = function() {
labelSet(); labelSet();
} };
//let Settings = new settingsObj(); //let Settings = new settingsObj();
let Settings = {}; let Settings = {};
@ -105,7 +104,7 @@ function settingsObj() {};
if (i.id != undefined && i.id.includes("Label")) { if (i.id != undefined && i.id.includes("Label")) {
label = browser.i18n.getMessage(i.id); label = browser.i18n.getMessage(i.id);
} else if (i.className != undefined && i.className.includes("Label")) { } else if (i.className != undefined && i.className.includes("Label")) {
const labelList = i.className.split(' ').filter((element, index, array) => { const labelList = i.className.split(" ").filter((element, index, array) => {
return element.includes("Label"); return element.includes("Label");
}); });
label = browser.i18n.getMessage(labelList[0]); label = browser.i18n.getMessage(labelList[0]);
@ -128,7 +127,6 @@ function settingsObj() {};
i.innerHTML = label; i.innerHTML = label;
} }
} }
} }
} }
} }
@ -136,9 +134,8 @@ function settingsObj() {};
//storageからSettingsの項目を取得して存在しない物をSettingsに上書き //storageからSettingsの項目を取得して存在しない物をSettingsに上書き
//Retrieve the Settings item from storage and overwrite Settings that do not exist //Retrieve the Settings item from storage and overwrite Settings that do not exist
function overRideSettingsByStorage() { function overRideSettingsByStorage() {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
browser.storage.local.get("Settings", function (value) { browser.storage.local.get("Settings", function(value) {
for (let i in Settings) { for (let i in Settings) {
if (value.Settings != undefined && value.Settings[i] != undefined) { if (value.Settings != undefined && value.Settings[i] != undefined) {
Settings[i] = value.Settings[i]; Settings[i] = value.Settings[i];
@ -148,8 +145,8 @@ function settingsObj() {};
if (Settings[i] == undefined) Settings[i] = value.Settings[i]; if (Settings[i] == undefined) Settings[i] = value.Settings[i];
} }
resolve(); resolve();
}) });
}) });
} }
//オプションページにSettingsを反映 //オプションページにSettingsを反映
@ -158,7 +155,8 @@ function settingsObj() {};
let inputs = document.getElementsByTagName("input"); let inputs = document.getElementsByTagName("input");
for (let i in inputs) { for (let i in inputs) {
if (inputs[i].id == undefined) continue; if (inputs[i].id == undefined) continue;
if (inputs[i].className != undefined && inputs[i].className.indexOf("noSetting") != -1) continue; if (inputs[i].className != undefined && inputs[i].className.indexOf("noSetting") != -1)
continue;
switch (inputs[i].type) { switch (inputs[i].type) {
case "text": case "text":
@ -190,14 +188,16 @@ function settingsObj() {};
let textareas = document.getElementsByTagName("textarea"); let textareas = document.getElementsByTagName("textarea");
for (let i in textareas) { for (let i in textareas) {
if (textareas[i].id == undefined) continue; if (textareas[i].id == undefined) continue;
if (textareas[i].className != undefined && textareas[i].className.indexOf("noSetting") != -1) continue; if (textareas[i].className != undefined && textareas[i].className.indexOf("noSetting") != -1)
continue;
textareas[i].value = Settings[textareas[i].id]; textareas[i].value = Settings[textareas[i].id];
} }
let selects = document.getElementsByTagName("select"); let selects = document.getElementsByTagName("select");
for (let i in selects) { for (let i in selects) {
if (selects[i].id == undefined) continue; if (selects[i].id == undefined) continue;
if (selects[i].className != undefined && inputs[i].className.indexOf("noSetting") != -1) continue; if (selects[i].className != undefined && inputs[i].className.indexOf("noSetting") != -1)
continue;
selects[i].value = Settings[selects[i].id]; selects[i].value = Settings[selects[i].id];
} }
@ -210,7 +210,8 @@ function settingsObj() {};
for (let i in inputs) { for (let i in inputs) {
if (inputs[i].id == undefined) continue; if (inputs[i].id == undefined) continue;
if (inputs[i].className != undefined && inputs[i].className.indexOf("noSetting") != -1) continue; if (inputs[i].className != undefined && inputs[i].className.indexOf("noSetting") != -1)
continue;
switch (inputs[i].type) { switch (inputs[i].type) {
case "text": case "text":
@ -243,14 +244,16 @@ function settingsObj() {};
let textareas = document.getElementsByTagName("textarea"); let textareas = document.getElementsByTagName("textarea");
for (let i in textareas) { for (let i in textareas) {
if (textareas[i].id == undefined) continue; if (textareas[i].id == undefined) continue;
if (textareas[i].className != undefined && textareas[i].className.indexOf("noSetting") != -1) continue; if (textareas[i].className != undefined && textareas[i].className.indexOf("noSetting") != -1)
continue;
Settings[textareas[i].id] = textareas[i].value; Settings[textareas[i].id] = textareas[i].value;
} }
let selects = document.getElementsByTagName("select"); let selects = document.getElementsByTagName("select");
for (let i in selects) { for (let i in selects) {
if (selects[i].id == undefined) continue; if (selects[i].id == undefined) continue;
if (selects[i].className != undefined && selects[i].className.indexOf("noSetting") != -1) continue; if (selects[i].className != undefined && selects[i].className.indexOf("noSetting") != -1)
continue;
Settings[selects[i].id] = selects[i].value; Settings[selects[i].id] = selects[i].value;
} }
@ -266,22 +269,23 @@ function settingsObj() {};
} }
function getSettings() { function getSettings() {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
browser.storage.local.get("Settings", function (value) { browser.storage.local.get("Settings", function(value) {
Settings = value.Settings; Settings = value.Settings;
resolve(Settings); resolve(Settings);
}); });
}) });
} }
function saveSettings() { function saveSettings() {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
browser.storage.local.set({ browser.storage.local
'Settings': Settings .set({
}).then(function () { Settings: Settings
})
.then(function() {
resolve(Settings); resolve(Settings);
}); });
}) });
} }
})();
}());

View file

@ -19,7 +19,8 @@
"message": "Target language" "message": "Target language"
}, },
"langList": { "langList": {
"message": "af:Afrikaans, sq:Albanian, am:Amharic, ar:Arabic, hy:Armenian, az:Azerbaijani, eu:Basque, be:Belarusian, bn:Bengali, bs:Bosnian, bg:Bulgarian, ca:Catalan, ceb:Cebuano, ny:Chewa, zh-CN:Chinese (PRC), zh-TW:Chinese (Taiwan), co:Corsican, hr:Croatian, cs:Czech, da:Danish, nl:Dutch, en:English, eo:Esperanto, et:Estonian, fi:Finnish, fr:French, fy:Frisian, gl:Galician, ka:Georgian, de:German, el:Greek, gu:Gujarati, ht:Haitian, ha:Hausa, haw:Hawaiian, he:Hebrew, hi:Hindi, hu:Hungarian, is:Icelandic, ig:Igbo, id:Indonesian, ga:Irish, it:Italian, ja:Japanese, jv:Javanese, kn:Kannada, kk:Kazakh, km:Khmer, ky:Kirghiz, ko:Korean, ku:Kurdish, lo:Laotian, la:Latin, lv:Latvian, lt:Lithuanian, lb:Luxembourgish, mk:Macedonian, mg:Malagasy, ms:Malay, ml:Malayalam, mt:Maltese, mi:Maori, mr:Marathi, mn:Mongolian, hmn:Monk, my:Myanmar, ne:Nepali, no:Norwegian, fa:Persian, pl:Polish, pt:Portuguese, pa:Punjabi, ps:Pushto, ro:Romanian, ru:Russian, sm:Samoan, gd:Scottish Gaelic, sr:Serbian, sn:Shona, sd:Sindhi, si:Sinhala, sk:Slovak, sl:Slovenian, so:Somali, sx:Sotho, es:Spanish, su:Sundanese, sw:Swahili, sv:Swedish, tl:Tagalog, tg:Tajiki, ta:Tamil, te:Telugu, th:Thai, tr:Turkish, uk:Ukrainian, ur:Urdu, uz:Uzbek, vi:Vietnamese, cy:Welsh, xh:Xosa, yi:Yiddish, yo:Yoruba, zu:Zulu" "message":
"af:Afrikaans, sq:Albanian, am:Amharic, ar:Arabic, hy:Armenian, az:Azerbaijani, eu:Basque, be:Belarusian, bn:Bengali, bs:Bosnian, bg:Bulgarian, ca:Catalan, ceb:Cebuano, ny:Chewa, zh-CN:Chinese (PRC), zh-TW:Chinese (Taiwan), co:Corsican, hr:Croatian, cs:Czech, da:Danish, nl:Dutch, en:English, eo:Esperanto, et:Estonian, fi:Finnish, fr:French, fy:Frisian, gl:Galician, ka:Georgian, de:German, el:Greek, gu:Gujarati, ht:Haitian, ha:Hausa, haw:Hawaiian, he:Hebrew, hi:Hindi, hu:Hungarian, is:Icelandic, ig:Igbo, id:Indonesian, ga:Irish, it:Italian, ja:Japanese, jv:Javanese, kn:Kannada, kk:Kazakh, km:Khmer, ky:Kirghiz, ko:Korean, ku:Kurdish, lo:Laotian, la:Latin, lv:Latvian, lt:Lithuanian, lb:Luxembourgish, mk:Macedonian, mg:Malagasy, ms:Malay, ml:Malayalam, mt:Maltese, mi:Maori, mr:Marathi, mn:Mongolian, hmn:Monk, my:Myanmar, ne:Nepali, no:Norwegian, fa:Persian, pl:Polish, pt:Portuguese, pa:Punjabi, ps:Pushto, ro:Romanian, ru:Russian, sm:Samoan, gd:Scottish Gaelic, sr:Serbian, sn:Shona, sd:Sindhi, si:Sinhala, sk:Slovak, sl:Slovenian, so:Somali, sx:Sotho, es:Spanish, su:Sundanese, sw:Swahili, sv:Swedish, tl:Tagalog, tg:Tajiki, ta:Tamil, te:Telugu, th:Thai, tr:Turkish, uk:Ukrainian, ur:Urdu, uz:Uzbek, vi:Vietnamese, cy:Welsh, xh:Xosa, yi:Yiddish, yo:Yoruba, zu:Zulu"
}, },
"settingsLabel": { "settingsLabel": {
@ -65,7 +66,8 @@
"message": "Do not display the button if translation is not required" "message": "Do not display the button if translation is not required"
}, },
"ifCheckLangCaptionLabel": { "ifCheckLangCaptionLabel": {
"message": "Detects the language of the selected text, and if it is the same as the target language, the button is not displayed." "message":
"Detects the language of the selected text, and if it is the same as the target language, the button is not displayed."
}, },
"toolbarLabel": { "toolbarLabel": {
@ -75,7 +77,8 @@
"message": "Automatically switch to the second language" "message": "Automatically switch to the second language"
}, },
"ifChangeSecondLangCaptionLabel": { "ifChangeSecondLangCaptionLabel": {
"message": "Detects the language of the input text, and if it is the same as the default target language, translate it into the second language." "message":
"Detects the language of the input text, and if it is the same as the default target language, translate it into the second language."
}, },
"secondTargetLangLabel": { "secondTargetLangLabel": {
"message": "Second language" "message": "Second language"
@ -84,14 +87,15 @@
"message": "Select the second target language." "message": "Select the second target language."
}, },
"menuLabel":{ "menuLabel": {
"message": "Context menu" "message": "Context menu"
}, },
"ifShowMenuLabel": { "ifShowMenuLabel": {
"message": "Display the context menu" "message": "Display the context menu"
}, },
"ifShowMenuCaptionLabel": { "ifShowMenuCaptionLabel": {
"message": "Add items to the context menu displayed when right clicking on the web page or the tab." "message":
"Add items to the context menu displayed when right clicking on the web page or the tab."
}, },
"styleLabel": { "styleLabel": {
@ -150,7 +154,8 @@
"message": "Please make a donation" "message": "Please make a donation"
}, },
"donationCaptionLabel": { "donationCaptionLabel": {
"message": "Thank you for using Simple Translate.<br>Your support will be a big encouragement, as I continue to develop the add-on.<br>If you like Simple Translate, I would be pleased if you could consider donating." "message":
"Thank you for using Simple Translate.<br>Your support will be a big encouragement, as I continue to develop the add-on.<br>If you like Simple Translate, I would be pleased if you could consider donating."
}, },
"amazonTitleLabel": { "amazonTitleLabel": {
"message": "amazon.co.jp eGift Cards" "message": "amazon.co.jp eGift Cards"
@ -162,10 +167,9 @@
"message": "https://www.amazon.co.jp/dp/B004N3APGO?language=en_US" "message": "https://www.amazon.co.jp/dp/B004N3APGO?language=en_US"
}, },
"addonUrl": { "addonUrl": {
"message": "https:\/\/addons.mozilla.org\/en-US\/firefox\/addon\/simple-translate\/?src=optionpage" "message": "https://addons.mozilla.org/en-US/firefox/addon/simple-translate/?src=optionpage"
}, },
"translatePageMenu": { "translatePageMenu": {
"message": "Translate this page" "message": "Translate this page"
}, },

View file

@ -4,8 +4,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//初回起動時にオプションページを表示して設定を初期化 //初回起動時にオプションページを表示して設定を初期化
browser.runtime.onInstalled.addListener((details) => { browser.runtime.onInstalled.addListener(details => {
if (details.reason != 'install' && details.reason != 'update') return; if (details.reason != "install" && details.reason != "update") return;
browser.tabs.create({ browser.tabs.create({
url: "options/options.html#information?action=updated", url: "options/options.html#information?action=updated",
@ -16,9 +16,10 @@ browser.runtime.onInstalled.addListener((details) => {
let S = new settingsObj(); let S = new settingsObj();
browser.storage.onChanged.addListener(showMenu); browser.storage.onChanged.addListener(showMenu);
if (typeof (browser.contextMenus.onShown) != 'undefined') browser.contextMenus.onShown.addListener(updateMenu); if (typeof browser.contextMenus.onShown != "undefined")
browser.contextMenus.onShown.addListener(updateMenu);
S.init().then(function () { S.init().then(function() {
showMenu(); showMenu();
}); });
@ -31,10 +32,10 @@ function showMenu() {
//テキストまたはリンクの選択時はページ翻訳を非表示にする //テキストまたはリンクの選択時はページ翻訳を非表示にする
function updateMenu(info, tab) { function updateMenu(info, tab) {
if (info.contexts.includes('selection') || info.contexts.includes('link')) { if (info.contexts.includes("selection") || info.contexts.includes("link")) {
browser.contextMenus.update('translatePage', { contexts: ['password'] }); //passwordにすることで事実上無効にする browser.contextMenus.update("translatePage", { contexts: ["password"] }); //passwordにすることで事実上無効にする
} else { } else {
browser.contextMenus.update('translatePage', { contexts: ['all'] }); browser.contextMenus.update("translatePage", { contexts: ["all"] });
} }
browser.contextMenus.refresh(); browser.contextMenus.refresh();
} }
@ -44,25 +45,25 @@ function menuCreate() {
browser.contextMenus.create({ browser.contextMenus.create({
id: "translatePageOnTab", id: "translatePageOnTab",
title: browser.i18n.getMessage("translatePageMenu"), title: browser.i18n.getMessage("translatePageMenu"),
contexts: ["tab"], contexts: ["tab"]
}); });
browser.contextMenus.create({ browser.contextMenus.create({
id: "translatePage", id: "translatePage",
title: browser.i18n.getMessage("translatePageMenu"), title: browser.i18n.getMessage("translatePageMenu"),
contexts: ["all"], contexts: ["all"]
}); });
browser.contextMenus.create({ browser.contextMenus.create({
id: "translateText", id: "translateText",
title: browser.i18n.getMessage("translateTextMenu"), title: browser.i18n.getMessage("translateTextMenu"),
contexts: ["selection"], contexts: ["selection"]
}); });
browser.contextMenus.create({ browser.contextMenus.create({
id: "translateLink", id: "translateLink",
title: browser.i18n.getMessage("translateLinkMenu"), title: browser.i18n.getMessage("translateLinkMenu"),
contexts: ["link"], contexts: ["link"]
}); });
} }
@ -71,9 +72,8 @@ function menuRemove() {
browser.contextMenus.removeAll(); browser.contextMenus.removeAll();
} }
//メニュークリック時 //メニュークリック時
browser.contextMenus.onClicked.addListener(function (info, tab) { browser.contextMenus.onClicked.addListener(function(info, tab) {
switch (info.menuItemId) { switch (info.menuItemId) {
case "translatePage": case "translatePage":
case "translatePageOnTab": case "translatePageOnTab":
@ -90,33 +90,39 @@ browser.contextMenus.onClicked.addListener(function (info, tab) {
//テキストを翻訳 //テキストを翻訳
function translateTextMenu(info, tab) { function translateTextMenu(info, tab) {
browser.tabs.sendMessage( browser.tabs.sendMessage(tab.id, {
tab.id, {
message: "showPanelFromMenu" message: "showPanelFromMenu"
} });
)
} }
//ページ全体を翻訳 //ページ全体を翻訳
function translatePageMenu(info, tab) { function translatePageMenu(info, tab) {
browser.tabs.create({ browser.tabs.create({
'url': "https://translate.google.com/translate?hl=" + S.get().targetLang + "&sl=auto&u=" + encodeURIComponent(info.pageUrl), url:
'active': true, "https://translate.google.com/translate?hl=" +
'index': tab.index + 1 S.get().targetLang +
"&sl=auto&u=" +
encodeURIComponent(info.pageUrl),
active: true,
index: tab.index + 1
}); });
} }
//リンクを翻訳 //リンクを翻訳
function translateLinkMenu(info, tab) { function translateLinkMenu(info, tab) {
browser.tabs.create({ browser.tabs.create({
'url': "https://translate.google.com/translate?hl=" + S.get().targetLang + "&sl=auto&u=" + encodeURIComponent(info.linkUrl), url:
'active': true, "https://translate.google.com/translate?hl=" +
'index': tab.index + 1 S.get().targetLang +
"&sl=auto&u=" +
encodeURIComponent(info.linkUrl),
active: true,
index: tab.index + 1
}); });
} }
//スクリプトからのメッセージに返信 //スクリプトからのメッセージに返信
browser.runtime.onMessage.addListener(function (request) { browser.runtime.onMessage.addListener(function(request) {
switch (request.message) { switch (request.message) {
case "getSetting": case "getSetting":
break; break;

View file

@ -25,7 +25,6 @@
"64": "icons/64.png", "64": "icons/64.png",
"48": "icons/48.png", "48": "icons/48.png",
"32": "icons/32.png" "32": "icons/32.png"
}, },
"background": { "background": {
@ -48,7 +47,7 @@
"content_scripts": [ "content_scripts": [
{ {
"all_frames":true, "all_frames": true,
"matches": ["http://*/*", "https://*/*", "<all_urls>"], "matches": ["http://*/*", "https://*/*", "<all_urls>"],
"css": ["simple-translate.css"], "css": ["simple-translate.css"],
"js": ["Settings.js", "translate.js", "simple-translate.js"] "js": ["Settings.js", "translate.js", "simple-translate.js"]

View file

@ -9,7 +9,8 @@
} }
body { body {
font-family: 'Segoe UI', 'San Francisco', 'Ubuntu', 'Fira Sans', 'Roboto', 'Arial', 'Helvetica', sans-serif; font-family: "Segoe UI", "San Francisco", "Ubuntu", "Fira Sans", "Roboto", "Arial", "Helvetica",
sans-serif;
font-size: 15px; font-size: 15px;
font-weight: 400; font-weight: 400;
color: var(--main-text); color: var(--main-text);
@ -17,7 +18,6 @@ body {
line-height: 1.5; line-height: 1.5;
display: flex; display: flex;
flex-direction: row; flex-direction: row;
} }
p { p {
@ -41,7 +41,6 @@ hr {
margin-bottom: 20px; margin-bottom: 20px;
} }
/*----sidebar----*/ /*----sidebar----*/
#sidebar { #sidebar {
@ -87,7 +86,6 @@ hr {
color: var(--highlight); color: var(--highlight);
} }
/*----contents----*/ /*----contents----*/
#contents { #contents {
@ -95,7 +93,6 @@ hr {
padding-left: 20px; padding-left: 20px;
padding-bottom: 50px; padding-bottom: 50px;
width: 650px; width: 650px;
} }
.contentTitle { .contentTitle {
@ -121,7 +118,8 @@ hr {
border-left: solid 10px var(--line); border-left: solid 10px var(--line);
} }
.categoryContainer {} .categoryContainer {
}
.categoryElements { .categoryElements {
padding-left: 20px; padding-left: 20px;
@ -198,7 +196,6 @@ hr {
float: left; float: left;
} }
/*----forms----*/ /*----forms----*/
input { input {
@ -273,7 +270,6 @@ a:link {
text-decoration-line: none; text-decoration-line: none;
} }
a:visited { a:visited {
color: var(--sub-text); color: var(--sub-text);
} }
@ -289,7 +285,6 @@ a:visited {
text-decoration-line: underline; text-decoration-line: underline;
} }
input[type="checkbox"] { input[type="checkbox"] {
display: none; display: none;
} }

View file

@ -2,7 +2,7 @@
* This Source Code Form is subject to the terms of the Mozilla Public * This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const S = new settingsObj() const S = new settingsObj();
let targetLang = document.getElementById("targetLang"); let targetLang = document.getElementById("targetLang");
let secondTargetLang = document.getElementById("secondTargetLang"); let secondTargetLang = document.getElementById("secondTargetLang");
@ -19,7 +19,7 @@ function setLangList() {
let langListHtml = ""; let langListHtml = "";
for (let i of langList) { for (let i of langList) {
langListHtml += `<option value=${i[0]}>${i[1]}</option>` langListHtml += `<option value=${i[0]}>${i[1]}</option>`;
} }
targetLang.innerHTML = langListHtml; targetLang.innerHTML = langListHtml;
secondTargetLang.innerHTML = langListHtml; secondTargetLang.innerHTML = langListHtml;
@ -36,7 +36,9 @@ function alphabeticallySort(a, b) {
} }
function initialSetting() { function initialSetting() {
switch (browser.i18n.getUILanguage()) { //一部の言語はブラウザの設定に合わせる switch (
browser.i18n.getUILanguage() //一部の言語はブラウザの設定に合わせる
) {
case "ja": case "ja":
case "zh-CN": case "zh-CN":
case "zh-TW": case "zh-TW":
@ -55,12 +57,12 @@ function initialSetting() {
} }
} }
S.initOptionsPage().then(function () { S.initOptionsPage().then(function() {
const saveByChangeItems = document.getElementsByClassName("saveByChange"); const saveByChangeItems = document.getElementsByClassName("saveByChange");
for (let item of saveByChangeItems) { for (let item of saveByChangeItems) {
item.addEventListener("change", save) item.addEventListener("change", save);
} }
}) });
function save() { function save() {
S.saveOptionsPage(); S.saveOptionsPage();

View file

@ -6,8 +6,8 @@
let e = {}; let e = {};
e.hash = location.href; e.hash = location.href;
if (e.hash.indexOf('#') != -1) { if (e.hash.indexOf("#") != -1) {
e.hash = '#' + e.hash.split('#')[1]; e.hash = "#" + e.hash.split("#")[1];
} else { } else {
e.hash = "#settings"; e.hash = "#settings";
} }
@ -18,7 +18,7 @@ tm.HashObserver.enable();
document.addEventListener("changehash", readHash, false); document.addEventListener("changehash", readHash, false);
function readHash(e) { function readHash(e) {
const hash = e.hash.split('?')[0]; const hash = e.hash.split("?")[0];
let selected = document.getElementsByClassName("selected"); let selected = document.getElementsByClassName("selected");
selected[0].classList.remove("selected"); selected[0].classList.remove("selected");
@ -43,7 +43,7 @@ function readHash(e) {
const params = getParams(e.hash); const params = getParams(e.hash);
switch (params.action) { switch (params.action) {
case 'updated': case "updated":
showUpdated(); showUpdated();
break; break;
} }
@ -51,19 +51,22 @@ function readHash(e) {
function getParams(hash) { function getParams(hash) {
let params = {}; let params = {};
if (hash.split('?')[1] == undefined) return params; if (hash.split("?")[1] == undefined) return params;
hash = hash.split('?')[1].split('&'); hash = hash.split("?")[1].split("&");
for (let i of hash) { for (let i of hash) {
params[i.split('=')[0]] = i.split('=')[1]; params[i.split("=")[0]] = i.split("=")[1];
} }
return params; return params;
} }
function showUpdated() { function showUpdated() {
const version = document.getElementsByClassName('addonVersion')[0]; const version = document.getElementsByClassName("addonVersion")[0];
version.classList.add('updated'); version.classList.add("updated");
} }
document.getElementsByClassName("addonUrl")[0].href = browser.i18n.getMessage("addonUrl"); document.getElementsByClassName("addonUrl")[0].href = browser.i18n.getMessage("addonUrl");
document.getElementsByClassName("amazonUrl")[0].href = browser.i18n.getMessage("amazonUrl"); document.getElementsByClassName("amazonUrl")[0].href = browser.i18n.getMessage("amazonUrl");
document.getElementsByClassName('addonVersion')[0].getElementsByClassName('caption')[0].getElementsByTagName('a')[0].innerText = `Version ${browser.runtime.getManifest().version}`; document
.getElementsByClassName("addonVersion")[0]
.getElementsByClassName("caption")[0]
.getElementsByTagName("a")[0].innerText = `Version ${browser.runtime.getManifest().version}`;

View file

@ -9,7 +9,8 @@
} }
body { body {
font-family: 'Segoe UI', 'San Francisco', 'Ubuntu', 'Fira Sans', 'Roboto', 'Arial', 'Helvetica', sans-serif; font-family: "Segoe UI", "San Francisco", "Ubuntu", "Fira Sans", "Roboto", "Arial", "Helvetica",
sans-serif;
text-align: left; text-align: left;
font-size: 13px; font-size: 13px;
width: 348px; width: 348px;
@ -119,7 +120,7 @@ textarea {
textarea:hover, textarea:hover,
textarea:focus { textarea:focus {
border-color: var(--highlight) border-color: var(--highlight);
} }
hr { hr {
@ -143,18 +144,18 @@ hr {
background-color: var(--main-bg); background-color: var(--main-bg);
} }
#target .result{ #target .result {
background-color: var(--main-bg); background-color: var(--main-bg);
} }
#target .candidate { #target .candidate {
color: var(--sub-text); color: var(--sub-text);
margin-top:1em; margin-top: 1em;
background-color: var(--main-bg); background-color: var(--main-bg);
} }
#target .candidate:empty { #target .candidate:empty {
margin-top:0; margin-top: 0;
} }
#footer { #footer {
@ -179,7 +180,6 @@ hr {
text-decoration: underline; text-decoration: underline;
} }
select { select {
-moz-appearance: none; -moz-appearance: none;
text-overflow: ellipsis; text-overflow: ellipsis;

View file

@ -7,14 +7,14 @@ const S = new settingsObj();
const T = new Translate(); const T = new Translate();
//設定を読み出し //設定を読み出し
S.init().then(function (value) { S.init().then(function(value) {
defaultTargetLang = value.targetLang; defaultTargetLang = value.targetLang;
secondTargetLang = value.secondTargetLang; secondTargetLang = value.secondTargetLang;
langList.value = value.targetLang; //リスト初期値をセット langList.value = value.targetLang; //リスト初期値をセット
langList.addEventListener("change", changeLang); langList.addEventListener("change", changeLang);
document.body.style.fontSize = value.fontSize; document.body.style.fontSize = value.fontSize;
}) });
let target = document.getElementById("target"); let target = document.getElementById("target");
let langList = document.getElementById("langList"); let langList = document.getElementById("langList");
@ -40,17 +40,17 @@ function setLangList() {
let langListHtml = ""; let langListHtml = "";
for (let i of langListStr) { for (let i of langListStr) {
langListHtml += `<option value=${i[0]}>${i[1]}</option>` langListHtml += `<option value=${i[0]}>${i[1]}</option>`;
} }
langList.innerHTML = langListHtml; langList.innerHTML = langListHtml;
} }
setTitles(); setTitles();
function setTitles(){ function setTitles() {
document.getElementById('donate').title = browser.i18n.getMessage('donateWithPaypalLabel'); document.getElementById("donate").title = browser.i18n.getMessage("donateWithPaypalLabel");
document.getElementById("setting").title = browser.i18n.getMessage('settingsLabel'); document.getElementById("setting").title = browser.i18n.getMessage("settingsLabel");
document.getElementById("langList").title = browser.i18n.getMessage('targetLangLabel'); document.getElementById("langList").title = browser.i18n.getMessage("targetLangLabel");
} }
function alphabeticallySort(a, b) { function alphabeticallySort(a, b) {
@ -63,7 +63,7 @@ function alphabeticallySort(a, b) {
//翻訳先言語変更時に更新 //翻訳先言語変更時に更新
async function changeLang() { async function changeLang() {
if (typeof (url) != "undefined") showLink(); if (typeof url != "undefined") showLink();
if (sourceWord !== "") { if (sourceWord !== "") {
const resultData = await T.translate(sourceWord, undefined, langList.value); const resultData = await T.translate(sourceWord, undefined, langList.value);
@ -72,32 +72,42 @@ async function changeLang() {
} }
//アクティブなタブを取得して渡す //アクティブなタブを取得して渡す
browser.tabs.query({ browser.tabs
.query({
currentWindow: true, currentWindow: true,
active: true active: true
}).then(function (tabs) { })
.then(function(tabs) {
getSelectionWord(tabs); getSelectionWord(tabs);
}); });
//アクティブタブから選択文字列とurlを取得 //アクティブタブから選択文字列とurlを取得
function getSelectionWord(tabs) { function getSelectionWord(tabs) {
for (let tab of tabs) { for (let tab of tabs) {
browser.tabs.sendMessage( browser.tabs
tab.id, { .sendMessage(tab.id, {
message: "fromPopup" message: "fromPopup"
} })
).then(response => { .then(response => {
sourceWord = response.word; sourceWord = response.word;
url = response.url; url = response.url;
refleshSource(); refleshSource();
showLink(); showLink();
}).catch(()=>{}); })
.catch(() => {});
} }
} }
//ページ翻訳へのリンクを表示 //ページ翻訳へのリンクを表示
function showLink() { function showLink() {
document.getElementById("link").innerHTML = "<a href=https://translate.google.com/translate?hl=" + langList.value + "&sl=auto&u=" + encodeURIComponent(url) + ">" + browser.i18n.getMessage('showLink') + "</a>"; document.getElementById("link").innerHTML =
"<a href=https://translate.google.com/translate?hl=" +
langList.value +
"&sl=auto&u=" +
encodeURIComponent(url) +
">" +
browser.i18n.getMessage("showLink") +
"</a>";
} }
//翻訳元テキストを表示 //翻訳元テキストを表示
@ -109,11 +119,11 @@ function refleshSource() {
} }
} }
textarea.addEventListener("paste", resize) textarea.addEventListener("paste", resize);
textarea.addEventListener("keydown", resize); textarea.addEventListener("keydown", resize);
textarea.addEventListener("keyup", function (event) { textarea.addEventListener("keyup", function(event) {
//if (event.keyCode == 13) resize(); //if (event.keyCode == 13) resize();
resize(); resize();
inputText(); inputText();
@ -121,7 +131,7 @@ textarea.addEventListener("keyup", function (event) {
//テキストボックスをリサイズ //テキストボックスをリサイズ
function resize() { function resize() {
setTimeout(function () { setTimeout(function() {
textarea.style.height = "0px"; textarea.style.height = "0px";
textarea.style.height = parseInt(textarea.scrollHeight) + "px"; textarea.style.height = parseInt(textarea.scrollHeight) + "px";
}, 0); }, 0);
@ -139,7 +149,7 @@ function textAreaClick() {
async function inputText() { async function inputText() {
sourceWord = textarea.value; sourceWord = textarea.value;
const resultData = await T.translate(sourceWord, 'auto', langList.value); const resultData = await T.translate(sourceWord, "auto", langList.value);
changeSecondLang(defaultTargetLang, resultData.sourceLanguage, resultData.percentage); changeSecondLang(defaultTargetLang, resultData.sourceLanguage, resultData.percentage);
showResult(resultData.resultText, resultData.candidateText); showResult(resultData.resultText, resultData.candidateText);
} }
@ -155,7 +165,7 @@ function showResult(resultText, candidateText) {
let changeLangFlag = false; let changeLangFlag = false;
function changeSecondLang(defaultTargetLang, sourceLang, percentage) { function changeSecondLang(defaultTargetLang, sourceLang, percentage) {
if(!S.get().ifChangeSecondLang) return; if (!S.get().ifChangeSecondLang) return;
//検出された翻訳元言語がターゲット言語と一致 //検出された翻訳元言語がターゲット言語と一致
const equalsSourceAndTarget = sourceLang == langList.value && percentage > 0; const equalsSourceAndTarget = sourceLang == langList.value && percentage > 0;
@ -179,7 +189,6 @@ function changeSecondLang(defaultTargetLang, sourceLang, percentage) {
changeLangFlag = false; changeLangFlag = false;
langList.value = defaultTargetLang; langList.value = defaultTargetLang;
changeLang(); changeLang();
} }
} }
} }

View file

@ -50,7 +50,8 @@
#simple-translate-panel p { #simple-translate-panel p {
all: initial; all: initial;
font-family: 'Segoe UI', 'San Francisco', 'Ubuntu', 'Fira Sans', 'Roboto', 'Arial', 'Helvetica', sans-serif !important; font-family: "Segoe UI", "San Francisco", "Ubuntu", "Fira Sans", "Roboto", "Arial", "Helvetica",
sans-serif !important;
text-align: left; text-align: left;
display: block; display: block;
font-size: inherit; font-size: inherit;
@ -65,11 +66,11 @@
#simple-translate-panel .candidate { #simple-translate-panel .candidate {
color: var(--simple-translate-sub-text); color: var(--simple-translate-sub-text);
margin-top:1em; margin-top: 1em;
} }
#simple-translate-panel .candidate:empty { #simple-translate-panel .candidate:empty {
margin-top:0; margin-top: 0;
} }
@keyframes simple-translate-showButton { @keyframes simple-translate-showButton {

View file

@ -3,7 +3,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
document.body.insertAdjacentHTML("afterend", "<div id='simple-translate-button'></div><div id='simple-translate-panel'><p>...</p></div>"); //bodyの直後にボタン配置 document.body.insertAdjacentHTML(
"afterend",
"<div id='simple-translate-button'></div><div id='simple-translate-panel'><p>...</p></div>"
); //bodyの直後にボタン配置
var button = document.getElementById("simple-translate-button"); var button = document.getElementById("simple-translate-button");
var panel = document.getElementById("simple-translate-panel"); var panel = document.getElementById("simple-translate-panel");
var selectionWord; var selectionWord;
@ -18,35 +21,39 @@ async function Select(e) {
hidePanel(e); hidePanel(e);
if (e.target.tagName == "INPUT" && e.target.type == "password") return; if (e.target.tagName == "INPUT" && e.target.type == "password") return;
setTimeout(async () => { //誤動作防止の為ディレイを設ける setTimeout(async () => {
//誤動作防止の為ディレイを設ける
//選択文の取得 テキストフィールド内を選択した場合にも対応 //選択文の取得 テキストフィールド内を選択した場合にも対応
const isTextField = (e.target.tagName == "INPUT") || (e.target.tagName == "TEXTAREA"); const isTextField = e.target.tagName == "INPUT" || e.target.tagName == "TEXTAREA";
if (isTextField) selectionWord = e.target.value.substring(e.target.selectionStart, e.target.selectionEnd); if (isTextField)
selectionWord = e.target.value.substring(e.target.selectionStart, e.target.selectionEnd);
else selectionWord = String(window.getSelection()); else selectionWord = String(window.getSelection());
//選択文が存在し,パネル外を左クリックした場合は翻訳する //選択文が存在し,パネル外を左クリックした場合は翻訳する
const existsSelectionWord = (selectionWord.length !== 0); const existsSelectionWord = selectionWord.length !== 0;
const isLeftClick = (e.button == 0); const isLeftClick = e.button == 0;
const isPanelOutside = (e.target.id !== 'simple-translate-panel') && (e.target.parentElement.id !== 'simple-translate-panel'); const isPanelOutside =
e.target.id !== "simple-translate-panel" &&
e.target.parentElement.id !== "simple-translate-panel";
const shouldTranslate = existsSelectionWord && isLeftClick && isPanelOutside; const shouldTranslate = existsSelectionWord && isLeftClick && isPanelOutside;
if (!shouldTranslate) return; if (!shouldTranslate) return;
//選択した言語が翻訳先言語と異なれば翻訳する //選択した言語が翻訳先言語と異なれば翻訳する
const needTranslate = await checkLang(selectionWord, 'auto', S.get().targetLang); const needTranslate = await checkLang(selectionWord, "auto", S.get().targetLang);
if (!needTranslate) return; if (!needTranslate) return;
clickPosition = e; clickPosition = e;
switch (S.get().whenSelectText) { switch (S.get().whenSelectText) {
case 'showButton': case "showButton":
if (selectionWord.length == 0) return; if (selectionWord.length == 0) return;
popupButton(e); popupButton(e);
break; break;
case 'showPanel': case "showPanel":
translate(selectionWord, 'auto', S.get().targetLang); translate(selectionWord, "auto", S.get().targetLang);
if (selectionWord.length == 0) return; if (selectionWord.length == 0) return;
showPanel(e); showPanel(e);
break; break;
case 'dontShowButton': case "dontShowButton":
break; break;
} }
}, 0); }, 0);
@ -58,7 +65,8 @@ async function checkLang(sourceWord, sourceLang, targetLang) {
sourceWord = sourceWord.substr(0, 100); //先頭100字で言語を判定 sourceWord = sourceWord.substr(0, 100); //先頭100字で言語を判定
const resultData = await T.translate(sourceWord, sourceLang, targetLang); const resultData = await T.translate(sourceWord, sourceLang, targetLang);
const needTranslate = (S.get().targetLang != resultData.sourceLanguage) && (resultData.percentage > 0); const needTranslate =
S.get().targetLang != resultData.sourceLanguage && resultData.percentage > 0;
return needTranslate; //ターゲットとソースの言語が不一致ならtrue return needTranslate; //ターゲットとソースの言語が不一致ならtrue
} }
@ -70,29 +78,33 @@ function popupButton(e) {
switch (S.get().buttonPosition) { switch (S.get().buttonPosition) {
case "rightUp": case "rightUp":
topPosition = (-1 * buttonSize) - 10; topPosition = -1 * buttonSize - 10;
break; break;
case "rightDown": case "rightDown":
break; break;
case "leftUp": case "leftUp":
topPosition = (-1 * buttonSize) - 10; topPosition = -1 * buttonSize - 10;
leftPosition = (-1 * buttonSize) - 10; leftPosition = -1 * buttonSize - 10;
break; break;
case "leftDown": case "leftDown":
leftPosition = (-1 * buttonSize) - 10; leftPosition = -1 * buttonSize - 10;
break; break;
} }
button.style.left = e.clientX + leftPosition + 'px'; button.style.left = e.clientX + leftPosition + "px";
button.style.top = e.clientY + topPosition + 'px'; button.style.top = e.clientY + topPosition + "px";
button.style.width = S.get().buttonSize + "px"; button.style.width = S.get().buttonSize + "px";
button.style.height = S.get().buttonSize + "px"; button.style.height = S.get().buttonSize + "px";
button.style.display = 'block'; button.style.display = "block";
} }
button.addEventListener("click", function (e) { button.addEventListener(
translate(selectionWord, 'auto', S.get().targetLang); "click",
function(e) {
translate(selectionWord, "auto", S.get().targetLang);
showPanel(e); showPanel(e);
}, false); },
false
);
async function translate(sourceWord, sourceLang, targetLang) { async function translate(sourceWord, sourceLang, targetLang) {
const resultData = await T.translate(sourceWord, sourceLang, targetLang); const resultData = await T.translate(sourceWord, sourceLang, targetLang);
@ -101,7 +113,7 @@ async function translate(sourceWord, sourceLang, targetLang) {
} }
function showResult(resultText, candidateText) { function showResult(resultText, candidateText) {
panel.innerHTML = '<p class=result></p><p class=candidate>'; panel.innerHTML = "<p class=result></p><p class=candidate>";
const resultArea = panel.getElementsByClassName("result")[0]; const resultArea = panel.getElementsByClassName("result")[0];
const candidateArea = panel.getElementsByClassName("candidate")[0]; const candidateArea = panel.getElementsByClassName("candidate")[0];
@ -112,30 +124,36 @@ function showResult(resultText, candidateText) {
//パネル表示 //パネル表示
function showPanel(e) { function showPanel(e) {
clickPosition = e; clickPosition = e;
panel.style.display = 'block'; panel.style.display = "block";
panelPosition(e); panelPosition(e);
} }
//パネル非表示 //パネル非表示
function hidePanel(e) { function hidePanel(e) {
button.style.display = 'none'; //ボタンを非表示 button.style.display = "none"; //ボタンを非表示
if ((e.target.id !== "simple-translate-panel") && (e.target.parentElement.id !== "simple-translate-panel")) { //パネル以外の場所をクリックでパネルを非表示 if (
panel.style.display = 'none'; e.target.id !== "simple-translate-panel" &&
e.target.parentElement.id !== "simple-translate-panel"
) {
//パネル以外の場所をクリックでパネルを非表示
panel.style.display = "none";
panel.innerHTML = "<p>...</p>"; panel.innerHTML = "<p>...</p>";
} }
} }
//Esc押下でパネルを閉じる //Esc押下でパネルを閉じる
document.addEventListener('keydown', (e) => { document.addEventListener("keydown", e => {
if (e.key == 'Escape') hidePanel(e); if (e.key == "Escape") hidePanel(e);
}) });
//パネルがウィンドウ外にはみ出る時に位置を調整 //パネルがウィンドウ外にはみ出る時に位置を調整
function panelPosition(e) { function panelPosition(e) {
var p = new Object(); var p = new Object();
panel.style.width = S.get().width + 'px'; //300px panel.style.width = S.get().width + "px"; //300px
var panelHeight = panel.clientHeight; var panelHeight = panel.clientHeight;
var panelWidth = parseInt(window.getComputedStyle(panel.getElementsByTagName("p")[0], null).width); var panelWidth = parseInt(
window.getComputedStyle(panel.getElementsByTagName("p")[0], null).width
);
//一旦パネルの横幅を300にしてpの横幅を取得 //一旦パネルの横幅を300にしてpの横幅を取得
if (e.clientX + panelWidth > window.innerWidth - 80) { if (e.clientX + panelWidth > window.innerWidth - 80) {
@ -148,9 +166,9 @@ function panelPosition(e) {
} else { } else {
p.y = e.clientY; p.y = e.clientY;
} }
panel.style.width = 'auto'; //panelWidth + 'px'; panel.style.width = "auto"; //panelWidth + 'px';
panel.style.top = p.y + 'px'; panel.style.top = p.y + "px";
panel.style.left = p.x + 'px'; panel.style.left = p.x + "px";
panel.style.maxWidth = S.get().width + "px"; panel.style.maxWidth = S.get().width + "px";
panel.style.maxHeight = S.get().height + "px"; panel.style.maxHeight = S.get().height + "px";
@ -158,9 +176,8 @@ function panelPosition(e) {
panel.style.backgroundColor = S.get().bgColor; panel.style.backgroundColor = S.get().bgColor;
} }
//スクリプトからのメッセージに返信 //スクリプトからのメッセージに返信
browser.runtime.onMessage.addListener(function (request) { browser.runtime.onMessage.addListener(function(request) {
switch (request.message) { switch (request.message) {
case "fromPopup": case "fromPopup":
return sendToPopup(); return sendToPopup();
@ -184,11 +201,16 @@ function showPanelFromMenu() {
button.style.display = "none"; button.style.display = "none";
//キャレットブラウズモードに対応 //キャレットブラウズモードに対応
const isTextField = (document.activeElement.tagName == "INPUT") || (document.activeElement.tagName == "TEXTAREA"); const isTextField =
if (isTextField) selectionWord = document.activeElement.value.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd); document.activeElement.tagName == "INPUT" || document.activeElement.tagName == "TEXTAREA";
if (isTextField)
selectionWord = document.activeElement.value.substring(
document.activeElement.selectionStart,
document.activeElement.selectionEnd
);
else selectionWord = String(window.getSelection()); else selectionWord = String(window.getSelection());
if (typeof (clickPosition) == 'undefined') clickPosition = { 'clientX': 0, 'clientY': 0 } if (typeof clickPosition == "undefined") clickPosition = { clientX: 0, clientY: 0 };
translate(selectionWord, 'auto', S.get().targetLang); translate(selectionWord, "auto", S.get().targetLang);
showPanel(clickPosition); showPanel(clickPosition);
} }

View file

@ -4,14 +4,13 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
class Translate { class Translate {
constructor() { constructor() {}
}
set sourceWord(word) { set sourceWord(word) {
this.sourceWord = word; this.sourceWord = word;
} }
translate(sourceWord, sourceLang = 'auto', targetLang) { translate(sourceWord, sourceLang = "auto", targetLang) {
//改行で分割 //改行で分割
const sourceLines = sourceWord.trim().split("\n"); const sourceLines = sourceWord.trim().split("\n");
@ -21,18 +20,18 @@ class Translate {
} }
return new Promise(resolve => { return new Promise(resolve => {
Promise.all(promises) Promise.all(promises).then(results => {
.then((results) => {
resolve(this.formatResult(results)); resolve(this.formatResult(results));
}); });
}); });
} }
sendRequest(word, sourceLang, targetLang) { sendRequest(word, sourceLang, targetLang) {
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sourceLang}&tl=${targetLang}&dt=t&dt=bd&q=${encodeURIComponent(word)}`; const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sourceLang}&tl=${targetLang}&dt=t&dt=bd&q=${encodeURIComponent(
word
)}`;
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.responseType = 'json'; xhr.responseType = "json";
xhr.open("GET", url); xhr.open("GET", url);
xhr.send(); xhr.send();
@ -40,22 +39,22 @@ class Translate {
xhr.onload = () => { xhr.onload = () => {
resolve(xhr); resolve(xhr);
}; };
}) });
} }
formatResult(results) { formatResult(results) {
const resultData = { const resultData = {
resultText: '', resultText: "",
candidateText: '', candidateText: "",
sourceLanguage: '', sourceLanguage: "",
percentage: 0 percentage: 0
} };
//翻訳元言語を取得 //翻訳元言語を取得
resultData.sourceLanguage = results[0].response[2]; resultData.sourceLanguage = results[0].response[2];
resultData.percentage = results[0].response[6]; resultData.percentage = results[0].response[6];
let candidateText = ''; let candidateText = "";
let wordCount = 0; let wordCount = 0;
let lineCount = 0; let lineCount = 0;
@ -66,7 +65,7 @@ class Translate {
for (const response of result.response[0]) { for (const response of result.response[0]) {
resultData.resultText += response[0]; resultData.resultText += response[0];
} }
resultData.resultText += '\n'; resultData.resultText += "\n";
//訳候補を取得 //訳候補を取得
if (result.response[1]) { if (result.response[1]) {
@ -74,7 +73,9 @@ class Translate {
for (let i = 0; i < result.response[1].length; i++) { for (let i = 0; i < result.response[1].length; i++) {
const partsOfSpeech = result.response[1][i][0]; const partsOfSpeech = result.response[1][i][0];
const candidates = result.response[1][i][1]; const candidates = result.response[1][i][1];
candidateText += `${partsOfSpeech}${partsOfSpeech != '' ? ': ' : ''}${candidates.join(', ')}\n`; candidateText += `${partsOfSpeech}${partsOfSpeech != "" ? ": " : ""}${candidates.join(
", "
)}\n`;
} }
} }
} }