SerialCom

Traduzir páginas da web

May 26th, 2022
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.18 KB | None | 0 0
  1. contentScript/translateSelected.js:822 (função anônima)
  2.  
  3. "use strict";
  4.  
  5. //TODO desativar o botão caso a pagina esteja traduzida
  6.  
  7. var translateSelected = {}
  8.  
  9. function getTabHostName() {
  10. return new Promise(resolve => chrome.runtime.sendMessage({action: "getTabHostName"}, result => resolve(result)))
  11. }
  12.  
  13. Promise.all([twpConfig.onReady(), getTabHostName()])
  14. .then(function (_) {
  15. const tabHostName = _[1]
  16. let styleTextContent = ""
  17. fetch(chrome.runtime.getURL("/contentScript/css/translateSelected.css"))
  18. .then(response => response.text())
  19. .then(response => {
  20. styleTextContent = response.replace('/icons/icon-32.png', chrome.runtime.getURL("/icons/icon-32.png"))
  21. })
  22. .catch(e => console.error(e))
  23.  
  24. let divElement
  25. let eButtonTransSelText
  26. let eDivResult
  27. let eSelTextTrans
  28. let eOrigText
  29. let eOrigTextDiv
  30.  
  31. let originalTabLanguage = "und"
  32. let currentTargetLanguages = twpConfig.get("targetLanguages")
  33. let currentTargetLanguage = twpConfig.get("targetLanguageTextTranslation")
  34. let currentTextTranslatorService = twpConfig.get("textTranslatorService")
  35. let awaysTranslateThisSite = twpConfig.get("alwaysTranslateSites").indexOf(tabHostName) !== -1
  36. let translateThisSite = twpConfig.get("neverTranslateSites").indexOf(tabHostName) === -1
  37. let translateThisLanguage = twpConfig.get("neverTranslateLangs").indexOf(originalTabLanguage) === -1
  38. let showTranslateSelectedButton = twpConfig.get("showTranslateSelectedButton")
  39. let dontShowIfPageLangIsTargetLang = twpConfig.get("dontShowIfPageLangIsTargetLang")
  40. let dontShowIfPageLangIsUnknown = twpConfig.get("dontShowIfPageLangIsUnknown")
  41. let dontShowIfSelectedTextIsTargetLang = twpConfig.get("dontShowIfSelectedTextIsTargetLang")
  42. let dontShowIfSelectedTextIsUnknown = twpConfig.get("dontShowIfSelectedTextIsUnknown")
  43. let fooCount = 0
  44.  
  45. pageTranslator.onGetOriginalTabLanguage(function (tabLanguage) {
  46. originalTabLanguage = tabLanguage
  47. translateThisLanguage = twpConfig.get("neverTranslateLangs").indexOf(originalTabLanguage) === -1
  48. updateEventListener()
  49. })
  50.  
  51. async function detectTextLanguage(text) {
  52. if (!chrome.i18n.detectLanguage) return "und"
  53.  
  54. return await new Promise(resolve => {
  55. chrome.i18n.detectLanguage(text, result => {
  56. if (!result) return resolve("und")
  57.  
  58. for (const langInfo of result.languages) {
  59. const langCode = twpLang.checkLanguageCode(langInfo.language)
  60. if (langCode) {
  61. return resolve(langCode)
  62. }
  63. }
  64.  
  65. return resolve("und")
  66. })
  67. })
  68. }
  69.  
  70. let audioDataUrls = null
  71. let isPlayingAudio = false
  72.  
  73. function stopAudio() {
  74. if (isPlayingAudio) {
  75. chrome.runtime.sendMessage({
  76. action: "stopAudio"
  77. })
  78. }
  79. isPlayingAudio = false
  80. }
  81.  
  82. function dragElement(elmnt, elmnt2) {
  83. var pos1 = 0,
  84. pos2 = 0,
  85. pos3 = 0,
  86. pos4 = 0;
  87. if (elmnt2) {
  88. elmnt2.addEventListener("mousedown", dragMouseDown);
  89. } else {
  90. elmnt.addEventListener("mousedown", dragMouseDown);
  91. }
  92.  
  93. function dragMouseDown(e) {
  94. e = e || window.event;
  95. e.preventDefault();
  96. // get the mouse cursor position at startup:
  97. pos3 = e.clientX;
  98. pos4 = e.clientY;
  99. document.addEventListener("mouseup", closeDragElement);
  100. // call a function whenever the cursor moves:
  101. document.addEventListener("mousemove", elementDrag);
  102. }
  103.  
  104. function elementDrag(e) {
  105. e = e || window.event;
  106. e.preventDefault();
  107. // calculate the new cursor position:
  108. pos1 = pos3 - e.clientX;
  109. pos2 = pos4 - e.clientY;
  110. pos3 = e.clientX;
  111. pos4 = e.clientY;
  112. // set the element's new position:
  113. elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
  114. elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  115. }
  116.  
  117. function closeDragElement() {
  118. // stop moving when mouse button is released:
  119. document.removeEventListener("mouseup", closeDragElement);
  120. document.removeEventListener("mousemove", elementDrag);
  121. }
  122. }
  123.  
  124. function setCaretAtEnd() {
  125. const el = eOrigText
  126. const range = document.createRange()
  127. const sel = window.getSelection()
  128. range.setStart(el, 1)
  129. range.collapse(true)
  130. sel.removeAllRanges()
  131. sel.addRange(range)
  132. el.focus()
  133. }
  134.  
  135. function init() {
  136. destroy()
  137.  
  138. window.isTranslatingSelected = true
  139.  
  140. divElement = document.createElement("div")
  141. divElement.style = "all: initial"
  142. divElement.classList.add("notranslate")
  143.  
  144. const shadowRoot = divElement.attachShadow({
  145. mode: "closed"
  146. })
  147. shadowRoot.innerHTML = `
  148. <link rel="stylesheet" href="${chrome.runtime.getURL("/contentScript/css/translateSelected.css")}">
  149.  
  150. <div id="eButtonTransSelText"></div>
  151. <div id="eDivResult">
  152. <div id="eOrigTextDiv">
  153. <div id="eOrigText" contentEditable="true" spellcheck="false" dir="auto"></div>
  154. <hr>
  155. </div>
  156. <div id="eSelTextTrans" dir="auto"></div>
  157. <hr>
  158. <div id="drag">
  159. <ul id="setTargetLanguage">
  160. <li value="en" title="English">en</li>
  161. <li value="es" title="Spanish">es</li>
  162. <li value="de" title="German">de</li>
  163. </ul>
  164. <div id="moreOrLess"><i class="arrow up" id="more"></i><i class="arrow down" id="less"></i></div>
  165. <ul>
  166. <li title="Google" id="sGoogle">g</li>
  167. <li title="Yandex" id="sYandex">y</li>
  168. <li title="Bing" id="sBing">b</li>
  169. <li title="DeepL" id="sDeepL" hidden>d</li>
  170. <li title="Listen" data-i18n-title="btnListen" id="listen">
  171. <svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  172. width="14px" height="12px" viewBox="0 0 93.038 93.038" xml:space="preserve">
  173. <g>
  174. <path d="M46.547,75.521c0,1.639-0.947,3.128-2.429,3.823c-0.573,0.271-1.187,0.402-1.797,0.402c-0.966,0-1.923-0.332-2.696-0.973
  175. l-23.098-19.14H4.225C1.892,59.635,0,57.742,0,55.409V38.576c0-2.334,1.892-4.226,4.225-4.226h12.303l23.098-19.14
  176. c1.262-1.046,3.012-1.269,4.493-0.569c1.481,0.695,2.429,2.185,2.429,3.823L46.547,75.521L46.547,75.521z M62.784,68.919
  177. c-0.103,0.007-0.202,0.011-0.304,0.011c-1.116,0-2.192-0.441-2.987-1.237l-0.565-0.567c-1.482-1.479-1.656-3.822-0.408-5.504
  178. c3.164-4.266,4.834-9.323,4.834-14.628c0-5.706-1.896-11.058-5.484-15.478c-1.366-1.68-1.24-4.12,0.291-5.65l0.564-0.565
  179. c0.844-0.844,1.975-1.304,3.199-1.231c1.192,0.06,2.305,0.621,3.061,1.545c4.977,6.09,7.606,13.484,7.606,21.38
  180. c0,7.354-2.325,14.354-6.725,20.24C65.131,68.216,64.007,68.832,62.784,68.919z M80.252,81.976
  181. c-0.764,0.903-1.869,1.445-3.052,1.495c-0.058,0.002-0.117,0.004-0.177,0.004c-1.119,0-2.193-0.442-2.988-1.237l-0.555-0.555
  182. c-1.551-1.55-1.656-4.029-0.246-5.707c6.814-8.104,10.568-18.396,10.568-28.982c0-11.011-4.019-21.611-11.314-29.847
  183. c-1.479-1.672-1.404-4.203,0.17-5.783l0.554-0.555c0.822-0.826,1.89-1.281,3.115-1.242c1.163,0.033,2.263,0.547,3.036,1.417
  184. c8.818,9.928,13.675,22.718,13.675,36.01C93.04,59.783,88.499,72.207,80.252,81.976z"/>
  185. </g>
  186. <g>
  187. </g>
  188. <g>
  189. </g>
  190. <g>
  191. </g>
  192. <g>
  193. </g>
  194. <g>
  195. </g>
  196. <g>
  197. </g>
  198. <g>
  199. </g>
  200. <g>
  201. </g>
  202. <g>
  203. </g>
  204. <g>
  205. </g>
  206. <g>
  207. </g>
  208. <g>
  209. </g>
  210. <g>
  211. </g>
  212. <g>
  213. </g>
  214. <g>
  215. </g>
  216. </svg>
  217. </li>
  218. </ul>
  219. </div>
  220. </div>
  221. `
  222.  
  223. {
  224. const style = document.createElement("style")
  225. style.textContent = styleTextContent
  226. shadowRoot.insertBefore(style, shadowRoot.getElementById("eButtonTransSelText"))
  227. }
  228.  
  229. dragElement(shadowRoot.getElementById("eDivResult"), shadowRoot.getElementById("drag"))
  230.  
  231. function enableDarkMode() {
  232. if (!shadowRoot.getElementById("darkModeElement")) {
  233. const el = document.createElement("style")
  234. el.setAttribute("id", "darkModeElement")
  235. el.setAttribute("rel", "stylesheet")
  236. el.textContent = `
  237. * {
  238. scrollbar-color: #202324 #454a4d;
  239. }
  240. #eDivResult {
  241. color: rgb(231, 230, 228) !important;
  242. background-color: #181a1b !important;
  243. }
  244. hr {
  245. border-color: #666;
  246. }
  247. li:hover, #moreOrLess:hover {
  248. color: rgb(231, 230, 228) !important;
  249. background-color: #454a4d !important;
  250. }
  251. .selected {
  252. background-color: #454a4d !important;
  253. }
  254. .arrow {
  255. border: solid rgb(231, 230, 228);
  256. border-width: 0 1px 1px 0;
  257. }
  258. `
  259. shadowRoot.appendChild(el)
  260. shadowRoot.querySelector("#listen svg").style = "fill: rgb(231, 230, 228)"
  261. }
  262. }
  263.  
  264. function disableDarkMode() {
  265. if (shadowRoot.getElementById("#darkModeElement")) {
  266. shadowRoot.getElementById("#darkModeElement").remove()
  267. shadowRoot.querySelector("#listen svg").style = "fill: black"
  268. }
  269. }
  270.  
  271. switch (twpConfig.get("darkMode")) {
  272. case "auto":
  273. if (matchMedia("(prefers-color-scheme: dark)").matches) {
  274. enableDarkMode()
  275. } else {
  276. disableDarkMode()
  277. }
  278. break
  279. case "yes":
  280. enableDarkMode()
  281. break
  282. case "no":
  283. disableDarkMode()
  284. break
  285. default:
  286. break
  287. }
  288.  
  289. eButtonTransSelText = shadowRoot.getElementById("eButtonTransSelText")
  290. eDivResult = shadowRoot.getElementById("eDivResult")
  291. eSelTextTrans = shadowRoot.getElementById("eSelTextTrans")
  292. eOrigText = shadowRoot.getElementById("eOrigText")
  293. eOrigTextDiv = shadowRoot.getElementById("eOrigTextDiv")
  294.  
  295. const eMoreOrLess = shadowRoot.getElementById("moreOrLess")
  296. const eMore = shadowRoot.getElementById("more")
  297. const eLess = shadowRoot.getElementById("less")
  298.  
  299. const sGoogle = shadowRoot.getElementById("sGoogle")
  300. const sYandex = shadowRoot.getElementById("sYandex")
  301. const sBing = shadowRoot.getElementById("sBing")
  302. const sDeepL = shadowRoot.getElementById("sDeepL")
  303.  
  304. eOrigText.onkeypress = e => {
  305. e.stopPropagation()
  306. }
  307.  
  308. eOrigText.onkeydown = e => {
  309. e.stopPropagation()
  310. }
  311.  
  312. let translateNewInputTimerHandler
  313. eOrigText.oninput = () => {
  314. clearTimeout(translateNewInputTimerHandler)
  315. translateNewInputTimerHandler = setTimeout(translateNewInput, 800)
  316. }
  317.  
  318. eMoreOrLess.onclick = () => {
  319. if (twpConfig.get("expandPanelTranslateSelectedText") === "no") {
  320. twpConfig.set("expandPanelTranslateSelectedText", "yes")
  321. } else {
  322. twpConfig.set("expandPanelTranslateSelectedText", "no")
  323. }
  324.  
  325. setCaretAtEnd()
  326. }
  327.  
  328. sGoogle.onclick = () => {
  329. currentTextTranslatorService = "google"
  330. twpConfig.set("textTranslatorService", "google")
  331. translateNewInput()
  332.  
  333. sGoogle.classList.remove("selected")
  334. sYandex.classList.remove("selected")
  335. sBing.classList.remove("selected")
  336. sDeepL.classList.remove("selected")
  337.  
  338. sGoogle.classList.add("selected")
  339. }
  340. sYandex.onclick = () => {
  341. currentTextTranslatorService = "yandex"
  342. twpConfig.set("textTranslatorService", "yandex")
  343. translateNewInput()
  344.  
  345. sGoogle.classList.remove("selected")
  346. sYandex.classList.remove("selected")
  347. sBing.classList.remove("selected")
  348. sDeepL.classList.remove("selected")
  349.  
  350. sYandex.classList.add("selected")
  351. }
  352. sBing.onclick = () => {
  353. currentTextTranslatorService = "bing"
  354. twpConfig.set("textTranslatorService", "bing")
  355. translateNewInput()
  356.  
  357. sGoogle.classList.remove("selected")
  358. sYandex.classList.remove("selected")
  359. sBing.classList.remove("selected")
  360. sDeepL.classList.remove("selected")
  361.  
  362. sBing.classList.add("selected")
  363. }
  364. sDeepL.onclick = () => {
  365. currentTextTranslatorService = "deepl"
  366. twpConfig.set("textTranslatorService", "deepl")
  367. translateNewInput()
  368.  
  369. sGoogle.classList.remove("selected")
  370. sYandex.classList.remove("selected")
  371. sBing.classList.remove("selected")
  372. sDeepL.classList.remove("selected")
  373.  
  374. sDeepL.classList.add("selected")
  375. }
  376.  
  377. const setTargetLanguage = shadowRoot.getElementById("setTargetLanguage")
  378. setTargetLanguage.onclick = e => {
  379. if (e.target.getAttribute("value")) {
  380. const langCode = twpLang.checkLanguageCode(e.target.getAttribute("value"))
  381. if (langCode) {
  382. currentTargetLanguage = langCode
  383. twpConfig.setTargetLanguageTextTranslation(langCode)
  384. translateNewInput()
  385. }
  386.  
  387. shadowRoot.querySelectorAll("#setTargetLanguage li").forEach(li => {
  388. li.classList.remove("selected")
  389. })
  390.  
  391. e.target.classList.add("selected")
  392. }
  393. }
  394.  
  395. const eListen = shadowRoot.getElementById("listen")
  396. eListen.onclick = () => {
  397. const msgListen = chrome.i18n.getMessage("btnListen")
  398. const msgStopListening = chrome.i18n.getMessage("btnStopListening")
  399.  
  400. eListen.classList.remove("selected")
  401. eListen.setAttribute("title", msgStopListening)
  402.  
  403. if (audioDataUrls) {
  404. if (isPlayingAudio) {
  405. stopAudio()
  406. eListen.setAttribute("title", msgListen)
  407. } else {
  408. isPlayingAudio = true
  409. chrome.runtime.sendMessage({
  410. action: "playAudio",
  411. audioDataUrls
  412. }, () => {
  413. eListen.classList.remove("selected")
  414. eListen.setAttribute("title", msgListen)
  415. })
  416. eListen.classList.add("selected")
  417. }
  418. } else {
  419. stopAudio()
  420. isPlayingAudio = true
  421. chrome.runtime.sendMessage({
  422. action: "textToSpeech",
  423. text: eSelTextTrans.textContent,
  424. targetLanguage: currentTargetLanguage
  425. }, result => {
  426. if (!result) return;
  427.  
  428. audioDataUrls = result
  429. chrome.runtime.sendMessage({
  430. action: "playAudio",
  431. audioDataUrls
  432. }, () => {
  433. isPlayingAudio = false
  434. eListen.classList.remove("selected")
  435. eListen.setAttribute("title", msgListen)
  436. })
  437. })
  438. eListen.classList.add("selected")
  439. }
  440. }
  441.  
  442. document.body.appendChild(divElement)
  443.  
  444. chrome.i18n.translateDocument(shadowRoot)
  445.  
  446. if (platformInfo.isMobile.any) {
  447. eButtonTransSelText.style.width = "30px"
  448. eButtonTransSelText.style.height = "30px"
  449. document.addEventListener("touchstart", onTouchstart)
  450. }
  451.  
  452. eButtonTransSelText.addEventListener("click", onClick)
  453. document.addEventListener("mousedown", onDown)
  454.  
  455. const targetLanguageButtons = shadowRoot.querySelectorAll("#setTargetLanguage li")
  456.  
  457. for (let i = 0; i < 3; i++) {
  458. if (currentTargetLanguages[i] == currentTargetLanguage) {
  459. targetLanguageButtons[i].classList.add("selected")
  460. }
  461. targetLanguageButtons[i].textContent = currentTargetLanguages[i]
  462. targetLanguageButtons[i].setAttribute("value", currentTargetLanguages[i])
  463. targetLanguageButtons[i].setAttribute("title", twpLang.codeToLanguage(currentTargetLanguages[i]))
  464. }
  465.  
  466. if (currentTextTranslatorService === "yandex") {
  467. sYandex.classList.add("selected")
  468. } else if (currentTextTranslatorService == "deepl") {
  469. sDeepL.classList.add("selected")
  470. } else if (currentTextTranslatorService == "bing") {
  471. sBing.classList.add("selected")
  472. } else {
  473. sGoogle.classList.add("selected")
  474. }
  475.  
  476. if (twpConfig.get("enableDeepL") === "yes") {
  477. sDeepL.removeAttribute("hidden")
  478. } else {
  479. sDeepL.setAttribute("hidden", "")
  480. }
  481. if (twpConfig.get("expandPanelTranslateSelectedText") === "yes") {
  482. eOrigTextDiv.style.display = "block"
  483. eMore.style.display = "none"
  484. eLess.style.display = "block"
  485. eMoreOrLess.setAttribute("title", chrome.i18n.getMessage("less"))
  486. } else {
  487. eOrigTextDiv.style.display = "none"
  488. eMore.style.display = "block"
  489. eLess.style.display = "none"
  490. eMoreOrLess.setAttribute("title", chrome.i18n.getMessage("more"))
  491. }
  492. twpConfig.onChanged((name, newvalue) => {
  493. switch (name) {
  494. case "enableDeepL":
  495. if (newvalue === "yes") {
  496. sDeepL.removeAttribute("hidden")
  497. } else {
  498. sDeepL.setAttribute("hidden", "")
  499. }
  500. break
  501. case "expandPanelTranslateSelectedText":
  502. if (newvalue === "yes") {
  503. eOrigTextDiv.style.display = "block"
  504. eMore.style.display = "none"
  505. eLess.style.display = "block"
  506. eMoreOrLess.setAttribute("title", chrome.i18n.getMessage("less"))
  507. } else {
  508. eOrigTextDiv.style.display = "none"
  509. eMore.style.display = "block"
  510. eLess.style.display = "none"
  511. eMoreOrLess.setAttribute("title", chrome.i18n.getMessage("more"))
  512. }
  513. break
  514. }
  515. })
  516. }
  517.  
  518. function destroy() {
  519. window.isTranslatingSelected = false
  520. fooCount++
  521. stopAudio()
  522. audioDataUrls = null
  523. if (!divElement) return;
  524.  
  525. eButtonTransSelText.removeEventListener("click", onClick)
  526. document.removeEventListener("mousedown", onDown)
  527. if (platformInfo.isMobile.any) {
  528. document.removeEventListener("touchstart", onTouchstart)
  529. }
  530. divElement.remove()
  531. divElement = eButtonTransSelText = eDivResult = null
  532. }
  533.  
  534. function destroyIfButtonIsShowing(e) {
  535. if (eButtonTransSelText && e.target !== divElement && eButtonTransSelText.style.display === "block") {
  536. destroy()
  537. }
  538. }
  539.  
  540. twpConfig.onChanged(function (name, newValue) {
  541. switch (name) {
  542. case "textTranslatorService":
  543. currentTextTranslatorService = newValue
  544. break
  545. case "targetLanguages":
  546. currentTargetLanguages = newValue
  547. break
  548. case "targetLanguageTextTranslation":
  549. currentTargetLanguage = newValue
  550. break
  551. case "alwaysTranslateSites":
  552. awaysTranslateThisSite = newValue.indexOf(tabHostName) !== -1
  553. updateEventListener()
  554. break
  555. case "neverTranslateSites":
  556. translateThisSite = newValue.indexOf(tabHostName) === -1
  557. updateEventListener()
  558. break
  559. case "neverTranslateLangs":
  560. translateThisLanguage = newValue.indexOf(originalTabLanguage) === -1
  561. updateEventListener()
  562. break
  563. case "showTranslateSelectedButton":
  564. showTranslateSelectedButton = newValue
  565. updateEventListener()
  566. break
  567. case "dontShowIfPageLangIsTargetLang":
  568. dontShowIfPageLangIsTargetLang = newValue
  569. updateEventListener()
  570. break
  571. case "dontShowIfPageLangIsUnknown":
  572. dontShowIfPageLangIsUnknown = newValue
  573. updateEventListener()
  574. break
  575. case "dontShowIfSelectedTextIsTargetLang":
  576. dontShowIfSelectedTextIsTargetLang = newValue
  577. break
  578. case "dontShowIfSelectedTextIsUnknown":
  579. dontShowIfSelectedTextIsUnknown = newValue
  580. break
  581. }
  582. })
  583.  
  584. function update_eDivResult(result = "") {
  585. if (eDivResult.style.display !== "block") {
  586. init()
  587. }
  588. const eTop = prevSelectionInfo.bottom
  589. const eLeft = prevSelectionInfo.left
  590.  
  591. if (twpLang.isRtlLanguage(currentTargetLanguage)) {
  592. eSelTextTrans.setAttribute("dir", "rtl")
  593. } else {
  594. eSelTextTrans.setAttribute("dir", "ltr")
  595. }
  596. eSelTextTrans.textContent = result
  597. if (eDivResult.style.display !== "block") {
  598. eDivResult.style.display = "block"
  599. eDivResult.style.top = "0px"
  600. eDivResult.style.left = "0px"
  601. eOrigText.textContent = prevSelectionInfo.text
  602.  
  603. setCaretAtEnd()
  604.  
  605. const height = parseInt(eDivResult.offsetHeight)
  606. let top = eTop + 5
  607. top = Math.max(0, top)
  608. top = Math.min(window.innerHeight - height, top)
  609.  
  610. const width = parseInt(eDivResult.offsetWidth)
  611. let left = parseInt(eLeft /*- width / 2*/ )
  612. left = Math.max(0, left)
  613. left = Math.min(window.innerWidth - width, left)
  614.  
  615. eDivResult.style.top = top + "px"
  616. eDivResult.style.left = left + "px"
  617. }
  618. }
  619.  
  620. function translateNewInput() {
  621. fooCount++
  622. let currentFooCount = fooCount
  623. stopAudio()
  624. audioDataUrls = null
  625.  
  626. backgroundTranslateSingleText(currentTextTranslatorService, currentTargetLanguage, eOrigText.textContent)
  627. .then(result => {
  628. if (currentFooCount !== fooCount) return;
  629.  
  630. update_eDivResult(result)
  631. })
  632. }
  633.  
  634. let gSelectionInfo
  635. let prevSelectionInfo
  636.  
  637. function translateSelText(usePrevSelectionInfo = false) {
  638. if (!usePrevSelectionInfo && gSelectionInfo) {
  639. prevSelectionInfo = gSelectionInfo
  640. } else if (!(usePrevSelectionInfo && prevSelectionInfo)) {
  641. return
  642. }
  643.  
  644. eOrigText.textContent = prevSelectionInfo.text
  645.  
  646. translateNewInput()
  647. const currentFooCount = fooCount
  648. setTimeout(() => {
  649. if (currentFooCount !== fooCount) return;
  650. update_eDivResult(eSelTextTrans.textContent)
  651. fooCount = currentFooCount
  652. }, 1000)
  653. }
  654.  
  655. function onClick(e) {
  656. translateSelText()
  657. eButtonTransSelText.style.display = "none"
  658. }
  659.  
  660. function onDown(e) {
  661. if (e.target != divElement) {
  662. eDivResult.style.display = "none"
  663. eButtonTransSelText.style.display = "none"
  664. destroy()
  665. }
  666. }
  667.  
  668.  
  669. let isTouchSelection = false
  670.  
  671. function onTouchstart(e) {
  672. isTouchSelection = true
  673. onDown(e)
  674. }
  675.  
  676. function getSelectionText() {
  677. let text = "";
  678. const activeEl = document.activeElement;
  679. const activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
  680. if (
  681. (activeElTagName == "textarea") || (activeElTagName == "input" &&
  682. /^(?:text|search)$/i.test(activeEl.type)) &&
  683. (typeof activeEl.selectionStart == "number")
  684. ) {
  685. text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
  686. } else if (window.getSelection) {
  687. text = window.getSelection().toString();
  688. }
  689. return text;
  690. }
  691.  
  692. function readSelection(dontReadIfSelectionDontChange = false) {
  693. let newSelectionInfo = null
  694.  
  695. const activeEl = document.activeElement;
  696. const activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
  697. if (
  698. (activeElTagName == "textarea") || (activeElTagName == "input" &&
  699. /^(?:text|search)$/i.test(activeEl.type)) &&
  700. (typeof activeEl.selectionStart == "number")
  701. ) {
  702. const text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
  703. const rect = activeEl.getBoundingClientRect()
  704. newSelectionInfo = {
  705. text: text,
  706. top: rect.top,
  707. left: rect.left,
  708. bottom: rect.bottom,
  709. right: rect.right
  710. }
  711. } else if (window.getSelection) {
  712. const selection = window.getSelection()
  713. if (selection.type == "Range") {
  714. const text = selection.toString();
  715. const rect = selection.getRangeAt(0).getBoundingClientRect()
  716. newSelectionInfo = {
  717. text: text,
  718. top: rect.top,
  719. left: rect.left,
  720. bottom: rect.bottom,
  721. right: rect.right
  722. }
  723. }
  724. }
  725.  
  726. if (dontReadIfSelectionDontChange && gSelectionInfo && newSelectionInfo && gSelectionInfo.text === newSelectionInfo.text) {
  727. gSelectionInfo = newSelectionInfo
  728. return false
  729. }
  730. gSelectionInfo = newSelectionInfo
  731. return true
  732. }
  733.  
  734. async function onUp(e) {
  735. if (e.target == divElement) return;
  736.  
  737. const clientX = Math.max((typeof e.clientX === 'undefined' ? 0 : e.clientX), (typeof e.changedTouches === 'undefined' ? 0 : e.changedTouches[0].clientX));
  738. const clientY = Math.max((typeof e.clientY === 'undefined' ? 0 : e.clientY), (typeof e.changedTouches === 'undefined' ? 0 : e.changedTouches[0].clientY));
  739.  
  740. const selectedText = getSelectionText().trim()
  741. if (!selectedText || selectedText.length < 1) return;
  742. let detectedLanguage = await detectTextLanguage(selectedText)
  743. if (!detectedLanguage) detectedLanguage = "und";
  744.  
  745. if (((dontShowIfSelectedTextIsTargetLang == "yes" && detectedLanguage !== currentTargetLanguage) || dontShowIfSelectedTextIsTargetLang != "yes") &&
  746. ((dontShowIfSelectedTextIsUnknown == "yes" && detectedLanguage !== "und") || dontShowIfSelectedTextIsUnknown != "yes")
  747. ) {
  748. init()
  749. if (platformInfo.isMobile.any) {
  750. eButtonTransSelText.style.left = window.innerWidth - 45 + "px"
  751. eButtonTransSelText.style.top = clientY + "px"
  752. } else {
  753. eButtonTransSelText.style.left = clientX + 20 + "px"
  754. eButtonTransSelText.style.top = clientY - 30 + "px"
  755. }
  756.  
  757. eButtonTransSelText.style.display = "block"
  758. }
  759. }
  760.  
  761. let showButtonTimerHandler = null
  762.  
  763. function onMouseup(e) {
  764. if (e.button != 0) return;
  765. if (e.target == divElement) return;
  766. if (readSelection(true)) {
  767. clearTimeout(showButtonTimerHandler)
  768. showButtonTimerHandler = setTimeout(() => onUp(e), 150)
  769. }
  770. }
  771.  
  772. function onTouchend(e) {
  773. if (e.target == divElement) return;
  774. readSelection()
  775. clearTimeout(showButtonTimerHandler)
  776. showButtonTimerHandler = setTimeout(() => onUp(e), 150)
  777. }
  778.  
  779. function onSelectionchange(e) {
  780. if (isTouchSelection) {
  781. readSelection()
  782. }
  783. }
  784.  
  785. function isSelectingText() {
  786. const activeEl = document.activeElement;
  787. const activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
  788. if (
  789. (activeElTagName == "textarea") || (activeElTagName == "input" &&
  790. /^(?:text|search)$/i.test(activeEl.type)) &&
  791. (typeof activeEl.selectionStart == "number")
  792. ) {
  793. const text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
  794. if (text) return true;
  795. } else if (window.getSelection) {
  796. const selection = window.getSelection()
  797. if (selection.type == "Range") {
  798. const text = selection.toString();
  799. if (text) return true;
  800. }
  801. }
  802. return false
  803. }
  804.  
  805. let lastTimePressedCtrl = null
  806.  
  807. function onKeyUp(e) {
  808. if (twpConfig.get("translateSelectedWhenPressTwice") !== "yes") return;
  809. if (e.key == "Control") {
  810. if (lastTimePressedCtrl && performance.now() - lastTimePressedCtrl < 280 && isSelectingText()) {
  811. lastTimePressedCtrl = performance.now()
  812. readSelection()
  813. init()
  814. translateSelText()
  815. }
  816. lastTimePressedCtrl = performance.now()
  817. }
  818. }
  819. document.addEventListener("keyup", onKeyUp)
  820.  
  821. let windowIsInFocus = true
  822. window.addEventListener("focus", function (e) {
  823. windowIsInFocus = true
  824. chrome.runtime.sendMessage({action: "thisFrameIsInFocus"})
  825. })
  826. window.addEventListener("blur", function (e) {
  827. windowIsInFocus = false
  828. })
  829.  
  830. window.addEventListener("beforeunload", function (e) {
  831. destroy()
  832. })
  833.  
  834. function updateEventListener() {
  835. if (showTranslateSelectedButton == "yes" && (awaysTranslateThisSite || (translateThisSite && translateThisLanguage)) &&
  836. ((dontShowIfPageLangIsTargetLang == "yes" && originalTabLanguage !== currentTargetLanguage) || dontShowIfPageLangIsTargetLang != "yes") &&
  837. ((dontShowIfPageLangIsUnknown == "yes" && originalTabLanguage !== "und") || dontShowIfPageLangIsUnknown != "yes")
  838. ) {
  839. document.addEventListener("mouseup", onMouseup)
  840.  
  841. document.addEventListener("blur", destroyIfButtonIsShowing)
  842. document.addEventListener("visibilitychange", destroyIfButtonIsShowing)
  843.  
  844. document.addEventListener("keydown", destroyIfButtonIsShowing)
  845. document.addEventListener("mousedown", destroyIfButtonIsShowing)
  846. document.addEventListener("wheel", destroyIfButtonIsShowing)
  847.  
  848. if (platformInfo.isMobile.any) {
  849. document.addEventListener("touchend", onTouchend)
  850. document.addEventListener("selectionchange", onSelectionchange)
  851. }
  852. } else {
  853. document.removeEventListener("mouseup", onMouseup)
  854.  
  855. document.removeEventListener("blur", destroyIfButtonIsShowing)
  856. document.removeEventListener("visibilitychange", destroyIfButtonIsShowing)
  857.  
  858. document.removeEventListener("keydown", destroyIfButtonIsShowing)
  859. document.removeEventListener("mousedown", destroyIfButtonIsShowing)
  860. document.removeEventListener("wheel", destroyIfButtonIsShowing)
  861.  
  862. if (platformInfo.isMobile.any) {
  863. document.removeEventListener("touchend", onTouchend)
  864. document.removeEventListener("selectionchange", onSelectionchange)
  865. }
  866. }
  867. }
  868. updateEventListener()
  869.  
  870. chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  871. if (request.action === "TranslateSelectedText") {
  872. readSelection()
  873. init()
  874. translateSelText()
  875. } else if (request.action === "anotherFrameIsInFocus") {
  876. if (!windowIsInFocus) {
  877. destroy()
  878. }
  879. }
  880. })
  881. })
Add Comment
Please, Sign In to add comment