Black Russia: RGB Палитра (для тем)

Добавляет кнопку "RGB Палитра" рядом с кнопкой ластика в редакторе на страницах тем форума Black Russia.

// ==UserScript==
// @name         Black Russia: RGB Палитра (для тем)
// @namespace    http://your.namespace.here
// @version      1.1
// @description  Добавляет кнопку "RGB Палитра" рядом с кнопкой ластика в редакторе на страницах тем форума Black Russia.
// @author       
// @match        https://forum.blackrussia.online/*
// @match        https://forum.blackrussia.online/threads/*
// @match        https://m.blackrussia.online/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function addRgbPaletteButton() {
        // Ищем кнопку "ластик". Для SCEditor или похожего редактора она может иметь класс "sceditor-button-removeformat" или отображаться через иконку.
        const eraserButton = document.querySelector('.sceditor-button-removeformat, i.fa.fa-eraser');
        if (!eraserButton) return;

        // Чтобы не создавать несколько копий кнопки:
        if (document.querySelector('.sceditor-button-rgbpalette')) return;

        // Создаем скрытый input для выбора цвета
        const colorInput = document.createElement('input');
        colorInput.type = 'color';
        colorInput.style.display = 'none';
        document.body.appendChild(colorInput);

        // Создаем кнопку "RGB Палитра"
        const rgbButton = document.createElement('a');
        rgbButton.href = '#';
        rgbButton.className = 'sceditor-button sceditor-button-rgbpalette';
        rgbButton.title = 'Выбрать цвет (RGB)';
        // Пример иконки: можно заменить на свою, здесь используется базовая иконка в формате SVG (base64)
        rgbButton.style.backgroundImage =
          'url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCI+PGNpcmNsZSBjeD0iMTIiIGN5PSIxMiIgcj0iMTEiIGZpbGw9IiNmZmMiIC8+PC9zdmc+")';
        rgbButton.style.backgroundRepeat = 'no-repeat';
        rgbButton.style.backgroundPosition = 'center';
        rgbButton.style.backgroundSize = '16px 16px';
        rgbButton.style.width = '26px';
        rgbButton.style.height = '26px';
        rgbButton.style.display = 'inline-block';
        rgbButton.style.verticalAlign = 'middle';
        rgbButton.style.marginLeft = '3px';

        // Вставляем кнопку сразу после кнопки "ластика"
        eraserButton.insertAdjacentElement('afterend', rgbButton);

        // При клике по кнопке открываем color input
        rgbButton.addEventListener('click', function(e) {
            e.preventDefault();
            colorInput.click();
        });

        // При выборе цвета вставляем BBCode в поле ввода сообщения
        colorInput.addEventListener('change', function() {
            const chosenColor = colorInput.value; // формат #RRGGBB
            if (!chosenColor) return;

            // Находим текстовое поле редактора. Обычно имеет атрибут name="message"
            const textarea = document.querySelector('textarea[name="message"]');
            if (!textarea) return;

            // Получаем выделенный текст
            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            const selectedText = textarea.value.substring(start, end);
            const before = textarea.value.substring(0, start);
            const after = textarea.value.substring(end);

            let newText;
            if (selectedText) {
                // Если есть выделенный текст — оборачиваем его тегами [color=...][/color]
                newText = `[color=${chosenColor}]${selectedText}[/color]`;
            } else {
                // Если ничего не выделено — вставляем открывающий и закрывающий теги с курсором между ними
                newText = `[color=${chosenColor}][/color]`;
            }

            textarea.value = before + newText + after;
            textarea.focus();
            // Устанавливаем курсор в конец вставленного блока
            const pos = before.length + newText.length;
            textarea.setSelectionRange(pos, pos);
        });
    }

    // Так как редактор может подгружаться динамически (особенно в темах),
    // используем MutationObserver для отслеживания изменений в DOM
    const observer = new MutationObserver(() => {
        addRgbPaletteButton();
    });
    observer.observe(document.body, { childList: true, subtree: true });

    // Пробуем добавить кнопку сразу при загрузке страницы
    window.addEventListener('load', addRgbPaletteButton);
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址