Module:InfoboxBuilder: Difference between revisions

From Sekaipedia
Content added Content deleted
(display ? and edit if empty and not hidden)
(changed to options table, applies to headers, images, and rows)
Line 21: Line 21:
},
},
params = {
params = {
{ name = 'bg color' },
['bg color'] = {},
{ name = 'text color' }
['text color'] = {}
},
},
paramnames = { 'bg color', 'text color' },
param_names = { 'bg color', 'text color' },
args = {},
raw_args = {},
final_args = {},
proc_args = {},
proto_infobox = {},
infobox = mw.html.create('table'):addClass('infobox'),
infobox = mw.html.create('table'):addClass('infobox'),
finished = false
finished = false
Line 118: Line 117:


--- Sets both the text and background color of the header
--- Sets both the text and background color of the header
-- @param param string
-- @param param_name string
-- Parameter name that helps map the colors
-- Parameter name that helps map the colors
-- @param color_table { text, bg }
-- @param color_table { text, bg }
-- text string
-- text string
Line 127: Line 126:
-- @return self
-- @return self
-- The current object
-- The current object
function InfoboxBuilder:setHeaderColorsByParam(param, color_table)
function InfoboxBuilder:setHeaderColorsByParam(param_name, color_table)
if param == nil then
if param_name == nil then
error("Parameter name must not be nil")
error("Parameter name must not be nil")
elseif color_table == nil then
elseif color_table == nil then
Line 134: Line 133:
end
end
local raw_param_value = self.args[param]
local raw_param_value = self.raw_args[param_name]
local colors = color_table[raw_param_value]
local colors = color_table[raw_param_value]
Line 165: Line 164:
error("name must not be nil or empty")
error("name must not be nil or empty")
end
end
if self.paramnames[v.name] then
if self.param_names[v.name] then
error("name cannot be duplicate")
error("name cannot be duplicate")
end
end
Line 174: Line 173:
default = v.default
default = v.default
}
}
table.insert(self.paramnames, v.name)
table.insert(self.param_names, v.name)
end
end
Line 188: Line 187:
for k,v in pairs(args) do
for k,v in pairs(args) do
if v ~= '' then
if v ~= '' then
self.args[k] = v
self.raw_args[k] = v
end
end
end
end
if self.args['bg color'] then
if self.raw_args['bg color'] then
self:setHeaderBackgroundColor(self.args['bg color'])
self:setHeaderBackgroundColor(self.raw_args['bg color'])
end
end
if self.args['text color'] then
if self.raw_args['text color'] then
self:setHeaderTextColor(self.args['text color'])
self:setHeaderTextColor(self.raw_args['text color'])
end
end
Line 203: Line 202:


--- Gets the content associated with a parameter
--- Gets the content associated with a parameter
-- @param param string
-- @param param_name string
-- The param name, not nil or empty
-- The param name, not nil or empty
-- @return content string
-- @return content string
-- A string containing the content
-- A string containing the content
function InfoboxBuilder:getContent(param)
function InfoboxBuilder:getContent(param_name)
if param == nil or param == "" then
if param_name == nil or param_name == "" then
error("Param must not be nil or empty")
error("Param must not be nil or empty")
end
end
if self.final_args[param] then
if self.proc_args[param_name] then
return self.final_args[param]
return self.proc_args[param_name]
end
end
local content = nil
local content = nil
local current_param = self.params[param]
local current_param = self.params[param_name]
if current_param == nil then
if current_param == nil then
error(string.format("No such param: %s", param))
error(string.format("No such param with name: %s", param_name))
end
end
local raw_param_value = self.args[param] or current_param.default
local raw_param_value = self.raw_args[param_name] or current_param.default
if raw_param_value == nil then
if raw_param_value == nil then
Line 237: Line 236:
end
end
self.final_args[param] = content
self.proc_args[param_name] = content
return content
return content
end
end

--- Determines if the row should be shown based of a list of param names
-- @param param_names { param_name, ... }
-- param_name string
-- The param name
-- @return should_show boolean
function InfoboxBuilder:shouldShow(param_names)
if param_names and #param_names > 0 then
local actual_values = {}
for i,v in ipairs(param_names) do
table.insert(actual_values, self:getContent(v))
end
if #actual_values == 0 then
return false
end
end
return true
end



--- Adds a header
--- Adds a header
-- @param arg { content, attr, colspan, rowspan, css }
-- @param arg { content, attr, colspan, rowspan, css }
-- content string or nil The wikitext to be rendered
-- content string or nil
-- attr {...} or nil The attributes of the cell in table form
-- The wikitext to be rendered
-- colspan number or nil The colspan of the cell
-- attr {...} or nil
-- roswpan number or nil The rowspan of the cell
-- The attributes of the cell in table form
-- css {...} or nil The css of the cell in table form
-- colspan number or nil
-- The colspan of the cell
-- roswpan number or nil
-- The rowspan of the cell
-- css {...} or nil
-- The css of the cell in table form
-- @param options { hideIfEmpty }
-- hideIfEmpty { param_name, ... }
-- param_name string
-- The param_name that will be used to check if corresponding
-- content is nil
-- @return self
-- @return self
-- The current object
-- The current object
function InfoboxBuilder:addHeader(arg)
function InfoboxBuilder:addHeader(arg, options)
if options then
if not self:shouldShow(options.hideIfEmpty) then
return self
end
end
self:addSpacer()
self:addSpacer()
Line 286: Line 322:


--- Adds an image, or switchable images
--- Adds an image, or switchable images
-- @param ... { { tag, content, title }, ... }
-- @param cols { { tag, content, title }, ... }
-- tag "artd" or "td" Whether or not an it is based off a parameter
-- tag "artd" or "td"
-- content string The content or the parameter name
-- Whether or not an it is based off a parameter
-- title string or nil The title, if using switchable images
-- content string
-- The content or the parameter name
-- title string or nil
-- The title, if using switchable images
-- @param options { hideIfEmpty }
-- hideIfEmpty { param_name, ... }
-- param_name string
-- The param_name that will be used to check if corresponding
-- content is nil
-- @return self
-- @return self
-- The current object
-- The current object
function InfoboxBuilder:addImage(...)
function InfoboxBuilder:addImage(cols, options)
if options then
local argt = ...
if not self:shouldShow(options.hideIfEmpty) then
return self
end
end
local _cell = self.infobox:tag('tr'):tag('td'):css('text-align', 'center')
local _cell = self.infobox:tag('tr'):tag('td'):css('text-align', 'center')
Line 299: Line 347:
local actual_args = {}
local actual_args = {}
for _,v in ipairs(argt) do
for _,v in ipairs(cols) do
local c = v.content
local c = v.content
if v.tag == 'argtd' then
if v.tag == 'argtd' then
Line 333: Line 381:


--- Adds a row, with columns up to 30 columns spanned
--- Adds a row, with columns up to 30 columns spanned
-- @param should_hide boolean
-- The row will be hidden if all varying columns are nil
-- @param cols { { tag, content, hide, attr, colspan, rowspan, css }, ... }
-- @param cols { { tag, content, hide, attr, colspan, rowspan, css }, ... }
-- tag "th", "td", "argth", "argtd"
-- tag "th", "td", "argth", "argtd"
-- A string containing one of the above, "th" or
-- A string containing one of the above, "th" or "td" uses
-- "td" uses content as the wikitext, "argth" or
-- content as the wikitext, "argth" or "argtd" uses content as
-- "argtd" uses content as the parameter name
-- the parameter name to produce the suitable content
-- content string
-- to produce the suitable content
-- content string Content to be used as wikitext or a parameter
-- Content to be used as wikitext or a parameter name
-- name
-- attr {...} or nil
-- attr {...} or nil The attributes of the cell in table form
-- The attributes of the cell in table form
-- colspan number or nil The colspan of the cell
-- colspan number or nil
-- rowspan number or nil The rowspan of the cell
-- The colspan of the cell
-- css {...} or nil The css of the cell in table form
-- rowspan number or nil
-- The rowspan of the cell
-- css {...} or nil
-- The css of the cell in table form
-- @param options { hideIfEmpty }
-- hideIfEmpty { param_name, ... }
-- param_name string
-- The param_name that will be used to check if corresponding
-- content is nil
-- @return self
-- @return self
-- The current object
-- The current object
function InfoboxBuilder:addRow(should_hide, cols)
function InfoboxBuilder:addRow(cols, options)
if options then
local actual_values = {}
if not self:shouldShow(options.hideIfEmpty) then
return self
for i,v in ipairs(cols) do
end
if v.tag == 'argth' or v.tag == 'argtd' then
end
table.insert(actual_values, self:getContent(v.content))
end
end
if should_hide and #actual_values == 0 then
return self
end
local _row = self.infobox:tag('tr')
local _row = self.infobox:tag('tr')

Revision as of 22:32, 26 June 2021

This module creates an infobox using the builder pattern. All infoboxes using this module can be found at Category:Infobox modules.

Building an infobox

For an infobox to be built without errors, certain essential functions must be called before others. The following table details groups of functions and their priorities. The lower the number, the higher the priority. The functions setHeaderTextColor() and setHeaderBackgroundColor() are not required, but their CSS changes will not be applied if called later. In addition, the functions that add rows to the table, addHeader(), addImage(), and addRow() are not all required, but is it recommended to use at least addHeader() and addRow().

Core function priority
Priority Functions
1
  • new
2
  • setParams
  • setArgs
3
  • processArgs
4
  • setHeaderTextColor
  • setHeaderBackgroundColor
5
  • setName
  • addHeader
  • addImage
  • addRow
6
  • tostring

Import the module

local InfoboxBuilder = require('Module:InfoboxBuilder')

Unpack the frame arguments

function p.main(frame)
	local args = frame:getParent().args
	...

Create the infobox object

local infobox = InfoboxBuilder.new()

Set the infobox name

Setting the infobox name sets the template that the infobox links to inside of the navbar.

infobox:setName('Infobox')

Define the parameters

When defining the parameters, the arguments will be processed when given a function or table. fn is an optional processing function or table that will transform the raw argument value into a specific format. An optional default value for the raw argument can be set using the default option.

An example of using fn would be to have fn be a function that splits a comma separated list into a table in Lua.

infobox:setParams {
	...
}

Pass in the arguments

infobox:setArgs(args)

Process the arguments

Processing the arguments will set default value (if it exists) and turn the raw argument passed in from setArgs(args) into a processed format for each parameter. This step is required or else the infobox will not work.

infobox:processArgs()

Specify a category map

A category map can be optionally set. This uses the processed argument and generates the correct categories.

infobox:setCategoryMap({
	...
})

Prepare

Create the look of the infobox by adding headers, images, or rows. If the values shown in these cells use values from parameters, an optional postprocessing function or table fn will transform the processed arguments for display purposes.

-- add a header or subheader
infobox:addHeader(
	{...},
	{...}
)

-- add an image
infobox:addImage(
	{...},
	{...}
)

-- add a row
infobox:addRow(
	{...},
	{...}
)

Build

To build the infobox from data into an HTML table, call the tostring() function.

infobox:tostring()

Get the categories from the category map

To get the categories, call the getCategories() function.

infobox:getCategories()

Functions

For the following functions, assume an InfoboxBuilder object called "infobox" already exists.

local infobox = InfoboxBuilder.new()

Public functions

new

This function is required.

InfoboxBuilder.new()

Creates a new InfoboxBuilder object.

↓ Jump to definition

setName

This function is required.
This function is chainable.

infobox:setName(arg)
arg

arg should be a string. Setting the infobox name will link the navbar to the correct template page and template talk page.

↓ Jump to definition

setHeaderTextColor

This function is optional.
This function is chainable.

infobox:setHeaderTextColor(arg)
arg

arg should be a string that contains a valid CSS color (hex code, rgb value, hsl value, etc.). Calling this function will change the color of the text in the infobox's headers and subheaders. The changes will not apply to headers added before this function is called, so it is recommended to call this function early.

↓ Jump to definition

setHeaderBackgroundColor

This function is optional.
This function is chainable.

infobox:setHeaderBackgroundColor(arg)
arg

arg should be a string that contains a valid CSS color (hex code, rgb value, hsl value, etc.). Calling this function will change the background color of the infobox's headers and subheaders. The changes will not apply to headers added before this function is called, so it is recommended to call this function early.

↓ Jump to definition

setParams

This function is required.
This function is chainable.

infobox:setParams(...)

This function sets the valid parameters, their default values, and their formatting.

The arguments passed in should be tables of format:

{
	name = <paramName>,
	fn = <processingFn>,
	default = <default>
}
paramName

paramName should be a valid string that is unique. This name serves the key used to grab the raw values from the args table passed in from setArgs(). It also serves as the key for each parameter and will be referenced later.

processingFn

processingFn should be a function or a table that transforms the raw value of the argument passed in. This value is optional.

A collection of predefined processing functions can be found at Module:ProcessingFunctions.

default

default should be a string that serves as the default value if no raw value is present for the key in the args table. This value is optional.

↓ Jump to definition

setArgs

This function is required.
This function is chainable.

infobox:setArgs(args)
args

args should be a table with key value pairs representing parameter names and values.

↓ Jump to definition

getRawArgs

infobox:getRawArgs()

This function returns the "private" rawArgs associative array containing the raw values passed in from setArgs().

↓ Jump to definition

getProcessedArgs

infobox:getProcessedArgs()

This function returns the "private" procArgs associative array after being processed.

↓ Jump to definition

getArgs

infobox:getArgs(which)
which

which should be a string that is either "raw" or "processed" for the raw argument values or processed argument values, respectively.

This function returns the "private" rawArgs or procArgs associative arrays depending on the value of which.

↓ Jump to definition

setCategoryMap

This function is optional.
This function is chainable.

infobox:setCategoryMap(catMap)
catMap

catMap should be a table of tables, where the key of the outer table corresponds with a parameter name and the key of the inner tables correspond with possible values of the associated parameter. The inner table values should be the category name related to each parameter value.

↓ Jump to definition

getCategories

infobox:getCategories()

This function returns a string with autogenerated categories in wikitext form.

↓ Jump to definition

processArgs

This function is required.
This function is chainable.

infobox:processArgs()

This function processes the all the arguments passed in with the given processing functions defined when setting parameters.

↓ Jump to definition

addHeader

This function is optional, but recommended.
This function is chainable.

infobox:addHeader(arg, options)

This functions adds a header or subheader to the infobox, depending on the option set.


arg

arg should be a table of the following format:

{
	tag = <tag>,
	content = <content>,
    fn = <displayFn>,
	attr = <attr>,
	colspan = <colspan>,
	rowspan = <rowspan>,
	css = <css>
}
tag

tag should be a string of value "argth" or "th".

content

When tag is set to "th", content should contain the wikitext that will show up.

When tag is set to "argth", content should be a string or table of parameter names. This value will be passed into displayFn if it is set.

displayFn

displayFn should be a function that transforms one or more processed arguments (based on content into something that can be displayed (ex. an HTML list). The order of the parameters in this function is the same as the order of content, if content is a table. This value is optional.

A collection of predefined display functions can be found at Module:DisplayFunctions.

attr

attr should be a table containing HTML attributes. The value gets passed into the mw.html:attr() function. This value is optional.

colspan

colspan should be a number or string denoting the number of columns this header spans. This value is optional.

rowspan

rowspan should be a number or string denoting the number of rows this header spans. This value is optional.

css

css should be a table of CSS names and values. The value gets passed into the mw.html:css() function. This value is optional.


options

options should be a table of the following format:

{
	hideIfEmpty = <hideIfEmpty>,
	subheader = <subheader>
}
hideIfEmpty

hideIfEmpty should be a table containing strings of parameter names. If all values for those parameters are empty, then the header or subheader is hidden. This value is optional.

subheader

subheader should be a boolean denoting whether the header should be a subheader or not. The default value is false. This value is optional.

↓ Jump to definition

addImage

This function is optional, but recommended.
This function is chainable.

infobox:addImage(cols, options)

This function adds a single image or multiple images inside of a row. For multiple images, it selectively hides all but one image using TabberNeue.


cols

cols should be a table that is a numeric array. Each entry in this table should have the following format:

{
	tag = <tag>,
	content = <content>,
    fn = <displayFn>,
	tabName = <tabName>,
    required = <required>
}
tag

tag should be a string of value "argtd" or "td".

content

When tag is set to "td", content should be a string that shows up as the wikitext.

When tag is set to "argtd", content should be a string or table of parameter names. This value will be passed into displayFn if it is set.

displayFn

displayFn should be a function that transforms one or more processed arguments (based on content into something that can be displayed (ex. an HTML list). The order of the parameters in this function is the same as the order of content, if content is a table. This value is optional.

tabName

tabName should be a string if there are multiple images. The value of this does nothing if there's only one image.

required

required should be a boolean if the tab is required. This means that even if no value is provided, the tab will show up with a '?'.


options

options should be a table of the following format:

{
	hideIfEmpty = <hideIfEmpty>
}
hideIfEmpty

hideIfEmpty should be a tablecontaining strings of parameter names. If all values for those parameters are empty, then the image section is hidden. This value is optional.

↓ Jump to definition

addRow

This function is optional, but recommended.
This function is chainable.

infobox:addRow(cols, options)

This function adds anywhere from 1 to 30 cells to a row. The colspan for each cell is automatically set to be evenly split so that all cells are the same width. The exception is when there are two cells, where the first cell spans 12 columns and the second cell spans 18 cells.


cols

cols should be a table that is a numeric array. Each entry in this table should have the following format:

{
	tag = <tag>,
	content = <content>,
    fn = <displayFn>,
	attr = <attr>,
	colspan = <colspan>,
	rowspan = <rowspan>,
	css = <css>,
	class = <class>,
	cssFns = <cssFns>,
	classFns = <classFns>
}
tag

tag should be a string of value "argth", "argtd", "th", or "td".

content

When tag is set to "td" or "th", content should contain the wikitext that will show up.

When tag is set to "argtd" or "argth", content should be a string or table of parameter names. This value will be passed into displayFn if it is set.

displayFn

displayFn should be a function that transforms one or more processed arguments (based on content into something that can be displayed (ex. an HTML list). The order of the parameters in this function is the same as the order of content, if content is a table. This value is optional.

A collection of predefined display functions can be found at Module:DisplayFunctions.

attr

attr should be a table containing HTML attributes. The value gets passed into the mw.html:attr() function. This value is optional.

colspan

colspan should be a number or string denoting the number of columns this header spans. This value is optional.

rowspan

rowspan should be a number or string denoting the number of rows this header spans. This value is optional.

css

css should be a table of CSS names and values. The value gets passed into the mw.html:css() function. This value is optional.

class

class should be either a string with a class name or table (numeric array) containing class names. Each class name gets passed into the mw.html:addClass() function. This value is optional.

cssFns

cssFns should be a table of functions. Each function takes the processed value of parameter content as input and should output a valid CSS table. This value only applies to cells with tag "argth" or "argtd". This value is optional.

classFns

classFns should be a table of functions. Each function takes the processed value of parameter content as input and should output a class name string. This value only applies to cells with tag "argth" or "argtd". This value is optional.


options

options should be a table of the following format:

{
	hideIfEmpty = <hideIfEmpty>,
	defaultCss = <defaultCss>
}
hideIfEmpty

hideIfEmpty should be a table containing strings of parameter names. If all values for those parameters are empty, then the cell is hidden. This value is optional.

defaultCss

defaultCss should be a table of CSS names and values. This CSS applies to all cells in this row. This value is optional.

↓ Jump to definition

tostring

This function is required.

infobox:tostring()

This function "finishes" the infobox and returns an output HTML table with all styles automatically applied from Template:Infobox/styles.css. In order to generate an infobox, this function must be called.

↓ Jump to definition

Private functions

While these are not necessarily "private", these functions are not intended to be called externally.

getContent

infobox:getContent(paramName)

Gets the content for display for a specified parameter. If the value for a parameter has not been postprocessed, then the dFunc for that parameter, if it exists, will be called.

↓ Jump to definition

shouldShow

infobox:shouldShow(paramNames)

This is a helper function to tell if a certain cell should be visible depending on the parameter names given. If all values for the parameters given have no value, then a cell should not show.

↓ Jump to definition

addSpacer

infobox:addSpacer()

This function sets up the 30 column layout by inserting an empty row. It also serves as a spacer.

↓ Jump to definition

addLinks

infobox:addLinks()

This function adds the navbar at the end of the infobox. This navbar contains links to the template page and the template talk page for this infobox. This uses the page using the value passed in from the setName() function.

↓ Jump to definition


local InfoboxBuilder = {}
InfoboxBuilder.__index = InfoboxBuilder
InfoboxBuilder.__tostring = InfoboxBuilder.tostring

local tagmap = {
	th = 'th',
	td = 'td',
	argth = 'th',
	argtd = 'td'
}

--- Create the infobox
-- @return obj metatable
--             A metatable describing the infobox
function InfoboxBuilder.new()
	local obj = setmetatable({
		name = '',
		headerColors = {
			text = '#000',
			bg   = 'transparent'
		},
		params = {
			['bg color'] = {},
			['text color'] = {}
		},
		param_names = { 'bg color', 'text color' },
		raw_args = {},
		proc_args = {},
		infobox = mw.html.create('table'):addClass('infobox'),
		finished = false
	}, InfoboxBuilder)

	return obj
end

--- Set the infobox name, for use with bottom links
-- @param arg string
--            Name of the template, not nil or empty
-- @return self
--         The current object
function InfoboxBuilder:setName(arg)
	if arg == nil or arg == '' then
		error("Template name must not be nil or empty")
	end
	
	self.name = arg
	
	return self
end

--- Set the width of the infobox
-- @param arg string
--            Width of the infobox, should be a valid value for the CSS "width" 
--            property, not nil or empty
-- @return self
--         The current object
function InfoboxBuilder:setWidth(arg)
	if arg == nil or arg == '' then
		error("Width must not be nil or empty")
	end
	
	self.infobox:css('width', arg)
	
	return self
end

--- Set the text color of the header
-- @param arg string
--            Text color of the header, should be a valid value for the CSS 
--            "color" property, not nil or empty
-- @return self
--         The current object
function InfoboxBuilder:setHeaderTextColor(arg)
	if arg == nil or arg == '' then
		error("Header text color must not be nil or empty")
	end
	
	self.headerColors.text = arg
	
	return self
end

--- Set the background color of the header
-- @param arg string
--            Background color of the header, should be a valid value for the 
--            CSS "background-color" property, not nil or empty
-- @return self 
--         The current object
function InfoboxBuilder:setHeaderBackgroundColor(arg)
	if arg == nil or arg == '' then
		error("Header background color must not be nil or empty")
	end
	
	self.headerColors.bg = arg
	
	return self
end

--- Sets both the text and background color of the header
-- @param arg { text, bg }
--        text string
--             Same as setHeaderTextColor
--        bg   string
--             Same as setHeaderBackgroundColor
-- @return self
--         The current object
function InfoboxBuilder:setHeaderColors(arg)
	if arg == nil then
		error("Header colors must not be nil")
	end
	
	self:setHeaderTextColor(arg.text)
	self:setHeaderBackgroundColor(arg.bg)
	
	return self
end

--- Sets both the text and background color of the header
-- @param param_name string
--                   Parameter name that helps map the colors
-- @param color_table { text, bg }
--        text string
--             Same as setHeaderTextColor
--        bg string
--             Same as setHeaderBackgroundColor
-- @return self
--         The current object
function InfoboxBuilder:setHeaderColorsByParam(param_name, color_table)
	if param_name == nil then
		error("Parameter name must not be nil")
	elseif color_table == nil then
		error("Header color table must not be nil")
	end
	
	local raw_param_value = self.raw_args[param_name]
	local colors = color_table[raw_param_value]
	
	if colors == nil then
		return self
	end
	
	self:setHeaderTextColor(colors.text)
	self:setHeaderBackgroundColor(colors.bg)
	
	return self
end

--- Sets the infobox params
-- @param ... {{ name, func, default, should_hide }, ...}
--        name    string
--                The name of the parameter, not nil, cannot be duplicate
--        func    function, table or string
--                A function that accepts the parameter as an argument and
--                returns a string, OR
--                A table that has the parameter as a key, OR
--                An empty string
--        default string or nil
--                The default value if no argument is given
-- @return self
--         The current object
function InfoboxBuilder:setParams(...)
	for i, v in ipairs(...) do
		if v.name == nil and v.name == "" then
			error("name must not be nil or empty")
		end
		if self.param_names[v.name] then
			error("name cannot be duplicate")
		end
		
		self.params[v.name] = {
			['type'] = type(v.func),
			func = v.func,
			default = v.default
		}
		table.insert(self.param_names, v.name)
	end
	
	return self
end

--- Sets the infobox arguments
-- @param args Frame
--             A frame object, passed in when invoked
-- @return self
--         The current object
function InfoboxBuilder:setArgs(args)
	for k,v in pairs(args) do
		if v ~= '' then
			self.raw_args[k] = v
		end
	end
	
	if self.raw_args['bg color'] then
		self:setHeaderBackgroundColor(self.raw_args['bg color'])
	end
	if self.raw_args['text color'] then
		self:setHeaderTextColor(self.raw_args['text color'])
	end
	
	return self
end

--- Gets the content associated with a parameter
-- @param param_name string
--                   The param name, not nil or empty
-- @return content string
--                 A string containing the content
function InfoboxBuilder:getContent(param_name)
	if param_name == nil or param_name == "" then
		error("Param must not be nil or empty")
	end
	
	if self.proc_args[param_name] then
		return self.proc_args[param_name]
	end
	
	local content = nil
	local current_param = self.params[param_name]
	
	if current_param == nil then
		error(string.format("No such param with name: %s", param_name))
	end
	
	local raw_param_value = self.raw_args[param_name] or current_param.default
	
	if raw_param_value == nil then
		return raw_param_value
	end
	
	if current_param['type'] == 'function' then
		content = current_param.func(raw_param_value)
	elseif current_param['type'] == 'table' then
		content = current_param.func[raw_param_value]
	else
		content = raw_param_value
	end
	
	self.proc_args[param_name] = content
	
	return content
end

--- Determines if the row should be shown based of a list of param names
-- @param param_names { param_name, ... }
--        param_name string
--                   The param name
-- @return should_show boolean
function InfoboxBuilder:shouldShow(param_names)
    if param_names and #param_names > 0 then
    	local actual_values = {}
	    for i,v in ipairs(param_names) do
	        table.insert(actual_values, self:getContent(v))
	    end
        
        if #actual_values == 0 then
            return false
        end
    end
    
    return true
end


--- Adds a header
-- @param arg { content, attr, colspan, rowspan, css }
--        content string or nil
--                The wikitext to be rendered
--        attr    {...} or nil 
--                The attributes of the cell in table form
--        colspan number or nil
--                The colspan of the cell
--        roswpan number or nil
--                The rowspan of the cell
--        css     {...} or nil
--                The css of the cell in table form
-- @param options { hideIfEmpty }
--        hideIfEmpty { param_name, ... }
--        param_name string
--                   The param_name that will be used to check if corresponding 
--                   content is nil
-- @return self
--         The current object
function InfoboxBuilder:addHeader(arg, options)
    if options then
        if not self:shouldShow(options.hideIfEmpty) then
        	return self
    	end
    end
    
	self:addSpacer()
	
	local _cell = self.infobox:tag('tr'):tag('th'):attr('colspan', 30)
	_cell:css({
		['text-align']       = 'center',
		['background-color'] = self.headerColors.bg,
		['color']            = self.headerColors.text
	})
	
	if arg.attr then
		_cell:attr(arg.attr)
	end
	if arg.colspan then
		_cell:attr('colspan', arg.colspan)
	end
	if arg.rowspan then
		_cell:attr('rowspan', arg.rowspan)
	end
	if arg.css then
		_cell:css(arg.css)
	end
	
	if arg.tag == 'th' then
		_cell:wikitext(arg.content)
	elseif arg.tag == 'argth' then
		_cell:wikitext(self:getContent(arg.content))
	end
	
	self:addSpacer()
	
	return self
end

--- Adds an image, or switchable images
-- @param cols { { tag, content, title }, ... }
--        tag     "artd" or "td"
--                Whether or not an it is based off a parameter
--        content string
--                The content or the parameter name
--        title   string or nil
--                The title, if using switchable images
-- @param options { hideIfEmpty }
--        hideIfEmpty { param_name, ... }
--        param_name string
--                   The param_name that will be used to check if corresponding 
--                   content is nil
-- @return self
--         The current object
function InfoboxBuilder:addImage(cols, options)
	if options then
        if not self:shouldShow(options.hideIfEmpty) then
        	return self
    	end
    end
	
	local _cell = self.infobox:tag('tr'):tag('td'):css('text-align', 'center')
	local content = '?'
	
	local actual_args = {}
	for _,v in ipairs(cols) do
		local c = v.content
		if v.tag == 'argtd' then
			c = self:getContent(c)
		end
		
		if c ~= nil then
			table.insert(actual_args, { title = v.title, content = c })
		end
	end
	
	if #actual_args == 0 then
		return self
	elseif #actual_args < 2 then
		content = actual_args[1].content
	else
		local t = {}
		for _,v in ipairs(actual_args) do
			table.insert(t, v.title .. '=' .. v.content)
		end
		
		content = mw.getCurrentFrame():callParserFunction({
					name = '#tag',
					args = { 'tabber', table.concat(t, '|-|') }
				})
	end
	
	_cell:attr('colspan', 30)
	_cell:wikitext(content)
	
	return self
end

--- Adds a row, with columns up to 30 columns spanned
-- @param cols    { { tag, content, hide, attr, colspan, rowspan, css }, ... }
--        tag     "th", "td", "argth", "argtd"
--                A string containing one of the above, "th" or "td" uses 
--                content as the wikitext, "argth" or "argtd" uses content as
--                the parameter name to produce the suitable content
--        content string
--                Content to be used as wikitext or a parameter name
--        attr    {...} or nil
--                The attributes of the cell in table form
--        colspan number or nil
--                The colspan of the cell
--        rowspan number or nil
--                The rowspan of the cell
--        css     {...} or nil
--                The css of the cell in table form
-- @param options { hideIfEmpty }
--        hideIfEmpty { param_name, ... }
--        param_name string
--                   The param_name that will be used to check if corresponding 
--                   content is nil
-- @return self
--         The current object
function InfoboxBuilder:addRow(cols, options)
    if options then
        if not self:shouldShow(options.hideIfEmpty) then
        	return self
    	end
    end
	
	local _row = self.infobox:tag('tr')
	for i,v in ipairs(cols) do
		local _cell = _row:tag(tagmap[v.tag] or 'td')
						:attr('colspan', 30 / #cols)
		
		if v.attr then
			_cell:attr(v.attr)
		end
		if v.colspan then
			_cell:attr('colspan', v.colspan)
		end
		if v.rowspan then
			_cell:attr('rowspan', v.rowspan)
		end
		if v.css then
			_cell:css(v.css)
		end
		
		if v.tag == 'th' or v.tag == 'td' then
			_cell:wikitext(v.content)
		elseif v.tag == 'argth' or v.tag == 'argtd' then
			local content = self:getContent(v.content)
			if content then
				_cell:wikitext(content)
			else
				_cell:tag('span'):addClass('plainlinks')
				:wikitext(
					string.format("[%s?action=edit ? (edit)]",
						tostring(mw.uri.fullUrl(mw.title.getCurrentTitle().text))
					)
				)
			end
		end
	end
	
	return self
end

--- Creates the 30-col layout
function InfoboxBuilder:addSpacer()
	local spacer = self.infobox:tag('tr')
	for i=1,30,1 do
		spacer:tag('td')
			:attr('colspan', 1)
			:css('width', 'calc(100% / 30)')
	end
end

--- Adds links to the bottom of the infobox
function InfoboxBuilder:addLinks()
	if not self.finished then
		self.finished = true
		
		local links = {
			"[[Template:%s|<span style=\"color: %s;\">View</span>]]",
			"[[Template talk:%s|<span style=\"color: %s;\">Talk</span>]]"
		}
		self:addHeader{
			tag = 'th',
			content = 
				string.format(links[1], self.name, self.headerColors.text)
				.. " &bull; " ..
				string.format(links[2], self.name, self.headerColors.text)
		}
	end
end

--- Generates the infobox
-- @return string
--         The html of the infobox
function InfoboxBuilder:tostring()
	if not self.finished then
		self:addLinks()
	end
	
	self.finished = true
	
	return tostring(self.infobox)
end

return InfoboxBuilder
Cookies help us deliver our services. By using our services, you agree to our use of cookies.