Difference between revisions of "Module:Set gallery/functions"

From Yugipedia
Jump to: navigation, search
(Fix _imageName (and rename). Special thanks to Fngplg.)
(F.tracking, to track unused parameters and parameters that shouldn't be used.)
Line 293: Line 293:
 
                         :done()
 
                         :done()
 
     return tostring(galleryWrap);
 
     return tostring(galleryWrap);
 +
end
 +
 +
-------------
 +
--  Tracking:
 +
function F.tracking( frame, parameters )
 +
    local _parameters = { 1 , 'region' , 'set' , 'abbr' , 'rarity' , 'alt', 'debug' };
 +
    --  Don't want «{{{gallery}}}» to be used.
 +
    local counter = 0;
 +
    for i = 1, #_parameters do
 +
      if parameters[_parameter[i]] then
 +
          counter = counter + 1;
 +
        end
 +
    end
 +
    if #(frame.args) > counter then
 +
        --  There are parameters not being used or used empty.
 +
        return '[['..'Category:((Set gallery)) with parameters to be checked]]';
 +
    end
 
end
 
end
  

Revision as of 22:18, 24 August 2017

--<pre>
--[[
    ->  F                       //  ;
    ->  trim                    //  mw.text.trim;
    ->  split                   //  mw.text.split;
    ################
    # Function list:
    ################
    ->  localized_name          //  Get localized name;
    ->  categories              //  Generate categories;
    ->  header                  //  Generate page header;
    ->  gallery                 //  Generate gallery;
    ##  Internal functions:
    ->  _trim                   //  Trim text;
    ->  _link                   //  Link;
    ->  _quotes                 //  Wrap with quotes;
    ->  _gallerySection         //  
    ->  _galleryCard            //  
    ->  _galleryDesign          //  
    ->  _imageName              //  
]]
----------
--  Start:
----------
local F = {};
local trim  = mw.text.trim;
local split = mw.text.split;

------------------------
--  Get localized names:
function F.localized_name( name, language )
    if not mw.smw then  --  If not available, return.
        return '(<strong class="error">mw.smw module not found</strong>)';
    end
    local name_strip = name:gsub( '#', '' );    --  Strip «#».
    local result =  mw.smw.ask{ '[['..name_strip..']]', '?'..language..' name=', limit = 1, mainlabel = '-' };
    --  Process SMW resutlt:
    if result == nil or result == '' then
        return nil; --  No result found.
    end
    
    return result[1][1];    --  First entry.
end

---------------
--  Categories:
function F.categories( namespace, region, edition )
    local categories = ('[['..'Category:%s %s]]'):format( region, namespace );
    if edition then
        categories = categories..('[['..'Category:%s %s]]'):format( edition, namespace );
    end
    
    return categories;
end

----------------------
--  Build page header:
function F.header( frame, name, name_local, medium, region, edition, notEnglish, italics )
    local template = frame:expandTemplate{ title = medium..'SetGalleries' };    --  {{(OCG|TCG)SetGalleries}}.
    
    local html = mw.html.create( 'div' ):css('text-align', 'center')
            :tag('span'):css{
                                ['font-size']   = '120%',
                                ['font-weight'] = 'bold',
                                ['font-style']  = 'italic'
                            }
                :wikitext(_link( name ))
            :done()
        if notEnglish and name_local then
            html:tag('br'):done()
                :tag('span'):css{
                                    ['font-weight'] ='bold',
                                    ['font-style']  = italics
                                }
                    :wikitext(name_local)
                :done()
        end
        html:tag('br'):done()
            :wikitext(region)
        if edition then
            html:wikitext(' - '..edition)
        end
        html:allDone();
    
    return template..'\n'..tostring(html);
end

---------
--  Trim:
function _trim( s )
    if s and not(s:match('^%s*$')) then
        return trim( s );
    else
        return nil; --  If nil or empty.
    end
end

----------------------------
--  Link set and card names:
function _link( name, label )
    local name_strip = name:gsub( '#', '' );    --  Strip «#».
    local name_noDab = name;
    if not(name:match('%(2011%)') or name:match('%(series%)')) then --  Don't remove «(2011)» nor «(series)».
        name_noDab = split( name, ' %(' )[1];   --  Remove dab text.
    end
    
    return ('[[%s|%s]]'):format( name_strip, label or name_noDab );
end

---------------
--  Add quotes:
function _quotes( name, language )
    if name == nil then
        return '';  --  Return empty string; don't wrap, but return string.
    end
    if language == 'Japanese' or language == 'Chinese' then
        return '「'..name..'」';
    else 
        return '"'..name..'"';
    end
end

---------------------
--  Generate gallery:

--  # Main function:
function F.gallery( frame, g_table, rg, language, ed, abbr, rarity, alt, notEnglish )
    local out_t = {};
    local _abbrSection, _raritySection, _altSection;  --  Section info to be applied to card entries.
    for _, entry in ipairs(g_table) do
        --  Iterate over the table:
        if entry:match('^%s*!:') then
            -- It's a section; contains section info.
            out_t, _abbrSection, _raritySection, _altSection = _gallerySection( out_t, entry );
            
        elseif entry:match('^(%s*)$') then
            --  Nothing: empty line.
            
        else
            --  Card info.
            out_t = _galleryCard( out_t, entry, rg, language, ed, _abbrSection or abbr, _raritySection or rarity, _altSection or alt, notEnglish );
        end
    end

    local out_s = table.concat( out_t, '\n' );  --  Convert to string, to split.
    return _galleryDesign( frame, out_s );
end

--  # Auxiliary functions:
function _gallerySection( out_t, entry )
    --  For sections.
    local header;
    local _headerSection = entry:match('header::(.-);')
                        or entry:match('header::(.+)' );
    local _abbrSection   = entry:match(  'abbr::(.-);')
                        or entry:match(  'abbr::(.+)' );
    local _raritySection = entry:match('rarity::(.-);')
                        or entry:match('rarity::(.+)' );
    local _altSection    = entry:match(   'alt::(.-);')
                        or entry:match(   'alt::(.+)' );
    if _headerSection then
        header = mw.html.create( 'div' ):addClass('gallery-header'):attr('id', _headerSection)
                        :wikitext(_headerSection)
                 :done();
    end
    --  Send header to table:
    table.insert( out_t, ';;SECTIONSPLIT:;;'..tostring(header) );
    --  Return all values (table and info that will be used on the card entries):
    return out_t, _abbrSection, _raritySection, _altSection;
end

function _galleryCard( out_t, entry, rg, language, ed, abbr, rarity, alt, notEnglish )
    --  For card entries.
    --  Initialize vars:
    local _name, _name_localized, _number, _rarity, _typeCard, _alt; -- Standard info.
    local _name_alt, _name_localized_alt,
          _file, _extension, _description;  -- Alternate info.
    local _abbr = abbr;
    --  Load data:
    local r_list      = mw.loadData( 'Module:Set gallery/data' ).r_list;
    local rarity_list = mw.loadData( 'Module:Set gallery/data' ).rarity_list;
    
    --  Split info:
    local standard_values  = split( split( entry, '//' )[1] , ';');
    local alternate_values =        split( entry, '//' )[2];
    
    --  Fetch standard values:
    if abbr then
        _name   = _trim( standard_values[1] );  --  NOTE: Must never be nil!
        _rarity = _trim( standard_values[2] );
        _alt    = _trim( standard_values[3] );
    else
        _number = _trim( standard_values[1] );
        _name   = _trim( standard_values[2] );  --  NOTE: Must never be nil!
        _rarity = _trim( standard_values[3] );
        _alt    = _trim( standard_values[4] );
        _abbr   = split( _number or '', '%-' )[1];
    end
    --  # Handle rarity:
    local _r = (_rarity or rarity) and r_list[(_rarity or rarity):lower():gsub(' rare$', '')] or 'C';
    
    --  Fetch alternate values:
    if alternate_values then
        _file               =  alternate_values:match(       'file::(.-);')
                            or alternate_values:match(       'file::(.+)' );
        _extension          =  alternate_values:match(  'extension::(.-);')
                            or alternate_values:match(  'extension::(.+)' );
        _name_alt           =  alternate_values:match(       'name::(.-);')
                            or alternate_values:match(       'name::(.+)' );
        _name_localized_alt =  alternate_values:match('name%-local::(.-);')
                            or alternate_values:match('name%-local::(.+)' );
        _description        =  alternate_values:match('description::(.-);')
                            or alternate_values:match('description::(.+)' );
    end
    
    --  Build file and caption:
    local file, caption;
    --  # File:
    if _file then
        file = _file;
    else
        file = _imageName( _name )..'-'.._abbr:upper()..'-'..rg:upper()..'-'.._r;
        if _trim( ed ) then
            file = file..'-'..ed:upper();
        end
        if _alt or alt then
            file = file..'-'..(_alt or alt);
        end
        file = file..'.'..(_extension or 'png');    --  Add file extension after everything.
    end
    --  # Caption:
    caption = '('.._link( rarity_list[_r:lower()], _r )..')<br />'..(_name_alt or _quotes( _link( _name ), 'English' ));
    if notEnglish then
        caption = caption..'<br />'..(_name_localized_alt or _quotes( F.localized_name( _name, language ), language ));
    end
    if _description then
        caption = caption..'<br />'.._description;
    end
    if _number then
        caption = _link( _number )..' '..caption;    --  Append the card number.
    end
            
    --  Send processed entry to table: 
    table.insert( out_t, file..' | '..caption );
    return out_t;
end

function _imageName( name )
    local _nameSMW;
    local name_strip = name:gsub( '#', '' );    --  Strip «#».
    if not mw.smw then
        --  If not available.
    else 
        local result =  mw.smw.ask{ '[[' ..name_strip.. ']]', '?Page name=', limit = 1, mainlabel = '-' };
        --  Process SMW resutlt:
        if result and _trim( result[1][1] ) then   --  Returns table, but check if its first index is nil or empty.
            _nameSMW = result[1][1];
        end
    end
    
    local imageName = (split( _nameSMW or name_strip, ' %(' )[1])
        :gsub( ' ' , '') --  White space;
        :gsub( '%-', ''):gsub( '–' , '')
        :gsub( ',' , ''):gsub( '%.', ''):gsub( ':' , '')
        :gsub( '\'', ''):gsub( '"' , ''):gsub( '&' , '')
        :gsub( '%?', ''):gsub( '!' , '')
        :gsub( '%%', ''):gsub( '=' , '')
        :gsub( '/' , ''):gsub( '\\', '')
        :gsub( '☆' , ''):gsub( '・' , '');
        
    return imageName;
end

function _galleryDesign( frame, out_s )
    local gallery   = '';
    local out_split = split( out_s, ';;SECTIONSPLIT:;;', true );
    for _, v in ipairs(out_split) do
        local header  = v:match('(<div.+/div>\n)');
        local content = v:match('<div.+/div>\n(.+)') or v;
        if header then
            gallery = gallery.._trim( header )..'\n';
        end
        if content then
            content = '<gallery widths="175px" position="center" captionalign="center">\n'..
                            _trim( content )..
                      '\n</gallery>';
            gallery = gallery..frame:preprocess(content)..'\n';
        end
    end

    local galleryWrap = mw.html.create( 'div' ):addClass('card-galleries')
                            :wikitext(gallery)
                        :done()
    return tostring(galleryWrap);
end

-------------
--  Tracking:
function F.tracking( frame, parameters )
    local _parameters = { 1 , 'region' , 'set' , 'abbr' , 'rarity' , 'alt', 'debug' };
    --  Don't want «{{{gallery}}}» to be used.
    local counter = 0; 
    for i = 1, #_parameters do
       if parameters[_parameter[i]] then
           counter = counter + 1;
        end
    end
    if #(frame.args) > counter then
        --  There are parameters not being used or used empty.
        return '[['..'Category:((Set gallery)) with parameters to be checked]]';
    end
end

return F;

--</pre>