Text Explainer

Explain selected text using LLM

目前为 2025-03-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Text Explainer
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2.3
  5. // @description Explain selected text using LLM
  6. // @author RoCry
  7. // @icon data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAwcHgiIGhlaWdodD0iODAwcHgiIHZpZXdCb3g9IjAgMCAxOTIgMTkyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiPjxjaXJjbGUgY3g9IjExNiIgY3k9Ijc2IiByPSI1NCIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2Utd2lkdGg9IjEyIi8+PHBhdGggc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS13aWR0aD0iMTIiIGQ9Ik04Ni41IDEyMS41IDQxIDE2N2MtNC40MTggNC40MTgtMTEuNTgyIDQuNDE4LTE2IDB2MGMtNC40MTgtNC40MTgtNC40MTgtMTEuNTgyIDAtMTZsNDQuNS00NC41TTkyIDYybDEyIDMyIDEyLTMyIDEyIDMyIDEyLTMyIi8+PC9zdmc+
  8. // @match *://*/*
  9. // @grant GM_setValue
  10. // @grant GM_getValue
  11. // @grant GM_addStyle
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_registerMenuCommand
  14. // @connect generativelanguage.googleapis.com
  15. // @connect *
  16. // @run-at document-end
  17. // @inject-into content
  18. // @require https://update.greasyfork.org/scripts/528704/1547031/SmolLLM.js
  19. // @require https://update.greasyfork.org/scripts/528703/1546610/SimpleBalancer.js
  20. // @require https://update.greasyfork.org/scripts/528763/1547460/Text%20Explainer%20Settings.js
  21. // @require https://update.greasyfork.org/scripts/528822/1547501/Selection%20Context.js
  22. // @license MIT
  23. // ==/UserScript==
  24.  
  25. (function () {
  26. 'use strict';
  27.  
  28. // Initialize settings manager with extended default config
  29. const settingsManager = new TextExplainerSettings({
  30. model: "gemini-2.0-flash",
  31. apiKey: null,
  32. baseUrl: "https://generativelanguage.googleapis.com",
  33. provider: "gemini",
  34. language: "Chinese", // Default language
  35. shortcut: {
  36. key: "d",
  37. ctrlKey: false,
  38. altKey: true,
  39. shiftKey: false,
  40. metaKey: false
  41. },
  42. floatingButton: {
  43. enabled: true,
  44. size: "medium",
  45. position: "bottom-right"
  46. }
  47. });
  48.  
  49. // Get current configuration
  50. let config = settingsManager.getAll();
  51.  
  52. // Initialize SmolLLM
  53. let llm;
  54. try {
  55. llm = new SmolLLM();
  56. } catch (error) {
  57. console.error('Failed to initialize SmolLLM:', error);
  58. llm = null;
  59. }
  60.  
  61. // Check if device is touch-enabled
  62. const isTouchDevice = () => {
  63. return ('ontouchstart' in window) ||
  64. (navigator.maxTouchPoints > 0) ||
  65. (navigator.msMaxTouchPoints > 0);
  66. };
  67.  
  68. const isIOS = () => {
  69. return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  70. };
  71.  
  72. // Create and manage floating button
  73. let floatingButton = null;
  74.  
  75. function createFloatingButton() {
  76. if (floatingButton) return;
  77.  
  78. floatingButton = document.createElement('div');
  79. floatingButton.id = 'explainer-floating-button';
  80.  
  81. // Determine size based on settings
  82. let buttonSize;
  83. switch (config.floatingButton.size) {
  84. case 'small': buttonSize = '40px'; break;
  85. case 'large': buttonSize = '60px'; break;
  86. default: buttonSize = '50px'; // medium
  87. }
  88.  
  89. // Position based on settings
  90. let positionCSS;
  91. switch (config.floatingButton.position) {
  92. case 'top-left': positionCSS = 'top: 20px; left: 20px;'; break;
  93. case 'top-right': positionCSS = 'top: 20px; right: 20px;'; break;
  94. case 'bottom-left': positionCSS = 'bottom: 20px; left: 20px;'; break;
  95. default: positionCSS = 'bottom: 20px; right: 20px;'; // bottom-right
  96. }
  97.  
  98. floatingButton.style.cssText = `
  99. width: ${buttonSize};
  100. height: ${buttonSize};
  101. border-radius: 50%;
  102. background-color: rgba(33, 150, 243, 0.8);
  103. color: white;
  104. display: flex;
  105. align-items: center;
  106. justify-content: center;
  107. position: fixed;
  108. ${positionCSS}
  109. z-index: 9999;
  110. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  111. cursor: pointer;
  112. font-weight: bold;
  113. font-size: ${parseInt(buttonSize) * 0.4}px;
  114. opacity: 0;
  115. transition: opacity 0.3s ease, transform 0.2s ease;
  116. pointer-events: none;
  117. touch-action: manipulation;
  118. -webkit-tap-highlight-color: transparent;
  119. `;
  120.  
  121. // Add icon or text
  122. floatingButton.innerHTML = '✓';
  123.  
  124. // Add to DOM
  125. document.body.appendChild(floatingButton);
  126.  
  127. // Add click event
  128. floatingButton.addEventListener('click', (e) => {
  129. e.preventDefault();
  130. processSelectedText();
  131. });
  132.  
  133. // Prevent text selection on button
  134. floatingButton.addEventListener('mousedown', (e) => {
  135. e.preventDefault();
  136. });
  137. }
  138.  
  139. function showFloatingButton() {
  140. if (!floatingButton || !config.floatingButton.enabled) return;
  141.  
  142. // Make visible and enable pointer events
  143. floatingButton.style.opacity = '1';
  144. floatingButton.style.pointerEvents = 'auto';
  145.  
  146. // Add active effect for touch
  147. floatingButton.addEventListener('touchstart', () => {
  148. floatingButton.style.transform = 'scale(0.95)';
  149. });
  150.  
  151. floatingButton.addEventListener('touchend', () => {
  152. floatingButton.style.transform = 'scale(1)';
  153. });
  154. }
  155.  
  156. function hideFloatingButton() {
  157. if (!floatingButton) return;
  158. floatingButton.style.opacity = '0';
  159. floatingButton.style.pointerEvents = 'none';
  160. }
  161.  
  162. // Add minimal styles for UI components
  163. GM_addStyle(`
  164. #explainer-popup {
  165. position: fixed;
  166. width: 450px;
  167. max-width: 90vw;
  168. max-height: 80vh;
  169. background: rgba(255, 255, 255, 0.3);
  170. backdrop-filter: blur(15px);
  171. -webkit-backdrop-filter: blur(15px);
  172. border-radius: 8px;
  173. box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  174. z-index: 10000;
  175. overflow: auto;
  176. padding: 16px;
  177. transition: top 0.3s, left 0.3s, bottom 0.3s, right 0.3s;
  178. }
  179. @keyframes slideInFromTop {
  180. from { transform: translateY(-20px); opacity: 0; }
  181. to { transform: translateY(0); opacity: 1; }
  182. }
  183. @keyframes slideInFromBottom {
  184. from { transform: translateY(20px); opacity: 0; }
  185. to { transform: translateY(0); opacity: 1; }
  186. }
  187. @keyframes slideInFromLeft {
  188. from { transform: translateX(-20px); opacity: 0; }
  189. to { transform: translateX(0); opacity: 1; }
  190. }
  191. @keyframes slideInFromRight {
  192. from { transform: translateX(20px); opacity: 0; }
  193. to { transform: translateX(0); opacity: 1; }
  194. }
  195. @keyframes fadeIn {
  196. from { opacity: 0; }
  197. to { opacity: 1; }
  198. }
  199. #explainer-loading {
  200. text-align: center;
  201. padding: 20px 0;
  202. display: flex;
  203. align-items: center;
  204. justify-content: center;
  205. }
  206. #explainer-loading:after {
  207. content: "";
  208. width: 24px;
  209. height: 24px;
  210. border: 3px solid #ddd;
  211. border-top: 3px solid #2196F3;
  212. border-radius: 50%;
  213. animation: spin 1s linear infinite;
  214. display: inline-block;
  215. }
  216. @keyframes spin {
  217. 0% { transform: rotate(0deg); }
  218. 100% { transform: rotate(360deg); }
  219. }
  220. #explainer-error {
  221. color: #d32f2f;
  222. padding: 8px;
  223. border-radius: 4px;
  224. margin-bottom: 10px;
  225. font-size: 14px;
  226. display: none;
  227. }
  228. /* Dark mode support - minimal */
  229. @media (prefers-color-scheme: dark) {
  230. #explainer-popup {
  231. background: rgba(35, 35, 40, 0.7);
  232. color: #e0e0e0;
  233. }
  234. #explainer-error {
  235. background-color: rgba(100, 25, 25, 0.4);
  236. color: #ff8a8a;
  237. }
  238. #explainer-floating-button {
  239. background-color: rgba(33, 150, 243, 0.9);
  240. }
  241. }
  242. `);
  243.  
  244. // Function to close the popup
  245. function closePopup() {
  246. const popup = document.getElementById('explainer-popup');
  247. if (popup) {
  248. popup.remove();
  249. }
  250. }
  251.  
  252. // Calculate optimal popup position based on selection
  253. function calculatePopupPosition() {
  254. const selection = window.getSelection();
  255. if (!selection || selection.rangeCount === 0) return null;
  256.  
  257. // Get selection position
  258. const range = selection.getRangeAt(0);
  259. const selectionRect = range.getBoundingClientRect();
  260.  
  261. // Get document dimensions
  262. const viewportWidth = window.innerWidth;
  263. const viewportHeight = window.innerHeight;
  264.  
  265. // Estimate popup dimensions (will be adjusted once created)
  266. const popupWidth = 450;
  267. const popupHeight = Math.min(500, viewportHeight * 0.8);
  268.  
  269. // Calculate optimal position
  270. let position = {};
  271.  
  272. // Default margin from selection
  273. const margin = 20;
  274.  
  275. // Try to position below the selection
  276. if (selectionRect.bottom + margin + popupHeight <= viewportHeight) {
  277. position.top = selectionRect.bottom + margin;
  278. position.left = Math.min(
  279. Math.max(10, selectionRect.left + (selectionRect.width / 2) - (popupWidth / 2)),
  280. viewportWidth - popupWidth - 10
  281. );
  282. position.placement = 'below';
  283. }
  284. // Try to position above the selection
  285. else if (selectionRect.top - margin - popupHeight >= 0) {
  286. position.bottom = viewportHeight - selectionRect.top + margin;
  287. position.left = Math.min(
  288. Math.max(10, selectionRect.left + (selectionRect.width / 2) - (popupWidth / 2)),
  289. viewportWidth - popupWidth - 10
  290. );
  291. position.placement = 'above';
  292. }
  293. // Try to position to the right
  294. else if (selectionRect.right + margin + popupWidth <= viewportWidth) {
  295. position.top = Math.max(10, Math.min(
  296. selectionRect.top,
  297. viewportHeight - popupHeight - 10
  298. ));
  299. position.left = selectionRect.right + margin;
  300. position.placement = 'right';
  301. }
  302. // Try to position to the left
  303. else if (selectionRect.left - margin - popupWidth >= 0) {
  304. position.top = Math.max(10, Math.min(
  305. selectionRect.top,
  306. viewportHeight - popupHeight - 10
  307. ));
  308. position.right = viewportWidth - selectionRect.left + margin;
  309. position.placement = 'left';
  310. }
  311. // Fallback to centered position if no good placement found
  312. else {
  313. position.top = Math.max(10, Math.min(
  314. selectionRect.top + selectionRect.height + margin,
  315. viewportHeight / 2 - popupHeight / 2
  316. ));
  317. position.left = Math.max(10, Math.min(
  318. selectionRect.left + selectionRect.width / 2 - popupWidth / 2,
  319. viewportWidth - popupWidth - 10
  320. ));
  321. position.placement = 'center';
  322. }
  323.  
  324. return position;
  325. }
  326.  
  327. // Create popup
  328. function createPopup() {
  329. // Remove existing popup if any
  330. closePopup();
  331.  
  332. const popup = document.createElement('div');
  333. popup.id = 'explainer-popup';
  334.  
  335. popup.innerHTML = `
  336. <div id="explainer-error"></div>
  337. <div id="explainer-loading"></div>
  338. <div id="explainer-content"></div>
  339. `;
  340.  
  341. document.body.appendChild(popup);
  342.  
  343. // Get optimal position for the popup
  344. const position = calculatePopupPosition();
  345.  
  346. // Apply dynamic positioning
  347. if (position) {
  348. popup.style.transform = 'none'; // Remove the default transform
  349.  
  350. // Apply positions based on the calculated values
  351. if (position.top !== undefined) popup.style.top = `${position.top}px`;
  352. if (position.bottom !== undefined) popup.style.bottom = `${position.bottom}px`;
  353. if (position.left !== undefined) popup.style.left = `${position.left}px`;
  354. if (position.right !== undefined) popup.style.right = `${position.right}px`;
  355.  
  356. // Add animation based on placement
  357. switch (position.placement) {
  358. case 'above':
  359. popup.style.animation = 'slideInFromTop 0.3s ease';
  360. break;
  361. case 'below':
  362. popup.style.animation = 'slideInFromBottom 0.3s ease';
  363. break;
  364. case 'left':
  365. popup.style.animation = 'slideInFromLeft 0.3s ease';
  366. break;
  367. case 'right':
  368. popup.style.animation = 'slideInFromRight 0.3s ease';
  369. break;
  370. default:
  371. popup.style.animation = 'fadeIn 0.3s ease';
  372. }
  373. } else {
  374. // Fallback to center positioning if we couldn't determine a good position
  375. popup.style.top = '50%';
  376. popup.style.left = '50%';
  377. popup.style.transform = 'translate(-50%, -50%)';
  378. }
  379.  
  380. // Add event listener for Escape key
  381. document.addEventListener('keydown', handleEscKey);
  382.  
  383. // Add event listener for clicking outside popup
  384. document.addEventListener('click', handleOutsideClick);
  385.  
  386. // Update popup position on resize or scroll
  387. window.addEventListener('resize', updatePopupPosition);
  388. window.addEventListener('scroll', updatePopupPosition);
  389.  
  390. return popup;
  391. }
  392.  
  393. // Update popup position on resize or scroll
  394. function updatePopupPosition() {
  395. const popup = document.getElementById('explainer-popup');
  396. if (!popup) return;
  397.  
  398. const position = calculatePopupPosition();
  399. if (position) {
  400. // Remove old positioning
  401. popup.style.transform = 'none';
  402. popup.style.top = '';
  403. popup.style.bottom = '';
  404. popup.style.left = '';
  405. popup.style.right = '';
  406.  
  407. // Apply new positions
  408. if (position.top !== undefined) popup.style.top = `${position.top}px`;
  409. if (position.bottom !== undefined) popup.style.bottom = `${position.bottom}px`;
  410. if (position.left !== undefined) popup.style.left = `${position.left}px`;
  411. if (position.right !== undefined) popup.style.right = `${position.right}px`;
  412. }
  413. }
  414.  
  415. // Handle Escape key to close popup
  416. function handleEscKey(e) {
  417. if (e.key === 'Escape') {
  418. closePopup();
  419. document.removeEventListener('keydown', handleEscKey);
  420. document.removeEventListener('click', handleOutsideClick);
  421. window.removeEventListener('resize', updatePopupPosition);
  422. window.removeEventListener('scroll', updatePopupPosition);
  423. }
  424. }
  425.  
  426. // Handle clicks outside popup to close it
  427. function handleOutsideClick(e) {
  428. const popup = document.getElementById('explainer-popup');
  429. if (popup && !popup.contains(e.target)) {
  430. closePopup();
  431. document.removeEventListener('keydown', handleEscKey);
  432. document.removeEventListener('click', handleOutsideClick);
  433. window.removeEventListener('resize', updatePopupPosition);
  434. window.removeEventListener('scroll', updatePopupPosition);
  435. }
  436. }
  437.  
  438. // Function to show an error in the popup
  439. function showError(message) {
  440. const errorDiv = document.getElementById('explainer-error');
  441. if (errorDiv) {
  442. errorDiv.textContent = message;
  443. errorDiv.style.display = 'block';
  444. document.getElementById('explainer-loading').style.display = 'none';
  445. }
  446. }
  447.  
  448. // Function to call the LLM using SmolLLM
  449. async function callLLM(prompt, systemPrompt, progressCallback) {
  450. if (!config.apiKey) {
  451. throw new Error("Please set up your API key in the settings.");
  452. }
  453.  
  454. if (!llm) {
  455. throw new Error("SmolLLM library not initialized. Please check console for errors.");
  456. }
  457.  
  458. console.log(`prompt: ${prompt}`);
  459. console.log(`systemPrompt: ${systemPrompt}`);
  460. try {
  461. return await llm.askLLM({
  462. prompt: prompt,
  463. systemPrompt: systemPrompt,
  464. model: config.model,
  465. apiKey: config.apiKey,
  466. baseUrl: config.baseUrl,
  467. providerName: config.provider,
  468. handler: progressCallback,
  469. timeout: 60000
  470. });
  471. } catch (error) {
  472. console.error('LLM API error:', error);
  473. throw error;
  474. }
  475. }
  476.  
  477. function getPrompt(selectedText, paragraphText, textBefore, textAfter) {
  478. const wordsCount = selectedText.split(' ').length;
  479. const systemPrompt = `Respond in ${config.language} using ONLY these HTML tags: <p>, <b>, <i>, <ul>, <ol>, <li>, <a>.
  480. - Maintain clean formatting without code blocks
  481. - Prioritize clarity and conciseness
  482. - Use bullet points when appropriate`;
  483.  
  484. // If we have context before/after, include it in the prompt
  485. const contextPrefix = textBefore || textAfter ?
  486. `Context before: "${textBefore || 'None'}"
  487. Selected text: "${selectedText}"
  488. Context after: "${textAfter || 'None'}"
  489. Based on the selected text and its surrounding context, ` : '';
  490.  
  491. if (selectedText === paragraphText || wordsCount >= 500) {
  492. return {
  493. prompt: `${contextPrefix}Create a structured summary in ${config.language}:\n\n"${selectedText}"\n\n
  494. - Identify key themes and concepts
  495. - Extract 3-5 main points
  496. - Use nested <ul> lists for hierarchy
  497. - Keep bullets concise (under 15 words)`,
  498. systemPrompt
  499. };
  500. }
  501.  
  502. // For short text that looks like a sentence, offer translation
  503. if (wordsCount > 3 && wordsCount < 100) {
  504. return {
  505. prompt: `Translate exactly to ${config.language} without commentary:\n\n"${selectedText}"\n\n
  506. - Preserve technical terms and names
  507. - Maintain original punctuation
  508. - Match formal/informal tone of source`,
  509. systemPrompt
  510. };
  511. }
  512.  
  513. const pinYinExtraPrompt = config.language === "Chinese" ? ' DO NOT add Pinyin for it.' : '';
  514. const ipaExtraPrompt = config.language === "Chinese" ? '(with IPA if necessary)' : '';
  515. const asciiChars = selectedText.replace(/[\s\.,\-_'"!?()]/g, '')
  516. .split('')
  517. .filter(char => char.charCodeAt(0) <= 127).length;
  518. const sampleSentenceLanguage = selectedText.length === asciiChars ? "English" : config.language;
  519. // Explain words prompt
  520. return {
  521. prompt: `Provide an explanation for the word: "${selectedText}${ipaExtraPrompt}" in ${config.language} without commentary.${pinYinExtraPrompt}
  522.  
  523. Use the context from the surrounding paragraph to inform your explanation when relevant:
  524.  
  525. "${paragraphText}"
  526.  
  527. # Consider these scenarios:
  528.  
  529. ## Names
  530. If "${selectedText}" is a person's name, company name, or organization name, provide a brief description (e.g., who they are or what they do).
  531. e.g.
  532. Alan Turing was a British mathematician and computer scientist. He is widely considered to be the father of theoretical computer science and artificial intelligence.
  533. His work was crucial to:
  534. Formalizing the concepts of algorithm and computation with the Turing machine.
  535. Breaking the German Enigma code during World War II, significantly contributing to the Allied victory.
  536. Developing the Turing test, a benchmark for artificial intelligence.
  537.  
  538.  
  539. ## Technical Terms
  540. If "${selectedText}" is a technical term or jargon, give a concise definition and explain the use case or context where it is commonly used. No need example sentences.
  541. e.g. GAN 生成对抗网络
  542. 生成对抗网络(Generative Adversarial Network),是一种深度学习框架,由Ian Goodfellow2014年提出。GAN包含两个神经网络:生成器(Generator)和判别器(Discriminator),它们相互对抗训练。生成器尝试创建看起来真实的数据,而判别器则尝试区分真实数据和生成的假数据。通过这种"博弈"过程,生成器逐渐学会创建越来越逼真的数据。
  543.  
  544. ## Normal Words
  545. - For any other word, explain its meaning and provide 1-2 example sentences with the word in ${sampleSentenceLanguage}.
  546. e.g. jargon \\ˈdʒɑrɡən\\ 行话,专业术语,特定领域内使用的专业词汇。在计算机科学和编程领域,指那些对外行人难以理解的专业术语和缩写。
  547. 例句: "When explaining code to beginners, try to avoid using too much technical jargon that might confuse them."(向初学者解释代码时,尽量避免使用太多可能让他们困惑的技术行话。)
  548.  
  549. # Format
  550.  
  551. - Output the words first, then the explanation, and then the example sentences in ${sampleSentenceLanguage} if necessary.
  552. - No extra explanation
  553. - Remember to using proper html format like <p> <b> <i> <a> <li> <ol> <ul> to improve readability.
  554. `,
  555. systemPrompt
  556. };
  557. }
  558.  
  559. // Main function to process selected text
  560. async function processSelectedText() {
  561. // Use the utility function instead of the local getSelectedText
  562. const { selectedText, textBefore, textAfter, paragraphText } = GetSelectionContext();
  563.  
  564. if (!selectedText) {
  565. showError('No text selected');
  566. return;
  567. }
  568.  
  569. console.log(`Selected text: '${selectedText}', Paragraph text:\n${paragraphText}`);
  570. // Create popup
  571. createPopup();
  572. const contentDiv = document.getElementById('explainer-content');
  573. const loadingDiv = document.getElementById('explainer-loading');
  574. const errorDiv = document.getElementById('explainer-error');
  575.  
  576. // Reset display
  577. errorDiv.style.display = 'none';
  578. loadingDiv.style.display = 'block';
  579.  
  580. // Assemble prompt with language preference
  581. const { prompt, systemPrompt } = getPrompt(selectedText, paragraphText, textBefore, textAfter);
  582.  
  583. // Variable to store ongoing response text
  584. let responseText = '';
  585. let responseStartTime = Date.now();
  586.  
  587. try {
  588. // Call LLM with progress callback and await the full response
  589. const fullResponse = await callLLM(prompt, systemPrompt, (textChunk, currentFullText) => {
  590. // Update response text with new chunk
  591. responseText = currentFullText || (responseText + textChunk);
  592.  
  593. // Hide loading message if this is the first chunk
  594. if (loadingDiv.style.display !== 'none') {
  595. loadingDiv.style.display = 'none';
  596. }
  597.  
  598. // Update content with either HTML or markdown
  599. updateContentDisplay(contentDiv, responseText);
  600. });
  601.  
  602. // If we got a response
  603. if (fullResponse && fullResponse.length > 0) {
  604. responseText = fullResponse;
  605. loadingDiv.style.display = 'none';
  606. updateContentDisplay(contentDiv, fullResponse);
  607. }
  608. // If no response was received at all
  609. else if (!fullResponse || fullResponse.length === 0) {
  610. // If we've received chunks but the final response is empty, use the accumulated text
  611. if (responseText && responseText.length > 0) {
  612. updateContentDisplay(contentDiv, responseText);
  613. } else {
  614. showError("No response received from the model. Please try again.");
  615. }
  616. }
  617.  
  618. // Hide loading indicator if it's still visible
  619. if (loadingDiv.style.display !== 'none') {
  620. loadingDiv.style.display = 'none';
  621. }
  622. } catch (error) {
  623. console.error('Error:', error);
  624. // Display error in popup
  625. showError(`Error: ${error.message}`);
  626. }
  627. }
  628.  
  629. // Main function to handle keyboard shortcuts
  630. function handleKeyPress(e) {
  631. // Get shortcut configuration from settings
  632. const shortcut = config.shortcut || { key: 'd', ctrlKey: false, altKey: true, shiftKey: false, metaKey: false };
  633.  
  634. // More robust shortcut detection using both key and code properties
  635. if (isShortcutMatch(e, shortcut)) {
  636. e.preventDefault();
  637. processSelectedText();
  638. }
  639. }
  640.  
  641. // Helper function for more robust shortcut detection
  642. function isShortcutMatch(event, shortcutConfig) {
  643. // Check all modifier keys first
  644. if (event.ctrlKey !== !!shortcutConfig.ctrlKey ||
  645. event.altKey !== !!shortcutConfig.altKey ||
  646. event.shiftKey !== !!shortcutConfig.shiftKey ||
  647. event.metaKey !== !!shortcutConfig.metaKey) {
  648. return false;
  649. }
  650.  
  651. const key = shortcutConfig.key.toLowerCase();
  652.  
  653. // Method 1: Direct key match (works for most standard keys)
  654. if (event.key.toLowerCase() === key) {
  655. return true;
  656. }
  657.  
  658. // Method 2: Key code match (more reliable for letter keys)
  659. // This handles the physical key position regardless of keyboard layout
  660. if (key.length === 1 && /^[a-z]$/.test(key) &&
  661. event.code === `Key${key.toUpperCase()}`) {
  662. return true;
  663. }
  664.  
  665. // Method 3: Handle known special characters from Option/Alt key combinations
  666. // These are the most common mappings on macOS when using Option+key
  667. const macOptionKeyMap = {
  668. 'a': 'å', 'b': '∫', 'c': 'ç', 'd': '∂', 'e': '´', 'f': 'ƒ',
  669. 'g': '©', 'h': '˙', 'i': 'ˆ', 'j': '∆', 'k': '˚', 'l': '¬',
  670. 'm': 'µ', 'n': '˜', 'o': 'ø', 'p': 'π', 'q': 'œ', 'r': '®',
  671. 's': 'ß', 't': '†', 'u': '¨', 'v': '√', 'w': '∑', 'x': '≈',
  672. 'y': '¥', 'z': 'Ω'
  673. };
  674.  
  675. if (shortcutConfig.altKey && macOptionKeyMap[key] === event.key) {
  676. return true;
  677. }
  678.  
  679. return false;
  680. }
  681.  
  682. // Helper function to update content display
  683. function updateContentDisplay(contentDiv, text) {
  684. if (!text) return;
  685.  
  686. try {
  687. if (!text.trim().startsWith('<')) {
  688. // fallback
  689. console.log(`Seems like the response is not HTML: ${text}`);
  690. text = `<p>${text.replace(/\n/g, '<br>')}</p>`;
  691. }
  692. contentDiv.innerHTML = text;
  693. } catch (e) {
  694. // Fallback if parsing fails
  695. console.error(`Error parsing content: ${e.message}`);
  696. contentDiv.innerHTML = `<p>${text.replace(/\n/g, '<br>')}</p>`;
  697. }
  698. }
  699.  
  700. // Monitor selection changes for floating button
  701. function handleSelectionChange() {
  702. const selection = window.getSelection();
  703. const hasSelection = selection && selection.toString().trim() !== '';
  704.  
  705. if (hasSelection && isTouchDevice() && config.floatingButton.enabled) {
  706. showFloatingButton();
  707. } else {
  708. hideFloatingButton();
  709. }
  710. }
  711.  
  712. // Settings update callback
  713. function onSettingsChanged(updatedConfig) {
  714. config = updatedConfig;
  715. console.log('Settings updated:', config);
  716.  
  717. // Recreate floating button if settings changed
  718. if (floatingButton) {
  719. floatingButton.remove();
  720. floatingButton = null;
  721.  
  722. if (isTouchDevice() && config.floatingButton.enabled) {
  723. createFloatingButton();
  724. handleSelectionChange(); // Check if there's already a selection
  725. }
  726. }
  727. }
  728.  
  729. // Initialize the script
  730. function init() {
  731. // Register settings menu in Tampermonkey
  732. GM_registerMenuCommand("Text Explainer Settings", () => {
  733. settingsManager.openDialog(onSettingsChanged);
  734. });
  735.  
  736. // Add keyboard shortcut listener
  737. document.addEventListener('keydown', handleKeyPress);
  738.  
  739. // For touch devices, create floating button
  740. if (isTouchDevice() && config.floatingButton.enabled) {
  741. createFloatingButton();
  742.  
  743. // Monitor text selection
  744. document.addEventListener('selectionchange', handleSelectionChange);
  745.  
  746. // Add touchend handler to show button after selection
  747. document.addEventListener('touchend', () => {
  748. // Small delay to ensure selection is updated
  749. setTimeout(handleSelectionChange, 100);
  750. });
  751. }
  752.  
  753. console.log('Text Explainer script initialized with language: ' + config.language);
  754. console.log('Touch device detected: ' + isTouchDevice());
  755. }
  756.  
  757. // Run initialization
  758. init();
  759. })();