Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

MediaWiki:Gadget-VaultAltarComponent.js: Difference between revisions

MediaWiki interface page
Created page with "* Gadget: VaultAltarComponent * ---------------------------- * Renders a Vault Level slider + dynamic ingredient tables * Only activates if #vault-altar-component is present on the page.: (function () { const JSON_PAGE = 'MediaWiki:Vault_altar_ingredients.json'; $(function () { const host = document.getElementById('vault-altar-component'); if (!host) return; $.getJSON(getRawURL(JSON_PAGE, 'application/json')) .done(data => initialise(ho..."
 
No edit summary
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
/*
( function ( mw, $ ) {
* Gadget: VaultAltarComponent
    'use strict';
* ----------------------------
* Renders a Vault Level slider + dynamic ingredient tables
* Only activates if #vault-altar-component is present on the page.
*/


(function () {
    // ------------------------ Configurable ------------------------- //
  const JSON_PAGE = 'MediaWiki:Vault_altar_ingredients.json';
    const JSON_PAGE = 'MediaWiki:Vault_altar_ingredients.json';
    const PLACEHOLDER_SELECTOR = '.js-vault-altar#vault-altar-component';


  $(function () {
    // ---------------------- Helper Functions ----------------------- //
     const host = document.getElementById('vault-altar-component');
    function nearestLevel ( levels, val ) {
    if (!host) return;
        let chosen = levels[ 0 ];
        for ( const lv of levels ) {
            if ( val >= lv ) {
                chosen = lv;
            } else {
                break;
            }
        }
        return chosen;
    }
 
    /** Return canonical file‑path URL for a given filename. */
    function filePath ( filename ) {
        return mw.util.getUrl( 'Special:FilePath/' + filename );
    }
 
    /** Convert an item id like "iron_ingot" → "Iron_Ingot" */
    function toIconName ( id ) {
        return id.split( '_' ).map( w => w.charAt( 0 ).toUpperCase() + w.slice( 1 ) ).join( '_' );
    }
 
    /**
    * Render the output tables for a particular vault level.
    * @param {Object} data – Parsed JSON object (the entire file).
    * @param {string} levelKey – The exact level key to show (e.g. "10").
    * @param {jQuery} $out – jQuery node where HTML will be injected.
    */
    function renderLevel ( data, levelKey, $out ) {
     const levelData = data.LEVELS[ levelKey ];
    if ( !levelData ) {
        $out.html( $( '<p>' ).text( 'No data found for level ' + levelKey + '.' ) );
        return;
    }
 
    Object.entries( levelData ).forEach( ( [ catName, entries ] ) => {
        const catId = 'vault-altar-cat-' + catName.toLowerCase().replace(/\s+/g, '-');
        let $details = $out.find( '#' + catId );
 
        // If category section doesn't exist, create it
        if ( $details.length === 0 ) {
            $details = $( '<details>' )
                .addClass( 'vault-altar-cat' )
                .attr( 'id', catId )
                .append( $( '<summary>' ).text( catName.charAt( 0 ).toUpperCase() + catName.slice( 1 ) ) );
            $out.append( $details );
        }
 
        // Remove old table, if any
        $details.find( 'table' ).remove();


    $.getJSON(getRawURL(JSON_PAGE, 'application/json'))
        // Create new table for this level
      .done(data => initialise(host, data))
        const $table = $( '<table>' )
      .fail(() => host.textContent = '❌ Could not load altar data.');
            .addClass( 'wikitable sortable' )
  });
            .append( $( '<thead>' ).append( $( '<tr>' )
                .append( $( '<th>' ).text( 'Items' ) )
                .append( $( '<th>' ).text( 'Amount (min‒max)' ) )
                .append( $( '<th>' ).text( 'Scale' ) )
                .append( $( '<th>' ).text( 'Weight' ) )
            ) );


  function getRawURL(title, type) {
        entries.forEach( entry => {
    return mw.util.wikiScript() +
            const itemNames = entry.value.items.map( o => o.item.replace( /^minecraft:/, '' ).replace( /_/g, ' ' ) );
      '?title=' + encodeURIComponent(title) +
            const itemsText = itemNames.join( ', ' );
      '&action=raw&ctype=' + encodeURIComponent(type || 'text/plain');
  }


  function initialise(root, data) {
            const firstId = entry.value.items[ 0 ].item.replace( /^minecraft:/, '' );
    const levels = Object.keys(data).map(Number).sort((a, b) => a - b);
            const iconFile = 'Invicon_' + toIconName( firstId ) + '.png';
    if (!levels.length) { root.textContent = 'No data.'; return; }
            const $img = $( '<img>' )
                .attr( 'src', filePath( iconFile ) )
                .attr( {
                    width: 20,
                    height: 20,
                    loading: 'lazy'
                } )
                .css( {
                    'vertical-align': 'middle',
                    'margin-right'  : '0.25em'
                } );


    const header = $('<div>', { class: 'vault-altar-header' }).appendTo(root);
            const amt    = entry.value.amount.min + '' + entry.value.amount.max;
    header.append('<span>Vault Level </span>');
            const scale  = entry.value.scale;
    const valueEl = $('<span>', { class: 'vault-altar-slider-value' }).appendTo(header);
            const weight = entry.weight;


    const slider = $('<input>', {
            const $itemCell = $( '<td>' ).append( $img ).append( document.createTextNode( ' ' + itemsText ) );
      type: 'range',
      min: levels[0],
      max: levels[levels.length - 1],
      value: levels[0],
      class: 'vault-altar-level-slider'
    }).appendTo(header);


    const output = $('<div>', { class: 'vault-altar-output' }).appendTo(root);
            $table.append( $( '<tr>' )
                .append( $itemCell )
                .append( $( '<td>' ).text( amt ) )
                .append( $( '<td>' ).text( scale ) )
                .append( $( '<td>' ).text( weight ) )
            );
        } );


    slider.on('input change', () => render(+slider.val()));
        $details.append( $table );
     render(levels[0]);
     } );
}


     function render(level) {
    // -------------------------- Main ------------------------------- //
      valueEl.text(level);
     function init () {
      output.empty();
        const host = document.querySelector( PLACEHOLDER_SELECTOR );
        if ( !host ) return; // Only activate where template is present


      const entry = data[level];
        const $wrapper  = $( '<div>' ).addClass( 'vault-altar-wrapper' );
      if (!entry) { output.text('No data for this level.'); return; }
        const $sliderRow = $( '<div>' ).addClass( 'vault-altar-slider' );


      Object.keys(entry).forEach(cat => {
        const $label      = $( '<label>' ).attr( 'for', 'vault-altar-level' ).text( 'Vault Level: ' );
         const catBox = $('<div>', { class: 'vault-altar-category' }).appendTo(output);
         const $valDisplay = $( '<span>' ).attr( 'id', 'vault-altar-level-val' ).text( '0' );
         $('<h3>').text(capitalise(cat)).appendTo(catBox);
         const $input      = $( '<input>' ).attr( {
            id  : 'vault-altar-level',
            type : 'range',
            min  : 0,
            max  : 100,
            step : 1,
            value: 0
        } ).css( 'width', '100%' );


         const table = $('<table>', { class: 'vault-altar-table' }).appendTo(catBox);
         $sliderRow.append( $label, $valDisplay, $input );
         table.append('<thead><tr><th>Item</th><th>Amount</th></tr></thead>');
         $wrapper.append( $sliderRow );
         const tbody = $('<tbody>').appendTo(table);
         const $output = $( '<div>' ).attr( 'id', 'vault-altar-output' );
        $wrapper.append( $output );


         (entry[cat] || []).forEach(row => {
         $( host ).empty().append( $wrapper );
          $('<tr>')
 
             .append($('<td>').text(row.item))
        $.getJSON( mw.util.wikiScript( 'index' ), {
            .append($('<td>').text(row.amount))
            title : JSON_PAGE,
             .appendTo(tbody);
            action: 'raw',
         });
            ctype : 'application/json'
      });
        } ).done( function ( data ) {
             const levels = Object.keys( data.LEVELS ).map( Number ).sort( ( a, b ) => a - b );
            $input.attr( { min: levels[ 0 ], max: levels[ levels.length - 1 ] } );
 
            function update () {
                const userVal = parseInt( $input.val(), 10 );
                const lvl = nearestLevel( levels, userVal );
                $valDisplay.text( userVal + ' (showing ' + lvl + ')' );
                renderLevel( data, String( lvl ), $output );
             }
 
            $input.on( 'input change', update );
            update();
         } ).fail( function () {
            $output.text( 'Failed to load Vault Altar data – please check that ' + JSON_PAGE + ' exists and is valid JSON.' );
        } );
     }
     }
  }


  function capitalise(str) {
     $( init );
     return str.charAt(0).toUpperCase() + str.slice(1);
 
  }
} )( mediaWiki, jQuery );
})();

Latest revision as of 23:19, 11 July 2025

( function ( mw, $ ) {
    'use strict';

    // ------------------------ Configurable ------------------------- //
    const JSON_PAGE = 'MediaWiki:Vault_altar_ingredients.json';
    const PLACEHOLDER_SELECTOR = '.js-vault-altar#vault-altar-component';

    // ---------------------- Helper Functions ----------------------- //
    function nearestLevel ( levels, val ) {
        let chosen = levels[ 0 ];
        for ( const lv of levels ) {
            if ( val >= lv ) {
                chosen = lv;
            } else {
                break;
            }
        }
        return chosen;
    }

    /** Return canonical file‑path URL for a given filename. */
    function filePath ( filename ) {
        return mw.util.getUrl( 'Special:FilePath/' + filename );
    }

    /** Convert an item id like "iron_ingot" → "Iron_Ingot" */
    function toIconName ( id ) {
        return id.split( '_' ).map( w => w.charAt( 0 ).toUpperCase() + w.slice( 1 ) ).join( '_' );
    }

    /**
     * Render the output tables for a particular vault level.
     * @param {Object} data – Parsed JSON object (the entire file).
     * @param {string} levelKey – The exact level key to show (e.g. "10").
     * @param {jQuery} $out – jQuery node where HTML will be injected.
     */
    function renderLevel ( data, levelKey, $out ) {
    const levelData = data.LEVELS[ levelKey ];
    if ( !levelData ) {
        $out.html( $( '<p>' ).text( 'No data found for level ' + levelKey + '.' ) );
        return;
    }

    Object.entries( levelData ).forEach( ( [ catName, entries ] ) => {
        const catId = 'vault-altar-cat-' + catName.toLowerCase().replace(/\s+/g, '-');
        let $details = $out.find( '#' + catId );

        // If category section doesn't exist, create it
        if ( $details.length === 0 ) {
            $details = $( '<details>' )
                .addClass( 'vault-altar-cat' )
                .attr( 'id', catId )
                .append( $( '<summary>' ).text( catName.charAt( 0 ).toUpperCase() + catName.slice( 1 ) ) );
            $out.append( $details );
        }

        // Remove old table, if any
        $details.find( 'table' ).remove();

        // Create new table for this level
        const $table = $( '<table>' )
            .addClass( 'wikitable sortable' )
            .append( $( '<thead>' ).append( $( '<tr>' )
                .append( $( '<th>' ).text( 'Items' ) )
                .append( $( '<th>' ).text( 'Amount (min‒max)' ) )
                .append( $( '<th>' ).text( 'Scale' ) )
                .append( $( '<th>' ).text( 'Weight' ) )
            ) );

        entries.forEach( entry => {
            const itemNames = entry.value.items.map( o => o.item.replace( /^minecraft:/, '' ).replace( /_/g, ' ' ) );
            const itemsText = itemNames.join( ', ' );

            const firstId = entry.value.items[ 0 ].item.replace( /^minecraft:/, '' );
            const iconFile = 'Invicon_' + toIconName( firstId ) + '.png';
            const $img = $( '<img>' )
                .attr( 'src', filePath( iconFile ) )
                .attr( {
                    width: 20,
                    height: 20,
                    loading: 'lazy'
                } )
                .css( {
                    'vertical-align': 'middle',
                    'margin-right'  : '0.25em'
                } );

            const amt    = entry.value.amount.min + '‒' + entry.value.amount.max;
            const scale  = entry.value.scale;
            const weight = entry.weight;

            const $itemCell = $( '<td>' ).append( $img ).append( document.createTextNode( ' ' + itemsText ) );

            $table.append( $( '<tr>' )
                .append( $itemCell )
                .append( $( '<td>' ).text( amt ) )
                .append( $( '<td>' ).text( scale ) )
                .append( $( '<td>' ).text( weight ) )
            );
        } );

        $details.append( $table );
    } );
}

    // -------------------------- Main ------------------------------- //
    function init () {
        const host = document.querySelector( PLACEHOLDER_SELECTOR );
        if ( !host ) return; // Only activate where template is present

        const $wrapper   = $( '<div>' ).addClass( 'vault-altar-wrapper' );
        const $sliderRow = $( '<div>' ).addClass( 'vault-altar-slider' );

        const $label      = $( '<label>' ).attr( 'for', 'vault-altar-level' ).text( 'Vault Level: ' );
        const $valDisplay = $( '<span>' ).attr( 'id', 'vault-altar-level-val' ).text( '0' );
        const $input      = $( '<input>' ).attr( {
            id   : 'vault-altar-level',
            type : 'range',
            min  : 0,
            max  : 100,
            step : 1,
            value: 0
        } ).css( 'width', '100%' );

        $sliderRow.append( $label, $valDisplay, $input );
        $wrapper.append( $sliderRow );
        const $output = $( '<div>' ).attr( 'id', 'vault-altar-output' );
        $wrapper.append( $output );

        $( host ).empty().append( $wrapper );

        $.getJSON( mw.util.wikiScript( 'index' ), {
            title : JSON_PAGE,
            action: 'raw',
            ctype : 'application/json'
        } ).done( function ( data ) {
            const levels = Object.keys( data.LEVELS ).map( Number ).sort( ( a, b ) => a - b );
            $input.attr( { min: levels[ 0 ], max: levels[ levels.length - 1 ] } );

            function update () {
                const userVal = parseInt( $input.val(), 10 );
                const lvl = nearestLevel( levels, userVal );
                $valDisplay.text( userVal + ' (showing ' + lvl + ')' );
                renderLevel( data, String( lvl ), $output );
            }

            $input.on( 'input change', update );
            update();
        } ).fail( function () {
            $output.text( 'Failed to load Vault Altar data – please check that ' + JSON_PAGE + ' exists and is valid JSON.' );
        } );
    }

    $( init );

} )( mediaWiki, jQuery );