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

View file

@ -19,7 +19,8 @@
"message": "Target language"
},
"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": {
@ -65,7 +66,8 @@
"message": "Do not display the button if translation is not required"
},
"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": {
@ -75,7 +77,8 @@
"message": "Automatically switch to the second language"
},
"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": {
"message": "Second language"
@ -84,14 +87,15 @@
"message": "Select the second target language."
},
"menuLabel":{
"menuLabel": {
"message": "Context menu"
},
"ifShowMenuLabel": {
"message": "Display the context menu"
},
"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": {
@ -150,7 +154,8 @@
"message": "Please make a donation"
},
"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": {
"message": "amazon.co.jp eGift Cards"
@ -162,10 +167,9 @@
"message": "https://www.amazon.co.jp/dp/B004N3APGO?language=en_US"
},
"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": {
"message": "Translate this page"
},

View file

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

View file

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

View file

@ -9,7 +9,8 @@
}
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-weight: 400;
color: var(--main-text);
@ -17,7 +18,6 @@ body {
line-height: 1.5;
display: flex;
flex-direction: row;
}
p {
@ -41,7 +41,6 @@ hr {
margin-bottom: 20px;
}
/*----sidebar----*/
#sidebar {
@ -87,7 +86,6 @@ hr {
color: var(--highlight);
}
/*----contents----*/
#contents {
@ -95,7 +93,6 @@ hr {
padding-left: 20px;
padding-bottom: 50px;
width: 650px;
}
.contentTitle {
@ -121,7 +118,8 @@ hr {
border-left: solid 10px var(--line);
}
.categoryContainer {}
.categoryContainer {
}
.categoryElements {
padding-left: 20px;
@ -198,7 +196,6 @@ hr {
float: left;
}
/*----forms----*/
input {
@ -273,7 +270,6 @@ a:link {
text-decoration-line: none;
}
a:visited {
color: var(--sub-text);
}
@ -289,7 +285,6 @@ a:visited {
text-decoration-line: underline;
}
input[type="checkbox"] {
display: none;
}

View file

@ -2,7 +2,7 @@
* 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
* 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 secondTargetLang = document.getElementById("secondTargetLang");
@ -19,7 +19,7 @@ function setLangList() {
let langListHtml = "";
for (let i of langList) {
langListHtml += `<option value=${i[0]}>${i[1]}</option>`
langListHtml += `<option value=${i[0]}>${i[1]}</option>`;
}
targetLang.innerHTML = langListHtml;
secondTargetLang.innerHTML = langListHtml;
@ -36,7 +36,9 @@ function alphabeticallySort(a, b) {
}
function initialSetting() {
switch (browser.i18n.getUILanguage()) { //一部の言語はブラウザの設定に合わせる
switch (
browser.i18n.getUILanguage() //一部の言語はブラウザの設定に合わせる
) {
case "ja":
case "zh-CN":
case "zh-TW":
@ -55,12 +57,12 @@ function initialSetting() {
}
}
S.initOptionsPage().then(function () {
S.initOptionsPage().then(function() {
const saveByChangeItems = document.getElementsByClassName("saveByChange");
for (let item of saveByChangeItems) {
item.addEventListener("change", save)
item.addEventListener("change", save);
}
})
});
function save() {
S.saveOptionsPage();

View file

@ -6,8 +6,8 @@
let e = {};
e.hash = location.href;
if (e.hash.indexOf('#') != -1) {
e.hash = '#' + e.hash.split('#')[1];
if (e.hash.indexOf("#") != -1) {
e.hash = "#" + e.hash.split("#")[1];
} else {
e.hash = "#settings";
}
@ -18,7 +18,7 @@ tm.HashObserver.enable();
document.addEventListener("changehash", readHash, false);
function readHash(e) {
const hash = e.hash.split('?')[0];
const hash = e.hash.split("?")[0];
let selected = document.getElementsByClassName("selected");
selected[0].classList.remove("selected");
@ -43,7 +43,7 @@ function readHash(e) {
const params = getParams(e.hash);
switch (params.action) {
case 'updated':
case "updated":
showUpdated();
break;
}
@ -51,19 +51,22 @@ function readHash(e) {
function getParams(hash) {
let params = {};
if (hash.split('?')[1] == undefined) return params;
hash = hash.split('?')[1].split('&');
if (hash.split("?")[1] == undefined) return params;
hash = hash.split("?")[1].split("&");
for (let i of hash) {
params[i.split('=')[0]] = i.split('=')[1];
params[i.split("=")[0]] = i.split("=")[1];
}
return params;
}
function showUpdated() {
const version = document.getElementsByClassName('addonVersion')[0];
version.classList.add('updated');
const version = document.getElementsByClassName("addonVersion")[0];
version.classList.add("updated");
}
document.getElementsByClassName("addonUrl")[0].href = browser.i18n.getMessage("addonUrl");
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 {
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;
font-size: 13px;
width: 348px;
@ -119,7 +120,7 @@ textarea {
textarea:hover,
textarea:focus {
border-color: var(--highlight)
border-color: var(--highlight);
}
hr {
@ -143,18 +144,18 @@ hr {
background-color: var(--main-bg);
}
#target .result{
#target .result {
background-color: var(--main-bg);
}
#target .candidate {
color: var(--sub-text);
margin-top:1em;
margin-top: 1em;
background-color: var(--main-bg);
}
#target .candidate:empty {
margin-top:0;
margin-top: 0;
}
#footer {
@ -179,7 +180,6 @@ hr {
text-decoration: underline;
}
select {
-moz-appearance: none;
text-overflow: ellipsis;

View file

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

View file

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

View file

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