Text Explainer

Explain selected text using LLM

当前为 2025-03-06 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Text Explainer
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2.10
  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. // Create and manage floating button
  69. let floatingButton = null;
  70. let isProcessingText = false;
  71.  
  72. function createFloatingButton() {
  73. if (floatingButton) return;
  74.  
  75. floatingButton = document.createElement('div');
  76. floatingButton.id = 'explainer-floating-button';
  77.  
  78. // Determine size based on settings
  79. let buttonSize;
  80. switch (config.floatingButton.size) {
  81. case 'small': buttonSize = '40px'; break;
  82. case 'large': buttonSize = '60px'; break;
  83. default: buttonSize = '50px'; // medium
  84. }
  85.  
  86. floatingButton.style.cssText = `
  87. width: ${buttonSize};
  88. height: ${buttonSize};
  89. border-radius: 50%;
  90. background-color: rgba(33, 150, 243, 0.8);
  91. color: white;
  92. display: flex;
  93. align-items: center;
  94. justify-content: center;
  95. position: fixed;
  96. z-index: 9999;
  97. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  98. cursor: pointer;
  99. font-weight: bold;
  100. font-size: ${parseInt(buttonSize) * 0.4}px;
  101. opacity: 0;
  102. transition: opacity 0.3s ease, transform 0.2s ease;
  103. pointer-events: none;
  104. touch-action: manipulation;
  105. -webkit-tap-highlight-color: transparent;
  106. `;
  107.  
  108. // Add icon or text
  109. floatingButton.innerHTML = '💬';
  110.  
  111. // Add to DOM
  112. document.body.appendChild(floatingButton);
  113.  
  114. // Handle button click/tap
  115. function handleButtonAction(e) {
  116. e.preventDefault();
  117. e.stopPropagation();
  118.  
  119. // Prevent multiple clicks while processing
  120. if (isProcessingText) return;
  121.  
  122. // Get selection context before clearing selection
  123. const selectionContext = GetSelectionContext();
  124.  
  125. if (!selectionContext.selectedText) {
  126. console.log('No valid selection to process');
  127. return;
  128. }
  129.  
  130. // Set processing flag
  131. isProcessingText = true;
  132.  
  133. // Hide the floating button
  134. hideFloatingButton();
  135.  
  136. // Blur selection to dismiss iOS menu
  137. window.getSelection().removeAllRanges();
  138.  
  139. // Now trigger the explainer with the stored selection
  140. // Create popup
  141. createPopup();
  142. const contentDiv = document.getElementById('explainer-content');
  143. const loadingDiv = document.getElementById('explainer-loading');
  144. const errorDiv = document.getElementById('explainer-error');
  145.  
  146. // Reset display
  147. errorDiv.style.display = 'none';
  148. loadingDiv.style.display = 'block';
  149.  
  150. // Assemble prompt with language preference
  151. const { prompt, systemPrompt } = getPrompt(
  152. selectionContext.selectedText,
  153. selectionContext.paragraphText,
  154. selectionContext.textBefore,
  155. selectionContext.textAfter
  156. );
  157.  
  158. // Variable to store ongoing response text
  159. let responseText = '';
  160.  
  161. // Call LLM with progress callback
  162. callLLM(prompt, systemPrompt, (textChunk, currentFullText) => {
  163. // Update response text with new chunk
  164. responseText = currentFullText || (responseText + textChunk);
  165.  
  166. // Hide loading message if this is the first chunk
  167. if (loadingDiv.style.display !== 'none') {
  168. loadingDiv.style.display = 'none';
  169. }
  170.  
  171. // Update content with either HTML or markdown
  172. updateContentDisplay(contentDiv, responseText);
  173. })
  174. .catch(error => {
  175. console.error('Error in LLM call:', error);
  176. errorDiv.textContent = error.message || 'Error processing request';
  177. errorDiv.style.display = 'block';
  178. loadingDiv.style.display = 'none';
  179. })
  180. .finally(() => {
  181. // Reset processing flag
  182. setTimeout(() => {
  183. isProcessingText = false;
  184. }, 1000);
  185. });
  186. }
  187.  
  188. // Add click event
  189. floatingButton.addEventListener('click', handleButtonAction);
  190.  
  191. // Add touch events
  192. floatingButton.addEventListener('touchstart', (e) => {
  193. e.preventDefault();
  194. e.stopPropagation();
  195. floatingButton.style.transform = 'scale(0.95)';
  196. }, { passive: false });
  197.  
  198. floatingButton.addEventListener('touchend', (e) => {
  199. e.preventDefault();
  200. e.stopPropagation();
  201. floatingButton.style.transform = 'scale(1)';
  202. handleButtonAction(e);
  203. }, { passive: false });
  204.  
  205. // Prevent text selection on button
  206. floatingButton.addEventListener('mousedown', (e) => {
  207. e.preventDefault();
  208. e.stopPropagation();
  209. });
  210. }
  211.  
  212. function showFloatingButton() {
  213. if (!floatingButton || !config.floatingButton.enabled || isProcessingText) return;
  214.  
  215. const selection = window.getSelection();
  216. if (!selection || selection.rangeCount === 0) {
  217. hideFloatingButton();
  218. return;
  219. }
  220.  
  221. const range = selection.getRangeAt(0);
  222. const rect = range.getBoundingClientRect();
  223.  
  224. // Calculate position near the selection
  225. const buttonSize = parseInt(floatingButton.style.width);
  226. const margin = 10; // Distance from selection
  227.  
  228. // Calculate position in viewport coordinates
  229. let top = rect.bottom + margin;
  230. let left = rect.left + (rect.width / 2) - (buttonSize / 2);
  231.  
  232. // If button would go off screen, try positioning above
  233. if (top + buttonSize > window.innerHeight) {
  234. top = rect.top - buttonSize - margin;
  235. }
  236.  
  237. // Ensure button stays within viewport horizontally
  238. left = Math.max(10, Math.min(left, window.innerWidth - buttonSize - 10));
  239.  
  240. // Apply position (using viewport coordinates for fixed positioning)
  241. floatingButton.style.top = `${top}px`;
  242. floatingButton.style.left = `${left}px`;
  243.  
  244. // Make visible and enable pointer events
  245. floatingButton.style.opacity = '1';
  246. floatingButton.style.pointerEvents = 'auto';
  247. }
  248.  
  249. function hideFloatingButton() {
  250. if (!floatingButton) return;
  251. floatingButton.style.opacity = '0';
  252. floatingButton.style.pointerEvents = 'none';
  253. }
  254.  
  255. // Add minimal styles for UI components
  256. GM_addStyle(`
  257. /* Base popup styles */
  258. #explainer-popup {
  259. position: absolute;
  260. width: 450px;
  261. max-width: 90vw;
  262. max-height: 80vh;
  263. padding: 20px;
  264. z-index: 2147483647;
  265. overflow: auto;
  266. overscroll-behavior: contain;
  267. -webkit-overflow-scrolling: touch;
  268. /* Visual styles */
  269. background: rgba(255, 255, 255, 0.85);
  270. backdrop-filter: blur(10px);
  271. -webkit-backdrop-filter: blur(10px);
  272. border-radius: 8px;
  273. box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  274. border: 1px solid rgba(0, 0, 0, 0.15);
  275. /* Text styles */
  276. color: #111;
  277. text-shadow: 0 0 1px rgba(255, 255, 255, 0.3);
  278. /* Animations */
  279. transition: all 0.3s ease;
  280. }
  281. /* Dark theme */
  282. #explainer-popup.dark-theme {
  283. background: rgba(45, 45, 50, 0.85);
  284. backdrop-filter: blur(10px);
  285. -webkit-backdrop-filter: blur(10px);
  286. color: #e0e0e0;
  287. border: 1px solid rgba(255, 255, 255, 0.15);
  288. box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);
  289. text-shadow: 0 0 1px rgba(0, 0, 0, 0.3);
  290. }
  291. /* iOS-specific overrides */
  292. @supports (-webkit-touch-callout: none) {
  293. #explainer-popup {
  294. background: rgba(255, 255, 255, 0.98);
  295. /* Disable backdrop-filter on iOS for better performance */
  296. backdrop-filter: none;
  297. -webkit-backdrop-filter: none;
  298. }
  299. #explainer-popup.dark-theme {
  300. background: rgba(35, 35, 40, 0.98);
  301. }
  302. }
  303.  
  304. @keyframes slideInFromTop {
  305. from { transform: translateY(-20px); opacity: 0; }
  306. to { transform: translateY(0); opacity: 1; }
  307. }
  308. @keyframes slideInFromBottom {
  309. from { transform: translateY(20px); opacity: 0; }
  310. to { transform: translateY(0); opacity: 1; }
  311. }
  312. @keyframes slideInFromLeft {
  313. from { transform: translateX(-20px); opacity: 0; }
  314. to { transform: translateX(0); opacity: 1; }
  315. }
  316. @keyframes slideInFromRight {
  317. from { transform: translateX(20px); opacity: 0; }
  318. to { transform: translateX(0); opacity: 1; }
  319. }
  320. @keyframes fadeIn {
  321. from { opacity: 0; }
  322. to { opacity: 1; }
  323. }
  324. #explainer-loading {
  325. text-align: center;
  326. padding: 20px 0;
  327. display: flex;
  328. align-items: center;
  329. justify-content: center;
  330. }
  331. #explainer-loading:after {
  332. content: "";
  333. width: 24px;
  334. height: 24px;
  335. border: 3px solid #ddd;
  336. border-top: 3px solid #2196F3;
  337. border-radius: 50%;
  338. animation: spin 1s linear infinite;
  339. display: inline-block;
  340. }
  341. @keyframes spin {
  342. 0% { transform: rotate(0deg); }
  343. 100% { transform: rotate(360deg); }
  344. }
  345. #explainer-error {
  346. color: #d32f2f;
  347. padding: 8px;
  348. border-radius: 4px;
  349. margin-bottom: 10px;
  350. font-size: 14px;
  351. display: none;
  352. }
  353. /* iOS-specific styles */
  354. @supports (-webkit-touch-callout: none) {
  355. #explainer-popup {
  356. background: rgba(255, 255, 255, 0.98);
  357. box-shadow: 0 5px 25px rgba(0, 0, 0, 0.3);
  358. border: 1px solid rgba(0, 0, 0, 0.1);
  359. }
  360. /* Dark mode for iOS */
  361. @media (prefers-color-scheme: dark) {
  362. #explainer-popup {
  363. background: rgba(35, 35, 40, 0.98);
  364. border: 1px solid rgba(255, 255, 255, 0.1);
  365. }
  366. }
  367. }
  368. /* Dark mode support - minimal */
  369. @media (prefers-color-scheme: dark) {
  370. #explainer-popup {
  371. background: rgba(35, 35, 40, 0.85);
  372. color: #e0e0e0;
  373. }
  374. #explainer-error {
  375. background-color: rgba(100, 25, 25, 0.4);
  376. color: #ff8a8a;
  377. }
  378. #explainer-floating-button {
  379. background-color: rgba(33, 150, 243, 0.9);
  380. }
  381. }
  382. /* Add touch-specific styles */
  383. @media (hover: none) and (pointer: coarse) {
  384. #explainer-popup {
  385. width: 95vw;
  386. max-height: 90vh;
  387. padding: 15px;
  388. font-size: 16px;
  389. }
  390. #explainer-popup p,
  391. #explainer-popup li {
  392. line-height: 1.6;
  393. margin-bottom: 12px;
  394. }
  395. #explainer-popup a {
  396. padding: 8px 0;
  397. }
  398. }
  399. `);
  400.  
  401. // Function to detect if the page has a dark background
  402. function isPageDarkMode() {
  403. // Try to get the background color of the body or html element
  404. const bodyEl = document.body;
  405. const htmlEl = document.documentElement;
  406.  
  407. // Get computed style
  408. const bodyStyle = window.getComputedStyle(bodyEl);
  409. const htmlStyle = window.getComputedStyle(htmlEl);
  410.  
  411. // Extract background color
  412. const bodyBg = bodyStyle.backgroundColor;
  413. const htmlBg = htmlStyle.backgroundColor;
  414.  
  415. // Parse RGB values
  416. function getRGBValues(color) {
  417. const match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
  418. if (!match) return null;
  419.  
  420. const r = parseInt(match[1], 10);
  421. const g = parseInt(match[2], 10);
  422. const b = parseInt(match[3], 10);
  423.  
  424. return { r, g, b };
  425. }
  426.  
  427. // Calculate luminance (brightness) - higher values are brighter
  428. function getLuminance(color) {
  429. const rgb = getRGBValues(color);
  430. if (!rgb) return 128; // Default to middle gray if can't parse
  431.  
  432. // Perceived brightness formula
  433. return (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b);
  434. }
  435.  
  436. const bodyLuminance = getLuminance(bodyBg);
  437. const htmlLuminance = getLuminance(htmlBg);
  438.  
  439. // If either background is dark, consider the page dark
  440. const threshold = 128; // Middle of 0-255 range
  441.  
  442. // Check system preference as a fallback
  443. const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  444.  
  445. // Page is dark if:
  446. // 1. Body background is dark, or
  447. // 2. HTML background is dark and body has no background set, or
  448. // 3. Both have no background set but system prefers dark
  449. if (bodyLuminance < threshold) {
  450. return true;
  451. } else if (bodyBg === 'rgba(0, 0, 0, 0)' && htmlLuminance < threshold) {
  452. return true;
  453. } else if (bodyBg === 'rgba(0, 0, 0, 0)' && htmlBg === 'rgba(0, 0, 0, 0)') {
  454. return prefersDark;
  455. }
  456.  
  457. return false;
  458. }
  459.  
  460. // Function to close the popup
  461. function closePopup() {
  462. const popup = document.getElementById('explainer-popup');
  463. if (popup) {
  464. popup.style.animation = 'fadeOut 0.3s ease';
  465. setTimeout(() => {
  466. popup.remove();
  467. }, 300);
  468. }
  469. }
  470.  
  471. // Calculate optimal popup position based on selection
  472. function calculatePopupPosition() {
  473. const selection = window.getSelection();
  474. if (!selection || selection.rangeCount === 0) return null;
  475.  
  476. // Get selection position
  477. const range = selection.getRangeAt(0);
  478. const selectionRect = range.getBoundingClientRect();
  479.  
  480. // Get scroll position to convert viewport coordinates to absolute
  481. const scrollLeft = window.scrollX || document.documentElement.scrollLeft;
  482. const scrollTop = window.scrollY || document.documentElement.scrollTop;
  483.  
  484. // Get document dimensions
  485. const viewportWidth = window.innerWidth;
  486. const viewportHeight = window.innerHeight;
  487.  
  488. // Estimate popup dimensions (will be adjusted once created)
  489. const popupWidth = 450;
  490. const popupHeight = Math.min(500, viewportHeight * 0.8);
  491.  
  492. // Calculate optimal position
  493. let position = {};
  494.  
  495. // Default margin from selection
  496. const margin = 20;
  497.  
  498. // Try to position below the selection
  499. if (selectionRect.bottom + margin + popupHeight <= viewportHeight) {
  500. position.top = selectionRect.bottom + scrollTop + margin;
  501. position.left = Math.min(
  502. Math.max(10 + scrollLeft, selectionRect.left + scrollLeft + (selectionRect.width / 2) - (popupWidth / 2)),
  503. viewportWidth + scrollLeft - popupWidth - 10
  504. );
  505. position.placement = 'below';
  506. }
  507. // Try to position above the selection
  508. else if (selectionRect.top - margin - popupHeight >= 0) {
  509. position.top = selectionRect.top + scrollTop - margin - popupHeight;
  510. position.left = Math.min(
  511. Math.max(10 + scrollLeft, selectionRect.left + scrollLeft + (selectionRect.width / 2) - (popupWidth / 2)),
  512. viewportWidth + scrollLeft - popupWidth - 10
  513. );
  514. position.placement = 'above';
  515. }
  516. // Try to position to the right
  517. else if (selectionRect.right + margin + popupWidth <= viewportWidth) {
  518. position.top = Math.max(10 + scrollTop, Math.min(
  519. selectionRect.top + scrollTop,
  520. viewportHeight + scrollTop - popupHeight - 10
  521. ));
  522. position.left = selectionRect.right + scrollLeft + margin;
  523. position.placement = 'right';
  524. }
  525. // Try to position to the left
  526. else if (selectionRect.left - margin - popupWidth >= 0) {
  527. position.top = Math.max(10 + scrollTop, Math.min(
  528. selectionRect.top + scrollTop,
  529. viewportHeight + scrollTop - popupHeight - 10
  530. ));
  531. position.left = selectionRect.left + scrollLeft - margin - popupWidth;
  532. position.placement = 'left';
  533. }
  534. // Fallback to centered position if no good placement found
  535. else {
  536. position.top = Math.max(10 + scrollTop, Math.min(
  537. selectionRect.top + selectionRect.height + scrollTop + margin,
  538. viewportHeight / 2 + scrollTop - popupHeight / 2
  539. ));
  540. position.left = Math.max(10 + scrollLeft, Math.min(
  541. selectionRect.left + selectionRect.width / 2 + scrollLeft - popupWidth / 2,
  542. viewportWidth + scrollLeft - popupWidth - 10
  543. ));
  544. position.placement = 'center';
  545. }
  546.  
  547. return position;
  548. }
  549.  
  550. // Create popup
  551. function createPopup() {
  552. // Remove existing popup if any
  553. closePopup();
  554.  
  555. const popup = document.createElement('div');
  556. popup.id = 'explainer-popup';
  557.  
  558. // Add dark-theme class if the page has a dark background
  559. if (isPageDarkMode()) {
  560. popup.classList.add('dark-theme');
  561. }
  562.  
  563. popup.innerHTML = `
  564. <div id="explainer-error"></div>
  565. <div id="explainer-loading"></div>
  566. <div id="explainer-content"></div>
  567. `;
  568.  
  569. document.body.appendChild(popup);
  570.  
  571. // For touch devices, use fixed positioning with transform
  572. if (isTouchDevice()) {
  573. popup.style.position = 'fixed';
  574. popup.style.top = '50%';
  575. popup.style.left = '50%';
  576. popup.style.transform = 'translate(-50%, -50%)';
  577. popup.style.width = '90vw';
  578. popup.style.maxHeight = '85vh';
  579. } else {
  580. // Desktop positioning logic
  581. const position = calculatePopupPosition();
  582. if (position) {
  583. popup.style.transform = 'none';
  584. if (position.top !== undefined) popup.style.top = `${position.top}px`;
  585. if (position.bottom !== undefined) popup.style.bottom = `${position.bottom}px`;
  586. if (position.left !== undefined) popup.style.left = `${position.left}px`;
  587. if (position.right !== undefined) popup.style.right = `${position.right}px`;
  588. } else {
  589. popup.style.top = '50%';
  590. popup.style.left = '50%';
  591. popup.style.transform = 'translate(-50%, -50%)';
  592. }
  593. }
  594.  
  595. // Add animation
  596. popup.style.animation = 'fadeIn 0.3s ease';
  597.  
  598. // Add event listeners
  599. document.addEventListener('keydown', handleEscKey);
  600.  
  601. // Use touchend instead of touchstart for better touch handling
  602. if (isTouchDevice()) {
  603. document.addEventListener('touchend', handleOutsideClick, { passive: true });
  604. // Prevent default touch behavior on the popup
  605. popup.addEventListener('touchstart', (e) => {
  606. e.stopPropagation();
  607. }, { passive: true });
  608. } else {
  609. document.addEventListener('click', handleOutsideClick);
  610. }
  611.  
  612. return popup;
  613. }
  614.  
  615. // Handle Escape key to close popup
  616. function handleEscKey(e) {
  617. if (e.key === 'Escape') {
  618. closePopup();
  619. document.removeEventListener('keydown', handleEscKey);
  620. document.removeEventListener('click', handleOutsideClick);
  621. }
  622. }
  623.  
  624. // Handle clicks outside popup to close it
  625. function handleOutsideClick(e) {
  626. const popup = document.getElementById('explainer-popup');
  627. if (!popup) return;
  628.  
  629. // Prevent closing if clicking inside the popup
  630. if (popup.contains(e.target)) {
  631. return;
  632. }
  633.  
  634. // For touch events, check if the touch ended outside
  635. if (e.type === 'touchend') {
  636. const touch = e.changedTouches[0];
  637. const rect = popup.getBoundingClientRect();
  638. const isOutsideTouch = touch.clientX < rect.left ||
  639. touch.clientX > rect.right ||
  640. touch.clientY < rect.top ||
  641. touch.clientY > rect.bottom;
  642.  
  643. if (isOutsideTouch) {
  644. closePopup();
  645. document.removeEventListener('keydown', handleEscKey);
  646. document.removeEventListener('touchend', handleOutsideClick);
  647. }
  648. } else if (!popup.contains(e.target)) {
  649. closePopup();
  650. document.removeEventListener('keydown', handleEscKey);
  651. document.removeEventListener('click', handleOutsideClick);
  652. }
  653. }
  654.  
  655. // Function to show an error in the popup
  656. function showError(message) {
  657. const errorDiv = document.getElementById('explainer-error');
  658. if (errorDiv) {
  659. errorDiv.textContent = message;
  660. errorDiv.style.display = 'block';
  661. document.getElementById('explainer-loading').style.display = 'none';
  662. }
  663. }
  664.  
  665. // Function to call the LLM using SmolLLM
  666. async function callLLM(prompt, systemPrompt, progressCallback) {
  667. if (!config.apiKey) {
  668. throw new Error("Please set up your API key in the settings.");
  669. }
  670.  
  671. if (!llm) {
  672. throw new Error("SmolLLM library not initialized. Please check console for errors.");
  673. }
  674.  
  675. console.log(`prompt: ${prompt}`);
  676. console.log(`systemPrompt: ${systemPrompt}`);
  677. try {
  678. return await llm.askLLM({
  679. prompt: prompt,
  680. systemPrompt: systemPrompt,
  681. model: config.model,
  682. apiKey: config.apiKey,
  683. baseUrl: config.baseUrl,
  684. providerName: config.provider,
  685. handler: progressCallback,
  686. timeout: 60000
  687. });
  688. } catch (error) {
  689. console.error('LLM API error:', error);
  690. throw error;
  691. }
  692. }
  693.  
  694. function getPrompt(selectedText, paragraphText, textBefore, textAfter) {
  695. const wordsCount = selectedText.split(' ').length;
  696. const systemPrompt = `Respond in ${config.language} with HTML tags to improve readability.
  697. - Prioritize clarity and conciseness
  698. - Use bullet points when appropriate
  699. - Do not add any code blocks for response`;
  700.  
  701. if (wordsCount >= 500) {
  702. return {
  703. prompt: `Create a structured summary in ${config.language}:
  704. - Identify key themes and concepts
  705. - Extract 3-5 main points
  706. - Use nested <ul> lists for hierarchy
  707. - Keep bullets concise
  708.  
  709. for the following selected text:
  710. \n\n${selectedText}
  711. `,
  712. systemPrompt
  713. };
  714. }
  715.  
  716. // For short text that looks like a sentence, offer translation
  717. if (wordsCount >= 5) {
  718. return {
  719. prompt: `Translate exactly to ${config.language} without commentary:
  720. - Preserve technical terms and names
  721. - Maintain original punctuation
  722. - Match formal/informal tone of source
  723.  
  724. for the following selected text:
  725. \n\n${selectedText}
  726. `,
  727. systemPrompt
  728. };
  729. }
  730.  
  731. const pinYinExtraPrompt = config.language === "Chinese" ? ' DO NOT add Pinyin for it.' : '';
  732. const ipaExtraPrompt = config.language === "Chinese" ? '(with IPA if necessary)' : '';
  733. const asciiChars = selectedText.replace(/[\s\.,\-_'"!?()]/g, '')
  734. .split('')
  735. .filter(char => char.charCodeAt(0) <= 127).length;
  736. const sampleSentenceLanguage = selectedText.length === asciiChars ? "English" : config.language;
  737.  
  738. // If we have context before/after, include it in the prompt
  739. const contextPrompt = textBefore || textAfter ?
  740. `# Context:
  741. ## Before selected text:
  742. ${textBefore || 'None'}
  743. ## Selected text:
  744. ${selectedText}
  745. ## After selected text:
  746. ${textAfter || 'None'}` : paragraphText;
  747.  
  748.  
  749. // Explain words prompt
  750. return {
  751. prompt: `Provide an explanation for the word: "${selectedText}${ipaExtraPrompt}" in ${config.language} without commentary.${pinYinExtraPrompt}
  752.  
  753. Use the context from the surrounding paragraph to inform your explanation when relevant:
  754.  
  755. ${contextPrompt}
  756.  
  757. # Consider these scenarios:
  758.  
  759. ## Names
  760. 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).
  761. e.g.
  762. Alan Turing was a British mathematician and computer scientist. He is widely considered to be the father of theoretical computer science and artificial intelligence.
  763. His work was crucial to:
  764. Formalizing the concepts of algorithm and computation with the Turing machine.
  765. Breaking the German Enigma code during World War II, significantly contributing to the Allied victory.
  766. Developing the Turing test, a benchmark for artificial intelligence.
  767.  
  768.  
  769. ## Technical Terms
  770. If "${selectedText}" is a technical term or jargon
  771. - give a concise definition and explain.
  772. - Some best practice of using it
  773. - Explain how it works.
  774. - No need example sentence for the technical term.
  775. e.g. GAN 生成对抗网络
  776. 生成对抗网络(Generative Adversarial Network),是一种深度学习框架,由Ian Goodfellow2014年提出。GAN包含两个神经网络:生成器(Generator)和判别器(Discriminator),它们相互对抗训练。生成器尝试创建看起来真实的数据,而判别器则尝试区分真实数据和生成的假数据。通过这种"博弈"过程,生成器逐渐学会创建越来越逼真的数据。
  777.  
  778. ## Normal Words
  779. - For any other word, explain its meaning and provide 1-2 example sentences with the word in ${sampleSentenceLanguage}.
  780. e.g. jargon \\ˈdʒɑrɡən\\ 行话,专业术语,特定领域内使用的专业词汇。在计算机科学和编程领域,指那些对外行人难以理解的专业术语和缩写。
  781. 例句: "When explaining code to beginners, try to avoid using too much technical jargon that might confuse them."(向初学者解释代码时,尽量避免使用太多可能让他们困惑的技术行话。)
  782.  
  783. # Format
  784.  
  785. - Output the words first, then the explanation, and then the example sentences in ${sampleSentenceLanguage} if necessary.
  786. - No extra explanation
  787. - Remember to using proper html format like <p> <b> <i> <a> <li> <ol> <ul> to improve readability.
  788. `,
  789. systemPrompt
  790. };
  791. }
  792.  
  793. // Main function to process selected text
  794. async function processSelectedText() {
  795. // Use the utility function instead of the local getSelectedText
  796. const { selectedText, textBefore, textAfter, paragraphText } = GetSelectionContext();
  797.  
  798. if (!selectedText) {
  799. showError('No text selected');
  800. return;
  801. }
  802.  
  803. console.log(`Selected text: '${selectedText}', Paragraph text:\n${paragraphText}`);
  804. // Create popup
  805. createPopup();
  806. const contentDiv = document.getElementById('explainer-content');
  807. const loadingDiv = document.getElementById('explainer-loading');
  808. const errorDiv = document.getElementById('explainer-error');
  809.  
  810. // Reset display
  811. errorDiv.style.display = 'none';
  812. loadingDiv.style.display = 'block';
  813.  
  814. // Assemble prompt with language preference
  815. const { prompt, systemPrompt } = getPrompt(selectedText, paragraphText, textBefore, textAfter);
  816.  
  817. // Variable to store ongoing response text
  818. let responseText = '';
  819.  
  820. try {
  821. // Call LLM with progress callback and await the full response
  822. const fullResponse = await callLLM(prompt, systemPrompt, (textChunk, currentFullText) => {
  823. // Update response text with new chunk
  824. responseText = currentFullText || (responseText + textChunk);
  825.  
  826. // Hide loading message if this is the first chunk
  827. if (loadingDiv.style.display !== 'none') {
  828. loadingDiv.style.display = 'none';
  829. }
  830.  
  831. // Update content with either HTML or markdown
  832. updateContentDisplay(contentDiv, responseText);
  833. });
  834.  
  835. console.log('fullResponse\n', fullResponse);
  836.  
  837. // If we got a response
  838. if (fullResponse && fullResponse.length > 0) {
  839. responseText = fullResponse;
  840. loadingDiv.style.display = 'none';
  841. updateContentDisplay(contentDiv, fullResponse);
  842. }
  843. // If no response was received at all
  844. else if (!fullResponse || fullResponse.length === 0) {
  845. // If we've received chunks but the final response is empty, use the accumulated text
  846. if (responseText && responseText.length > 0) {
  847. updateContentDisplay(contentDiv, responseText);
  848. } else {
  849. showError("No response received from the model. Please try again.");
  850. }
  851. }
  852.  
  853. // Hide loading indicator if it's still visible
  854. if (loadingDiv.style.display !== 'none') {
  855. loadingDiv.style.display = 'none';
  856. }
  857. } catch (error) {
  858. console.error('Error:', error);
  859. // Display error in popup
  860. showError(`Error: ${error.message}`);
  861. }
  862. }
  863.  
  864. // Main function to handle keyboard shortcuts
  865. function handleKeyPress(e) {
  866. // Get shortcut configuration from settings
  867. const shortcut = config.shortcut || { key: 'd', ctrlKey: false, altKey: true, shiftKey: false, metaKey: false };
  868.  
  869. // More robust shortcut detection using both key and code properties
  870. if (isShortcutMatch(e, shortcut)) {
  871. e.preventDefault();
  872. processSelectedText();
  873. }
  874. }
  875.  
  876. // Helper function for more robust shortcut detection
  877. function isShortcutMatch(event, shortcutConfig) {
  878. // Check all modifier keys first
  879. if (event.ctrlKey !== !!shortcutConfig.ctrlKey ||
  880. event.altKey !== !!shortcutConfig.altKey ||
  881. event.shiftKey !== !!shortcutConfig.shiftKey ||
  882. event.metaKey !== !!shortcutConfig.metaKey) {
  883. return false;
  884. }
  885.  
  886. const key = shortcutConfig.key.toLowerCase();
  887.  
  888. // Method 1: Direct key match (works for most standard keys)
  889. if (event.key.toLowerCase() === key) {
  890. return true;
  891. }
  892.  
  893. // Method 2: Key code match (more reliable for letter keys)
  894. // This handles the physical key position regardless of keyboard layout
  895. if (key.length === 1 && /^[a-z]$/.test(key) &&
  896. event.code === `Key${key.toUpperCase()}`) {
  897. return true;
  898. }
  899.  
  900. // Method 3: Handle known special characters from Option/Alt key combinations
  901. // These are the most common mappings on macOS when using Option+key
  902. const macOptionKeyMap = {
  903. 'a': 'å', 'b': '∫', 'c': 'ç', 'd': '∂', 'e': '´', 'f': 'ƒ',
  904. 'g': '©', 'h': '˙', 'i': 'ˆ', 'j': '∆', 'k': '˚', 'l': '¬',
  905. 'm': 'µ', 'n': '˜', 'o': 'ø', 'p': 'π', 'q': 'œ', 'r': '®',
  906. 's': 'ß', 't': '†', 'u': '¨', 'v': '√', 'w': '∑', 'x': '≈',
  907. 'y': '¥', 'z': 'Ω'
  908. };
  909.  
  910. if (shortcutConfig.altKey && macOptionKeyMap[key] === event.key) {
  911. return true;
  912. }
  913.  
  914. return false;
  915. }
  916.  
  917. // Helper function to update content display
  918. function updateContentDisplay(contentDiv, text) {
  919. if (!text) return;
  920.  
  921. try {
  922. if (!text.trim().startsWith('<')) {
  923. // fallback
  924. console.log(`Seems like the response is not HTML: ${text}`);
  925. text = `<p>${text.replace(/\n/g, '<br>')}</p>`;
  926. }
  927. contentDiv.innerHTML = text;
  928. } catch (e) {
  929. // Fallback if parsing fails
  930. console.error(`Error parsing content: ${e.message}`);
  931. contentDiv.innerHTML = `<p>${text.replace(/\n/g, '<br>')}</p>`;
  932. }
  933. }
  934.  
  935. // Monitor selection changes for floating button
  936. function handleSelectionChange() {
  937. // Don't update button visibility if we're processing text
  938. if (isProcessingText) return;
  939.  
  940. const selection = window.getSelection();
  941. const hasSelection = selection && selection.toString().trim() !== '';
  942.  
  943. if (hasSelection && isTouchDevice() && config.floatingButton.enabled) {
  944. // Small delay to ensure selection is fully updated
  945. setTimeout(showFloatingButton, 100);
  946. } else {
  947. hideFloatingButton();
  948. }
  949. }
  950.  
  951. // Settings update callback
  952. function onSettingsChanged(updatedConfig) {
  953. config = updatedConfig;
  954. console.log('Settings updated:', config);
  955.  
  956. // Recreate floating button if settings changed
  957. if (floatingButton) {
  958. floatingButton.remove();
  959. floatingButton = null;
  960.  
  961. if (isTouchDevice() && config.floatingButton.enabled) {
  962. createFloatingButton();
  963. handleSelectionChange(); // Check if there's already a selection
  964. }
  965. }
  966. }
  967.  
  968. // Initialize the script
  969. function init() {
  970. // Register settings menu in Tampermonkey
  971. GM_registerMenuCommand("Text Explainer Settings", () => {
  972. settingsManager.openDialog(onSettingsChanged);
  973. });
  974.  
  975. // Add keyboard shortcut listener
  976. document.addEventListener('keydown', handleKeyPress);
  977.  
  978. // For touch devices, create floating button
  979. if (isTouchDevice() && config.floatingButton.enabled) {
  980. createFloatingButton();
  981.  
  982. // Monitor text selection
  983. document.addEventListener('selectionchange', handleSelectionChange);
  984.  
  985. // Add touchend handler to show button after selection
  986. document.addEventListener('touchend', () => {
  987. // Small delay to ensure selection is updated
  988. setTimeout(handleSelectionChange, 100);
  989. });
  990. }
  991.  
  992. console.log('Text Explainer script initialized with language: ' + config.language);
  993. console.log('Touch device detected: ' + isTouchDevice());
  994. }
  995.  
  996. // Run initialization
  997. init();
  998. })();