CSES copy button

Add copy buttons for input and output

  1. // ==UserScript==
  2. // @name CSES copy button
  3. // @namespace https://github.com/zica87/self-made-userscipts
  4. // @version 1.0
  5. // @description Add copy buttons for input and output
  6. // @author zica
  7. // @match https://cses.fi/problemset/task/*
  8. // @grant GM_addStyle
  9. // @license GPL-3.0
  10. // ==/UserScript==
  11.  
  12. (function () {
  13. "use strict";
  14.  
  15. const cssString = `
  16. .copy-button {
  17. margin-left: 0.5em;
  18. }
  19.  
  20. .copy-mode {
  21. cursor: pointer;
  22. }
  23.  
  24. .copied-mode {
  25. cursor: unset;
  26. }
  27.  
  28. .copied-block{
  29. border: solid #ff9b30;
  30. padding: 10px;
  31. }
  32. `;
  33. GM_addStyle(cssString);
  34. add_buttons();
  35.  
  36. function toCopyMode(button, block) {
  37. button.textContent = "copy";
  38. button.classList.add("copy-mode");
  39. button.classList.remove("copied-mode");
  40. block.classList.remove("copied-block");
  41. }
  42. function toCopiedMode(button, block) {
  43. button.textContent = "✅copied";
  44. button.classList.add("copied-mode");
  45. button.classList.remove("copy-mode");
  46. block.classList.add("copied-block");
  47. }
  48. function add_buttons() {
  49. const blocks = document.getElementsByTagName("pre");
  50. for (const block of blocks) {
  51. const button = document.createElement("button");
  52. button.className = "copy-button";
  53. button.onclick = async () => {
  54. if (button.textContent[0] === "✅") {
  55. return;
  56. }
  57. try {
  58. await navigator.clipboard.writeText(block.textContent);
  59. toCopiedMode(button, block);
  60. setTimeout(() => {
  61. toCopyMode(button, block);
  62. }, 3000);
  63. } catch (error) {
  64. alert(error.message);
  65. console.error(error);
  66. }
  67. };
  68. toCopyMode(button, block);
  69. block.previousElementSibling.append(button);
  70. }
  71. }
  72. })();