Zum Inhalt springen

MediaWiki:Gadget-CodeGenerator.js

Aus Home Wiki

Hinweis: Leere nach dem Veröffentlichen den Browser-Cache, um die Änderungen sehen zu können.

  • Firefox/Safari: Umschalttaste drücken und gleichzeitig Aktualisieren anklicken oder entweder Strg+F5 oder Strg+R (⌘+R auf dem Mac) drücken
  • Google Chrome: Umschalttaste+Strg+R (⌘+Umschalttaste+R auf dem Mac) drücken
  • Edge: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
mw.loader.using(['mediawiki.util']).then(function () {

    // --- Globale Variablen ---
    const globalVars = {};
    const seenVars = new Set();
    const variableBlocks = {};

    // --- Erstellung der Leiste ---
    const bar = document.createElement('div');
    bar.id = 'global-var-bar';
    bar.style.display = 'none'; // Initial versteckt
    bar.style.flexWrap = 'wrap';
    bar.style.alignItems = 'flex-end'; // Ausrichtung an der Unterkante der Inputs
    bar.style.gap = '12px';
    bar.style.padding = '12px';
    bar.style.border = '1px solid #bbb';
    bar.style.borderRadius = '6px';
    bar.style.background = '#f5f5f5';
    bar.style.marginBottom = '20px';
    bar.style.marginTop = '10px';

    // Kleine Überschrift für die Leiste
    const barTitle = document.createElement('div');
    barTitle.textContent = 'Globale Variablen';
    barTitle.style.width = '100%';
    barTitle.style.fontWeight = 'bold';
    barTitle.style.fontSize = '14px';
    barTitle.style.marginBottom = '4px';
    barTitle.style.color = '#000';
    bar.appendChild(barTitle);

    // Einbauposition: Unter die Hauptüberschrift (h1) der Seite
    const pageTitle = document.querySelector('.firstHeading');
    if (pageTitle) {
        pageTitle.parentNode.insertBefore(bar, pageTitle.nextSibling);
    } else {
        document.querySelector('#content').prepend(bar);
    }

    const applyAllBtn = document.createElement('button');
    applyAllBtn.textContent = '→ Auf alle anwenden';
    applyAllBtn.style.padding = '6px 12px';
    applyAllBtn.style.cursor = 'pointer';
    applyAllBtn.style.border = '1px solid #888';
    applyAllBtn.style.borderRadius = '4px';
    applyAllBtn.style.background = '#eee';
    applyAllBtn.style.marginLeft = 'auto';
    applyAllBtn.style.fontWeight = 'bold';
    bar.appendChild(applyAllBtn);

    function addVarOnce(varName, defaultValue = '') {
        bar.style.display = 'flex'; // Einblenden sobald Variablen da sind

        if (seenVars.has(varName)) return;
        seenVars.add(varName);

        const formattedValue = defaultValue.startsWith('{{') ? defaultValue : `{{${defaultValue}}}`;
        globalVars[varName] = formattedValue;

        const lbl = document.createElement('label');
        lbl.style.display = 'flex';
        lbl.style.flexDirection = 'column';
        lbl.style.gap = '4px';

        const span = document.createElement('span');
        span.textContent = varName + ':';
        span.style.fontWeight = 'bold';
        span.style.fontSize = '13px'; // Etwas größer
        span.style.color = '#222';
        lbl.appendChild(span);

        const inp = document.createElement('input');
        inp.type = 'text';
        inp.value = formattedValue;
        inp.dataset.varId = varName;
        inp.style.width = '140px'; // Etwas breiter für die Optik
        inp.style.padding = '4px';
        inp.style.border = '1px solid #ccc';
        inp.style.borderRadius = '4px';
        inp.style.fontFamily = 'monospace';
        inp.style.fontSize = '12px';
        lbl.appendChild(inp);

        inp.addEventListener('input', () => {
            globalVars[varName] = inp.value;
        });

        bar.insertBefore(lbl, applyAllBtn);
    }

    // --- Hilfsfunktionen ---
    function copyText(text, btn) {
        const plainText = text.replace(/<[^>]+>/g, '');
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(plainText).then(() => success());
        } else {
            const textarea = document.createElement("textarea");
            textarea.value = plainText;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand("copy");
            document.body.removeChild(textarea);
            success();
        }
        function success() {
            btn.textContent = "✅ Kopiert!";
            setTimeout(() => btn.textContent = "📋 Kopieren", 1500);
        }
    }

    function highlightPlaceholdersAndValues(code, replacements) {
        let highlighted = code.replace(/{{(\w+)}}/g, '<span class="placeholder">{{$1}}</span>');
        Object.keys(replacements).forEach(varName => {
            const val = replacements[varName];
            if (!val) return;
            const escapedVal = val.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const re = new RegExp(escapedVal, 'g');

            highlighted = highlighted.replace(/(<span class="placeholder">.*?<\/span>|[^<]+)/g, segment => {
                if (segment.startsWith('<span class="placeholder">')) return segment;
                return segment.replace(re, `<span class="value">${val}</span>`);
            });
        });
        return highlighted;
    }

    function updateBlockContent(pre, inputWrapper, varsInBlock) {
        const currentValues = {};
        let updated = pre.dataset.originalCode;
        varsInBlock.forEach(vv => {
            const val = inputWrapper.querySelector(`input[data-var-id="${vv}"]`).value;
            updated = updated.replace(new RegExp(`{{${vv}}}`, 'g'), val);
            currentValues[vv] = val;
        });
        pre.innerHTML = highlightPlaceholdersAndValues(updated, currentValues);
    }

    // --- Block Initialisierung ---
    function initDynamicCodeBlock(pre) {
        if (pre.dataset.dynamicInit) return;
        pre.dataset.dynamicInit = true;

        const originalCode = pre.textContent;
        pre.dataset.originalCode = originalCode;

        const regex = /{{(\w+)}}/g;
        const varsInBlock = [];
        let match;
        while ((match = regex.exec(originalCode)) !== null) {
            if (!varsInBlock.includes(match[1])) varsInBlock.push(match[1]);
        }
        if (varsInBlock.length === 0) return;

        const container = document.createElement('div');
        container.style.display = 'flex';
        container.style.flexWrap = 'wrap';
        container.style.alignItems = 'center';
        container.style.justifyContent = 'space-between';
        container.style.gap = '6px';
        container.style.marginBottom = '4px';
        container.style.padding = '6px';
        container.style.border = '1px solid #ddd';
        container.style.borderRadius = '6px';
        container.style.background = '#f9f9f9';

        const inputWrapper = document.createElement('div');
        inputWrapper.style.display = 'flex';
        inputWrapper.style.flexWrap = 'wrap';
        inputWrapper.style.gap = '8px';
        container.appendChild(inputWrapper);

        varsInBlock.forEach(v => {
            const lbl = document.createElement('label');
            lbl.style.display = 'flex';
            lbl.style.alignItems = 'center';
            lbl.style.gap = '4px';
            lbl.style.fontSize = '12px';
            lbl.style.fontWeight = 'bold';
            lbl.textContent = v + ':';

            const inp = document.createElement('input');
            inp.type = 'text';
            inp.value = `{{${v}}}`;
            inp.dataset.varId = v;
            inp.style.width = '110px';
            inp.style.padding = '2px';
            inp.style.border = '1px solid #ccc';
            inp.style.borderRadius = '4px';
            inp.style.fontWeight = 'normal';

            lbl.appendChild(inp);
            inputWrapper.appendChild(lbl);
            inp.addEventListener('input', () => updateBlockContent(pre, inputWrapper, varsInBlock));
        });

        const btn = document.createElement('button');
        btn.textContent = '📋 Kopieren';
        btn.style.padding = '2px 8px';
        btn.style.fontSize = '12px';
        btn.style.cursor = 'pointer';
        btn.style.border = '1px solid #888';
        btn.style.borderRadius = '4px';
        btn.style.background = '#eee';
        btn.onclick = () => copyText(pre.innerHTML, btn);

        container.appendChild(btn);
        pre.parentNode.insertBefore(container, pre);
        pre.innerHTML = highlightPlaceholdersAndValues(originalCode, {});
    }

    function initStaticCodeBlock(pre) {
        if (pre.dataset.staticInit) return;
        pre.dataset.staticInit = true;
        const container = document.createElement('div');
        container.style.position = 'relative';
        container.style.marginBottom = '6px';
        pre.parentNode.replaceChild(container, pre);
        container.appendChild(pre);

        const btn = document.createElement('button');
        btn.textContent = '📋 Kopieren';
        btn.style.position = 'absolute';
        btn.style.top = '4px';
        btn.style.right = '4px';
        btn.style.padding = '2px 6px';
        btn.style.fontSize = '12px';
        btn.style.cursor = 'pointer';
        btn.style.border = '1px solid #888';
        btn.style.borderRadius = '4px';
        btn.style.background = '#eee';
        btn.onclick = () => copyText(pre.textContent, btn);
        container.appendChild(btn);
    }

    function initPage() {
        const dynamicBlocks = document.querySelectorAll('pre.dynamic-code');
        const staticBlocks = document.querySelectorAll('pre.static-code');
        
        dynamicBlocks.forEach(initDynamicCodeBlock);
        staticBlocks.forEach(initStaticCodeBlock);

        dynamicBlocks.forEach(pre => {
            const regex = /{{(\w+)}}/g;
            let match;
            while ((match = regex.exec(pre.dataset.originalCode || pre.textContent)) !== null) {
                const varName = match[1];
                addVarOnce(varName, varName);
                if (!variableBlocks[varName]) variableBlocks[varName] = [];
                if (!variableBlocks[varName].includes(pre)) variableBlocks[varName].push(pre);
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initPage);
    } else {
        initPage();
    }
    mw.hook('wikipage.content').add(initPage);

    const style = document.createElement('style');
    style.textContent = `
        .placeholder { color: #d14; font-weight: bold; }
        .value { color: #1a73e8; font-weight: bold; }
    `;
    document.head.appendChild(style);

    applyAllBtn.onclick = () => {
        const allPreBlocks = new Set();
        Object.values(variableBlocks).forEach(list => list.forEach(p => allPreBlocks.add(p)));

        allPreBlocks.forEach(pre => {
            const container = pre.previousSibling;
            if (!container || !container.querySelector) return;

            const varsInBlock = [];
            const regex = /{{(\w+)}}/g;
            let match;
            while ((match = regex.exec(pre.dataset.originalCode)) !== null) {
                if (!varsInBlock.includes(match[1])) varsInBlock.push(match[1]);
            }

            varsInBlock.forEach(vName => {
                const localInp = container.querySelector(`input[data-var-id="${vName}"]`);
                if (localInp && globalVars[vName] !== undefined) {
                    localInp.value = globalVars[vName];
                }
            });
            updateBlockContent(pre, container, varsInBlock);
        });
    };
});