Module:Set gallery/functions

From Yugipedia
Jump to: navigation, search
Module documentation[create]
--<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;
	->  tracking                //  Tracking categories;
	##  Internal functions:
	->  _trim                   //  Trim text;
	->  _link                   //  Link;
	->  _quotes                 //  Wrap with quotes;
	->  _gallerySection         //  Handle section header;
	->  _galleryCard            //  Handle card entry;
	->  _imageName              //  Card imaga name for the file
	->  _galleryDesign          //  Format gallery code;
]]
----------
--  Start:
----------
local F = {};
local trim  = mw.text.trim;
local split = mw.text.split;

-----------------------
-- Tracking categories:
local trackingCategories = {}

------------------------
--  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 ); --  If not nil nor 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 or (_headerSection:lower():match('reprint') and 'Reprint');
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::(.+)' );
		_abbr2              = alternate_values:match(        'abbr::(.-);')
						   or alternate_values:match(        'abbr::(.+)' );
		_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

	for k,v in pairs{
		['file']        = _file,
		['abbr']        = _abbr2,
		['name']        = _name_alt,
		['name-local']  = _name_localized_alt,
		['rarity']      = _rarityAlt,
		['description'] = _description,
	} do
		if _trim( v ) then
			table.insert(
				trackingCategories,
				( '[[Category:((Set gallery)) transclusion using alt values (%s)]]' )
					:format( k )
			)
		end
	end
	
	--  Build file and caption:
	local file, caption;
	--  # File:
	if _file then
		file = _file;
	else
		file = _imageName( _name )..'-'..(_abbr2 or _abbr:gsub( '/', '' ) ):upper()..'-'..rg:upper()..'-'.._r;
		if _trim( ed ) then
			ed = ((ed == 'reprint') and 'Reprint') or ed:upper();
			file = file..'-'..ed;
		end
		if _alt or alt then
			file = file..'-'..(_alt or alt);
		end
		file = ( file..'.'..(_extension or 'png') ):gsub( '[/:]', '' );    --  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.

		if _abbr2 then
			table.insert(
				trackingCategories,
				'[[Category:((Set gallery)) transclusion using alt value abbr and a card number]]'
			)
		end
	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( '☆' , ''):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 _trim( content ) then
			content = '<gallery heights="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)
		:wikitext( table.concat( trackingCategories ) )
	:done();
	return tostring(galleryWrap);
end

-------------
--  Tracking:
function F.tracking( frameArgs )
	local _parameters = {
		1,  --  Don't want «{{{gallery}}}» to be used.
		['region']  = 'region',
		['set']     = 'set',
		['abbr']    = 'abbr',
		['rarity']  = 'rarity',
		['alt']     = 'alt',
		['debug']   = 'debug'
	}
	for key, value in pairs( frameArgs ) do
	   if not(_parameters[key]) or not(_trim( value )) then
		   --  There are parameters not being used or used empty.
		   return '[[Category:((Set gallery)) with parameters to be checked]]';
		end
	end
end

return F;

--</pre>