Auto Replace Color with CSS Variable

try to take over the world

当前为 2022-08-12 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Auto Replace Color with CSS Variable
  3. // @namespace linghao.su
  4. // @version 0.1
  5. // @description try to take over the world
  6. // @author slh001@live.cn
  7. // @match https://www.figma.com/file/*/DCE-5-Prototype?*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=figma.com
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. const aliasUrl = 'https://cdn.jsdelivr.net/npm/@dao-style/core@latest/dist/styles/color/alias.css';
  13. const varUrl = 'https://cdn.jsdelivr.net/npm/@dao-style/core@latest/dist/styles/color/var.css';
  14.  
  15. const DELAY_MS = 500;
  16. const targetStr = 'colors_inspect_panel--paintColor';
  17.  
  18. let lastLastTimeoutId = -1;
  19.  
  20. const cssMap = new Map();
  21.  
  22. async function init() {
  23. cssMap.clear();
  24. const handler = await fetch(varUrl);
  25. const cssStr = await handler.text();
  26.  
  27. const aliasHandler = await fetch(aliasUrl);
  28. const aliasStr = await aliasHandler.text();
  29.  
  30. const cssArr = cssStr.split('\n').map(item=>item.split(':').map(iitem => iitem.trim())).slice(1, -1).map(item => [item[1].slice(0, -1), item[0]]).filter(item => item[0].startsWith('#'));
  31. const aliasArr = aliasStr.split('\n').map(item=>item.split(':').map(iitem => iitem.trim())).slice(1, -1).map(item => [item[1].slice(0, -1), item[0]]).filter(item => item[0].startsWith('#'));
  32.  
  33. cssArr.forEach(item => cssMap.set(item[0].toUpperCase(), item[1]));
  34. aliasArr.forEach(item => cssMap.set(item[0].toUpperCase(), item[1]));
  35. }
  36.  
  37. function getSuitableTag(item) {
  38. while(item) {
  39. item = item.parentNode;
  40. if (!item.className) {
  41. return item;
  42. }
  43. }
  44. }
  45. function getTargetList() {
  46. const spanList = Array.from(document.querySelectorAll('span'));
  47.  
  48. const targetList = spanList.filter(item => item.className.includes(targetStr));
  49.  
  50. targetList.forEach(item => {
  51. const innerText = item.innerText;
  52. const cssVariable = cssMap.get(innerText.toUpperCase());
  53. if (cssVariable) {
  54. item.innerHTML = cssVariable;
  55. const eventBindingDom = getSuitableTag(item);
  56. if (eventBindingDom) {
  57. let fn = (e) => {
  58. setTimeout(() => {
  59. navigator.clipboard.writeText(e?.target?.innerText ?? cssVariable);
  60. }, DELAY_MS)
  61. }
  62. eventBindingDom.addEventListener('click', fn);
  63. }
  64.  
  65. }
  66. })
  67. lastLastTimeoutId = -1;
  68. }
  69.  
  70. (async function() {
  71. 'use strict';
  72.  
  73. await init();
  74. document.body.addEventListener('click', () => {
  75. if (lastLastTimeoutId !== -1) {
  76. clearTimeout(lastLastTimeoutId);
  77. lastLastTimeoutId = -1;
  78. }
  79. lastLastTimeoutId = setTimeout(getTargetList, DELAY_MS);
  80. })
  81. })();