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
No edit summary
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
/*
( function ( mw, $ ) {
* Gadget: VaultAltarComponent
    'use strict';
* ----------------------------
* Activated only when a <div class="js-vault-altar" id="vault-altar-component"> is present.
* Loads Vault altar data from: MediaWiki:Vault_altar_ingredients.json
*/


(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.querySelector('.js-vault-altar#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;
    }


     $.getJSON(getRawURL(JSON_PAGE, 'application/json'))
     /** Return canonical file‑path URL for a given filename. */
      .done(data => initialise(host, data))
    function filePath ( filename ) {
      .fail(() => host.textContent = '❌ Could not load altar data.');
        return mw.util.getUrl( 'Special:FilePath/' + filename );
  });
    }


  function getRawURL(title, type) {
    /** Convert an item id like "iron_ingot" → "Iron_Ingot" */
    return mw.util.wikiScript() +
    function toIconName ( id ) {
      '?title=' + encodeURIComponent(title) +
        return id.split( '_' ).map( w => w.charAt( 0 ).toUpperCase() + w.slice( 1 ) ).join( '_' );
      '&action=raw&ctype=' + encodeURIComponent(type || 'text/plain');
    }
  }


  function initialise(root, data) {
    /**
    const levels = Object.keys(data).map(Number).sort((a, b) => a - b);
    * Render the output tables for a particular vault level.
     if (!levels.length) {
    * @param {Object} data – Parsed JSON object (the entire file).
      root.textContent = 'No data.';
    * @param {string} levelKey – The exact level key to show (e.g. "10").
      return;
    * @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;
     }
     }


     const header = $('<div>', { class: 'vault-altar-header' }).appendTo(root);
     Object.entries( levelData ).forEach( ( [ catName, entries ] ) => {
    header.append('<span>Vault Level </span>');
        const catId = 'vault-altar-cat-' + catName.toLowerCase().replace(/\s+/g, '-');
    const valueEl = $('<span>', { class: 'vault-altar-slider-value' }).appendTo(header);
        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' ) )
            ) );


    const slider = $('<input>', {
        entries.forEach( entry => {
      type: 'range',
            const itemNames = entry.value.items.map( o => o.item.replace( /^minecraft:/, '' ).replace( /_/g, ' ' ) );
      min: levels[0],
            const itemsText = itemNames.join( ', ' );
      max: levels[levels.length - 1],
      value: levels[0],
      class: 'vault-altar-level-slider'
    }).appendTo(header);


    const output = $('<div>', { class: 'vault-altar-output' }).appendTo(root);
            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'
                } );


    slider.on('input change', () => render(+slider.val()));
            const amt    = entry.value.amount.min + '' + entry.value.amount.max;
    render(levels[0]);
            const scale  = entry.value.scale;
            const weight = entry.weight;


    function render(level) {
            const $itemCell = $( '<td>' ).append( $img ).append( document.createTextNode( ' ' + itemsText ) );
      valueEl.text(level);
      output.empty();


      const entry = data[level];
            $table.append( $( '<tr>' )
      if (!entry) {
                .append( $itemCell )
         output.text('No data for this level.');
                .append( $( '<td>' ).text( amt ) )
         return;
                .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 );


      Object.keys(entry).forEach(category => {
        $.getJSON( mw.util.wikiScript( 'index' ), {
        const catBox = $('<div>', { class: 'vault-altar-category' }).appendTo(output);
            title : JSON_PAGE,
        $('<h3>').text(capitalise(category)).appendTo(catBox);
            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 ] } );


        const table = $('<table>', { class: 'vault-altar-table' }).appendTo(catBox);
            function update () {
        table.append('<thead><tr><th>Item</th><th>Amount</th></tr></thead>');
                const userVal = parseInt( $input.val(), 10 );
        const tbody = $('<tbody>').appendTo(table);
                const lvl = nearestLevel( levels, userVal );
                $valDisplay.text( userVal + ' (showing ' + lvl + ')' );
                renderLevel( data, String( lvl ), $output );
            }


        (entry[category] || []).forEach(row => {
            $input.on( 'input change', update );
          $('<tr>')
             update();
             .append($('<td>').text(row.item))
        } ).fail( function () {
             .append($('<td>').text(row.amount))
             $output.text( 'Failed to load Vault Altar data – please check that ' + JSON_PAGE + ' exists and is valid JSON.' );
            .appendTo(tbody);
         } );
         });
      });
     }
     }
  }


  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 );