Greasy Fork is available in English.

Chess Plus+

Add Essential/Quality of life tweaks to Chess.com

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