Chess Plus+

Add Essential/Quality of life tweaks to Chess.com

目前为 2024-10-05 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Chess Plus+
  3. // @namespace https://github.com/longkidkoolstar
  4. // @version 2.0.1
  5. // @description Add Essential/Quality of life tweaks to Chess.com
  6. // @author longkidkoolstar
  7. // @license BSD-3-Clause
  8. // @icon https://cdn4.iconfinder.com/data/icons/chess-game-funny-colour/32/chess_game_funy_colour_ok_13-1024.png
  9. // @require https://greasyfork.org/scripts/471295-tweaking/code/Tweaking.js
  10. // @require https://update.greasyfork.org/scripts/21927/198809/arrivejs.js
  11. // @require https://code.jquery.com/jquery-3.6.0.min.js
  12. // @match https://www.chess.com/*
  13. // @grant GM_getValue
  14. // @grant GM_setValue
  15. // ==/UserScript==
  16.  
  17.  
  18. /*
  19. Copyright (c) 2023 longkidkoolstar
  20.  
  21. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  22.  
  23. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  24.  
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. */
  27.  
  28.  
  29.  
  30.  
  31. //Maybe Future stuff
  32.  
  33. // Function for Lichess game analysis
  34. //function request_analysis() {
  35. //var button = $("button.text span[data-icon='']");
  36. // if (button) {
  37. // button.click();
  38. // }
  39. //}
  40.  
  41. // Call request_analysis() only on Lichess game pages
  42. //if (window.location.href.match('https://lichess.org/*')) {
  43. // request_analysis();
  44. //}
  45.  
  46.  
  47. (function () {
  48. 'use strict';
  49. // Check if Auto Queue is on
  50. var autoQueue = GM_getValue('autoQueue', false);
  51. var lichessAnalysis = GM_getValue('lichessAnalysis', true);
  52. // Function to toggle Lichess Analysis on/off
  53. function toggleLichessAnalysis() {
  54. lichessAnalysis = !lichessAnalysis;
  55. GM_setValue('lichessAnalysis', lichessAnalysis);
  56. console.log('Lichess Analysis is now ' + (lichessAnalysis ? 'on' : 'off'));
  57. }
  58. // Function to handle the Lichess Analysis button click
  59. function handleLichessAnalysisClick() {
  60. if (lichessAnalysis) {
  61. sendToLichess();
  62. }
  63. else {
  64. alert("Tweak not Enabled in Menu. Enable it to Use!");
  65. }
  66. }
  67. // Function to toggle Auto Queue on/off
  68. function toggleAutoQueue() {
  69. autoQueue = !autoQueue;
  70. GM_setValue('autoQueue', autoQueue);
  71. console.log('Auto Queue is now ' + (autoQueue ? 'on' : 'off'));
  72. if (autoQueue) {
  73. clickButton();
  74. startObserver();
  75. } else {
  76. stopObserver();
  77. }
  78. }
  79. // Function to click the "New" button
  80. function clickButton() {
  81. var buttons = document.querySelectorAll('button');
  82. for (var i = 0; i < buttons.length; i++) {
  83. if (buttons[i].innerText.includes('New')) {
  84. buttons[i].click();
  85. break;
  86. }
  87. }
  88. }
  89. // Observer instance
  90. var observer = null;
  91. // Function to start observing the button
  92. function startObserver() {
  93. observer = new MutationObserver(function (mutations) {
  94. mutations.forEach(function (mutation) {
  95. if (mutation.addedNodes.length > 0) {
  96. clickButton();
  97. }
  98. });
  99. });
  100. observer.observe(document.body, { childList: true, subtree: true });
  101. }
  102. // Function to stop observing the button
  103. function stopObserver() {
  104. if (observer) {
  105. observer.disconnect();
  106. observer = null;
  107. }
  108. }
  109. // If Auto Queue is on, click the button whenever it becomes available
  110. if (autoQueue) {
  111. clickButton();
  112. startObserver();
  113. }
  114. // Main loop
  115. checkGameStatus();
  116. function checkGameStatus() {
  117. document.arrive('.game-review-buttons-review', function () {
  118. // Find chess.com analysisButton
  119. var analysisButton = document.querySelector('.ui_v5-button-component.ui_v5-button-primary.ui_v5-button-full.game-review-buttons-button');
  120. if (analysisButton.className == 'ui_v5-button-component ui_v5-button-primary ui_v5-button-full game-review-buttons-button') {
  121. Arrive.unbindAllArrive();
  122. injectButton(analysisButton);
  123. checkGameStatus();
  124. }
  125. });
  126. }
  127. let isChessCom = true;
  128. if (!window.location.href.includes("chess.com")) {
  129. isChessCom = false;
  130. }
  131.  
  132. function showRatingWindow() {
  133. if(localStorage.getItem('extensionRatingWindowClosed') === null){
  134. localStorage.setItem('extensionRatingWindowClosed', (Math.random() * 4)+15);
  135. }
  136. if (localStorage.getItem('extensionRatingWindowClosed') > 0) {
  137. return; // If so, do not show the rating window again
  138. }
  139. if(document.ratingWindow){
  140. return; // already showing a rating window
  141. }
  142. // Create a div element for the rating window
  143. document.ratingWindow = document.createElement('div');
  144. document.ratingWindow.style.position = 'fixed';
  145. document.ratingWindow.style.top = '9%'; // Adjust the top position as needed
  146. document.ratingWindow.style.right = '10px'; // Adjust the right position as needed
  147. document.ratingWindow.style.width = '30vw';
  148. document.ratingWindow.style.backgroundColor = '#fff';
  149. document.ratingWindow.style.padding = '20px';
  150. document.ratingWindow.style.border = '1px solid #ccc';
  151. document.ratingWindow.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
  152. document.ratingWindow.style.textAlign = 'center';
  153. document.ratingWindow.style.zIndex = 99999;
  154. document.ratingWindow.innerHTML = `
  155. <div style="display: inline-block; text-align: center;">
  156. <p>Hey!</p>
  157. <p>My name is Victor. I am a college student who made the UCSD Schedule Visualizer extension! </p>
  158. <p>I made it on my own time entirely for free.</p>
  159. <p>I would really appreciate it if you could rate it on google chrome store, or could share it with your classmates!</p>
  160. <p>It would help me and my work a lot!</p>
  161. <div style="display: inline-block; text-align: left;">
  162. <p>Thank you!</p>
  163. </div>
  164. </div>
  165. <button id="rateButton" style="padding: 10px 20px; background-color: #4CAF50; color: #fff; border: none; border-radius: 5px; cursor: pointer;">Rate Now</button>
  166. <button id="dismissButton" style="margin-left: 10px; padding: 10px 20px; background-color: #ccc; color: #333; border: none; border-radius: 5px; cursor: pointer;">Dismiss</button>
  167. `;
  168.  
  169. // Append the rating window to the body
  170. document.body.appendChild(document.ratingWindow);
  171.  
  172. document.getElementById('rateButton').addEventListener('click', onRatingNow);
  173. document.getElementById('dismissButton').addEventListener('click', onRatingDismiss);
  174. }
  175.  
  176. function getRatingWindow(){
  177. return document.ratingWindow;
  178. }
  179.  
  180. function checkToShowButton() {
  181. if (lichessAnalysis) {
  182. if (!document.importToLichessButton) {
  183. document.importToLichessButton = injectImportButton();
  184. }
  185. showRatingWindow();
  186. const ratingWindow = getRatingWindow();
  187. if (shouldShowImportButton()) {
  188. document.importToLichessButton.hidden = false;
  189. if (ratingWindow) {
  190. ratingWindow.hidden = false;
  191. }
  192. return;
  193. }
  194. // Don't do anything if not on live chess
  195. document.importToLichessButton.hidden = true;
  196. if (ratingWindow) {
  197. ratingWindow.hidden = true;
  198. }
  199. } else {
  200. if (document.importToLichessButton) {
  201. document.importToLichessButton.parentNode.removeChild(document.importToLichessButton);
  202. delete document.importToLichessButton;
  203. }
  204. }
  205. }
  206.  
  207.  
  208. function injectImportButton() {
  209. let analyseButton = document.createElement("button");
  210.  
  211. // Create a span element for the icon
  212. var iconSpan = document.createElement("span");
  213. iconSpan.setAttribute("aria-hidden", "true");
  214. iconSpan.className = "ui_v5-button-icon icon-font-chess chess-board-search";
  215. // Append the icon span to the button
  216. analyseButton.appendChild(iconSpan);
  217. // Style the button
  218. analyseButton.style.position = "fixed";
  219. analyseButton.style.top = "5%"; // Adjust the top position as needed
  220. analyseButton.style.right = "10px"; // Adjust the right position as needed
  221. analyseButton.style.backgroundColor = "#363732"; // gray color
  222. analyseButton.style.color = "#C7C7C5";
  223. analyseButton.style.padding = ".5rem 0.5rem";
  224. analyseButton.style.border = "1px solid #272422"; // Border color
  225. analyseButton.style.borderRadius = "5px";
  226. analyseButton.style.cursor = "pointer";
  227. analyseButton.style.fontSize = "16px";
  228. analyseButton.style.zIndex = 9999;
  229. analyseButton.innerHTML += "Lichess Analysis";
  230. document.body.appendChild(analyseButton);
  231. analyseButton.addEventListener("click", importGame);
  232. return analyseButton;
  233. }
  234.  
  235. function shouldShowImportButton() {
  236. const currentUrl = window.location.href;
  237. if (currentUrl.includes("chess.com/game/live")
  238. || currentUrl.includes("chess.com/live#g=")
  239. || currentUrl.includes("chess.com/game/daily")) {
  240. // if you are on live game but don't have a share button, don't show
  241. if (currentUrl.includes("chess.com/game/live") && !getShareButton()) {
  242. return false;
  243. }
  244. return true;
  245. }
  246. return false;
  247. }
  248.  
  249. function getShareButton() {
  250. // Find and press the share button
  251. const shareButtonClasses = [
  252. "icon-font-chess share daily-game-footer-icon",
  253. "icon-font-chess share live-game-buttons-button",
  254. "icon-font-chess share game-buttons-button", // in case of chess.com/live#g=
  255. "icon-font-chess share daily-game-footer-icon", // in case of chess.com/game/daily
  256. "icon-font-chess share daily-game-footer-button" // in case of chess.com/game/live
  257. ];
  258.  
  259. let shareButton = null;
  260. for (let i = 0; i < shareButtonClasses.length; i++) {
  261. shareButton = document.getElementsByClassName(shareButtonClasses[i])[0];
  262. if (shareButton) {
  263. break;
  264. }
  265. }
  266. if (!shareButton) {
  267. // in other cases, try to find the button by aria-label "Share"
  268. shareButton = document.querySelector('button[aria-label="Share"]');
  269. }
  270. return shareButton;
  271. }
  272.  
  273. async function importGame() {
  274. const gameURL = window.location.href.trim();
  275. // Website check
  276. if (!gameURL.includes("chess.com")) {
  277. alert("You are not on chess.com! Press me when you are viewing the game you'd like to analyze!");
  278. throw new Error("Wrong website");
  279. }
  280. // URL on game check
  281. if (!gameURL.includes("chess.com/game/live")
  282. && !gameURL.includes("chess.com/live#g=")
  283. && !gameURL.includes("chess.com/game/daily")) {
  284. alert("You are not viewing a game! Press me when you are viewing the game you'd like to analyze! (when URL contains chess.com/game/live)");
  285. throw new Error("Not on game");
  286. }
  287.  
  288. if (localStorage.getItem(gameURL)) {
  289. // This game was cached before!
  290. window.open(localStorage.getItem(gameURL));
  291. getCloserToShowingRatingWindow();
  292. return;
  293. }
  294.  
  295. const shareButton = getShareButton();
  296. if (!shareButton) {
  297. alert("I could not find the FEN! The game is probably not finished. Try clicking me when the game is over.");
  298. throw new Error("No share button");
  299. }
  300. shareButton.click();
  301.  
  302. const pgnTabButton = await findElementByClassName("board-tab-item-underlined-component share-menu-tab-selector-tab");
  303. if (!pgnTabButton) {
  304. console.log("Could not get the PGN");
  305. return;
  306. }
  307. // Find PGN window and copy the text value
  308. const pgnTextArea = await findElementByClassName("share-menu-tab-pgn-textarea");
  309. if (!pgnTextArea) {
  310. console.log("Could not get the PGN");
  311. return;
  312. }
  313. let gamePGN = pgnTextArea.value;
  314. // Close the share window
  315. let closeButton = document.querySelector('.icon-font-chess.x') || document.querySelector('[aria-label="Close"]');
  316. if (closeButton) {
  317. closeButton.click();
  318. }
  319. // Ensure the game PGN has value
  320. if (!gamePGN.trim()) {
  321. alert("Not a valid PGN! Make sure you are on chess.com/games! If this is not correct, please contact the creator.");
  322. return;
  323. }
  324.  
  325. // Ensure that the game is finished
  326. if (!gamePGN.includes("[Termination")) {
  327. // Don't import unfinished games, personal policy
  328. alert("Can only import finished games!");
  329. return;
  330. }
  331.  
  332. // Send a post request to Lichess to import a game
  333. requestLichessURL(gamePGN, (url) => {
  334. if (url) {
  335. const lichessImportedGameURL = `${url}?from_chesscom=true`;
  336. window.open(lichessImportedGameURL);
  337. localStorage.setItem('extensionRatingWindowClosed', localStorage.getItem('extensionRatingWindowClosed') - 1);
  338. localStorage.setItem(gameURL, lichessImportedGameURL);
  339. getCloserToShowingRatingWindow();
  340. showRatingWindow();
  341. } else alert("Could not import game");
  342. });
  343. }
  344.  
  345. // Async post function
  346. async function requestLichessURL(pgn, callback) {
  347. let url = "https://lichess.org/api/import";
  348. chrome.runtime.sendMessage(
  349. {
  350. data: { pgn: pgn },
  351. url: url
  352. }, function (response) {
  353. if (response) {
  354. callback(response);
  355. } else {
  356. callback(null);
  357. }
  358. });
  359. }
  360.  
  361. function findElementByClassName(className, maxAttempts = Infinity, interval = 100, minDuration = 4000) {
  362. return new Promise((resolve, reject) => {
  363. let startTime = Date.now();
  364. let attempts = 0;
  365.  
  366. function search() {
  367. const element = document.getElementsByClassName(className)[0];
  368. if (element) {
  369. resolve(element);
  370. } else {
  371. attempts++;
  372.  
  373. if (attempts < maxAttempts && (Date.now() - startTime) < minDuration) {
  374. setTimeout(search, interval);
  375. } else {
  376. resolve(null);
  377. }
  378. }
  379. }
  380.  
  381. search();
  382. });
  383. }
  384.  
  385. if (isChessCom) {
  386. // Listen for changes, the event listeners don't seem to work
  387. setInterval(() => {
  388. checkToShowButton();
  389. }, 500);
  390. checkToShowButton();
  391. if (localStorage.getItem('extensionRatingWindowClosed') === null) {
  392. localStorage.setItem('extensionRatingWindowClosed', 3);
  393. }
  394. }
  395.  
  396. // Injects a button similar to chess.com's native "Analysis" button
  397. function injectButton(analysisButton) {
  398. // Duplicate the original button
  399. let newButton = analysisButton.cloneNode(true);
  400. // Style it and link it to the Lichess import function.
  401. newButton.childNodes[2].innerText = 'Lichess Analysis';
  402. newButton.style.margin = '8px 0px 0px 0px';
  403. newButton.style.padding = '0px 0px 0px 0px';
  404. newButton.childNodes[0].classList.remove('icon-font-chess');
  405. newButton.childNodes[0].classList.add('button-class');
  406. newButton.classList.add('shine-hope-anim');
  407. newButton.childNodes[0].style['height'] = '3.805rem';
  408. newButton.addEventListener('click', handleLichessAnalysisClick); // Update the click event handler);
  409. // Append back into the DOM
  410. let parentNode = analysisButton.parentNode;
  411. parentNode.append(newButton);
  412. }
  413.  
  414. // Make request to Lichess through the API (fetch)
  415. function sendToLichess() {
  416. // 1. Get PGN
  417. // Get and click download button on chess.com
  418. let downloadButton = document.getElementsByClassName('icon-font-chess share live-game-buttons-button')[0];
  419. downloadButton.click();
  420. // Wait for share tab to pop up
  421. document.arrive('.share-menu-tab-pgn-textarea', function () {
  422. Arrive.unbindAllArrive();
  423. // Get PGN from text Area
  424. var PGN = document.getElementsByClassName('share-menu-tab-pgn-textarea')[0].value;
  425. // Exit out of download view (x button)
  426. document.querySelector('div.icon-font-chess.x.ui_outside-close-icon').click();
  427. // 2. Send a POST request to Lichess to import the current game
  428. let importUrl = 'https://lichess.org/api/import';
  429. let req = { pgn: PGN };
  430. post(importUrl, req, oauthToken) // Pass the OAuth token to the post function
  431. .then((response) => {
  432. // Open the page on a new tab
  433. let url = response['url'] ? response['url'] : '';
  434. if (url) {
  435. let lichessPage = window.open(url);
  436. } else alert('Could not import game');
  437. })
  438. .catch((e) => {
  439. console.error('Error getting response from lichess.org', e);
  440. alert('Error getting response from lichess.org');
  441. throw new Error('Response error');
  442. });
  443. });
  444. }
  445. // async POST function with the OAuth token in the headers
  446. async function post(url = '', data = {}, token) {
  447. var formBody = [];
  448. for (var property in data) {
  449. var encodedKey = encodeURIComponent(property);
  450. var encodedValue = encodeURIComponent(data[property]);
  451. formBody.push(encodedKey + '=' + encodedValue);
  452. }
  453. const response = await fetch(url, {
  454. method: 'POST',
  455. headers: {
  456. 'Content-Type': 'application/x-www-form-urlencoded',
  457. 'Authorization': `Bearer ${token}`, // Include the OAuth token in the headers
  458. },
  459. body: formBody.join('&'),
  460. });
  461. return response.json();
  462. }
  463. // Add a Tweaks dropdown menu
  464. var tweaksMenu = document.createElement('div');
  465. tweaksMenu.classList.add('chess-com-tweaks-menu');
  466. tweaksMenu.innerHTML = `
  467. <style>
  468. /* Chess.com theme styles */
  469. .chess-com-tweaks-menu {
  470. position: fixed;
  471. bottom: 20px;
  472. right: 20px;
  473. background-color: #5E9949;
  474. color: #EEEED2;
  475. border-radius: 4px;
  476. box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  477. font-family: Arial, sans-serif;
  478. z-index: 9999;
  479. max-width: 100%;
  480. min-width: 60px;
  481. overflow: hidden;
  482. opacity: 0.9;
  483. transition: all 0.3s;
  484. transform: translateX(100%);
  485. }
  486. .chess-com-tweaks-menu.expanded {
  487. transform: translateX(0);
  488. }
  489. .chess-com-tweaks-menu__button-wrapper {
  490. padding: 8px;
  491. text-align: center;
  492. background-color: #2B4730;
  493. border-radius: 4px 4px 0 0;
  494. cursor: pointer;
  495. }
  496. .chess-com-tweaks-menu__button {
  497. color: white;
  498. padding: 8px 16px;
  499. font-size: 14px;
  500. border: none;
  501. cursor: pointer;
  502. border-radius: 4px;
  503. transition: background-color 0.3s;
  504. }
  505. .chess-com-tweaks-menu.expanded .chess-com-tweaks-menu__button {
  506. border-radius: 4px 4px 0 0;
  507. }
  508. .chess-com-tweaks-menu__button:hover {
  509. background-color: #1C3523;
  510. }
  511. .chess-com-tweaks-menu__dropdown {
  512. padding: 8px;
  513. max-height: 250px;
  514. overflow-y: auto;
  515. }
  516. .chess-com-tweaks-menu.expanded .chess-com-tweaks-menu__dropdown {
  517. display: block;
  518. }
  519. .chess-com-tweaks-menu__item {
  520. display: flex;
  521. align-items: center;
  522. padding: 4px;
  523. font-size: 14px;
  524. }
  525. .chess-com-tweaks-menu__label {
  526. flex-grow: 1;
  527. margin: 0;
  528. padding-left: 8px;
  529. color: #EEEED2;
  530. }
  531. .chess-com-tweaks-menu__toggle-wrapper {
  532. margin-right: 8px;
  533. }
  534. .chess-com-tweaks-menu__toggle {
  535. display: none;
  536. }
  537. .chess-com-tweaks-menu__toggle-label {
  538. position: relative;
  539. display: inline-block;
  540. width: 40px;
  541. height: 20px;
  542. background-color: #ccc;
  543. border-radius: 10px;
  544. cursor: pointer;
  545. }
  546. .chess-com-tweaks-menu__toggle-label::after {
  547. content: "";
  548. position: absolute;
  549. top: 2px;
  550. left: 2px;
  551. width: 16px;
  552. height: 16px;
  553. background-color: #fff;
  554. border-radius: 50%;
  555. transition: transform 0.3s;
  556. }
  557. .chess-com-tweaks-menu__toggle:checked + .chess-com-tweaks-menu__toggle-label::after {
  558. transform: translateX(20px);
  559. background-color: #4CAF50;
  560. }
  561. </style>
  562. <div class="chess-com-tweaks-menu__button-wrapper" id="tweaksButton">Tweaks</div>
  563. <div class="chess-com-tweaks-menu__dropdown" id="tweaksDropdown">
  564. <div class="chess-com-tweaks-menu__item">
  565. <label class="chess-com-tweaks-menu__label">Auto Queue</label>
  566. <div class="chess-com-tweaks-menu__toggle-wrapper">
  567. <input class="chess-com-tweaks-menu__toggle" type="checkbox" id="autoQueueToggle" ${autoQueue ? 'checked' : ''}>
  568. <label class="chess-com-tweaks-menu__toggle-label" for="autoQueueToggle"></label>
  569. </div>
  570. </div>
  571. <div class="chess-com-tweaks-menu__item">
  572. <label class="chess-com-tweaks-menu__label">Lichess Analysis</label>
  573. <div class="chess-com-tweaks-menu__toggle-wrapper">
  574. <input class="chess-com-tweaks-menu__toggle" type="checkbox" id="lichessAnalysisToggle" ${lichessAnalysis ? 'checked' : ''}>
  575. <label class="chess-com-tweaks-menu__toggle-label" for="lichessAnalysisToggle"></label>
  576. </div>
  577. </div>
  578. <!-- Add more tweaks here as needed -->
  579. </div>
  580. `;
  581. var expanded = false;
  582. var menuButton = tweaksMenu.querySelector('#tweaksButton');
  583. menuButton.addEventListener('click', function (event) {
  584. event.preventDefault();
  585. expanded = !expanded;
  586. tweaksMenu.classList.toggle('expanded', expanded);
  587. });
  588. tweaksMenu.querySelector('#lichessAnalysisToggle').addEventListener('change', function (event) {
  589. toggleLichessAnalysis();
  590. });
  591. tweaksMenu.querySelector('#autoQueueToggle').addEventListener('change', function (event) {
  592. toggleAutoQueue();
  593. });
  594. // Add a CSS class to the document body for the chess.com theme
  595. document.body.classList.add('chess-com-theme');
  596. document.body.appendChild(tweaksMenu);
  597. })();