AO3: Initialize jQueryUI

library to load the jQuery, jQueryUI and TouchPunch JS from CDN only if it hasn't already, and create the menu

Este script não deve ser instalado diretamente. É uma biblioteca destinada a ser incluída por outros scripts através da diretiva de metadados // @require https://update.greasyfork.org/scripts/542049/1780689/AO3%3A%20Initialize%20jQueryUI.js

Terá de instalar uma extensão como Tampermonkey, Greasemonkey ou Violentmonkey para instalar este script.

Terá de instalar uma extensão como Tampermonkey para instalar este script.

Terá de instalar uma extensão como Tampermonkey ou Violentmonkey para instalar este script.

Terá de instalar uma extensão como Tampermonkey ou Userscripts para instalar este script.

Terá de instalar uma extensão como Tampermonkey para instalar este script.

Terá de instalar uma extensão de gestão de scripts de utilizador para instalar este script.

(Já tenho um gestor de scripts de utilizador, deixe-me instalá-lo!)

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão como Stylus para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

Terá de instalar uma extensão de gestão de estilos de utilizador para instalar este estilo.

(Já tenho um gestor de estilos de utilizador, deixe-me instalá-lo!)

// ==UserScript==
// @name         AO3: Initialize jQueryUI
// @namespace    https://greasyfork.org/en/users/906106-escctrl
// @description  library to load the jQuery, jQueryUI and TouchPunch JS from CDN only if it hasn't already, and create the menu
// @author       escctrl
// @version      2.1
// @grant        none
// @license      GNU GPL-3.0-only
// ==/UserScript==

// HOW TO USE:
// please refer to https://greasyfork.org/en/scripts/542049 for a full description how to use this library

/* global jQuery, $ */
'use strict';

// utility to reduce verboseness
const q = (selector, node=document) => node.querySelector(selector);
const qa = (selector, node=document) => node.querySelectorAll(selector);
const ins = (n, l, html) => n.insertAdjacentHTML(l, html);

function createMenu(id, heading) {
    // if no other script has created it yet, write out a "Userscripts" option to the main navigation
    if (qa('#scriptconfig').length === 0) {
        ins(qa('#header nav[aria-label="Site"] li.search')[0], // insert as last li before search
            'beforebegin', `<li class="dropdown" id="scriptconfig">
                <a class="dropdown-toggle" href="/" data-toggle="dropdown" data-target="#">Userscripts</a>
                <ul class="menu dropdown-menu"></ul></li>`);
    }

    // then add this script's config option to navigation dropdown
    ins(q('#scriptconfig .dropdown-menu'), 'beforeend', `<li><a href="javascript:void(0);" id="opencfg_${id}">${heading}</a></li>`);
}

function loadjQuery(URI) {
    // based on https://stackoverflow.com/a/44807594
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        document.head.appendChild(script);
        script.onload = () => resolve("success");
        script.onerror = (ev) => reject(ev);
        script.async = true;
        script.src = URI;
    });
}

async function initGUI(e, id, heading, maxWidth) {
    try {
        if (!q("head script[src*='/3.7.0/jquery.min.js']")) await loadjQuery('https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js');
        if (!q("head script[src*='/1.13.2/jquery-ui.min.js']")) await loadjQuery('https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js');
        if (!q("head script[src*='/0.2.3/jquery.ui.touch-punch.min.js']")) await loadjQuery('https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js');
    }
    catch(evError) {
        console.error(`Library has failed to load ${evError.target.src}. Dialog can't be displayed.`);
        return false;
    }

    // automatic darkmode if the background is dark (e.g. Reversi)
    let theme = lightOrDark(getComputedStyle(q("body")).getPropertyValue("background-color"));
    theme = theme == "dark" ? "dark-hive" : "base";

    id = "#"+id;
    // setting up the GUI CSS (only if no other script has created it yet)
    if (!q("head link[href*='jquery-ui.css']")) {
        ins(q("head"), 'beforeend',`<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/${theme}/jquery-ui.css" type="text/css">`);
    }
    ins(q("head"), 'beforeend',`<style type="text/css">/* jQueryUI stuff that's messed up by AO3 default skins */
        .ui-widget, ${id}, .ui-dialog .ui-dialog-buttonpane button {font-size: revert !important; line-height: 1.286;}
        .ui-dialog.scriptconfigUI { z-index: 101; }
        ${id} {
            form, fieldset {border: revert; box-shadow: revert; background: revert; cursor:auto;}
            ol { margin-left: 2em; li { list-style: decimal; } }
            fieldset p { padding-left: 0; padding-right: 0; }
            legend {font-size: inherit; height: auto; width: auto; opacity: inherit;}
            label { margin: 0; }
            select { vertical-align: baseline; }
            .ui-sortable li { background-color: revert; border: revert; margin: 0; float: none; clear: none; box-shadow: revert; width: auto; display: inline-block; }

            /* Toggle Switches (CSS) */
            --switch-height: 1.5em;
            --slider-size: calc(var(--switch-height) - 0.2em);
            --slider-color: currentColor;

            /* The switch - the box around the slider */
            .switch { position: relative; bottom: 0.1em; display: inline-block; width: 3em; height: var(--switch-height); padding: 0; border-radius: 1em; }
            /* Hide default HTML checkbox */
            .switch input { opacity: 0; width: 0; height: 0; }
            /* The slider */
            .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; -webkit-transition: .4s; transition: .4s; }
            .slider:before { position: absolute; content: ""; height: var(--slider-size); width: var(--slider-size); left: 0.2em; bottom: 0.1em;
                background-color: var(--slider-color); -webkit-transition: .4s; transition: .4s; }
            input:checked + .slider { }
            input:focus + .slider { }
            input:checked + .slider:before { -webkit-transform: translateX(var(--slider-size)); -ms-transform: translateX(var(--slider-size)); transform: translateX(var(--slider-size)); }
            /* Rounded sliders */
            .slider.round { border-radius: 1em; }
            .slider.round:before { border-radius: 50%; }
        }</style>`);

    // wrapper div for the dialog
    $("body").append(`<div id="${id.slice(1)}"></div>`);

    let dialogwidth = parseInt($("body").css("width"));
    dialogwidth = dialogwidth > maxWidth ? maxWidth : dialogwidth * 0.9;

    $(id).dialog({
        appendTo: "#main",
        modal: true,
        title: heading,
        classes: { "ui-dialog": "scriptconfigUI" },
        draggable: false,
        resizable: false,
        autoOpen: false,
        width: dialogwidth,
        position: {my:"center", at: "center top", of: window},
    });

    // event listener for reopening the dialog on subsequent menu clicks (without recreating the whole GUI)
    e.target.addEventListener("click", function(e) { $( id ).dialog('open'); });

    // if the window resizes the dialog would move off of the screen
    window.addEventListener('resize', function(e) {
        let dialogwidth = parseInt($("body").css("width")); // get the new browser width
        dialogwidth = dialogwidth > maxWidth ? maxWidth : dialogwidth * 0.9;

        $(id).dialog("option", "width", dialogwidth) // resize the dialog
             .dialog("option", "position", {my:"center top", at: "center top", of: window} ); // reposition the dialog
    });

    return $(id);
}

// helper function to determine whether a color (the background in use) is light or dark
// https://awik.io/determine-color-bright-dark-using-javascript/
function lightOrDark(color) {
    var r, g, b, hsp;
    if (color.match(/^rgb/)) { color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
        r = color[1]; g = color[2]; b = color[3]; }
    else { color = +("0x" + color.slice(1).replace(color.length < 5 && /./g, '$&$&'));
        r = color >> 16; g = color >> 8 & 255; b = color & 255; }
    hsp = Math.sqrt( 0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b) );
    if (hsp>127.5) { return 'light'; } else { return 'dark'; }
}