Font Awesome Pro SVG Downloader & Copier

Adds download and copy buttons for Font Awesome Pro icons.

目前為 2024-11-07 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Font Awesome Pro SVG Downloader & Copier
// @description  Adds download and copy buttons for Font Awesome Pro icons.
// @icon         https://fontawesome.com/images/favicon/icon.svg
// @version      debug
// @author       avkarxyz
// @namespace    https://github.com/avkarxyz/misc-scripts/
// @supportURL   https://github.com/avkarxyz/misc-scripts/issues
// @license      MIT
// @match        https://fontawesome.com/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function () {
    'use strict';

    const DOWNLOAD_ICON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="12" height="12"><path d="M378.1 198.6L249.5 341.4c-6.1 6.7-14.7 10.6-23.8 10.6l-3.5 0c-9.1 0-17.7-3.8-23.8-10.6L69.9 198.6c-3.8-4.2-5.9-9.8-5.9-15.5C64 170.4 74.4 160 87.1 160l72.9 0 0-128c0-17.7 14.3-32 32-32l64 0c17.7 0 32 14.3 32 32l0 128 72.9 0c12.8 0 23.1 10.4 23.1 23.1c0 5.7-2.1 11.2-5.9 15.5zM64 352l0 64c0 17.7 14.3 32 32 32l256 0c17.7 0 32-14.3 32-32l0-64c0-17.7 14.3-32 32-32s32 14.3 32 32l0 64c0 53-43 96-96 96L96 512c-53 0-96-43-96-96l0-64c0-17.7 14.3-32 32-32s32 14.3 32 32z"/></svg>`;
    const COPY_ICON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512" width="12" height="12"><path d="M192 0c-41.8 0-77.4 26.7-90.5 64L64 64C28.7 64 0 92.7 0 128L0 448c0 35.3 28.7 64 64 64l256 0c35.3 0 64-28.7 64-64l0-320c0-35.3-28.7-64-64-64l-37.5 0C269.4 26.7 233.8 0 192 0zm0 64a32 32 0 1 1 0 64 32 32 0 1 1 0-64zM72 272a24 24 0 1 1 48 0 24 24 0 1 1 -48 0zm104-16l128 0c8.8 0 16 7.2 16 16s-7.2 16-16 16l-128 0c-8.8 0-16-7.2-16-16s7.2-16 16-16zM72 368a24 24 0 1 1 48 0 24 24 0 1 1 -48 0zm88 0c0-8.8 7.2-16 16-16l128 0c8.8 0 16 7.2 16 16s-7.2 16-16 16l-128 0c-8.8 0-16-7.2-16-16z"/></svg>`;
    const SUCCESS_ICON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="12" height="12"><path d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM369 209L241 337c-9.4 9.4-24.6 9.4-33.9 0l-64-64c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0l47 47L335 175c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9z"/></svg>`;

    const processedIcons = new WeakSet();
    const svgCache = new Map();

    function showSuccessAnimation(button, originalIcon) {
        const originalContent = button.innerHTML;
        const parser = new DOMParser();
        const successSvg = parser.parseFromString(SUCCESS_ICON, 'image/svg+xml');

        button.innerHTML = '';
        button.appendChild(successSvg.documentElement);

        setTimeout(() => {
            button.innerHTML = originalContent;
        }, 250);
    }

    async function fetchAndCacheSVG(url) {
        if (svgCache.has(url)) {
            return svgCache.get(url);
        }

        const response = await fetch(url);
        if (!response.ok) throw new Error('Network response was not ok.');
        let svgContent = await response.text();
        svgContent = svgContent.replace(/<!--[\s\S]*?-->/g, '');
        svgCache.set(url, svgContent);
        return svgContent;
    }

    async function copySVG(url, button) {
        try {
            const svgContent = await fetchAndCacheSVG(url);
            await navigator.clipboard.writeText(svgContent);
            showSuccessAnimation(button, COPY_ICON);
        } catch (error) {
            console.error('Failed to copy SVG:', error);
            alert('Failed to copy SVG. Check the console for details.');
        }
    }

    async function downloadSVG(url, filename, button) {
        try {
            const svgContent = await fetchAndCacheSVG(url);
            const blob = new Blob([svgContent], { type: 'image/svg+xml' });
            const a = document.createElement('a');
            a.href = URL.createObjectURL(blob);
            a.download = filename;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(a.href);
            showSuccessAnimation(button, DOWNLOAD_ICON);
        } catch (error) {
            console.error('Failed to download SVG:', error);
            alert('Failed to download SVG. Check the console for details.');
        }
    }

    function getSelectedVersion() {
        const selectElement = document.getElementById('choose_aversionoffontawesome');
        return selectElement ? selectElement.value.trim() : '6.6.0';
    }

    function createButton(icon, title, className) {
        const button = document.createElement('span');
        button.className = `fa-icon-button ${className}`;
        button.title = title;
        const parser = new DOMParser();
        const svgDoc = parser.parseFromString(icon, 'image/svg+xml');
        button.appendChild(svgDoc.documentElement);
        return button;
    }

    function getIconStyle(iconElement) {
        const classes = Array.from(iconElement.classList);
        const relevantClasses = classes.filter(c => c !== 'fa-fw' && c.startsWith('fa-'));

        if (relevantClasses.includes('fa-brands')) {
            return 'brands';
        }

        let iconStyle = '';
        let combinedStyle = '';

        if (relevantClasses.includes('fa-duotone')) combinedStyle += 'duotone';
        if (relevantClasses.includes('fa-sharp')) {
            combinedStyle += (combinedStyle ? '-' : '') + 'sharp';
        }
        if (relevantClasses.includes('fa-sharp-duotone')) {
            combinedStyle += (combinedStyle ? '-' : '') + 'sharp-duotone';
        }

        if (combinedStyle) {
            if (relevantClasses.includes('fa-solid')) combinedStyle += '-solid';
            else if (relevantClasses.includes('fa-light')) combinedStyle += '-light';
            else if (relevantClasses.includes('fa-thin')) combinedStyle += '-thin';
            else if (relevantClasses.includes('fa-regular')) combinedStyle += '-regular';
            iconStyle = combinedStyle;
        } else {
            if (relevantClasses.includes('fa-solid')) iconStyle = 'solid';
            else if (relevantClasses.includes('fa-light')) iconStyle = 'light';
            else if (relevantClasses.includes('fa-thin')) iconStyle = 'thin';
            else if (relevantClasses.includes('fa-regular')) iconStyle = 'regular';
        }

        return iconStyle;
    }

    function processIcon(icon) {
        if (processedIcons.has(icon)) {
            return;
        }

        const iconElement = icon.querySelector('i');
        const iconName = icon.querySelector('.icon-name')?.textContent.trim();

        if (!iconElement || !iconName) {
            return;
        }

        const iconStyle = getIconStyle(iconElement);
        const version = getSelectedVersion();
        const url = `https://site-assets.fontawesome.com/releases/v${version}/svgs/${iconStyle}/${iconName}.svg`;
        const filename = `${iconName}.svg`;

        const container = document.createElement('div');
        container.className = 'fa-buttons-container';

        const downloadButton = createButton(DOWNLOAD_ICON, 'Download SVG', 'fa-download-button');
        const copyButton = createButton(COPY_ICON, 'Copy SVG', 'fa-copy-button');

        downloadButton.addEventListener('click', () => downloadSVG(url, filename, downloadButton));
        copyButton.addEventListener('click', () => copySVG(url, copyButton));

        container.appendChild(copyButton);
        container.appendChild(downloadButton);

        let tagContainer = icon.querySelector('.tag');
        if (!tagContainer) {
            tagContainer = document.createElement('div');
            tagContainer.className = 'tag';
        }

        tagContainer.innerHTML = '';

        tagContainer.appendChild(container);

        const buttonElement = icon.querySelector('button');
        if (buttonElement && !buttonElement.parentNode.querySelector('.tag')) {
            buttonElement.parentNode.insertBefore(tagContainer, buttonElement.nextSibling);
        }

        processedIcons.add(icon);
    }

    function throttle(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        }
    }

    function processBatch(icons, batchSize = 10) {
        let index = 0;

        function processNextBatch() {
            const batch = Array.from(icons).slice(index, index + batchSize);
            if (batch.length === 0) return;

            batch.forEach(processIcon);
            index += batchSize;

            if (index < icons.length) {
                requestAnimationFrame(processNextBatch);
            }
        }

        processNextBatch();
    }

    const throttledProcessBatch = throttle((icons) => {
        processBatch(icons);
    }, 100);

    function setupMutationObserver() {
        const observer = new MutationObserver((mutations) => {
            const icons = document.querySelectorAll('article.wrap-icon');
            throttledProcessBatch(icons);
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    const style = document.createElement('style');
    style.textContent = `
        .fa-buttons-container {
            display: inline-flex;
            gap: 3px;
            align-items: center;
            justify-content: center;
            min-width: 50px;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
        }
        .tag {
            display: flex;
            justify-content: center;
            position: relative;
            min-height: 28px;
            padding: 0 4px !important;
            margin: 0 !important;
            background: transparent !important;
        }
        .fa-icon-button {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            border-radius: 4px;
            background-color: var(--fa-yellow);
            color: var(--fa-navy);
            cursor: pointer;
            padding: 3px;
        }
        .fa-icon-button svg {
            width: 100%;
            height: 100%;
        }
        .fa-icon-button svg path {
            fill: var(--fa-navy);
        }
    `;

    document.head.appendChild(style);

    const initialIcons = document.querySelectorAll('article.wrap-icon');
    processBatch(initialIcons);
    setupMutationObserver();
})();