Gelbooru sort by hotkeys

This script allows you to automatically fill a search input with predefined keywords and trigger the search button using keyboard shortcuts.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Gelbooru sort by hotkeys
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  This script allows you to automatically fill a search input with predefined keywords and trigger the search button using keyboard shortcuts.
// @author       Peepo
// @match        *://gelbooru.com/*
// @license MIT
// ==/UserScript==

(function() {
    const keyToTextMap = {
        'r': 'sort:random',
        's': 'sort:score'
    };

    const input = document.getElementById('tags-search');
    const searchButton = document.querySelector('input.searchList[type="submit"]');

    if (!input || !searchButton) return;

    function updateInputValue(newKey) {
        const newText = keyToTextMap[newKey];
        if (!newText) return;

        let foundKey = null;
        for (const k in keyToTextMap) {
            if (input.value.includes(keyToTextMap[k])) {
                foundKey = k;
                break;
            }
        }

        if (foundKey === newKey) {
            return;
        } else if (foundKey) {
            input.value = input.value.replace(keyToTextMap[foundKey], newText);
        } else {
            if (input.value.length > 0) {
                input.value += " " + newText;
            } else {
                input.value = newText;
            }
        }

        searchButton.click();
    }

    document.addEventListener('keydown', function(event) {
        const activeTag = document.activeElement.tagName.toUpperCase();
        if (activeTag === 'INPUT' || activeTag === 'TEXTAREA') return;

        if (keyToTextMap[event.key]) {
            event.preventDefault();
            updateInputValue(event.key);
        }
    });
})();