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.8
  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/1547803/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.85);
  170. backdrop-filter: blur(10px);
  171. -webkit-backdrop-filter: blur(10px);
  172. border-radius: 8px;
  173. box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  174. z-index: 2147483647;
  175. overflow: auto;
  176. padding: 20px;
  177. transition: all 0.3s ease;
  178. -webkit-overflow-scrolling: touch;
  179. overscroll-behavior: contain;
  180. }
  181. @keyframes slideInFromTop {
  182. from { transform: translateY(-20px); opacity: 0; }
  183. to { transform: translateY(0); opacity: 1; }
  184. }
  185. @keyframes slideInFromBottom {
  186. from { transform: translateY(20px); opacity: 0; }
  187. to { transform: translateY(0); opacity: 1; }
  188. }
  189. @keyframes slideInFromLeft {
  190. from { transform: translateX(-20px); opacity: 0; }
  191. to { transform: translateX(0); opacity: 1; }
  192. }
  193. @keyframes slideInFromRight {
  194. from { transform: translateX(20px); opacity: 0; }
  195. to { transform: translateX(0); opacity: 1; }
  196. }
  197. @keyframes fadeIn {
  198. from { opacity: 0; }
  199. to { opacity: 1; }
  200. }
  201. #explainer-loading {
  202. text-align: center;
  203. padding: 20px 0;
  204. display: flex;
  205. align-items: center;
  206. justify-content: center;
  207. }
  208. #explainer-loading:after {
  209. content: "";
  210. width: 24px;
  211. height: 24px;
  212. border: 3px solid #ddd;
  213. border-top: 3px solid #2196F3;
  214. border-radius: 50%;
  215. animation: spin 1s linear infinite;
  216. display: inline-block;
  217. }
  218. @keyframes spin {
  219. 0% { transform: rotate(0deg); }
  220. 100% { transform: rotate(360deg); }
  221. }
  222. #explainer-error {
  223. color: #d32f2f;
  224. padding: 8px;
  225. border-radius: 4px;
  226. margin-bottom: 10px;
  227. font-size: 14px;
  228. display: none;
  229. }
  230. /* iOS-specific styles */
  231. @supports (-webkit-touch-callout: none) {
  232. #explainer-popup {
  233. background: rgba(255, 255, 255, 0.98);
  234. box-shadow: 0 5px 25px rgba(0, 0, 0, 0.3);
  235. border: 1px solid rgba(0, 0, 0, 0.1);
  236. }
  237. /* Dark mode for iOS */
  238. @media (prefers-color-scheme: dark) {
  239. #explainer-popup {
  240. background: rgba(35, 35, 40, 0.98);
  241. border: 1px solid rgba(255, 255, 255, 0.1);
  242. }
  243. }
  244. }
  245. /* Dark mode support - minimal */
  246. @media (prefers-color-scheme: dark) {
  247. #explainer-popup {
  248. background: rgba(35, 35, 40, 0.85);
  249. color: #e0e0e0;
  250. }
  251. #explainer-error {
  252. background-color: rgba(100, 25, 25, 0.4);
  253. color: #ff8a8a;
  254. }
  255. #explainer-floating-button {
  256. background-color: rgba(33, 150, 243, 0.9);
  257. }
  258. }
  259. /* Remove backdrop-filter as it's not well supported on iOS */
  260. /* Add touch-specific styles */
  261. @media (hover: none) and (pointer: coarse) {
  262. #explainer-popup {
  263. width: 95vw;
  264. max-height: 90vh;
  265. padding: 15px;
  266. font-size: 16px;
  267. }
  268. #explainer-popup p,
  269. #explainer-popup li {
  270. line-height: 1.6;
  271. margin-bottom: 12px;
  272. }
  273. #explainer-popup a {
  274. padding: 8px 0;
  275. }
  276. }
  277. `);
  278.  
  279. // Function to close the popup
  280. function closePopup() {
  281. const popup = document.getElementById('explainer-popup');
  282. if (popup) {
  283. popup.style.animation = 'fadeOut 0.3s ease';
  284. setTimeout(() => {
  285. popup.remove();
  286. }, 300);
  287. }
  288. }
  289.  
  290. // Calculate optimal popup position based on selection
  291. function calculatePopupPosition() {
  292. const selection = window.getSelection();
  293. if (!selection || selection.rangeCount === 0) return null;
  294.  
  295. // Get selection position
  296. const range = selection.getRangeAt(0);
  297. const selectionRect = range.getBoundingClientRect();
  298.  
  299. // Get scroll position to convert viewport coordinates to absolute
  300. const scrollLeft = window.scrollX || document.documentElement.scrollLeft;
  301. const scrollTop = window.scrollY || document.documentElement.scrollTop;
  302.  
  303. // Get document dimensions
  304. const viewportWidth = window.innerWidth;
  305. const viewportHeight = window.innerHeight;
  306.  
  307. // Estimate popup dimensions (will be adjusted once created)
  308. const popupWidth = 450;
  309. const popupHeight = Math.min(500, viewportHeight * 0.8);
  310.  
  311. // Calculate optimal position
  312. let position = {};
  313.  
  314. // Default margin from selection
  315. const margin = 20;
  316.  
  317. // Try to position below the selection
  318. if (selectionRect.bottom + margin + popupHeight <= viewportHeight) {
  319. position.top = selectionRect.bottom + scrollTop + margin;
  320. position.left = Math.min(
  321. Math.max(10 + scrollLeft, selectionRect.left + scrollLeft + (selectionRect.width / 2) - (popupWidth / 2)),
  322. viewportWidth + scrollLeft - popupWidth - 10
  323. );
  324. position.placement = 'below';
  325. }
  326. // Try to position above the selection
  327. else if (selectionRect.top - margin - popupHeight >= 0) {
  328. position.top = selectionRect.top + scrollTop - margin - popupHeight;
  329. position.left = Math.min(
  330. Math.max(10 + scrollLeft, selectionRect.left + scrollLeft + (selectionRect.width / 2) - (popupWidth / 2)),
  331. viewportWidth + scrollLeft - popupWidth - 10
  332. );
  333. position.placement = 'above';
  334. }
  335. // Try to position to the right
  336. else if (selectionRect.right + margin + popupWidth <= viewportWidth) {
  337. position.top = Math.max(10 + scrollTop, Math.min(
  338. selectionRect.top + scrollTop,
  339. viewportHeight + scrollTop - popupHeight - 10
  340. ));
  341. position.left = selectionRect.right + scrollLeft + margin;
  342. position.placement = 'right';
  343. }
  344. // Try to position to the left
  345. else if (selectionRect.left - margin - popupWidth >= 0) {
  346. position.top = Math.max(10 + scrollTop, Math.min(
  347. selectionRect.top + scrollTop,
  348. viewportHeight + scrollTop - popupHeight - 10
  349. ));
  350. position.left = selectionRect.left + scrollLeft - margin - popupWidth;
  351. position.placement = 'left';
  352. }
  353. // Fallback to centered position if no good placement found
  354. else {
  355. position.top = Math.max(10 + scrollTop, Math.min(
  356. selectionRect.top + selectionRect.height + scrollTop + margin,
  357. viewportHeight / 2 + scrollTop - popupHeight / 2
  358. ));
  359. position.left = Math.max(10 + scrollLeft, Math.min(
  360. selectionRect.left + selectionRect.width / 2 + scrollLeft - popupWidth / 2,
  361. viewportWidth + scrollLeft - popupWidth - 10
  362. ));
  363. position.placement = 'center';
  364. }
  365.  
  366. return position;
  367. }
  368.  
  369. // Create popup
  370. function createPopup() {
  371. // Remove existing popup if any
  372. closePopup();
  373.  
  374. const popup = document.createElement('div');
  375. popup.id = 'explainer-popup';
  376.  
  377. popup.innerHTML = `
  378. <div id="explainer-error"></div>
  379. <div id="explainer-loading"></div>
  380. <div id="explainer-content"></div>
  381. `;
  382.  
  383. document.body.appendChild(popup);
  384.  
  385. // For touch devices, use fixed positioning with transform
  386. if (isTouchDevice()) {
  387. popup.style.position = 'fixed';
  388. popup.style.top = '50%';
  389. popup.style.left = '50%';
  390. popup.style.transform = 'translate(-50%, -50%)';
  391. popup.style.width = '90vw';
  392. popup.style.maxHeight = '85vh';
  393. } else {
  394. // Desktop positioning logic
  395. const position = calculatePopupPosition();
  396. if (position) {
  397. popup.style.transform = 'none';
  398. if (position.top !== undefined) popup.style.top = `${position.top}px`;
  399. if (position.bottom !== undefined) popup.style.bottom = `${position.bottom}px`;
  400. if (position.left !== undefined) popup.style.left = `${position.left}px`;
  401. if (position.right !== undefined) popup.style.right = `${position.right}px`;
  402. } else {
  403. popup.style.top = '50%';
  404. popup.style.left = '50%';
  405. popup.style.transform = 'translate(-50%, -50%)';
  406. }
  407. }
  408.  
  409. // Add animation
  410. popup.style.animation = 'fadeIn 0.3s ease';
  411.  
  412. // Add event listeners
  413. document.addEventListener('keydown', handleEscKey);
  414. // Use touchend instead of touchstart for better touch handling
  415. if (isTouchDevice()) {
  416. document.addEventListener('touchend', handleOutsideClick, { passive: true });
  417. // Prevent default touch behavior on the popup
  418. popup.addEventListener('touchstart', (e) => {
  419. e.stopPropagation();
  420. }, { passive: true });
  421. } else {
  422. document.addEventListener('click', handleOutsideClick);
  423. }
  424.  
  425. return popup;
  426. }
  427.  
  428. // Handle Escape key to close popup
  429. function handleEscKey(e) {
  430. if (e.key === 'Escape') {
  431. closePopup();
  432. document.removeEventListener('keydown', handleEscKey);
  433. document.removeEventListener('click', handleOutsideClick);
  434. }
  435. }
  436.  
  437. // Handle clicks outside popup to close it
  438. function handleOutsideClick(e) {
  439. const popup = document.getElementById('explainer-popup');
  440. if (!popup) return;
  441.  
  442. // Prevent closing if clicking inside the popup
  443. if (popup.contains(e.target)) {
  444. return;
  445. }
  446.  
  447. // For touch events, check if the touch ended outside
  448. if (e.type === 'touchend') {
  449. const touch = e.changedTouches[0];
  450. const rect = popup.getBoundingClientRect();
  451. const isOutsideTouch = touch.clientX < rect.left ||
  452. touch.clientX > rect.right ||
  453. touch.clientY < rect.top ||
  454. touch.clientY > rect.bottom;
  455. if (isOutsideTouch) {
  456. closePopup();
  457. document.removeEventListener('keydown', handleEscKey);
  458. document.removeEventListener('touchend', handleOutsideClick);
  459. }
  460. } else if (!popup.contains(e.target)) {
  461. closePopup();
  462. document.removeEventListener('keydown', handleEscKey);
  463. document.removeEventListener('click', handleOutsideClick);
  464. }
  465. }
  466.  
  467. // Function to show an error in the popup
  468. function showError(message) {
  469. const errorDiv = document.getElementById('explainer-error');
  470. if (errorDiv) {
  471. errorDiv.textContent = message;
  472. errorDiv.style.display = 'block';
  473. document.getElementById('explainer-loading').style.display = 'none';
  474. }
  475. }
  476.  
  477. // Function to call the LLM using SmolLLM
  478. async function callLLM(prompt, systemPrompt, progressCallback) {
  479. if (!config.apiKey) {
  480. throw new Error("Please set up your API key in the settings.");
  481. }
  482.  
  483. if (!llm) {
  484. throw new Error("SmolLLM library not initialized. Please check console for errors.");
  485. }
  486.  
  487. console.log(`prompt: ${prompt}`);
  488. console.log(`systemPrompt: ${systemPrompt}`);
  489. try {
  490. return await llm.askLLM({
  491. prompt: prompt,
  492. systemPrompt: systemPrompt,
  493. model: config.model,
  494. apiKey: config.apiKey,
  495. baseUrl: config.baseUrl,
  496. providerName: config.provider,
  497. handler: progressCallback,
  498. timeout: 60000
  499. });
  500. } catch (error) {
  501. console.error('LLM API error:', error);
  502. throw error;
  503. }
  504. }
  505.  
  506. function getPrompt(selectedText, paragraphText, textBefore, textAfter) {
  507. const wordsCount = selectedText.split(' ').length;
  508. const systemPrompt = `Respond in ${config.language} using ONLY these HTML tags: <p>, <b>, <i>, <ul>, <ol>, <li>, <a>.
  509. - Maintain clean formatting without code blocks
  510. - Prioritize clarity and conciseness
  511. - Use bullet points when appropriate`;
  512.  
  513. if (wordsCount >= 500) {
  514. return {
  515. prompt: `Create a structured summary in ${config.language}:
  516. - Identify key themes and concepts
  517. - Extract 3-5 main points
  518. - Use nested <ul> lists for hierarchy
  519. - Keep bullets concise
  520.  
  521. for the following selected text:
  522. \n\n${selectedText}
  523. `,
  524. systemPrompt
  525. };
  526. }
  527.  
  528. // For short text that looks like a sentence, offer translation
  529. if (wordsCount >= 5) {
  530. return {
  531. prompt: `Translate exactly to ${config.language} without commentary:
  532. - Preserve technical terms and names
  533. - Maintain original punctuation
  534. - Match formal/informal tone of source
  535.  
  536. for the following selected text:
  537. \n\n${selectedText}
  538. `,
  539. systemPrompt
  540. };
  541. }
  542.  
  543. const pinYinExtraPrompt = config.language === "Chinese" ? ' DO NOT add Pinyin for it.' : '';
  544. const ipaExtraPrompt = config.language === "Chinese" ? '(with IPA if necessary)' : '';
  545. const asciiChars = selectedText.replace(/[\s\.,\-_'"!?()]/g, '')
  546. .split('')
  547. .filter(char => char.charCodeAt(0) <= 127).length;
  548. const sampleSentenceLanguage = selectedText.length === asciiChars ? "English" : config.language;
  549.  
  550. // If we have context before/after, include it in the prompt
  551. const contextPrompt = textBefore || textAfter ?
  552. `# Context:
  553. ## Before selected text:
  554. ${textBefore || 'None'}
  555. ## Selected text:
  556. ${selectedText}
  557. ## After selected text:
  558. ${textAfter || 'None'}` : paragraphText;
  559.  
  560.  
  561. // Explain words prompt
  562. return {
  563. prompt: `Provide an explanation for the word: "${selectedText}${ipaExtraPrompt}" in ${config.language} without commentary.${pinYinExtraPrompt}
  564.  
  565. Use the context from the surrounding paragraph to inform your explanation when relevant:
  566.  
  567. ${contextPrompt}
  568.  
  569. # Consider these scenarios:
  570.  
  571. ## Names
  572. 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).
  573. e.g.
  574. Alan Turing was a British mathematician and computer scientist. He is widely considered to be the father of theoretical computer science and artificial intelligence.
  575. His work was crucial to:
  576. Formalizing the concepts of algorithm and computation with the Turing machine.
  577. Breaking the German Enigma code during World War II, significantly contributing to the Allied victory.
  578. Developing the Turing test, a benchmark for artificial intelligence.
  579.  
  580.  
  581. ## Technical Terms
  582. If "${selectedText}" is a technical term or jargon
  583. - give a concise definition and explain.
  584. - Some best practice of using it
  585. - Explain how it works.
  586. - No need example sentence for the technical term.
  587. e.g. GAN 生成对抗网络
  588. 生成对抗网络(Generative Adversarial Network),是一种深度学习框架,由Ian Goodfellow2014年提出。GAN包含两个神经网络:生成器(Generator)和判别器(Discriminator),它们相互对抗训练。生成器尝试创建看起来真实的数据,而判别器则尝试区分真实数据和生成的假数据。通过这种"博弈"过程,生成器逐渐学会创建越来越逼真的数据。
  589.  
  590. ## Normal Words
  591. - For any other word, explain its meaning and provide 1-2 example sentences with the word in ${sampleSentenceLanguage}.
  592. e.g. jargon \\ˈdʒɑrɡən\\ 行话,专业术语,特定领域内使用的专业词汇。在计算机科学和编程领域,指那些对外行人难以理解的专业术语和缩写。
  593. 例句: "When explaining code to beginners, try to avoid using too much technical jargon that might confuse them."(向初学者解释代码时,尽量避免使用太多可能让他们困惑的技术行话。)
  594.  
  595. # Format
  596.  
  597. - Output the words first, then the explanation, and then the example sentences in ${sampleSentenceLanguage} if necessary.
  598. - No extra explanation
  599. - Remember to using proper html format like <p> <b> <i> <a> <li> <ol> <ul> to improve readability.
  600. `,
  601. systemPrompt
  602. };
  603. }
  604.  
  605. // Main function to process selected text
  606. async function processSelectedText() {
  607. // Use the utility function instead of the local getSelectedText
  608. const { selectedText, textBefore, textAfter, paragraphText } = GetSelectionContext();
  609.  
  610. if (!selectedText) {
  611. showError('No text selected');
  612. return;
  613. }
  614.  
  615. console.log(`Selected text: '${selectedText}', Paragraph text:\n${paragraphText}`);
  616. // Create popup
  617. createPopup();
  618. const contentDiv = document.getElementById('explainer-content');
  619. const loadingDiv = document.getElementById('explainer-loading');
  620. const errorDiv = document.getElementById('explainer-error');
  621.  
  622. // Reset display
  623. errorDiv.style.display = 'none';
  624. loadingDiv.style.display = 'block';
  625.  
  626. // Assemble prompt with language preference
  627. const { prompt, systemPrompt } = getPrompt(selectedText, paragraphText, textBefore, textAfter);
  628.  
  629. // Variable to store ongoing response text
  630. let responseText = '';
  631.  
  632. try {
  633. // Call LLM with progress callback and await the full response
  634. const fullResponse = await callLLM(prompt, systemPrompt, (textChunk, currentFullText) => {
  635. // Update response text with new chunk
  636. responseText = currentFullText || (responseText + textChunk);
  637.  
  638. // Hide loading message if this is the first chunk
  639. if (loadingDiv.style.display !== 'none') {
  640. loadingDiv.style.display = 'none';
  641. }
  642.  
  643. // Update content with either HTML or markdown
  644. updateContentDisplay(contentDiv, responseText);
  645. });
  646.  
  647. // If we got a response
  648. if (fullResponse && fullResponse.length > 0) {
  649. responseText = fullResponse;
  650. loadingDiv.style.display = 'none';
  651. updateContentDisplay(contentDiv, fullResponse);
  652. }
  653. // If no response was received at all
  654. else if (!fullResponse || fullResponse.length === 0) {
  655. // If we've received chunks but the final response is empty, use the accumulated text
  656. if (responseText && responseText.length > 0) {
  657. updateContentDisplay(contentDiv, responseText);
  658. } else {
  659. showError("No response received from the model. Please try again.");
  660. }
  661. }
  662.  
  663. // Hide loading indicator if it's still visible
  664. if (loadingDiv.style.display !== 'none') {
  665. loadingDiv.style.display = 'none';
  666. }
  667. } catch (error) {
  668. console.error('Error:', error);
  669. // Display error in popup
  670. showError(`Error: ${error.message}`);
  671. }
  672. }
  673.  
  674. // Main function to handle keyboard shortcuts
  675. function handleKeyPress(e) {
  676. // Get shortcut configuration from settings
  677. const shortcut = config.shortcut || { key: 'd', ctrlKey: false, altKey: true, shiftKey: false, metaKey: false };
  678.  
  679. // More robust shortcut detection using both key and code properties
  680. if (isShortcutMatch(e, shortcut)) {
  681. e.preventDefault();
  682. processSelectedText();
  683. }
  684. }
  685.  
  686. // Helper function for more robust shortcut detection
  687. function isShortcutMatch(event, shortcutConfig) {
  688. // Check all modifier keys first
  689. if (event.ctrlKey !== !!shortcutConfig.ctrlKey ||
  690. event.altKey !== !!shortcutConfig.altKey ||
  691. event.shiftKey !== !!shortcutConfig.shiftKey ||
  692. event.metaKey !== !!shortcutConfig.metaKey) {
  693. return false;
  694. }
  695.  
  696. const key = shortcutConfig.key.toLowerCase();
  697.  
  698. // Method 1: Direct key match (works for most standard keys)
  699. if (event.key.toLowerCase() === key) {
  700. return true;
  701. }
  702.  
  703. // Method 2: Key code match (more reliable for letter keys)
  704. // This handles the physical key position regardless of keyboard layout
  705. if (key.length === 1 && /^[a-z]$/.test(key) &&
  706. event.code === `Key${key.toUpperCase()}`) {
  707. return true;
  708. }
  709.  
  710. // Method 3: Handle known special characters from Option/Alt key combinations
  711. // These are the most common mappings on macOS when using Option+key
  712. const macOptionKeyMap = {
  713. 'a': 'å', 'b': '∫', 'c': 'ç', 'd': '∂', 'e': '´', 'f': 'ƒ',
  714. 'g': '©', 'h': '˙', 'i': 'ˆ', 'j': '∆', 'k': '˚', 'l': '¬',
  715. 'm': 'µ', 'n': '˜', 'o': 'ø', 'p': 'π', 'q': 'œ', 'r': '®',
  716. 's': 'ß', 't': '†', 'u': '¨', 'v': '√', 'w': '∑', 'x': '≈',
  717. 'y': '¥', 'z': 'Ω'
  718. };
  719.  
  720. if (shortcutConfig.altKey && macOptionKeyMap[key] === event.key) {
  721. return true;
  722. }
  723.  
  724. return false;
  725. }
  726.  
  727. // Helper function to update content display
  728. function updateContentDisplay(contentDiv, text) {
  729. if (!text) return;
  730.  
  731. try {
  732. if (!text.trim().startsWith('<')) {
  733. // fallback
  734. console.log(`Seems like the response is not HTML: ${text}`);
  735. text = `<p>${text.replace(/\n/g, '<br>')}</p>`;
  736. }
  737. contentDiv.innerHTML = text;
  738. } catch (e) {
  739. // Fallback if parsing fails
  740. console.error(`Error parsing content: ${e.message}`);
  741. contentDiv.innerHTML = `<p>${text.replace(/\n/g, '<br>')}</p>`;
  742. }
  743. }
  744.  
  745. // Monitor selection changes for floating button
  746. function handleSelectionChange() {
  747. const selection = window.getSelection();
  748. const hasSelection = selection && selection.toString().trim() !== '';
  749.  
  750. if (hasSelection && isTouchDevice() && config.floatingButton.enabled) {
  751. showFloatingButton();
  752. } else {
  753. hideFloatingButton();
  754. }
  755. }
  756.  
  757. // Settings update callback
  758. function onSettingsChanged(updatedConfig) {
  759. config = updatedConfig;
  760. console.log('Settings updated:', config);
  761.  
  762. // Recreate floating button if settings changed
  763. if (floatingButton) {
  764. floatingButton.remove();
  765. floatingButton = null;
  766.  
  767. if (isTouchDevice() && config.floatingButton.enabled) {
  768. createFloatingButton();
  769. handleSelectionChange(); // Check if there's already a selection
  770. }
  771. }
  772. }
  773.  
  774. // Initialize the script
  775. function init() {
  776. // Register settings menu in Tampermonkey
  777. GM_registerMenuCommand("Text Explainer Settings", () => {
  778. settingsManager.openDialog(onSettingsChanged);
  779. });
  780.  
  781. // Add keyboard shortcut listener
  782. document.addEventListener('keydown', handleKeyPress);
  783.  
  784. // For touch devices, create floating button
  785. if (isTouchDevice() && config.floatingButton.enabled) {
  786. createFloatingButton();
  787.  
  788. // Monitor text selection
  789. document.addEventListener('selectionchange', handleSelectionChange);
  790.  
  791. // Add touchend handler to show button after selection
  792. document.addEventListener('touchend', () => {
  793. // Small delay to ensure selection is updated
  794. setTimeout(handleSelectionChange, 100);
  795. });
  796. }
  797.  
  798. console.log('Text Explainer script initialized with language: ' + config.language);
  799. console.log('Touch device detected: ' + isTouchDevice());
  800. }
  801.  
  802. // Run initialization
  803. init();
  804. })();