GC - Universal Userscripts Settings

Library for adding a user interface to manage settings for grundos.cafe userscripts

Устаревшая версия за 28.10.2024. Перейдите к последней версии.

Этот скрипт недоступен для установки пользователем. Он является библиотекой, которая подключается к другим скриптам мета-ключом // @require https://update.greasyfork.org/scripts/514423/1472892/GC%20-%20Universal%20Userscripts%20Settings.js

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey, Greasemonkey или Violentmonkey.

Для установки этого скрипта вам необходимо установить расширение, такое как Tampermonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Violentmonkey.

Чтобы установить этот скрипт, вы сначала должны установить расширение браузера, например Tampermonkey или Userscripts.

Чтобы установить этот скрипт, сначала вы должны установить расширение браузера, например Tampermonkey.

Чтобы установить этот скрипт, вы должны установить расширение — менеджер скриптов.

(у меня уже есть менеджер скриптов, дайте мне установить скрипт!)

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение браузера, например Stylus.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

Чтобы установить этот стиль, сначала вы должны установить расширение — менеджер стилей.

(у меня уже есть менеджер стилей, дайте мне установить скрипт!)

function _addSettingsLink() {
    const existingNav = document.querySelector('nav.center.margin-1');
  
    if (existingNav) {
      const newNav = document.createElement('nav');
      newNav.classList.add('center', 'margin-1');
      newNav.id = 'userscript-navigation';
      
      const newLink = document.createElement('a');
      newLink.href = '/help/userscripts/';
      newLink.textContent = 'Userscript Preferences';
      
      newNav.appendChild(newLink);
      
      existingNav.after(newNav);
    } else {
      console.error('Existing navigation element not found.');
    }
}

function _createLabel(labelText) {
    const labelContainer = document.createElement('div');
    labelContainer.classList.add('data', 'left');

    const label = document.createElement('span');
    label.textContent = labelText;
    labelContainer.appendChild(label);
    return labelContainer;
}

function _createInput(input) {
    const inputContainer = document.createElement('div');
    inputContainer.classList.add('data', 'flex-column', 'right');
    inputContainer.appendChild(input);
    return inputContainer;
}

function _addCallback(callbackFunction) {
    document.getElementById('userscript-update').addEventListener('click', callbackFunction);
}

async function _addCategoryHeader(categoryName) {
    if (!window.location.href.includes('/help/userscripts/')) return;
    await _checkSettingsSetup();
    const settings = document.querySelector('.market_grid.profile.prefs.margin-auto');
    const footer = document.querySelector('#userscript-preferences>.market_grid.profile.prefs.margin-auto>.footer.small-gap');
    if (!settings) {
        console.error('Settings not found.');
        return;
    }

    const headers = Array.from(settings.querySelectorAll('.header'));
    let header = headers.find(header => header.textContent.trim() === categoryName);

    if (!header) {
        header = document.createElement('div');
        header.classList.add('header');
        header.innerHTML = `<strong>${categoryName}</strong>`;
    
        const insertionPoint = headers.find(existingHeader => existingHeader.textContent.trim().localeCompare(categoryName) > 0);
    
        if (insertionPoint) {
            insertionPoint.insertAdjacentElement('beforebegin', header);
        } else {
            footer.insertAdjacentElement('beforebegin', header);
        }
    }

    return header;
}

async function addTextInput(categoryName, settingName, labelText, currentSetting = undefined, callbackFunction = undefined) {
    if (!window.location.href.includes('/help/userscripts/')) throw Error('Attempted to add setting outside of settings page.');    const header = await _addCategoryHeader(categoryName);

    if (currentSetting === undefined) {
        currentSetting = await GM.getValue(settingName, '');
    }

    const textInput = document.createElement('input');
    textInput.type = 'text';
    textInput.name = settingName;
    textInput.value = currentSetting;
    
    const label = _createLabel(labelText);
    header.insertAdjacentElement('afterend', label);

    const inputElement = _createInput(textInput);
    label.insertAdjacentElement('afterend', inputElement);

    if (callbackFunction) {
        _addCallback(() => callbackFunction(settingName, textInput.value));
    } else {
        _addCallback(async () => await GM.setValue(settingName, checkbox.checked));
    }
}

async function addNumberInput(categoryName, settingName, labelText, min = 0, max = 100, step = 1, currentSetting = undefined, callbackFunction = undefined) {
    if (!window.location.href.includes('/help/userscripts/')) throw Error('Attempted to add setting outside of settings page.');    const header = await _addCategoryHeader(categoryName);
    if (currentSetting === undefined) {
        currentSetting = await GM.getValue(settingName, min);
    }

    const numberInput = document.createElement('input');
    numberInput.type = 'number';
    numberInput.name = settingName;
    numberInput.value = currentSetting;
    numberInput.min = min;
    numberInput.max = max;
    numberInput.step = step;
    
    const label = _createLabel(labelText);
    header.insertAdjacentElement('afterend', label);

    const inputElement = _createInput(numberInput);
    label.insertAdjacentElement('afterend', inputElement);

    if (callbackFunction) {
        _addCallback(() => callbackFunction(settingName, numberInput.value));
    } else {
        _addCallback(async () => await GM.setValue(settingName, checkbox.checked));
    }
}

async function addCheckboxInput(categoryName, settingName, labelText, currentSetting = undefined, callbackFunction = undefined) {
    if (!window.location.href.includes('/help/userscripts/')) throw Error('Attempted to add setting outside of settings page.');    const header = await _addCategoryHeader(categoryName);
    if (currentSetting === undefined) {
        currentSetting = await GM.getValue(settingName, false);
    }

    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.name = settingName;
    checkbox.checked = currentSetting;
    
    const label = _createLabel(labelText);
    header.insertAdjacentElement('afterend', label);

    const inputElement = _createInput(checkbox);
    label.insertAdjacentElement('afterend', inputElement);

    if (callbackFunction) {
        _addCallback(() => callbackFunction(settingName, checkbox.checked));
    } else {
        _addCallback(async () => await GM.setValue(settingName, checkbox.checked));
    }
}

async function addDropdown(categoryName, settingName, labelText, options, currentSetting = undefined, callbackFunction = undefined) {
    if (!window.location.href.includes('/help/userscripts/')) throw Error('Attempted to add setting outside of settings page.');
    const header = await _addCategoryHeader(categoryName);
    if (currentSetting === undefined) {
        currentSetting = await GM.getValue(settingName, options[0].value);
    }

    const select = document.createElement('select');
    select.name = settingName;
    select.classList.add('form-control');

    options.forEach(option => {
        const optionElement = document.createElement('option');
        optionElement.value = option.value;
        optionElement.textContent = option.text;
        if (option.value === currentSetting) {
            optionElement.selected = true;
        }
        select.appendChild(optionElement);
    });
    
    const label = _createLabel(labelText);
    header.insertAdjacentElement('afterend', label);

    const inputElement = _createInput(select);
    label.insertAdjacentElement('afterend', inputElement);

    if (callbackFunction) {
        _addCallback(() => callbackFunction(settingName, select.value));
    } else {
        _addCallback(async () => await GM.setValue(settingName, checkbox.checked));
    }
}

function _replaceBannerImage() {
    const bannerImage = document.getElementById('top-header-image');
    if (bannerImage) {
        bannerImage.src = 'https://grundoscafe.b-cdn.net/misc/banners/userinfo.gif';
    } else {
        console.error('Banner image not found.');
    }
}

function _setupShareSettings() {
    const urlPattern = /\/help\/(?:profile|siteprefs|sidebar|randomevents)\/|\/discord\//;
    const settings = window.location.href.includes('/help/userscripts/');
    const help = urlPattern.test(window.location.href) && !settings;
    if (help) {
        _addSettingsLink();
    } else if (settings) {
        _replaceBannerImage();
        const element = document.querySelector('main');
        if (element) {
            element.id = 'userscript-preferences';  
            element.innerHTML = `
                <h1>Userscript Preferences</h1>
                <nav class="center margin-1">
                    <a href="/help/profile/">Edit Profile</a> |
                    <a href="/help/siteprefs/">Site Preferences</a> |
                    <a href="/help/sidebar/">Edit Sidebar</a> |
                    <a href="/discord/">Discord</a> |
                    <a href="/help/randomevents/">Random Event Log</a>
                </nav>
                <nav class="center margin-1" id="userscript-navigation"><a href="/help/userscripts/">Userscript Preferences</a></nav>
                <p>Here you can adjust settings for participating userscripts.</p>
                <div class="market_grid profile prefs margin-auto">
                    <div class="footer small-gap">
                        <input class="form-control half-width" type="submit" value="Update Preferences" id="userscript-update">
                    </div>
                </div>
                `;
        }
    }
}

async function _checkSettingsSetup() {
    return new Promise((resolve, reject) => {
        const interval = setInterval(() => {
            if (document.getElementById('userscript-preferences') !== null) {
                clearInterval(interval);
                clearTimeout(timeout);
                resolve(true);
            }
        }, 50);

        const timeout = setTimeout(() => {
            clearInterval(interval);
            reject(new Error('Timeout: userscript-preferences element not found within 10 seconds'));
        }, 10000);
    });
}

if (!document.getElementById('userscript-navigation')) {
    console.log("settings running");
    _setupShareSettings();
}