User:Polygnotus/Scripts/Userinfo.js

This is an old revision of this page, as edited by Polygnotus (talk | contribs) at 12:03, 9 July 2025 (Created page with '// Wikipedia API Explorer Module const WikipediaAPI = { // Fetch Wikipedia userinfo data async fetchUserInfo() { const params = { action: 'query', meta: 'userinfo', uiprop: 'options', format: 'json', origin: '*' }; const url = 'https://en.wikipedia.org/w/api.php?' + new URLSearchParams(params); try { const response = await fetch(...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Wikipedia API Explorer Module
const WikipediaAPI = {
    // Fetch Wikipedia userinfo data
    async fetchUserInfo() {
        const params = {
            action: 'query',
            meta: 'userinfo',
            uiprop: 'options',
            format: 'json',
            origin: '*'
        };
        
        const url = 'https://en.wikipedia.org/w/api.php?' + new URLSearchParams(params);
        
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('Wikipedia API error:', error);
            throw error;
        }
    },

    // Create JSON tree viewer
    createJSONTree(containerId, data) {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`Container with id '${containerId}' not found`);
            return;
        }

        // Clear container
        container.innerHTML = '';
        
        // Create tree structure
        const tree = document.createElement('div');
        tree.className = 'json-tree';
        tree.appendChild(this.createNode('root', data, 0));
        container.appendChild(tree);
        
        // Add styles if not already present
        this.addStyles();
    },

    // Create individual node
    createNode(key, value, depth) {
        const node = document.createElement('div');
        node.className = 'json-node';
        
        if (value === null) {
            node.innerHTML = `<span class="json-key">${key}:</span> <span class="json-null">null</span>`;
        } else if (typeof value === 'string') {
            node.innerHTML = `<span class="json-key">${key}:</span> <span class="json-string">"${this.escapeHtml(value)}"</span>`;
        } else if (typeof value === 'number') {
            node.innerHTML = `<span class="json-key">${key}:</span> <span class="json-number">${value}</span>`;
        } else if (typeof value === 'boolean') {
            node.innerHTML = `<span class="json-key">${key}:</span> <span class="json-boolean">${value}</span>`;
        } else if (Array.isArray(value)) {
            const toggleId = `toggle-${Date.now()}-${Math.random()}`;
            
            const toggle = document.createElement('span');
            toggle.className = 'json-toggle';
            toggle.textContent = '▼';
            toggle.id = toggleId;
            
            const keySpan = document.createElement('span');
            keySpan.className = 'json-key';
            keySpan.textContent = `${key}:`;
            
            const summary = document.createElement('span');
            summary.className = 'json-collapsed';
            summary.textContent = ` [${value.length} items]`;
            
            node.appendChild(toggle);
            node.appendChild(keySpan);
            node.appendChild(summary);
            
            const children = document.createElement('div');
            children.className = 'json-children';
            
            value.forEach((item, index) => {
                children.appendChild(this.createNode(`[${index}]`, item, depth + 1));
            });
            
            node.appendChild(children);
            
            toggle.onclick = () => this.toggleNode(toggleId);
            
        } else if (typeof value === 'object') {
            const keys = Object.keys(value);
            const toggleId = `toggle-${Date.now()}-${Math.random()}`;
            
            const toggle = document.createElement('span');
            toggle.className = 'json-toggle';
            toggle.textContent = '▼';
            toggle.id = toggleId;
            
            const keySpan = document.createElement('span');
            keySpan.className = 'json-key';
            keySpan.textContent = `${key}:`;
            
            const summary = document.createElement('span');
            summary.className = 'json-collapsed';
            summary.textContent = ` {${keys.length} properties}`;
            
            node.appendChild(toggle);
            node.appendChild(keySpan);
            node.appendChild(summary);
            
            const children = document.createElement('div');
            children.className = 'json-children';
            
            keys.forEach(objKey => {
                children.appendChild(this.createNode(objKey, value[objKey], depth + 1));
            });
            
            node.appendChild(children);
            
            toggle.onclick = () => this.toggleNode(toggleId);
        }
        
        return node;
    },

    // Toggle node visibility
    toggleNode(toggleId) {
        const toggle = document.getElementById(toggleId);
        const children = toggle.parentNode.querySelector('.json-children');
        
        if (children.classList.contains('hidden')) {
            children.classList.remove('hidden');
            toggle.textContent = '▼';
        } else {
            children.classList.add('hidden');
            toggle.textContent = '▶';
        }
    },

    // Expand all nodes
    expandAll(containerId) {
        const container = document.getElementById(containerId);
        const toggles = container.querySelectorAll('.json-toggle');
        toggles.forEach(toggle => {
            const children = toggle.parentNode.querySelector('.json-children');
            if (children) {
                children.classList.remove('hidden');
                toggle.textContent = '▼';
            }
        });
    },

    // Collapse all nodes
    collapseAll(containerId) {
        const container = document.getElementById(containerId);
        const toggles = container.querySelectorAll('.json-toggle');
        toggles.forEach(toggle => {
            const children = toggle.parentNode.querySelector('.json-children');
            if (children) {
                children.classList.add('hidden');
                toggle.textContent = '▶';
            }
        });
    },

    // Escape HTML
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    },

    // Add required CSS styles
    addStyles() {
        if (document.getElementById('json-tree-styles')) return;
        
        const style = document.createElement('style');
        style.id = 'json-tree-styles';
        style.textContent = `
            .json-tree {
                font-family: 'Courier New', monospace;
                background: #f8f9fa;
                border: 1px solid #e1e5e9;
                border-radius: 5px;
                padding: 15px;
                margin: 10px 0;
                overflow-x: auto;
            }
            
            .json-node {
                margin: 2px 0;
            }
            
            .json-key {
                color: #0645ad;
                font-weight: bold;
            }
            
            .json-string {
                color: #d73a49;
            }
            
            .json-number {
                color: #005cc5;
            }
            
            .json-boolean {
                color: #6f42c1;
            }
            
            .json-null {
                color: #6a737d;
            }
            
            .json-toggle {
                cursor: pointer;
                user-select: none;
                display: inline-block;
                width: 20px;
                color: #666;
                font-weight: bold;
            }
            
            .json-toggle:hover {
                color: #0645ad;
            }
            
            .json-collapsed {
                color: #666;
            }
            
            .json-children {
                margin-left: 20px;
                border-left: 1px solid #e1e5e9;
                padding-left: 10px;
            }
            
            .json-children.hidden {
                display: none;
            }
        `;
        document.head.appendChild(style);
    },

    // Main function to fetch and display
    async displayWikipediaData(containerId) {
        try {
            const data = await this.fetchUserInfo();
            this.createJSONTree(containerId, data);
            console.log('Wikipedia data loaded successfully');
        } catch (error) {
            const container = document.getElementById(containerId);
            if (container) {
                container.innerHTML = `<div style="color: red; padding: 10px;">Error loading data: ${error.message}</div>`;
            }
        }
    }
};

// Usage examples:
/*
// Fetch and display data
WikipediaAPI.displayWikipediaData('my-container');

// Or fetch data manually and create tree
WikipediaAPI.fetchUserInfo().then(data => {
    WikipediaAPI.createJSONTree('my-container', data);
});

// Control functions
WikipediaAPI.expandAll('my-container');
WikipediaAPI.collapseAll('my-container');
*/