AI Everywhere

Highly customizable mini A.I. floating menu that can define words, answer questions, translate, and much more in a single click and with your custom prompts. Includes useful click to search on Google and copy selected text buttons, along with Rocker+Mouse Gestures and Units+Currency Converters, all features can be easily modified or disabled.

当前为 2024-10-04 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AI Everywhere
  3. // @namespace OperaBrowserGestures
  4. // @description Highly customizable mini A.I. floating menu that can define words, answer questions, translate, and much more in a single click and with your custom prompts. Includes useful click to search on Google and copy selected text buttons, along with Rocker+Mouse Gestures and Units+Currency Converters, all features can be easily modified or disabled.
  5. // @version 70
  6. // @author hacker09
  7. // @include *
  8. // @exclude https://accounts.google.com/v3/signin/*
  9. // @icon https://i.imgur.com/8iw8GOm.png
  10. // @grant GM_registerMenuCommand
  11. // @grant GM_getResourceText
  12. // @grant GM.xmlHttpRequest
  13. // @grant GM_setClipboard
  14. // @grant GM_deleteValue
  15. // @grant GM_openInTab
  16. // @grant window.close
  17. // @run-at document-end
  18. // @grant GM_setValue
  19. // @grant GM_getValue
  20. // @connect google.com
  21. // @connect generativelanguage.googleapis.com
  22. // @resource AICSS https://hacker09.glitch.me/AICSS.css
  23. // @require https://update.greasyfork.org/scripts/506699/1440902/marked.js
  24. // ==/UserScript==
  25.  
  26. /* jshint esversion: 11 */
  27.  
  28. if (GM_getResourceText('AICSS') === '') {
  29. alert('Failed to load the .css file resource!\n\nPlease contact your network admin to have the https://glitch.me/ domain unblocked.\n\n');
  30. return; //Stop running
  31. }
  32.  
  33. const BypassTT = window.trustedTypes?.createPolicy('BypassTT', { createHTML: HTML => HTML }); //Bypass trustedTypes
  34.  
  35. if (GM_getValue("APIKey") === undefined || GM_getValue("APIKey") === null || GM_getValue("APIKey") === '') { //Set up the API Key
  36. window.onload = function() {
  37. if (location.href === 'https://aistudio.google.com/app/apikey' && document.querySelector(".apikey-link") !== null) {
  38. setTimeout(function() {
  39. document.querySelectorAll(".apikey-link")[1].click(); //Click on the API Key
  40. setTimeout(function() {
  41. GM_setValue("APIKey", document.querySelector(".apikey-text").innerText); //Store the API Key
  42. (GM_getValue("APIKey") !== undefined && GM_getValue("APIKey") !== null && GM_getValue("APIKey") !== '') ? alert('API Key automatically added!') : alert('Failed to automatically add API Key!');
  43. }, 500);
  44. }, 500);
  45. }
  46. };
  47. }
  48.  
  49. // Mouse Gestures _________________________________________________________________________________________________________________________________________________________
  50. GM_registerMenuCommand("Enable/Disable Mouse Gestures", MouseGestures);
  51. if (GM_getValue("MouseGestures") !== true && GM_getValue("MouseGestures") !== false) {
  52. GM_setValue("MouseGestures", true);
  53. }
  54.  
  55. function MouseGestures() //Enable/disable MouseGestures
  56. {
  57. if (GM_getValue("MouseGestures") === true) {
  58. GM_setValue("MouseGestures", false);
  59. }
  60. else {
  61. GM_setValue("MouseGestures", true);
  62. location.reload();
  63. }
  64. }
  65.  
  66. if (GM_getValue("MouseGestures") === true) //If the MouseGestures is enabled
  67. {
  68. const SENSITIVITY = 3;
  69. const TOLERANCE = 3;
  70.  
  71. const funcs = { //Store the MouseGestures functions
  72.  
  73. 'L': function() { //Detect the Left movement
  74. window.history.back();
  75. },
  76.  
  77. 'R': function() { //Detect the Right movement
  78. window.history.forward();
  79. },
  80.  
  81. 'D': function() { //Detect the Down movement
  82. if (IsShiftNotPressed === true) { //If the shift key isn't being pressed
  83. GM_openInTab(link, {
  84. active: true,
  85. insert: true,
  86. setParent: true
  87. });
  88. }
  89. },
  90.  
  91. 'UD': function() { //Detect the Up+Down movement
  92. location.reload();
  93. },
  94.  
  95. 'DR': function(e) { //Detect the Down+Right movement
  96. top.close();
  97. e.preventDefault();
  98. e.stopPropagation();
  99. },
  100.  
  101. 'DU': function() { //Detect the Down+Up movement
  102. GM_openInTab(link, {
  103. active: false,
  104. insert: true,
  105. setParent: true
  106. });
  107. }
  108.  
  109. };
  110.  
  111. //Math codes to track the mouse movement gestures
  112. const s = 1 << ((7 - SENSITIVITY) << 1);
  113. const t1 = Math.tan(0.15708 * TOLERANCE),t2 = 1 / t1;
  114.  
  115. var x, y, path;
  116.  
  117. const tracer = function(e) { //Start the const tracer
  118. var cx = e.clientX, cy = e.clientY, deltaX = cx - x, deltaY = cy - y, distance = deltaX * deltaX + deltaY * deltaY;
  119. if (distance > s) {
  120. var slope = Math.abs(deltaY / deltaX), direction = '';
  121. if (slope > t1) {
  122. direction = deltaY > 0 ? 'D' : 'U';
  123. } else if (slope <= t2) {
  124. direction = deltaX > 0 ? 'R' : 'L';
  125. }
  126. if (path.charAt(path.length - 1) !== direction) {
  127. path += direction;
  128. }
  129. x = cx;
  130. y = cy;
  131. }
  132. };
  133.  
  134. window.addEventListener('mousedown', function(e) {
  135. if (e.which === 3) {
  136. x = e.clientX;
  137. y = e.clientY;
  138. path = "";
  139. window.addEventListener('mousemove', tracer, false); //Detect the mouse position
  140. }
  141. }, false);
  142.  
  143. var IsShiftNotPressed = true; //Hold the shift key status
  144. window.addEventListener("contextmenu", function(e) { //When the shift key is/isn't pressed
  145. if (e.shiftKey) {
  146. IsShiftNotPressed = false;
  147. open(link, '_blank', 'height=' + screen.height + ',width=' + screen.width);
  148. }
  149. if (LeftClicked === true) { //If the Left Click was released when the Rocker Mouse Gestures were enabled
  150. e.preventDefault();
  151. e.stopPropagation();
  152. }
  153. setTimeout(function() {
  154. IsShiftNotPressed = true;
  155. }, 500);
  156. }, false);
  157.  
  158. window.addEventListener('contextmenu', function(e) { //When the right click BTN is released
  159. window.removeEventListener('mousemove', tracer, false); //Track the mouse movements
  160. if (path !== "") {
  161. e.preventDefault();
  162. if (funcs.hasOwnProperty(path)) {
  163. funcs[path]();
  164. }
  165. }
  166. }, false);
  167.  
  168. var link;
  169. Array.from(document.querySelectorAll('a')).forEach(Element => Element.onmouseover = function() {
  170. link = this.href; //Store the hovered link to a variable
  171. });
  172.  
  173. Array.from(document.querySelectorAll('a')).forEach(Element => Element.onmouseout = function() {
  174. const PreviousLink = link; //Save the hovered link to a variable
  175. setTimeout(function() {
  176. if (PreviousLink === link) //If the hovered link is still the same as the previously hovered Link
  177. {
  178. link = 'about:newtab'; //Make the script open a new browser tab when the mouse leaves any link that was hovered
  179. }
  180. }, 200);
  181. });
  182. }
  183.  
  184. //Rocker Mouse Gesture Settings _________________________________________________________________________________________________________________________________________________________
  185. GM_registerMenuCommand("Enable/Disable Rocker Mouse Gestures", RockerMouseGestures);
  186. if (GM_getValue("RockerMouseGestures") !== true && GM_getValue("RockerMouseGestures") !== false) { //Set up the RockerMouseGestures
  187. GM_setValue("RockerMouseGestures", false);
  188. }
  189.  
  190. function RockerMouseGestures() //Enable/disable RockerMouseGestures
  191. {
  192. if (GM_getValue("RockerMouseGestures") === true) {
  193. GM_setValue("RockerMouseGestures", false);
  194. }
  195. else {
  196. GM_setValue("RockerMouseGestures", true);
  197. location.reload();
  198. }
  199. }
  200.  
  201. if (GM_getValue("RockerMouseGestures") === true || GM_getValue("SearchHiLight") === true) //If the RockerMouseGestures or the SearchHiLight is enabled
  202. {
  203. var LeftClicked, RightClicked;
  204. window.addEventListener("mousedown", function(e) { //Track which side of the mouse was the first one to be pressed
  205. switch (e.button) {
  206. case 0:
  207. LeftClicked = true;
  208. break;
  209. case 2:
  210. RightClicked = true;
  211. break;
  212. }
  213. }, false);
  214.  
  215. window.addEventListener("mouseup", function(e) { //Track which side of the mouse was the last one to be released
  216. switch (e.button) {
  217. case 0:
  218. LeftClicked = false;
  219. break;
  220. case 2:
  221. RightClicked = false;
  222. break;
  223. }
  224. if (LeftClicked && RightClicked === false) { //If Left was Clicked and then Right Click was released
  225. history.back(); //Go Back
  226. }
  227. if (RightClicked && LeftClicked === false) { //If Right was Clicked and then Left Click was released
  228. history.forward(); //Go Forward
  229. }
  230. }, false);
  231. }
  232.  
  233. //SearchHighLight + CurrenciesConverter + UnitsConverter _______________________________________________________________________________________________________________________________________
  234. GM_registerMenuCommand("Enable/Disable SearchHiLight", SearchHiLight);
  235. if (GM_getValue("SearchHiLight") !== true && GM_getValue("SearchHiLight") !== false) { //Set up the SearchHiLight
  236. GM_setValue("SearchHiLight", true);
  237. }
  238.  
  239. if (GM_getValue("CurrenciesConverter") !== true && GM_getValue("CurrenciesConverter") !== false) {
  240. GM_setValue("CurrenciesConverter", true);
  241. }
  242.  
  243. if (GM_getValue("UnitsConverter") !== true && GM_getValue("UnitsConverter") !== false) {
  244. GM_setValue("UnitsConverter", true);
  245. }
  246.  
  247. function SearchHiLight() //Enable/disable the SearchHiLight and the Currency/Unit converters
  248. {
  249. if (GM_getValue("SearchHiLight") === true) {
  250. GM_setValue("SearchHiLight", false);
  251. GM_setValue("CurrenciesConverter", false);
  252. GM_deleteValue('YourLocalCurrency');
  253. GM_setValue("UnitsConverter", false);
  254. }
  255. else {
  256. GM_setValue("SearchHiLight", true);
  257.  
  258. if (confirm('If you want to enable the Currency Converter press OK.'))
  259. {
  260. GM_setValue("CurrenciesConverter", true);
  261. }
  262. else
  263. {
  264. GM_setValue("CurrenciesConverter", false);
  265. }
  266.  
  267. if (confirm('If you want to enable the Units Converter press OK.'))
  268. {
  269. GM_setValue("UnitsConverter", true);
  270. }
  271. else
  272. {
  273. GM_setValue("UnitsConverter", false);
  274. }
  275. location.reload();
  276. }
  277. }
  278.  
  279. if (GM_getValue("SearchHiLight") === true) //If the SearchHiLight is enabled
  280. {
  281. var SelectedTextIsLink, FinalCurrency, SelectedText, SelectedTextSearch = '';
  282. const Links = new RegExp(/\.org|\.ly|\.net|\.co|\.tv|\.me|\.biz|\.club|\.site|\.br|\.gov|\.io|\.jp|\.edu|\.au|\.in|\.it|\.ca|\.mx|\.fr|\.tw|\.il|\.uk|\.zoom\.us|\youtu.be/i);
  283.  
  284. window.addEventListener('load', function() { //Start the script after the page loads
  285. document.body.addEventListener('mouseup', function() { //When the user releases the mouse click after selecting something
  286. SelectedText = getSelection().toString(); //Store the selected text
  287. SelectedTextSearch = getSelection().toString().replaceAll('&', '%26'); //Store the selected text to be opened on Google
  288. const CurrencySymbols = new RegExp(/\$|R\$|HK\$|US\$|\$US|¥|€|Rp|kn|Kč|kr|zł|£|฿|₩/i);
  289. const Currencies = new RegExp(/^[ \t\xA0]*(?=.*?(\d+(?:.\d+)?))(?=(?:\1[ \t\xA0]*)?(Dólares|dolares|dólares|dollars|AUD|BGN|BRL|BCH|BTC|BYN|CAD|CHF|CNY|CZK|DKK|EUR|EGP|ETH|GBP|GEL|HKD|HRK|HUF|IDR|ILS|INR|JPY|LTC|KRW|MXN|MYR|NOK|NZD|PHP|PLN|RON|RM|RUB|SEK|SGD|THB|TRY|USD|UAH|ZAR|KZT|YTL|\$|R\$|HK\$|US\$|\$US|¥|€|Rp|kn|Kč|kr|zł|£|฿|₩))(?:\1[ \t\xA0]*\2|\2[ \t\xA0]*\1)[ \t\xA0]*$/i);
  290.  
  291. function ShowConvertion(UnitORCurrency, Type, Result) {
  292. shadowRoot.querySelector("#SearchBTN span")?.remove(); //Return previous HTML
  293. shadowRoot.querySelector("#SearchBTN").innerHTML = (html => BypassTT?.createHTML(html) || html)('<span class="GreyBar">│ </span>' + shadowRoot.querySelector("#SearchBTN").innerHTML);
  294.  
  295. if (UnitORCurrency === 'Currencies' && SelectedText.match(Currencies)[2].match(CurrencySymbols) !== null) { //If the selected currency contains a symbol
  296. shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = (html => BypassTT?.createHTML(html) || html)(Type + ' 🠂 ' + Intl.NumberFormat(navigator.language, {
  297. style: 'currency',
  298. currency: GM_getValue("YourLocalCurrency")
  299. }).format(Result)); //Show the FinalCurrency
  300. }
  301. if (UnitORCurrency === 'Currencies' && SelectedText.match(Currencies)[2].match(CurrencySymbols) === null) { //If the selected currency contains no symbol
  302. shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = (html => BypassTT?.createHTML(html) || html)(Intl.NumberFormat(navigator.language, {
  303. style: 'currency',
  304. currency: GM_getValue("YourLocalCurrency")
  305. }).format(Result)); //Show the FinalCurrency
  306. }
  307.  
  308. UnitORCurrency === 'Units' ? shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = (html => BypassTT?.createHTML(html) || html)(Result + ' ' + Type) : ''; //Show the converted unit results
  309.  
  310. var htmlcode = shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML; //Save the converted unit/currency value
  311. setTimeout(() => { //Wait for Units to show up to get the right offsetWidth
  312. var offsetWidth = shadowRoot.querySelector("#ShowCurrencyORUnits").offsetWidth; //Store the current menu size
  313. shadowRoot.querySelector("#ShowCurrencyORUnits").onmouseover = function() { //When the mouse hovers the unit/currency
  314. shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = (html => BypassTT?.createHTML(html) || html)(`Copy`);
  315. shadowRoot.querySelector("#ShowCurrencyORUnits").style.display = 'inline-flex';
  316. shadowRoot.querySelector("#ShowCurrencyORUnits").style.width = `${offsetWidth}px`; //Maintain the aspect ratio
  317. };
  318. }, 0);
  319.  
  320. shadowRoot.querySelector("#ShowCurrencyORUnits").onmouseout = function() { //When the mouse leaves the unit/currency
  321. shadowRoot.querySelector("#ShowCurrencyORUnits").style.width = ''; //Return the original aspect ratio
  322. shadowRoot.querySelector("#ShowCurrencyORUnits").style.display = ''; //Return the original aspect ratio
  323. shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = (html => BypassTT?.createHTML(html) || html)(htmlcode); //Return the previous html
  324. };
  325.  
  326. shadowRoot.querySelector("#ShowCurrencyORUnits").onclick = function() { //When the unit/currency is clicked
  327. UnitORCurrency === 'Units' ? GM_setClipboard(`${Result} ${Type}`) : GM_setClipboard(Intl.NumberFormat(navigator.language, { style: 'currency', currency: GM_getValue("YourLocalCurrency") }).format(Result));
  328. };
  329. }
  330.  
  331. //CurrenciesConverter _______________________________________________________________________________________________________________________________________
  332. if (GM_getValue("CurrenciesConverter") === true) { //If Currencies Converter is enabled
  333. shadowRoot.querySelector("#ShowCurrencyORUnits").innerText = ''; //Remove the previous Currency text
  334.  
  335. if (SelectedText.match(Currencies) !== null) //If the selected text is a currency
  336. {
  337. if (GM_getValue("YourLocalCurrency") === undefined) {
  338. const UserInput = prompt('Write your local currency.\nThe script will always use your local currency to make exchange-rate conversions.\n\n*Currency input examples:\nBRL\nCAD\nUSD\netc...\n\n*Press OK');
  339. GM_setValue("YourLocalCurrency", UserInput);
  340. }
  341.  
  342. (async () => { //Get the final converted currency value
  343. const currencyMap = { '$': 'USD', 'us$': 'USD', '$us': 'USD', 'r$': 'BRL', 'hk$': 'HKD', '¥': 'JPY', '€': 'EUR', 'rp': 'IDR', 'kn': 'HRK', 'kč': 'CZK', 'kr': 'DKK', 'zł': 'PLN', '£': 'GBP', '฿': 'THB', '₩': 'KRW' };
  344. const CurrencySymbol = currencyMap[SelectedText.match(CurrencySymbols)?.[0].toLowerCase()] || SelectedText.match(Currencies)[2]; //Store the currency symbol
  345.  
  346. GM.xmlHttpRequest({ //Get the final converted currency value
  347. method: "GET",
  348. url: `https://www.google.com/search?q=${SelectedText.match(Currencies)[1]} ${CurrencySymbol} in ${GM_getValue("YourLocalCurrency")}`,
  349. onload: (response) => {
  350. const newDocument = new DOMParser().parseFromString(response.responseText, 'text/html'); //Parse the fetch response
  351. const FinalCurrency = parseFloat(newDocument.querySelector(".SwHCTb").innerText.split(' ')[0].replaceAll(',', '')); //Store the FinalCurrency and erase all commas
  352. ShowConvertion('Currencies', CurrencySymbol, FinalCurrency);
  353. }
  354. });
  355. })();
  356. }
  357. }
  358.  
  359. //UnitsConverter _________________________________________________________________________________________________________________________________________________________________________
  360. if (GM_getValue("UnitsConverter") === true) { //If the Units Converter option is enabled
  361. shadowRoot.querySelector("#ShowCurrencyORUnits").innerText = ''; //Remove the previous Units text
  362. const Units = new RegExp(/^[ \t\xA0]*(-?\d+(?:[., ]\d+)?)(?:[ \t\xA0]*x[ \t\xA0]*(-?\d+(?:[., ]\d+)?))?[ \t\xA0]*(in|inch|inches|cm|cms|centimeters?|mt|mts|meters?|ft|kg|lbs?|pounds?|kilograms?|ounces?|g|ozs?|fl oz|fl oz (us)|fluid ounces?|kphs?|km\/h|kilometers per hours?|mphs?|meters per hours?|°?º?[CF]|km\/hs?|ml|milliliters?|l|liters?|litres?|gal|gallons?|yards?|yd|Millimeter|millimetre|kilometers?|mi|mm|miles?|km|ft|fl|feets?|grams?|kilowatts?|kws?|brake horsepower|mechanical horsepower|hps?|bhps?|miles per gallons?|mpgs?|liters per 100 kilometers?|l\/100km|liquid quarts?|lqs?|foot-?pounds?|ft-?lbs?|lb fts?|newton-?meters?|nm|\^\d+)[ \t\xA0]*(?:\(\w+\)[ \t\xA0]*)?$/i);
  363.  
  364. if (SelectedText.match(Units) !== null) //If the selected text is an unit
  365. {
  366. const conversionMap = {};
  367.  
  368. function addConversion(keys, unit, factor, convert) { //Helper function to add multiple keys with the same value
  369. keys.forEach(key => {
  370. conversionMap[key] = { unit, factor, convert };
  371. });
  372. }
  373.  
  374. addConversion(['inch', 'inches', 'in', '"', '”'], 'cm', 2.54);
  375. addConversion(['centimeter', 'centimeters', 'cm', 'cms'], 'in', 1 / 2.54);
  376. addConversion(['meter', 'meters', 'mt', 'mts'], 'ft', 3.281);
  377. addConversion(['kilogram', 'kilograms', 'kg'], 'lb', 2.205);
  378. addConversion(['pound', 'pounds', 'lb', 'lbs'], 'kg', 1 / 2.205);
  379. addConversion(['ounce', 'ounces', 'oz', 'ozs'], 'g', 28.35);
  380. addConversion(['gram', 'grams', 'g'], 'oz', 1 / 28.35);
  381. addConversion(['kilometer', 'kilometers', 'km'], 'mi', 1 / 1.609);
  382. addConversion(['kph', 'kphs', 'km/h', 'km/hs', 'kilometers per hour', 'kilometers per hours'], 'mph', 0.621371);
  383. addConversion(['mph', 'mphs', 'meters per hour', 'meters per hours'], 'km/h', 1 / 1.000);
  384. addConversion(['mi', 'mile', 'miles'], 'km', 1.609);
  385. addConversion(['°c', '°f', 'ºc', 'ºf'], '°F', v => (v * 9 / 5) + 32);
  386. addConversion(['°f', 'ºf'], '°C', v => (v - 32) * 5 / 9);
  387. addConversion(['milliliter', 'milliliters', 'ml'], 'fl oz (US)', 1 / 29.574);
  388. addConversion(['fl oz (US)', 'fl oz', 'fl', 'fluid ounce', 'fluid ounces'], 'ml', 29.574);
  389. addConversion(['litre', 'liter', 'litres', 'liters', 'l'], 'gal (US)', 1 / 3.785);
  390. addConversion(['gal', 'gallon', 'gallons'], 'lt', 3.785);
  391. addConversion(['yard', 'yards', 'yd'], 'm', 1 / 1.094);
  392. addConversion(['millimetre', 'millimeters', 'millimetres', 'mm'], 'in', 1 / 25.4);
  393. addConversion(['feet', 'feets', 'ft'], 'mt', 0.3048);
  394. addConversion(['kilowatt', 'kilowatts', 'kw', 'kws'], 'mhp', 1.341);
  395. addConversion(['mhp', 'mhps', 'hp', 'hps', 'brake horsepower', 'mechanical horsepower'], 'kw', 1 / 1.341);
  396. addConversion(['mpg', 'mpgs', 'miles per gallon', 'miles per gallons'], 'l/100km', v => 235.215 / v);
  397. addConversion(['l/100km', 'liters per 100 kilometer', 'liters per 100 kilometers'], 'US mpg', v => 235.215 / v);
  398. addConversion(['lq', 'lqs', 'liquid quart', 'liquid quarts'], 'l', 1 / 1.057);
  399. addConversion(['foot-pound', 'foot-pounds', 'foot pound', 'foot pounds', 'ft-lbs', 'ft-lb', 'ft lbs', 'ft lb', 'lb ft', 'lb-ft'], 'Nm', 1.3558179483);
  400. addConversion(['nm', 'newton-meter', 'newton-meters', 'newton meter', 'newton meters'], 'ft lb', 1 / 1.3558179483);
  401.  
  402. const SelectedUnitValue = SelectedText.match(Units)[1].replaceAll(',', '.');
  403. const SecondSelectedUnitValue = SelectedText.match(Units)[2]?.replaceAll(',', '.') || 0;
  404. const selectedUnitType = SelectedText.match(Units)[3].toLowerCase();
  405.  
  406. const convertValue = (value, unitType) => {
  407. const { factor, convert } = conversionMap[unitType] || {};
  408. return convert ? convert(value) : value * factor;
  409. };
  410.  
  411. var NewUnit = conversionMap[selectedUnitType]?.unit || selectedUnitType;
  412. var ConvertedUnit = SecondSelectedUnitValue != 0 ? `${convertValue(parseFloat(SelectedUnitValue), selectedUnitType).toFixed(2)} x ${convertValue(parseFloat(SecondSelectedUnitValue), selectedUnitType).toFixed(2)}` : convertValue(parseFloat(SelectedUnitValue), selectedUnitType).toFixed(2);
  413. ConvertedUnit = SelectedText.match(/\^(\d+\.?\d*)/) ? (NewUnit = 'power', Math.pow(parseFloat(SelectedUnitValue), parseFloat(SelectedText.match(/\^(\d+\.?\d*)/)[1]))) : ConvertedUnit;
  414. ShowConvertion('Units', NewUnit, ConvertedUnit);
  415. }
  416. }
  417.  
  418. //Menu ___________________________________________________________________________________________________________________________________________________________________________
  419. if (shadowRoot.querySelector("#SearchBTN").innerText === 'Open') //If the Search BTN text is 'Open'
  420. {
  421. shadowRoot.querySelector("#highlight_menu > ul").style.paddingInlineStart = '19px'; //Increase the menu size
  422. shadowRoot.querySelector("#SearchBTN").innerText = 'Search'; //Display the BTN text as Search again
  423. shadowRoot.querySelectorAll(".AI-BG-box button").forEach(button => { button.style.marginLeft = ''; }); //Remove the margin left
  424. shadowRoot.querySelector("#OpenAfter").remove(); //Remove the custom Open white hover overlay
  425. SelectedTextIsLink = false; //Make common words searchable again
  426. }
  427.  
  428. if (SelectedText.match(Links) !== null) //If the selected text is a link
  429. {
  430. SelectedTextIsLink = true;
  431. shadowRoot.querySelector("#highlight_menu > ul").style.paddingInlineStart = '27px'; //Increase the menu size
  432. shadowRoot.querySelector("#SearchBTN").innerText = 'Open'; //Change the BTN text to Open
  433. shadowRoot.querySelectorAll(".AI-BG-box button").forEach(button => { button.style.marginLeft = '-2%'; }); //Add a margin left
  434. shadowRoot.innerHTML += (html => BypassTT?.createHTML(html) || html)(` <style id="OpenAfter"> #SearchBTN::after { width: 177% !important; transform: translate(-34%, -71%) !important; } </style> `); //Add a custom Open white hover overlay
  435. }
  436.  
  437. shadowRoot.querySelector("#SearchBTN").onmousedown = function() {
  438. var LinkfyOrSearch = 'https://www.google.com/search?q=';
  439. if (SelectedTextIsLink === true)
  440. {
  441. LinkfyOrSearch = 'https://'; //Make the non-HTTP and non-HTTPS links able to be opened
  442. }
  443. if (SelectedText.match(/http:|https:/) !== null) //If the selected text is a link that already has HTTP or HTTPS
  444. {
  445. LinkfyOrSearch = ''; //Remove the https:// that was previously added to this variable
  446. }
  447.  
  448. GM_openInTab(LinkfyOrSearch + SelectedTextSearch, { //Open google and search for the selected text
  449. active: true,
  450. setParent: true,
  451. loadInBackground: true
  452. });
  453. getSelection().removeAllRanges(); //UnSelect the selected text after the search BTN is clicked so that if the user clicks on the past selected text the menu won't show up again.
  454. shadowRoot.querySelector("#highlight_menu").classList.remove('show'); //Hide the menu
  455. };
  456.  
  457. const menu = shadowRoot.querySelector("#highlight_menu");
  458. if (document.getSelection().toString().trim() !== '') { //If text has been selected
  459. const p = document.getSelection().getRangeAt(0).getBoundingClientRect(); //Store the selected position
  460.  
  461. menu.classList.add('show'); //Show the menu
  462. menu.offsetHeight; //Trigger reflow by forcing a style calculation
  463. menu.style.left = p.left + (p.width / 2) - (menu.offsetWidth / 2) + 'px';
  464. menu.style.top = p.top - menu.offsetHeight - 10 + 'px';
  465. menu.classList.add('highlight_menu_animate');
  466.  
  467. return; //Keep the menu open
  468. }
  469. menu.classList.remove('show'); //Hide the menu
  470. shadowRoot.querySelector("#SearchBTN span")?.remove(); //Return previous HTML
  471. });
  472. });
  473.  
  474. //AI Menu ___________________________________________________________________________________________________________________________________________________________________________
  475. var desiredVoice = null, isRecognizing = false;
  476. const HtmlMenu = document.createElement('div'); //Create a container div
  477. HtmlMenu.setAttribute('style', `width: 0px; height: 0px; display: block;`); //Hide the container div by default
  478. const shadowRoot = HtmlMenu.attachShadow({ mode: 'closed' });
  479. const BGColor = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'rgb(37, 36, 53)' : '#e7edf1'; //Change AI theme according to the browser theme
  480. const IMGsColor = BGColor === '#e7edf1' ? 'filter: invert(1)' : ''; //If on white mode invert black svg colors to white
  481. const TextColor = BGColor === '#e7edf1' ? 'black' : 'white'; //Depending on the browser theme change the AI menu text color
  482. const UniqueLangs = navigator.languages.filter((l, i, arr) => !arr.slice(0, i).some(e => e.split('-')[0].toLowerCase() === l.split('-')[0].toLowerCase()) ); //Filter unique languages
  483. const Lang = UniqueLangs.length > 1 ? `${UniqueLangs[0]} and into ${UniqueLangs[1]}` : UniqueLangs[0]; //Use 1 or 2 languages
  484. const GeminiSVG = '<svg viewBox="0 0 32 32" fill="none"> <path d="M14 28C14 26.0633 13.6267 24.2433 12.88 22.54C12.1567 20.8367 11.165 19.355 9.905 18.095C8.645 16.835 7.16333 15.8433 5.46 15.12C3.75667 14.3733 1.93667 14 0 14C1.93667 14 3.75667 13.6383 5.46 12.915C7.16333 12.1683 8.645 11.165 9.905 9.905C11.165 8.645 12.1567 7.16333 12.88 5.46C13.6267 3.75667 14 1.93667 14 0C14 1.93667 14.3617 3.75667 15.085 5.46C15.8317 7.16333 16.835 8.645 18.095 9.905C19.355 11.165 20.8367 12.1683 22.54 12.915C24.2433 13.6383 26.0633 14 28 14C26.0633 14 24.2433 14.3733 22.54 15.12C20.8367 15.8433 19.355 16.835 18.095 18.095C16.835 19.355 15.8317 20.8367 15.085 22.54C14.3617 24.2433 14 26.0633 14 28Z" fill="url(#paint)"></path></svg>';
  485.  
  486. shadowRoot.innerHTML = (html => BypassTT?.createHTML(html) || html)(`<svg width=" 0" height=" 0">
  487. <defs>
  488. <radialGradient cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(2.77876 11.3795) rotate(18.6832) scale(29.8025 238.737)" id="paint">
  489. <stop offset="0.0671246" stop-color="#9168C0"></stop>
  490. <stop offset="0.342551" stop-color="#5684D1"></stop>
  491. <stop offset="0.672076" stop-color="#1BA1E3"></stop>
  492. </radialGradient>
  493. </defs>
  494. </svg>
  495. <style>
  496. ${GM_getResourceText('AICSS')}
  497. .animated-border {
  498. background: border-box border-box ${BGColor};
  499. }
  500. #prompt {
  501. color: ${TextColor};
  502. }
  503. #AIBox.AnswerBox {
  504. background: ${BGColor};
  505. }
  506. </style>
  507. <div id="highlight_menu">
  508. <div class="AI-BG-box">
  509. <button id="AIBTN" class="show-button">
  510. <div class="MenuGemini">${GeminiSVG}Explore more</div>
  511. </button>
  512. <button id="AIBTN" class="translate show-button">
  513. <div class="MenuGemini">${GeminiSVG}Translate</div>
  514. </button>
  515. </div>
  516. <ul id="MenuList">
  517. <li class="popuptext"></li>
  518. <li id="ShowCurrencyORUnits"></li>
  519. <li class="popuptext" id="SearchBTN">Search</li>
  520. <li class="popuptext" id="CopyBTN">
  521. <span>│</span> Copy
  522. </li>
  523. </ul>
  524. </div>
  525. <div class="animated-border" id="AIBox">
  526. <div id="tabcontext">
  527. <p>Page Context</p>
  528. <p id="TabBox">Tab</p>
  529. </div>
  530. <button id="dictate">
  531. <svg id="dictateSvg" viewBox="0 0 700 700">
  532. <defs>
  533. <path id="commonPath1" d="M439.5,236c0-11.3-9.1-20.4-20.4-20.4s-20.4,9.1-20.4,20.4c0,70-64,126.9-142.7,126.9s-142.7-56.9-142.7-126.9c0-11.3-9.1-20.4-20.4-20.4s-20.4,9.1-20.4,20.4c0,86.2,71.5,157.4,163.1,166.7v57.5h-23.6c-11.3,0-20.4,9.1-20.4,20.4s9.1,20.4,20.4,20.4h88c11.3,0,20.4-9.1,20.4-20.4s-9.1-20.4-20.4-20.4h-23.6v-57.5C368,393.4,439.5,322.2,439.5,236Z" fill="#fff"></path>
  534. <path id="commonPath2" d="M256,323.5c51,0,92.3-41.3,92.3-92.3v-127.9C348.3,52.3,307,11,256,11s-92.3,41.3-92.3,92.3v127.9c0,51,41.3,92.3,92.3,92.3ZM203.7,103.3C203.7,74.5,227.2,51,256,51s52.3,23.5,52.3,52.3v127.9c0,28.8-23.5,52.3-52.3,52.3s-52.3-23.5-52.3-52.3v-127.9Z" fill="#fff"></path>
  535. <ellipse id="commonEllipse" rx="53" ry="59" transform="translate(255.581 226.12)" fill="#0f0"></ellipse>
  536. </defs>
  537. <g class="state1">
  538. <use href="#commonPath1"></use>
  539. <use href="#commonPath2"></use>
  540. </g>
  541. <g class="state2">
  542. <use href="#commonPath1"></use>
  543. <use href="#commonPath2"></use>
  544. <use href="#commonEllipse"></use>
  545. <rect width="106" height="68.751" transform="translate(202.581 167.12)" fill="#0f0"></rect>
  546. </g>
  547. <g class="state3">
  548. <use href="#commonPath1"></use>
  549. <use href="#commonPath2"></use>
  550. <use href="#commonEllipse"></use>
  551. <ellipse rx="53" ry="59.21" transform="translate(255.581 226.457)" fill="#0f0"></ellipse>
  552. <rect width="106" height="136.9" transform="translate(202.581 89.492)" fill="#0f0"></rect>
  553. <ellipse rx="35" ry="40.072" transform="matrix(1.513 0 0 1 255.557 89.492)" fill="#0f0"></ellipse>
  554. </g>
  555. </svg>
  556. </button>
  557. <button id="TopPause">
  558. <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
  559. <rect x="0.499756" y="0.5" width="11" height="11" rx="1.5" fill="white" stroke="white" />
  560. </svg>
  561. </button>
  562. <div class="BoxGemini" id="gemini">${GeminiSVG}</div>
  563. <div id="context">PAGE CONTEXT</div>
  564. <input class="Prompt" id="prompt" placeholder="Enter your prompt to Gemini">
  565. </div>
  566. <div id="CloseOverlay"></div>
  567. <div id="AIBox" class="AnswerBox">
  568. <div id="AIAnswer">
  569. <div id="avatar">
  570. <svg width="32" height="32" viewBox="0 0 32 32">
  571. <rect width="32" height="32" rx="8" fill="#5021FF"></rect>
  572. <path fill-rule="evenodd" clip-rule="evenodd" d="M12.7375 12.5186C12.7375 10.7594 14.1636 9.33333 15.9228 9.33333C17.6819 9.33333 19.108 10.7594 19.108 12.5186C19.108 14.2778 17.6819 15.7039 15.9228 15.7039C14.1636 15.7039 12.7375 14.2778 12.7375 12.5186ZM15.9228 8C13.4272 8 11.4042 10.023 11.4042 12.5186C11.4042 15.0142 13.4272 17.0372 15.9228 17.0372C18.4183 17.0372 20.4414 15.0142 20.4414 12.5186C20.4414 10.023 18.4183 8 15.9228 8ZM11.5819 17.6255C11.8982 17.437 12.0018 17.0278 11.8133 16.7115C11.6248 16.3952 11.2156 16.2916 10.8993 16.4801C10.6831 16.6089 10.4663 16.8148 10.2746 17.0349C10.0746 17.2644 9.87008 17.546 9.68554 17.8601C9.32327 18.4767 9 19.2839 9 20.1144C9 20.8532 9.12214 21.4899 9.41978 22.0347C9.72071 22.5855 10.1679 22.9818 10.7122 23.2937C11.2082 23.5779 11.7335 23.8486 12.5469 24.0394C13.3432 24.2262 14.3899 24.3308 15.9368 24.3308C19.0007 24.3308 20.5881 23.9091 21.6046 22.9619C22.5374 22.0927 22.9531 21.1528 22.9506 20.1128C22.9489 19.4161 22.6359 18.6481 22.2905 18.0381C21.9435 17.4254 21.4844 16.8333 21.0628 16.5185C20.7678 16.2983 20.3501 16.3589 20.1298 16.6539C19.9095 16.949 19.9701 17.3667 20.2652 17.587C20.4764 17.7446 20.826 18.1578 21.1302 18.695C21.4359 19.2349 21.6164 19.7615 21.6173 20.116C21.6188 20.7365 21.3947 21.3351 20.6956 21.9864C20.0802 22.5599 18.9602 22.9975 15.9368 22.9975C14.4401 22.9975 13.5073 22.8952 12.8514 22.7414C12.2127 22.5915 11.8133 22.3879 11.375 22.1368C10.9852 21.9134 10.7439 21.6773 10.5899 21.3954C10.4326 21.1075 10.3333 20.7113 10.3333 20.1144C10.3333 19.609 10.5393 19.039 10.8351 18.5355C10.9796 18.2896 11.1364 18.0755 11.2798 17.9108C11.4315 17.7368 11.5404 17.6502 11.5819 17.6255Z" fill="white"></path>
  573. </svg>
  574. </div>
  575. <div class="AnswerContainer" style="color: ${TextColor};">
  576. <div id="msg"></div>
  577. <div id="LineEl"></div>
  578. <div class="BoxGemini" id="ContainerGemini">${GeminiSVG}</div>
  579. <div id="finalanswer"></div><p id="LoadBar">ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ</p>
  580. <div id="AIMenu">
  581. <button id="SpeakingPause" class="MenuBTNs" style="display: none; ${IMGsColor};">
  582. <svg width="16" height="16" viewBox="0 -2 8 13" fill="none">
  583. <path fill-rule="evenodd" clip-rule="evenodd" d="M1.49879 0.5C0.671042 0.5 1.52588e-05 1.17103 1.52588e-05 1.99878V8.00122C1.52588e-05 8.82897 0.671042 9.5 1.49879 9.5C2.32655 9.5 2.99757 8.82897 2.99757 8.00122V1.99878C2.99757 1.17103 2.32655 0.5 1.49879 0.5ZM1.00002 1.99878C1.00002 1.72331 1.22333 1.5 1.49879 1.5C1.77426 1.5 1.99757 1.72331 1.99757 1.99878V8.00122C1.99757 8.27669 1.77426 8.5 1.49879 8.5C1.22333 8.5 1.00002 8.27669 1.00002 8.00122V1.99878ZM6.50575 0.5C5.678 0.5 5.00697 1.17103 5.00697 1.99878V8.00122C5.00697 8.82897 5.678 9.5 6.50575 9.5C7.33351 9.5 8.00453 8.82897 8.00453 8.00122V1.99878C8.00453 1.17103 7.33351 0.5 6.50575 0.5ZM6.00697 1.99878C6.00697 1.72331 6.23028 1.5 6.50575 1.5C6.78122 1.5 7.00453 1.72331 7.00453 1.99878V8.00122C7.00453 8.27669 6.78122 8.5 6.50575 8.5C6.23028 8.5 6.00697 8.27669 6.00697 8.00122V1.99878Z" fill="white"></path>
  584. </svg>
  585. </button>
  586. <button id="speak" class="MenuBTNs" style="display: inline-flex; ${IMGsColor};">
  587. <svg width="16" height="16" viewBox="0 0 16 16" fill="#fff">
  588. <path fill-rule="inherit" clip-rule="evenodd" d="M6.99585 3.24577C6.81771 3.36247 6.58157 3.56921 6.2112 3.89612L4.20926 5.66321L4.18027 5.68895C4.07192 5.78537 3.93427 5.90788 3.75948 5.97398C3.58469 6.04009 3.40043 6.03934 3.25538 6.03875L3.21662 6.03864H2.50001C2.25017 6.03864 2.11309 6.03971 2.018 6.05249L2.01435 6.05299L2.01385 6.05663C2.00107 6.15173 2.00001 6.28881 2.00001 6.53864V9.53864C2.00001 9.78848 2.00107 9.92556 2.01385 10.0207L2.01435 10.0243L2.01799 10.0248C2.11309 10.0376 2.25017 10.0386 2.50001 10.0386H3.2338L3.27297 10.0385C3.41953 10.0379 3.60574 10.0372 3.78206 10.1046C3.95838 10.172 4.09659 10.2968 4.20536 10.395L4.23448 10.4212L6.20852 12.189C6.57949 12.5212 6.81642 12.7317 6.99537 12.8508L7.00796 12.8591L7.01018 12.8442C7.04081 12.6314 7.04208 12.3145 7.04208 11.8166V4.27098C7.04208 3.77697 7.04081 3.46312 7.01041 3.25234L7.00823 3.23776L6.99585 3.24577ZM7.1278 3.17543C7.12773 3.17558 7.1259 3.17617 7.12253 3.17674C7.12619 3.17556 7.12788 3.17528 7.1278 3.17543ZM6.97834 3.11168C6.97653 3.10878 6.97576 3.10702 6.97583 3.10686C6.97589 3.10671 6.9768 3.10815 6.97834 3.11168ZM6.97515 12.9916C6.97508 12.9915 6.97586 12.9897 6.97769 12.9867C6.97613 12.9903 6.97522 12.9918 6.97515 12.9916ZM7.12322 12.9217C7.12662 12.9223 7.12847 12.9229 7.12854 12.9231C7.12862 12.9232 7.12692 12.9229 7.12322 12.9217ZM6.44789 2.40927C6.69128 2.24984 7.05663 2.07222 7.45332 2.25119C7.85002 2.43016 7.95863 2.82161 8.00017 3.10959C8.04215 3.40069 8.04212 3.78842 8.04209 4.23246L8.04208 4.27098V11.8166L8.04209 11.8551C8.04212 12.3031 8.04215 12.6937 7.99998 12.9867C7.95838 13.2757 7.84954 13.67 7.45005 13.8485C7.05057 14.027 6.68423 13.845 6.44119 13.6832C6.19482 13.5192 5.90383 13.2586 5.57013 12.9597L5.57012 12.9597L5.5414 12.934L3.56736 11.1662C3.49189 11.0986 3.45417 11.0652 3.42542 11.0429L3.4238 11.0417L3.42176 11.0415C3.38548 11.0389 3.3351 11.0386 3.2338 11.0386H2.50001L2.47281 11.0386C2.26077 11.0387 2.05471 11.0387 1.88475 11.0159C1.69315 10.9901 1.47451 10.9274 1.2929 10.7458C1.11129 10.5641 1.04853 10.3455 1.02277 10.1539C0.999921 9.98395 0.999962 9.77788 1 9.56585L1.00001 9.53864V6.53864L1 6.51144C0.999962 6.29941 0.999921 6.09334 1.02277 5.92338C1.04853 5.73178 1.11129 5.51315 1.2929 5.33154C1.47451 5.14993 1.69315 5.08717 1.88475 5.06141C2.0547 5.03856 2.26076 5.0386 2.4728 5.03864H2.4728L2.50001 5.03864H3.21662C3.31686 5.03864 3.36669 5.03836 3.40258 5.03584L3.40461 5.03569L3.40622 5.03446C3.4348 5.0126 3.47234 4.97984 3.5475 4.9135L5.54944 3.14641L5.57832 3.12091L5.57834 3.1209L5.57835 3.12089C5.91122 2.82703 6.20187 2.57043 6.44789 2.40927ZM10.1345 5.33693C10.2257 5.07628 10.5109 4.93892 10.7716 5.03012C11.5468 5.30139 12.1156 5.71974 12.4845 6.27343C12.851 6.82368 12.9896 7.46152 12.9888 8.12059C12.9881 8.77784 12.8479 9.36588 12.4685 9.8652C12.095 10.3568 11.5331 10.7045 10.8038 10.9736C10.5448 11.0692 10.2573 10.9367 10.1617 10.6777C10.0661 10.4186 10.1986 10.1311 10.4577 10.0355C11.0913 9.80166 11.4579 9.54244 11.6723 9.2602C11.8809 8.98566 11.9883 8.63292 11.9888 8.11953C11.9894 7.59876 11.8804 7.1703 11.6522 6.82786C11.4264 6.48888 11.0533 6.18815 10.4413 5.97401C10.1807 5.88281 10.0433 5.59758 10.1345 5.33693ZM10.5874 3.04341C10.3154 2.99552 10.0561 3.17716 10.0082 3.44912C9.96033 3.72108 10.142 3.98036 10.4139 4.02825C11.5592 4.22994 12.4289 4.71111 13.0117 5.38193C13.5932 6.05126 13.9207 6.94547 13.9201 8.03323C13.9195 9.12625 13.5988 9.99297 13.0242 10.6448C12.4457 11.3008 11.573 11.7808 10.3984 12.026C10.1281 12.0825 9.95475 12.3474 10.0112 12.6177C10.0676 12.888 10.3325 13.0614 10.6028 13.0049C11.9332 12.7271 13.0195 12.1622 13.7743 11.3061C14.5328 10.4457 14.9194 9.33294 14.9201 8.03375C14.9208 6.7372 14.5263 5.60054 13.7666 4.72609C13.0082 3.85314 11.9174 3.27763 10.5874 3.04341Z"></path>
  589. </svg>
  590. </button>
  591. <button id="AnswerCopied" class="MenuBTNs" style="display: none; ${IMGsColor};">
  592. <svg width="16" height="16" viewBox="0 0 10 8" fill="none">
  593. <path d="M1.02063 3.68066L3.67635 6.65194L8.97935 1.34802" stroke="white" stroke-linecap="round" />
  594. </svg>
  595. </button>
  596. <button id="copyAnswer" class="MenuBTNs" style="display: inline-flex; ${IMGsColor};">
  597. <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
  598. <path fill-rule="evenodd" clip-rule="evenodd" d="M4.22727 4.5H3.5C2.39543 4.5 1.5 5.39543 1.5 6.5V12.5C1.5 13.6046 2.39543 14.5 3.5 14.5H9.5C10.6046 14.5 11.5 13.6046 11.5 12.5V11.7727H10.5V12.5C10.5 13.0523 10.0523 13.5 9.5 13.5H3.5C2.94772 13.5 2.5 13.0523 2.5 12.5V6.5C2.5 5.94772 2.94772 5.5 3.5 5.5H4.22727V4.5Z" fill="white"></path>
  599. <rect x="5" y="2" width="9" height="9" rx="1.5" stroke="white"></rect>
  600. </svg>
  601. </button>
  602. <button id="NewAnswer" class="MenuBTNs" style="display: inline-flex; ${IMGsColor};">
  603. <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
  604. <path d="M3.64362 8.00003C3.64362 5.70974 5.50027 3.85309 7.79056 3.85309C9.06546 3.85309 10.2057 4.42786 10.9671 5.33402C11.0399 5.42069 11.0743 5.56527 10.9942 5.64533L10.5291 6.11045C10.2141 6.42543 10.4372 6.964 10.8826 6.964H12.75C13.0261 6.964 13.25 6.74015 13.25 6.464V4.59664C13.25 4.15119 12.7114 3.92811 12.3964 4.24309L11.8532 4.78632C11.7983 4.84128 11.7013 4.81866 11.6513 4.75915C10.7273 3.65956 9.34048 2.95947 7.79056 2.95947C5.00674 2.95947 2.75 5.21621 2.75 8.00003C2.75 10.7839 5.00674 13.0406 7.79056 13.0406C9.95003 13.0406 11.7913 11.6828 12.5092 9.77593C12.5962 9.54499 12.4795 9.28729 12.2485 9.20034C12.0176 9.11338 11.7599 9.2301 11.6729 9.46104C11.0818 11.0312 9.5659 12.147 7.79056 12.147C5.50027 12.147 3.64362 10.2903 3.64362 8.00003Z" fill="white"></path>
  605. </svg>
  606. </button>
  607. </div>
  608. </div>
  609. </div>`); //Set the AI menu html
  610.  
  611. function Generate(Prompt, button) { //Call the AI endpoint
  612. const context = !!shadowRoot.querySelector("#context.show") ? `(You're not allowed to say anything like "Based on the provided text")\n"${Prompt} mainly base yourself on the text below\n${document.body.innerText}` : Prompt; //Add the page context if context is enabled
  613. const IsQuestion = Prompt.includes('?') ? 'Give me a very short, then a long detailed answer' : 'Help me further explore a term or topic from the text/word';
  614. const AIFunction = button.match('translate') ? `(You're not allowed to say anything like (The text is already in ${UniqueLangs[0]}"\nNo translation is needed).\Translate into ${Lang} the following text:\n"${Prompt}".\nAfter showing (in order) a few possible "Translations:" also give me a "Definition:" and "Examples:".You must answer using only 1 language first, then use only the other language, don't mix both languages! ` : button.match('Prompt') ? context : `(PS*I'm unable to provide you with more context, so don't ask for it! Also, don't mention that I haven't provided context or anything similar to it!) ${IsQuestion}: "${Prompt}"`; //AI prompts
  615. const msg = button.match('translate') ? `Translate this text: "${Prompt.length > 215 ? Prompt.trim().slice(0, 215) + '…' : Prompt.trim()}"` : button.match('Prompt') ? Prompt.length > 240 ? Prompt.trim().slice(0, 240) + '…' : Prompt.trim() : `Help me further explore a term or topic from the text: "${Prompt.length > 180 ? Prompt.trim().slice(0, 180) + '…' : Prompt.trim()}"`; //User text
  616.  
  617. const request = GM.xmlHttpRequest({ //Call the AI API
  618. method: "POST",
  619. url: `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:streamGenerateContent?key=${GM_getValue("APIKey")}`,
  620. responseType: 'stream',
  621. headers: {
  622. "Content-Type": "application/json"
  623. },
  624. data: JSON.stringify({
  625. contents: [{
  626. parts: [{
  627. text: `${AIFunction}` //Use our AI prompt
  628. }]
  629. }],
  630. safetySettings: [ //Allow all content
  631. { category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_NONE" },
  632. { category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_NONE" },
  633. { category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_NONE" },
  634. { category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_NONE" }
  635. ],
  636. }),
  637. onerror: function(err) {
  638. shadowRoot.querySelector("#finalanswer").innerHTML = (html => BypassTT?.createHTML(html) || html)(`<br>Please copy and paste the error below:<br><a class="feedback" href="https://greasyfork.org/scripts/419825/feedback">Click here to report this bug</a><br><br> Prompt: ${Prompt}<br> Button: ${button}<br> Error: ${err}}<br><br><br>`);
  639. },
  640. onload: function(response) {
  641. shadowRoot.querySelector("#AIMenu").classList.add('show');
  642. shadowRoot.querySelector("#dictate").classList.add('show');
  643. shadowRoot.querySelector("#TopPause").classList.remove('show');
  644. },
  645. onabort: function(response) {
  646. shadowRoot.querySelector("#AIMenu").classList.add('show');
  647. shadowRoot.querySelector("#dictate").classList.add('show');
  648. shadowRoot.querySelector("#TopPause").classList.remove('show');
  649. shadowRoot.querySelector("#finalanswer").innerText = 'ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤResponse has been interrupted.';
  650. },
  651. onloadstart: function(test) {
  652. shadowRoot.querySelector("#prompt").focus();
  653. shadowRoot.querySelector("#msg").innerHTML = msg
  654. shadowRoot.querySelector("#TopPause").classList.add('show');
  655. shadowRoot.querySelector("#AIMenu").classList.remove('show');
  656. shadowRoot.querySelector("#dictate").classList.remove('show');
  657.  
  658. shadowRoot.querySelector("#copyAnswer").onclick = function() {
  659. shadowRoot.querySelector("#copyAnswer").style.display = 'none';
  660. shadowRoot.querySelector("#AnswerCopied").style.display = 'inline-flex';
  661. GM_setClipboard(shadowRoot.querySelector("#finalanswer").innerText.replace('ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ', ''));
  662. setTimeout(() => { //Return play BTN svg
  663. shadowRoot.querySelector("#copyAnswer").style.display = 'inline-flex';
  664. shadowRoot.querySelector("#AnswerCopied").style.display = 'none';
  665. }, 1000);
  666. };
  667.  
  668. const reader = test.response.getReader();
  669. const decoder = new TextDecoder();
  670. var buffer = '', partialMarkdown = '';
  671.  
  672. function readStream() {
  673. reader.read().then(({ value }) => {
  674. buffer += decoder.decode(value, { stream: true });
  675. var startIdx = 0;
  676. while (true) {
  677. const openBrace = buffer.indexOf('{', startIdx);
  678. if (openBrace === -1) break;
  679. var balance = 1, closeBrace = openBrace + 1;
  680.  
  681. while (balance > 0 && closeBrace < buffer.length) {
  682. if (buffer[closeBrace] === '{') balance++;
  683. if (buffer[closeBrace] === '}') balance--;
  684. closeBrace++;
  685. }
  686.  
  687. if (balance !== 0) break; //Incomplete JSON object
  688.  
  689. const jsonString = buffer.substring(openBrace, closeBrace);
  690. const item = JSON.parse(jsonString);
  691. partialMarkdown += item.candidates[0].content.parts[0].text;
  692.  
  693. const tempDiv = document.createElement('div');
  694. tempDiv.innerHTML = marked.parse(partialMarkdown);
  695.  
  696. shadowRoot.querySelector("#finalanswer").innerHTML = '';
  697. shadowRoot.querySelector("#finalanswer").appendChild(tempDiv);
  698. startIdx = closeBrace;
  699. }
  700. buffer = buffer.substring(startIdx);
  701. readStream();
  702. })
  703. }
  704.  
  705. readStream();
  706.  
  707. shadowRoot.querySelector("#CloseOverlay").classList.add('show');
  708. shadowRoot.querySelector("#highlight_menu").classList.remove('show'); //Hide the mini menu on the page
  709. shadowRoot.querySelectorAll("#AIBox, .animated-border, #AIBox.AnswerBox").forEach(el => el.classList.add('show')); //Show the AI input and box
  710. getSelection().removeAllRanges(); //UnSelect the selected text so that if the user clicks on a previously selected text the menu won't show up again
  711.  
  712. var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
  713. const recognition = new SpeechRecognition();
  714. recognition.interimResults = true; //Show partial results
  715. recognition.continuous = true; //Keep listening until stopped
  716.  
  717. var transcript = ""; //Add words
  718. shadowRoot.querySelector("#CloseOverlay").onclick = function() {
  719. [...shadowRoot.querySelector("#finalanswer div").childNodes].slice(0, -1).forEach(node => node.remove()); //Reset the text content
  720. shadowRoot.querySelectorAll("#AIBox, .animated-border, #AIBox.AnswerBox").forEach(el => el.classList.remove('show')); //Hide the AI input and box
  721. this.classList.remove('show');
  722. recognition.stop(); //Stop recognizing audio
  723. speechSynthesis.cancel(); //Stop speaking
  724. request.abort(); //Abort any ongoing request
  725. if (shadowRoot.querySelector("#gemini").style.display === 'none') {
  726. shadowRoot.querySelector("#AddContext").remove(); //Return original prompt input styles
  727. shadowRoot.querySelector("#context").classList.remove('show');
  728. shadowRoot.querySelector("#prompt").placeholder = 'Enter your prompt to Gemini'; //Return default placeholder
  729. }
  730. };
  731.  
  732. shadowRoot.querySelector("#TopPause").onclick = function() {
  733. shadowRoot.querySelector("#dictate").classList.add('show');
  734. shadowRoot.querySelector("#TopPause").classList.remove('show');
  735. request.abort();
  736. };
  737.  
  738. recognition.onend = function() {
  739. isRecognizing = false;
  740. shadowRoot.querySelectorAll('.state1, .state2, .state3').forEach((state, index) => { //ForEach SVG animation state
  741. index.toString().match(/1|2/) ? state.style.display = 'none' : ''; //Show only the 1 state
  742. state.classList.remove('animate'+index); //Stop the voice recording animation
  743. });
  744.  
  745. transcript !== '' ? Generate(transcript, shadowRoot.querySelector("#prompt").className) : shadowRoot.querySelector("#finalanswer").innerHTML = (html => BypassTT?.createHTML(html) || html)(`<br>No audio detected. Please try again or check your mic settings.ㅤㅤㅤㅤㅤㅤㅤㅤㅤ<br><br>`); //Call the AI API if audio has been detected or show an error message
  746. }; //Finish the recognition end event listener
  747.  
  748. recognition.onresult = function(event) { //Handle voice recognition results
  749. transcript = ""; //Clear the transcript at the start of the event
  750. for (var i = 0; i < event.results.length; i++) { //For all transcript results
  751. transcript += event.results[i][0].transcript + ' '; //Concatenate all intermediate transcripts
  752. }
  753. shadowRoot.querySelector("#msg").innerText = transcript.length > 240 ? transcript.slice(0, 240) + '…' : transcript; //Display recognized words
  754. };
  755.  
  756. shadowRoot.querySelector("#dictate").onclick = function() {
  757. if (isRecognizing) {
  758. recognition.stop();
  759. } else {
  760. isRecognizing = true;
  761. recognition.start();
  762. shadowRoot.querySelectorAll('.state1, .state2, .state3').forEach((state, index) => { //ForEach SVG animation state
  763. state.style.display = 'unset'; //Show all states
  764. state.classList.add('animate'+index); //Start the voice recording animation
  765. });
  766. }
  767. };
  768.  
  769. speechSynthesis.onvoiceschanged = () => desiredVoice = speechSynthesis.getVoices().find(v => v.name === "Microsoft Zira - English (United States)"); //Get and store the desired voice
  770. speechSynthesis.onvoiceschanged(); //Handle cases where the event doesn't fire
  771.  
  772. shadowRoot.querySelectorAll("#speak, #SpeakingPause").forEach(function(el) {
  773. el.onclick = function() { //When the speak or the bottom pause BTNs are clicked
  774. if (speechSynthesis.speaking) {
  775. speechSynthesis.cancel();
  776. shadowRoot.querySelector("#speak").style.display = 'inline-flex'; //Show the play BTN
  777. shadowRoot.querySelector("#SpeakingPause").classList.remove('show'); //Hide the pause BTN
  778. }
  779. else
  780. {
  781. shadowRoot.querySelector("#speak").style.display = 'none'; //Hide the play BTN
  782. shadowRoot.querySelector("#SpeakingPause").classList.add('show');
  783.  
  784. var audio = new SpeechSynthesisUtterance(shadowRoot.querySelector("#finalanswer").innerText.replace(/\(?..-..\)?:?|[^a-zA-Z0-9\s%.,!?]/g, '')); //Play the AI response text, removing non-alphanumeric characters and lang locales for better pronunciation
  785. audio.voice = desiredVoice; //Use the desiredVoice
  786. speechSynthesis.speak(audio); //Speak the text
  787.  
  788. audio.onend = (event) => {
  789. shadowRoot.querySelector("#speak").style.display = 'inline-flex'; //Show the play BTN
  790. shadowRoot.querySelector("#SpeakingPause").classList.remove('show');
  791. };
  792. }
  793. };
  794. });
  795.  
  796. shadowRoot.querySelector("#NewAnswer").onclick = function() {
  797. recognition.stop(); //Stop recognizing audio
  798. speechSynthesis.cancel(); //Stop speaking
  799. shadowRoot.querySelector("#speak").style.display = 'inline-flex'; //Show the play BTN
  800. shadowRoot.querySelector("#SpeakingPause").classList.remove('show'); //Hide the pause BTN
  801. shadowRoot.querySelector("#dictate").classList.remove('show');
  802. shadowRoot.querySelector("#TopPause").classList.add('show');
  803. Generate(Prompt, button); //Call the AI API
  804. };
  805. } //Finishes the onloadstart event listener
  806. });//Finishes the GM.xmlHttpRequest function
  807. } //Finishes the Generate function
  808.  
  809. shadowRoot.querySelector('#CopyBTN').onmousedown = function() {
  810. GM_setClipboard(getSelection().toString());
  811. };
  812.  
  813. shadowRoot.querySelector("#prompt").addEventListener("keydown", (event) => {
  814. if (event.key === "Enter") {
  815. Generate(shadowRoot.querySelector("#prompt").value, shadowRoot.querySelector("#prompt").className); //Call the AI API
  816. shadowRoot.querySelector("#prompt").value = ''; //Erase the prompt text
  817. }
  818. if (event.key === "Tab") {
  819. if (shadowRoot.querySelector("#prompt").placeholder.match('using')) { //If the input bar contains the word "using"
  820. shadowRoot.querySelector("#AddContext").remove(); //Return original prompt input styles
  821. shadowRoot.querySelector("#context").classList.remove('show'); //Hide the context view
  822. shadowRoot.querySelector("#prompt").placeholder = 'Enter your prompt to Gemini'; //Return default placeholder
  823. }
  824. else
  825. {
  826. shadowRoot.querySelector("#context").classList.add('show'); //Show the context view
  827. shadowRoot.querySelector("#prompt").placeholder = `Gemini is using ${location.host.replace('www.','')} for context...`; //Change placeholder
  828. shadowRoot.querySelector("#highlight_menu").insertAdjacentHTML('beforebegin', ` <style id="AddContext"> #gemini { display: none; } #prompt { left: 12%; width: 75%; } #tabcontext { display: none; } .animated-border { --color-OrangeORLilac: #FF8051; /* Change the border effect color to orange */ } </style> `); //Show the context bar
  829. }
  830. }
  831. setTimeout(() => { //Wait for the code above to execute
  832. shadowRoot.querySelector("#prompt").focus(); //Refocus on the input bar
  833. }, 0);
  834. });
  835.  
  836. if (document.body.textContent !== '' || document.body.innerText !== '') //If the body has any text
  837. {
  838. document.body.appendChild(HtmlMenu); //Add the script menu div container
  839. }
  840.  
  841. shadowRoot.querySelectorAll("#AIBTN").forEach(function(button) {
  842. button.onmousedown = function(event, i) { //When the Explore or the Translate BTNs are clicked
  843. if (GM_getValue("APIKey") === undefined || GM_getValue("APIKey") === null || GM_getValue("APIKey") === '') { //Set up the API Key if it isn't already set
  844. GM_setValue("APIKey", prompt('Enter your API key\n*Press OK\n\nYou can get a free API key at https://aistudio.google.com/app/apikey'));
  845. }
  846. if (GM_getValue("APIKey") !== null && GM_getValue("APIKey") !== '') {
  847. Generate(SelectedText, this.className); //Call the AI API
  848. }
  849. };
  850. });
  851.  
  852. window.addEventListener('scroll', async function() {
  853. shadowRoot.querySelector("#highlight_menu").classList.remove('show'); //Hide the menu
  854. if (LeftClicked === false && SelectedText !== '') { //If the Left Click isn't being held, and if something is currently selected
  855. getSelection().removeAllRanges(); //UnSelect the selected text when scrolling the page down so that if the user clicks on the past selected text the menu won't show up again
  856. }
  857. });
  858. }