Auto Replace Color with CSS Variable

try to take over the world

目前為 2022-08-12 提交的版本,檢視 最新版本

// ==UserScript==
// @name         Auto Replace Color with CSS Variable
// @namespace    linghao.su
// @version      0.1
// @description  try to take over the world
// @author       [email protected]
// @match        https://www.figma.com/file/*/DCE-5-Prototype?*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=figma.com
// @license MIT
// ==/UserScript==

const aliasUrl = 'https://cdn.jsdelivr.net/npm/@dao-style/core@latest/dist/styles/color/alias.css';
const varUrl = 'https://cdn.jsdelivr.net/npm/@dao-style/core@latest/dist/styles/color/var.css';

const DELAY_MS = 500;
const targetStr = 'colors_inspect_panel--paintColor';

let lastLastTimeoutId = -1;

const cssMap = new Map();

async function init() {
    cssMap.clear();
    const handler = await fetch(varUrl);
    const cssStr = await handler.text();

    const aliasHandler = await fetch(aliasUrl);
    const aliasStr = await aliasHandler.text();

    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('#'));
    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('#'));

    cssArr.forEach(item => cssMap.set(item[0].toUpperCase(), item[1]));
    aliasArr.forEach(item => cssMap.set(item[0].toUpperCase(), item[1]));
}

function getSuitableTag(item) {
    while(item) {
        item = item.parentNode;
        if (!item.className) {
            return item;
        }
    }
}
function getTargetList() {
    const spanList = Array.from(document.querySelectorAll('span'));

    const targetList = spanList.filter(item => item.className.includes(targetStr));

    targetList.forEach(item => {
        const innerText = item.innerText;
        const cssVariable = cssMap.get(innerText.toUpperCase());
        if (cssVariable) {
            item.innerHTML = cssVariable;
            const eventBindingDom = getSuitableTag(item);
            if (eventBindingDom) {
                let fn = (e) => {
                    setTimeout(() => {
                        navigator.clipboard.writeText(e?.target?.innerText ?? cssVariable);
                    }, DELAY_MS)
                }
                eventBindingDom.addEventListener('click', fn);
            }

        }
    })
    lastLastTimeoutId = -1;
}

(async function() {
    'use strict';

    await init();
    document.body.addEventListener('click', () => {
        if (lastLastTimeoutId !== -1) {
            clearTimeout(lastLastTimeoutId);
            lastLastTimeoutId = -1;
        }
        lastLastTimeoutId = setTimeout(getTargetList, DELAY_MS);
    })
})();