Anonymous
×
Create a new article
Write your page title here:
We currently have 97 articles on The Dream Shrine. Type your article name above or click on one of the titles below and start writing!



The Dream Shrine

Module:Infobox: Difference between revisions

(Created page with "local p = {} local args = {} local origArgs = {} local root local empty_row_categories = {} local category_in_empty_row_pattern = '%[%[%s*[Cc][Aa][Tt][Ee][Gg][Oo][Rr][Yy]%s*:[^]]*]]' local has_rows = false local lists = { plainlist_t = { patterns = { '^plainlist$', '%splainlist$', '^plainlist%s', '%splainlist%s' }, found = false, styles = 'Plainlist/styles.css' }, hlist_t = { patterns = { '^hlist$', '%shlist$', '^hlist%s', '%shlist%s'...")
 
No edit summary
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
local p = {}
local p = {}
local args = {}
local h = {}
local origArgs = {}
 
local root
local File = require("Module:File")
local empty_row_categories = {}
local Franchise = require("Module:Franchise")
local category_in_empty_row_pattern = '%[%[%s*[Cc][Aa][Tt][Ee][Gg][Oo][Rr][Yy]%s*:[^]]*]]'
local Term = require("Module:Term")
local has_rows = false
local utilsArg = require("Module:UtilsArg")
local lists = {
local utilsMarkup = require("Module:UtilsMarkup")
plainlist_t = {
local utilsString = require("Module:UtilsString")
patterns = {
local utilsTable = require("Module:UtilsTable")
'^plainlist$',
'%splainlist$',
'^plainlist%s',
'%splainlist%s'
},
found = false,
styles = 'Plainlist/styles.css'
},
hlist_t = {
patterns = {
'^hlist$',
'%shlist$',
'^hlist%s',
'%shlist%s'
},
found = false,
styles = 'Hlist/styles.css'
}
}


local function has_list_class(args_to_check)
local CATEGORY_INVALID_ARGS = "[[Category:"..require("Module:Constants/category/invalidArgs").."]]"
for _, list in pairs(lists) do
local CATEGORY_PARAM_CAPTION = "[[Category:Infoboxes using captions]]"
if not list.found then
local CATEGORY_PARAM_NAME = "[[Category:Infoboxes using the name parameter]]"
for _, arg in pairs(args_to_check) do
local CLASS_TOOLTIP = require("Module:Constants/class/tooltip")
for _, pattern in ipairs(list.patterns) do
local DEFAULT_IMG_SIZE = "320x320px"
if mw.ustring.find(arg or '', pattern) then
list.found = true
break
end
end
if list.found then break end
end
end
end
end


local function fixChildBoxes(sval, tt)
function p.Main(frame)
local function notempty( s ) return s and s:match( '%S' ) end
local templateName = "Infobox "..frame:getParent():getTitle()
if notempty(sval) then
local args, err, categories
local marker = '<span class=special_infobox_marker>'
local templateSpec = p.Templates[templateName]
local s = sval
if templateSpec then
-- start moving templatestyles and categories inside of table rows
args, err = utilsArg.parse(frame:getParent().args, templateSpec)
local slast = ''
while slast ~= s do
slast = s
s = mw.ustring.gsub(s, '(</[Tt][Rr]%s*>%s*)(%[%[%s*[Cc][Aa][Tt][Ee][Gg][Oo][Rr][Yy]%s*:[^]]*%]%])', '%2%1')
s = mw.ustring.gsub(s, '(</[Tt][Rr]%s*>%s*)(\127[^\127]*UNIQ%-%-templatestyles%-%x+%-QINU[^\127]*\127)', '%2%1')
end
-- end moving templatestyles and categories inside of table rows
s = mw.ustring.gsub(s, '(<%s*[Tt][Rr])', marker .. '%1')
s = mw.ustring.gsub(s, '(</[Tt][Rr]%s*>)', '%1' .. marker)
if s:match(marker) then
s = mw.ustring.gsub(s, marker .. '%s*' .. marker, '')
s = mw.ustring.gsub(s, '([\r\n]|-[^\r\n]*[\r\n])%s*' .. marker, '%1')
s = mw.ustring.gsub(s, marker .. '%s*([\r\n]|-)', '%1')
s = mw.ustring.gsub(s, '(</[Cc][Aa][Pp][Tt][Ii][Oo][Nn]%s*>%s*)' .. marker, '%1')
s = mw.ustring.gsub(s, '(<%s*[Tt][Aa][Bb][Ll][Ee][^<>]*>%s*)' .. marker, '%1')
s = mw.ustring.gsub(s, '^(%{|[^\r\n]*[\r\n]%s*)' .. marker, '%1')
s = mw.ustring.gsub(s, '([\r\n]%{|[^\r\n]*[\r\n]%s*)' .. marker, '%1')
s = mw.ustring.gsub(s, marker .. '(%s*</[Tt][Aa][Bb][Ll][Ee]%s*>)', '%1')
s = mw.ustring.gsub(s, marker .. '(%s*\n|%})', '%1')
end
if s:match(marker) then
local subcells = mw.text.split(s, marker)
s = ''
for k = 1, #subcells do
if k == 1 then
s = s .. subcells[k] .. '</' .. tt .. '></tr>'
elseif k == #subcells then
local rowstyle = ' style="display:none"'
if notempty(subcells[k]) then rowstyle = '' end
s = s .. '<tr' .. rowstyle ..'><' .. tt .. ' colspan=2>\n' ..
subcells[k]
elseif notempty(subcells[k]) then
if (k % 2) == 0 then
s = s .. subcells[k]
else
s = s .. '<tr><' .. tt .. ' colspan=2>\n' ..
subcells[k] .. '</' .. tt .. '></tr>'
end
end
end
end
-- the next two lines add a newline at the end of lists for the PHP parser
-- [[Special:Diff/849054481]]
-- remove when [[:phab:T191516]] is fixed or OBE
s = mw.ustring.gsub(s, '([\r\n][%*#;:][^\r\n]*)$', '%1\n')
s = mw.ustring.gsub(s, '^([%*#;:][^\r\n]*)$', '%1\n')
s = mw.ustring.gsub(s, '^([%*#;:])', '\n%1')
s = mw.ustring.gsub(s, '^(%{%|)', '\n%1')
return s
else
else
return sval
args = frame:getParent().args
end
end
end
categories = err and err.categoryText or ""
 
-- Cleans empty tables
if args.name and args.name ~= "" then
local function cleanInfobox()
categories = categories..CATEGORY_PARAM_NAME
root = tostring(root)
if has_rows == false then
root = mw.ustring.gsub(root, '<table[^<>]*>%s*</table>', '')
end
end
 
-- Returns the union of the values of two tables, as a sequence.
local function union(t1, t2)
 
local vals = {}
for k, v in pairs(t1) do
vals[v] = true
end
end
for k, v in pairs(t2) do
if args.caption and args.caption ~= "" then
vals[v] = true
categories = categories..CATEGORY_PARAM_CAPTION
end
end
local ret = {}
for k, v in pairs(vals) do
local styles = frame:extensionTag({
table.insert(ret, k)
name = "templatestyles",
end
args = { src = "Module:Infobox/Styles.css" }
return ret
})
return styles, categories
end
end


-- Returns a table containing the numbers of the arguments that exist
function p.Image(frame)
-- for the specified prefix. For example, if the prefix was 'data', and
local file = frame.args[1]
-- 'data1', 'data2', and 'data5' exist, it would return {1, 2, 5}.
local caption = frame.args[2]
local function getArgNums(prefix)
if file == nil or file == "" then
local nums = {}
return nil
for k, v in pairs(args) do
elseif not utilsString.startsWith(file, "File:") then
local num = tostring(k):match('^' .. prefix .. '([1-9]%d*)$')
return file
if num then table.insert(nums, tonumber(num)) end
else
end
local image, exists = File.image(file, {
table.sort(nums)
size = frame.args.size or DEFAULT_IMG_SIZE, -- unclear whether we should even support custom sizing or force them all to 320x320px.
return nums
scale = 10,
end
})
 
if exists then
-- Adds a row to the infobox, with either a header cell
-- Set this image as the article's representative image for things like page previews
-- or a label/data cell combination.
mw.ext.seo.set({
local function addRow(rowArgs)
image = file
})
if rowArgs.header and rowArgs.header ~= '_BLANK_' then
has_rows = true
has_list_class({ rowArgs.rowclass, rowArgs.class, args.headerclass })
root
:tag('tr')
:addClass(rowArgs.rowclass)
:cssText(rowArgs.rowstyle)
:tag('th')
:attr('colspan', '2')
:addClass('infobox-header')
:addClass(rowArgs.class)
:addClass(args.headerclass)
-- @deprecated next; target .infobox-<name> .infobox-header
:cssText(args.headerstyle)
:cssText(rowArgs.rowcellstyle)
:wikitext(fixChildBoxes(rowArgs.header, 'th'))
if rowArgs.data then
root:wikitext(
'[[Category:Pages using infobox templates with ignored data cells]]'
)
end
end
elseif rowArgs.data and rowArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
if caption and caption ~= "" then
has_rows = true
local html = mw.html.create("div")
has_list_class({ rowArgs.rowclass, rowArgs.class })
:addClass("infobox__image-caption")
:wikitext(caption)
local row = root:tag('tr')
image = image .. tostring(html)
row:addClass(rowArgs.rowclass)
row:cssText(rowArgs.rowstyle)
if rowArgs.label then
row
:tag('th')
:attr('scope', 'row')
:addClass('infobox-label')
-- @deprecated next; target .infobox-<name> .infobox-label
:cssText(args.labelstyle)
:cssText(rowArgs.rowcellstyle)
:wikitext(rowArgs.label)
:done()
end
end
 
return image
local dataCell = row:tag('td')
dataCell
:attr('colspan', not rowArgs.label and '2' or nil)
:addClass(not rowArgs.label and 'infobox-full-data' or 'infobox-data')
:addClass(rowArgs.class)
-- @deprecated next; target .infobox-<name> .infobox(-full)-data
:cssText(rowArgs.datastyle)
:cssText(rowArgs.rowcellstyle)
:wikitext(fixChildBoxes(rowArgs.data, 'td'))
else
table.insert(empty_row_categories, rowArgs.data or '')
end
end
end
end


local function renderTitle()
function p.Games(frame)
if not args.title then return end
local games = frame.args[1]
local categories = ""


has_rows = true
games = games and utilsString.trim(games)
has_list_class({args.titleclass})
if games == nil or games == "" then
return nil
root
:tag('caption')
:addClass('infobox-title')
:addClass(args.titleclass)
-- @deprecated next; target .infobox-<name> .infobox-title
:cssText(args.titlestyle)
:wikitext(args.title)
end
 
local function renderAboveRow()
if not args.above then return end
 
has_rows = true
has_list_class({ args.aboveclass })
root
:tag('tr')
:tag('th')
:attr('colspan', '2')
:addClass('infobox-above')
:addClass(args.aboveclass)
-- @deprecated next; target .infobox-<name> .infobox-above
:cssText(args.abovestyle)
:wikitext(fixChildBoxes(args.above,'th'))
end
 
local function renderBelowRow()
if not args.below then return end
 
has_rows = true
has_list_class({ args.belowclass })
root
:tag('tr')
:tag('td')
:attr('colspan', '2')
:addClass('infobox-below')
:addClass(args.belowclass)
-- @deprecated next; target .infobox-<name> .infobox-below
:cssText(args.belowstyle)
:wikitext(fixChildBoxes(args.below,'td'))
end
 
local function addSubheaderRow(subheaderArgs)
if subheaderArgs.data and
subheaderArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
has_rows = true
has_list_class({ subheaderArgs.rowclass, subheaderArgs.class })
local row = root:tag('tr')
row:addClass(subheaderArgs.rowclass)
 
local dataCell = row:tag('td')
dataCell
:attr('colspan', '2')
:addClass('infobox-subheader')
:addClass(subheaderArgs.class)
:cssText(subheaderArgs.datastyle)
:cssText(subheaderArgs.rowcellstyle)
:wikitext(fixChildBoxes(subheaderArgs.data, 'td'))
else
table.insert(empty_row_categories, subheaderArgs.data or '')
end
end
end
games = utilsString.split(games)


local function renderSubheaders()
local gameLinks = utilsTable.map(games, p.link)
if args.subheader then
local gameLinks = utilsTable.compact(gameLinks)
args.subheader1 = args.subheader
if #gameLinks ~= #games then
categories = categories..CATEGORY_INVALID_ARGS
end
end
if args.subheaderrowclass then
args.subheaderrowclass1 = args.subheaderrowclass
if #gameLinks == 1 then
end
return gameLinks[1], categories
local subheadernums = getArgNums('subheader')
for k, num in ipairs(subheadernums) do
addSubheaderRow({
data = args['subheader' .. tostring(num)],
-- @deprecated next; target .infobox-<name> .infobox-subheader
datastyle = args.subheaderstyle,
rowcellstyle = args['subheaderstyle' .. tostring(num)],
class = args.subheaderclass,
rowclass = args['subheaderrowclass' .. tostring(num)]
})
end
end
 
local function addImageRow(imageArgs)
 
if imageArgs.data and
imageArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
 
has_rows = true
has_list_class({ imageArgs.rowclass, imageArgs.class })
local row = root:tag('tr')
row:addClass(imageArgs.rowclass)
 
local dataCell = row:tag('td')
dataCell
:attr('colspan', '2')
:addClass('infobox-image')
:addClass(imageArgs.class)
:cssText(imageArgs.datastyle)
:wikitext(fixChildBoxes(imageArgs.data, 'td'))
else
else
table.insert(empty_row_categories, imageArgs.data or '')
local gameList = utilsMarkup.list(gameLinks)
return gameList, categories
end
end
end
end
 
function p.link(game)
local function renderImages()
if utilsMarkup.containsLink(game) then
if args.image then
return game
args.image1 = args.image
end
end
if args.caption then
local game, notes = utilsMarkup.separateMarkup(game)
args.caption1 = args.caption
local link = Franchise.link(game)
end
local properCode = Franchise.code(game)
local imagenums = getArgNums('image')
if not link then
for k, num in ipairs(imagenums) do
h.warn(string.format("Invalid entry <code>%s</code>. See [[Data:Franchise]] for a list of valid entries.", game))
local caption = args['caption' .. tostring(num)]
return nil
local data = mw.html.create():wikitext(args['image' .. tostring(num)])
elseif properCode and properCode ~= game then
if caption then
h.warn(string.format("<code>%s</code> should be written as <code>%s</code>", game, properCode))
data
:tag('div')
:addClass('infobox-caption')
-- @deprecated next; target .infobox-<name> .infobox-caption
:cssText(args.captionstyle)
:wikitext(caption)
end
addImageRow({
data = tostring(data),
-- @deprecated next; target .infobox-<name> .infobox-image
datastyle = args.imagestyle,
class = args.imageclass,
rowclass = args['imagerowclass' .. tostring(num)]
})
end
end
return link..notes
end
end


-- When autoheaders are turned on, preprocesses the rows
function p.GameBlocks(frame)
local function preprocessRows()
local args = frame:getParent().args
if not args.autoheaders then return end
local blocks, categories = h.parseBlocks(args)
local rownums = union(getArgNums('header'), getArgNums('data'))
local html = mw.html.create("ul"):addClass("infobox-game-blocks")
table.sort(rownums)
for i, block in ipairs(blocks) do
local lastheader
local gameText = html
for k, num in ipairs(rownums) do
:tag("li")
if args['header' .. tostring(num)] then
:addClass("infobox-game-blocks__game")
if lastheader then
:tag("span")
args['header' .. tostring(lastheader)] = nil
:addClass("infobox-game-blocks__game-text")
end
local game = gameText:done()
lastheader = num
elseif args['data' .. tostring(num)] and
if blocks.compact then
args['data' .. tostring(num)]:gsub(
gameText:wikitext(Franchise.display(block.game))
category_in_empty_row_pattern, ''
local gameList = game
):match('^%S') then
:tag("ul")
local data = args['data' .. tostring(num)]
:addClass("infobox-game-blocks__game-list")
if data:gsub(category_in_empty_row_pattern, ''):match('%S') then
for j, listItem in ipairs(block.listItems) do
lastheader = nil
gameList
:tag("li")
:addClass("infobox-game-blocks__game-list-item")
:wikitext(listItem)
end
end
else
html:addClass("infobox-game-blocks--compact")
gameText
:tag("span")
:addClass(CLASS_TOOLTIP)
:attr("title", Franchise.shortName(block.game))
:wikitext(block.game)
:done()
:wikitext(": ")
game:wikitext(block.listItems[1])
end
end
end
end
if lastheader then
args['header' .. tostring(lastheader)] = nil
end
end
-- Gets the union of the header and data argument numbers,
-- and renders them all in order
local function renderRows()


local rownums = union(getArgNums('header'), getArgNums('data'))
return tostring(html), categories
table.sort(rownums)
for k, num in ipairs(rownums) do
addRow({
header = args['header' .. tostring(num)],
label = args['label' .. tostring(num)],
data = args['data' .. tostring(num)],
datastyle = args.datastyle,
class = args['class' .. tostring(num)],
rowclass = args['rowclass' .. tostring(num)],
-- @deprecated next; target .infobox-<name> rowclass
rowstyle = args['rowstyle' .. tostring(num)],
rowcellstyle = args['rowcellstyle' .. tostring(num)]
})
end
end
end
function h.parseBlocks(args)
local categories = ""


local function renderNavBar()
local seenParams = {}
if not args.name then return end
local blocks = {}
 
blocks.compact = false
has_rows = true
for i, game in ipairs(Franchise.enum({ includeSeries = true })) do
root
seenParams[game] = true
:tag('tr')
local listItems = args[game]
:tag('td')
listItems = listItems and utilsString.trim(listItems)
:attr('colspan', '2')
listItems = listItems and utilsString.nilIfEmpty(listItems)
:addClass('infobox-navbar')
if listItems and string.find(listItems, ", %l") then
:wikitext(require('Module:Navbar')._navbar{
h.warn("Lowercase character detected following comma. Within <code>Template:Infobox Game Blocks</code>, commas are used to separate list items. All list items should be in sentence case. Literal commas can be escaped using {{Template|,}}.")
args.name,
categories = categories..CATEGORY_INVALID_ARGS
mini = 1,
end
})
if listItems then
end
listItems = utilsString.split(listItems, '%s*,%f[^,%d]%s*') -- %f[^,%d] is so we don't split numbers on their thousands separator (e.g., 1,500)
 
table.insert(blocks, {
local function renderItalicTitle()
game = game,  
local italicTitle = args['italic title'] and mw.ustring.lower(args['italic title'])
listItems = listItems,
if italicTitle == '' or italicTitle == 'force' or italicTitle == 'yes' then
})
root:wikitext(require('Module:Italic title')._main({}))
end
local hasDiv = listItems and listItems[1] and string.find(listItems[1], "<div") -- See [[Minuet of Forest]] "Notes" field, for example
if listItems and #listItems > 1 or hasDiv then
blocks.compact = true
end
if listItems and listItems[1] and string.find(listItems[1], "plainlist") then
blocks.compact = true
end
end
end
end


-- Categories in otherwise empty rows are collected in empty_row_categories.
for k, v in pairs(args) do
-- This function adds them to the module output. It is not affected by
if not seenParams[k] then
-- args.decat because this module should not prevent module-external categories
local errorMessage = string.format("Invalid game <code>%s</code>", k)
-- from rendering.
h.warn(errorMessage)
local function renderEmptyRowCategories()
categories = categories..CATEGORY_INVALID_ARGS
for _, s in ipairs(empty_row_categories) do
root:wikitext(s)
end
end
 
-- Render tracking categories. args.decat == turns off tracking categories.
local function renderTrackingCategories()
if args.decat == 'yes' then return end
if args.child == 'yes' then
if args.title then
root:wikitext(
'[[Category:Pages using embedded infobox templates with the title parameter]]'
)
end
end
elseif #(getArgNums('data')) == 0 and mw.title.getCurrentTitle().namespace == 0 then
root:wikitext('[[Category:Articles using infobox templates with no data rows]]')
end
end
--[=[
Loads the templatestyles for the infobox.
TODO: FINISH loading base templatestyles here rather than in
MediaWiki:Common.css. There are 4-5000 pages with 'raw' infobox tables.
See [[Mediawiki_talk:Common.css/to_do#Infobox]] and/or come help :).
When we do this we should clean up the inline CSS below too.
Will have to do some bizarre conversion category like with sidebar.
]=]
local function loadTemplateStyles()
local frame = mw.getCurrentFrame()
local hlist_templatestyles = ''
if lists.hlist_t.found then
hlist_templatestyles = frame:extensionTag{
name = 'templatestyles', args = { src = lists.hlist_t.styles }
}
end
local plainlist_templatestyles = ''
if lists.plainlist_t.found then
plainlist_templatestyles = frame:extensionTag{
name = 'templatestyles', args = { src = lists.plainlist_t.styles }
}
end
-- See function description
local base_templatestyles = frame:extensionTag{
name = 'templatestyles', args = { src = 'Module:Infobox/styles.css' }
}
local templatestyles = ''
if args['templatestyles'] then
templatestyles = frame:extensionTag{
name = 'templatestyles', args = { src = args['templatestyles'] }
}
end
local child_templatestyles = ''
if args['child templatestyles'] then
child_templatestyles = frame:extensionTag{
name = 'templatestyles', args = { src = args['child templatestyles'] }
}
end
end
local grandchild_templatestyles = ''
return blocks, categories
if args['grandchild templatestyles'] then
grandchild_templatestyles = frame:extensionTag{
name = 'templatestyles', args = { src = args['grandchild templatestyles'] }
}
end
return table.concat({
-- hlist -> plainlist -> base is best-effort to preserve old Common.css ordering.
-- this ordering is not a guarantee because the rows of interest invoking
-- each class may not be on a specific page
hlist_templatestyles,
plainlist_templatestyles,
base_templatestyles,
templatestyles,
child_templatestyles,
grandchild_templatestyles
})
end
end


-- common functions between the child and non child cases
function p.Title(frame)
local function structure_infobox_common()
local subpageName = mw.title.getCurrentTitle().subpageText
renderSubheaders()
local term = Term.fetchTerm(subpageName, "Series")
renderImages()
return term or utilsString.stripTrailingParentheses(subpageName)
preprocessRows()
renderRows()
renderBelowRow()
renderNavBar()
renderItalicTitle()
renderEmptyRowCategories()
renderTrackingCategories()
cleanInfobox()
end
end


-- Specify the overall layout of the infobox, with special settings if the
function h.warn(msg, ...)
-- infobox is used as a 'child' inside another infobox.
local utilsError = require("Module:UtilsError")
local function _infobox()
local warnMessage = string.format(msg, ...)
if args.child ~= 'yes' then
utilsError.warn(warnMessage, {
root = mw.html.create('table')
includeInstance = false,
 
})
root
:addClass(args.subbox == 'yes' and 'infobox-subbox' or 'infobox')
:addClass(args.bodyclass)
-- @deprecated next; target .infobox-<name>
:cssText(args.bodystyle)
has_list_class({ args.bodyclass })
 
renderTitle()
renderAboveRow()
else
root = mw.html.create()
 
root
:wikitext(args.title)
end
structure_infobox_common()
return loadTemplateStyles() .. root
end
end


-- If the argument exists and isn't blank, add it to the argument table.
local templateSpec = function(args)
-- Blank arguments are treated as nil to match the behaviour of ParserFunctions.
local singular = args.singular
local function preprocessSingleArg(argName)
local plural = args.plural
if origArgs[argName] and origArgs[argName] ~= '' then
local params = args.params
args[argName] = origArgs[argName]
local productionParams = args.productionParams
end
local imageSuchAs = args.imageSuchAs
end


-- Assign the parameters with the given prefixes to the args table, in order, in
local spec = {
-- batches of the step size specified. This is to prevent references etc. from
format = "block",
-- appearing in the wrong order. The prefixTable should be an array containing
purpose = string.format("[[Guidelines:Articles#Infobox|Infobox]] for [[:Category:%s|%s]].", plural, string.lower(plural)),
-- tables, each of which has two possible fields, a "prefix" string and a
categories = {"Infobox templates"},
-- "depend" table. The function always parses parameters containing the "prefix"
boilerplate = {
-- string, but only parses parameters in the "depend" table if the prefix
separateRequiredParams = false,
-- parameter is present and non-blank.
},
local function preprocessArgs(prefixTable, step)
paramOrder = {"name", "image", "caption"},
if type(prefixTable) ~= 'table' then
params = {
error("Non-table value detected for the prefix table", 2)
name = {
desc = "<p>Name to use in the infobox header. Defaults to {{Template|Page Name}}.</p><p>In general, this parameter should be omitted unless the title requires italics.</p>",
type = "content",
},
image = {
desc = string.format("An image to represent the %s, such as %s.", singular, imageSuchAs),
type = "wiki-file-name",
},
caption = {
desc = "A caption for the image.",
type = "content",
}
},
}
for i, param in ipairs(params or {}) do
spec.params[param.name] = param
table.insert(spec.paramOrder, param.name)
end
end
if type(step) ~= 'number' then
for i, param in ipairs(productionParams or {}) do
error("Invalid step value detected", 2)
spec.params[param.name] = param
end
table.insert(spec.paramOrder, param.name)
 
-- Get arguments without a number suffix, and check for bad input.
for i,v in ipairs(prefixTable) do
if type(v) ~= 'table' or type(v.prefix) ~= "string" or
(v.depend and type(v.depend) ~= 'table') then
error('Invalid input detected to preprocessArgs prefix table', 2)
end
preprocessSingleArg(v.prefix)
-- Only parse the depend parameter if the prefix parameter is present
-- and not blank.
if args[v.prefix] and v.depend then
for j, dependValue in ipairs(v.depend) do
if type(dependValue) ~= 'string' then
error('Invalid "depend" parameter value detected in preprocessArgs')
end
preprocessSingleArg(dependValue)
end
end
end
 
-- Get arguments with number suffixes.
local a = 1 -- Counter variable.
local moreArgumentsExist = true
while moreArgumentsExist == true do
moreArgumentsExist = false
for i = a, a + step - 1 do
for j,v in ipairs(prefixTable) do
local prefixArgName = v.prefix .. tostring(i)
if origArgs[prefixArgName] then
-- Do another loop if any arguments are found, even blank ones.
moreArgumentsExist = true
preprocessSingleArg(prefixArgName)
end
-- Process the depend table if the prefix argument is present
-- and not blank, or we are processing "prefix1" and "prefix" is
-- present and not blank, and if the depend table is present.
if v.depend and (args[prefixArgName] or (i == 1 and args[v.prefix])) then
for j,dependValue in ipairs(v.depend) do
local dependArgName = dependValue .. tostring(i)
preprocessSingleArg(dependArgName)
end
end
end
end
a = a + step
end
end
return spec
end
end


-- Parse the data parameters in the same order that the old {{infobox}} did, so
local released = {
-- that references etc. will display in the expected places. Parameters that
name = "released",
-- depend on another parameter are only processed if that parameter is present,
desc = "Release date(s) of the film. Use [[Template:Release]].",
-- to avoid phantom references appearing in article reference lists.
type = "content",
local function parseDataParameters()
}


preprocessSingleArg('autoheaders')
p.Templates = {
preprocessSingleArg('child')
["Infobox Game Blocks"] = {},
preprocessSingleArg('bodyclass')
["Infobox Film"] = templateSpec({
preprocessSingleArg('subbox')
singular = "film",
preprocessSingleArg('bodystyle')
plural = "films",
preprocessSingleArg('title')
imageSuchAs = "a release poster or a DVD cover",
preprocessSingleArg('titleclass')
params = {
preprocessSingleArg('titlestyle')
{
preprocessSingleArg('above')
name = "director",
preprocessSingleArg('aboveclass')
desc = "The director(s) of the film.",
preprocessSingleArg('abovestyle')
type = "content",
preprocessArgs({
},
{prefix = 'subheader', depend = {'subheaderstyle', 'subheaderrowclass'}}
{
}, 10)
name = "producer",
preprocessSingleArg('subheaderstyle')
desc = "The producer(s) of the film.",
preprocessSingleArg('subheaderclass')
type = "content",
preprocessArgs({
},
{prefix = 'image', depend = {'caption', 'imagerowclass'}}
{
}, 10)
name = "writer",
preprocessSingleArg('captionstyle')
desc = "The writer(s) of the film.",
preprocessSingleArg('imagestyle')
type = "content",
preprocessSingleArg('imageclass')
},
preprocessArgs({
{
{prefix = 'header'},
name = "production",
{prefix = 'data', depend = {'label'}},
desc = "The companies producing the film.",
{prefix = 'rowclass'},
type = "content",
{prefix = 'rowstyle'},
},
{prefix = 'rowcellstyle'},
{
{prefix = 'class'}
name = "distributor",
}, 50)
desc = "The companies distributing the film.",
preprocessSingleArg('headerclass')
type = "content",
preprocessSingleArg('headerstyle')
},
preprocessSingleArg('labelstyle')
{
preprocessSingleArg('datastyle')
name = "country",
preprocessSingleArg('below')
desc = "Country or countries of production.",
preprocessSingleArg('belowclass')
},
preprocessSingleArg('belowstyle')
released,
preprocessSingleArg('name')
}
-- different behaviour for italics if blank or absent
}),
args['italic title'] = origArgs['italic title']
["Infobox Television"] = templateSpec({
preprocessSingleArg('decat')
singular = "television",
preprocessSingleArg('templatestyles')
plural = "television",
preprocessSingleArg('child templatestyles')
imageSuchAs = "the series' logo or title card",
preprocessSingleArg('grandchild templatestyles')
params = {
end
{
name = "basedOn",
type = "string",
desc = "Comma separated list of [[Data:Franchise|games]] that the series is based on.",
enum = Franchise.enum(),
trim = true,
split = true,
},
{
name = "seasons",
type = "content",
desc = "Number of seasons.",
},
{
name = "episodes",
type = "content",
desc = "Number of total episodes.",
},
{
name = "company",
type = "content",
desc = "Production comapany or companies.",
},
{
name = "distributor",
type = "content",
desc = "Distributor(s) of the television series.",
},
released,
}
})
}


-- If called via #invoke, use the args passed into the invoking template.
function p.Documentation()
-- Otherwise, for testing purposes, assume args are being passed directly in.
return {
function p.infobox(frame)
Games = {
if frame == mw.getCurrentFrame() then
desc = "Used by [[:Category:Infobox templates|infobox templates]] to turn comma-separated [[Data:Franchise|game codes]] into lists of games.",
origArgs = frame:getParent().args
frameParams = {
else
[1] = {
origArgs = frame
name = "param",
end
desc = "The infobox parameter, usually <code><nowiki>{{{game|}}}</nowiki></code> or <code><nowiki>{{{other|}}}</nowiki></code>.",
},
parseDataParameters()
},
cases = {
return _infobox()
{
args = {"TLoZ, TAoL, ALttP"},
},
{
args = {"TLoZ (Ran), BoMC, TLoZ (Susumu)"},
},
{
args = {""},
},
{
args = {},
},
{
args = {"invalid game"},
},
{
args = {"OoT, invalid game, TP"},
},
}
},
Image = {
desc = "Used by [[:Category:Infobox templates|infobox templates]] to generate an image when [[Template:Media]] is not used.",
frameParams = {
[1] = {
name = "file",
desc = "The image parameter - a file name.",
},
[2] = {
name = "caption",
desc = "The caption parameter.",
},
size = {
desc = "Image size in pixels. Sprites are scaled to a maximum of 10 times their original size.",
default = DEFAULT_IMG_SIZE,
},
},
cases = {
{
args = {"File:TWW Great Fairy Figurine Model.png"},
},
{
args = {"File:TWW Great Fairy Figurine Model.png", "Great Fairy Figurine", size = "250px"}
},
{
desc = "Sprites are scaled to a maximum of 10 times their original size.",
args = {"File:ALttP Apple Sprite.png"},
},
{
desc = "[[Template:Media]] output is rendered as-is",
args = {"{{Media|Model TWW= TWW Great Fairy Figurine Model.png}}"}
},
{
desc = "Anything other than a file name starting with <code>File:</code> is rendered as-is",
args = {"{{Plural|Series|Cyber Pico Bloom}} are never seen in-game"},
},
},
},
}
end
end


-- For calling via #invoke within a template
function p.infoboxTemplate(frame)
origArgs = {}
for k,v in pairs(frame.args) do origArgs[k] = mw.text.trim(v) end
parseDataParameters()
return _infobox()
end
return p
return p

Latest revision as of 08:17, 6 August 2024

Documentation for this module may be created at Module:Infobox/doc

local p = {}
local h = {}

local File = require("Module:File")
local Franchise = require("Module:Franchise")
local Term = require("Module:Term")
local utilsArg = require("Module:UtilsArg")
local utilsMarkup = require("Module:UtilsMarkup")
local utilsString = require("Module:UtilsString")
local utilsTable = require("Module:UtilsTable")

local CATEGORY_INVALID_ARGS = "[[Category:"..require("Module:Constants/category/invalidArgs").."]]"
local CATEGORY_PARAM_CAPTION = "[[Category:Infoboxes using captions]]"
local CATEGORY_PARAM_NAME = "[[Category:Infoboxes using the name parameter]]"
local CLASS_TOOLTIP = require("Module:Constants/class/tooltip")
local DEFAULT_IMG_SIZE = "320x320px"

function p.Main(frame)
	local templateName = "Infobox "..frame:getParent():getTitle()
	
	local args, err, categories
	local templateSpec = p.Templates[templateName]
	if templateSpec then
		args, err = utilsArg.parse(frame:getParent().args, templateSpec)
	else
		args = frame:getParent().args
	end
	categories = err and err.categoryText or ""
	
	if args.name and args.name ~= "" then
		categories = categories..CATEGORY_PARAM_NAME
	end
	if args.caption and args.caption ~= "" then
		categories = categories..CATEGORY_PARAM_CAPTION
	end
	
	local styles = frame:extensionTag({
		name = "templatestyles",
		args = { src = "Module:Infobox/Styles.css" }
	})
	
	return styles, categories
end

function p.Image(frame)
	local file = frame.args[1]
	local caption = frame.args[2]
	if file == nil or file == "" then
		return nil
	elseif not utilsString.startsWith(file, "File:") then
		return file
	else
		local image, exists = File.image(file, {
			size = frame.args.size or DEFAULT_IMG_SIZE, -- unclear whether we should even support custom sizing or force them all to 320x320px.
			scale = 10,
		})
		if exists then
			-- Set this image as the article's representative image for things like page previews
			mw.ext.seo.set({
				image = file
			})
		end
		if caption and caption ~= "" then
			local html = mw.html.create("div")
				:addClass("infobox__image-caption")
				:wikitext(caption)
			image = image .. tostring(html)
		end
		return image
	end
end

function p.Games(frame)
	local games = frame.args[1]
	local categories = ""

	games = games and utilsString.trim(games)
	if games == nil or games == "" then
		return nil
	end
	games = utilsString.split(games)

	local gameLinks = utilsTable.map(games, p.link)
	local gameLinks = utilsTable.compact(gameLinks)
	if #gameLinks ~= #games then
		categories = categories..CATEGORY_INVALID_ARGS
	end
	
	if #gameLinks == 1 then
		return gameLinks[1], categories
	else
		local gameList = utilsMarkup.list(gameLinks)
		return gameList, categories
	end
end
function p.link(game)
	if utilsMarkup.containsLink(game) then
		return game
	end
	local game, notes = utilsMarkup.separateMarkup(game)
	local link = Franchise.link(game)
	local properCode = Franchise.code(game)
	if not link then
		h.warn(string.format("Invalid entry <code>%s</code>. See [[Data:Franchise]] for a list of valid entries.", game))
		return nil
	elseif properCode and properCode ~= game then
		h.warn(string.format("<code>%s</code> should be written as <code>%s</code>", game, properCode))
	end
	return link..notes
end

function p.GameBlocks(frame)
	local args = frame:getParent().args
	local blocks, categories = h.parseBlocks(args)
	
	local html = mw.html.create("ul"):addClass("infobox-game-blocks")
	for i, block in ipairs(blocks) do
		local gameText = html
			:tag("li")
			:addClass("infobox-game-blocks__game")
			:tag("span")
				:addClass("infobox-game-blocks__game-text")
		local game = gameText:done()
	
		if blocks.compact then
			gameText:wikitext(Franchise.display(block.game))
			local gameList = game
				:tag("ul")
				:addClass("infobox-game-blocks__game-list")
			for j, listItem in ipairs(block.listItems) do
				gameList
					:tag("li")
					:addClass("infobox-game-blocks__game-list-item")
					:wikitext(listItem)
			end
		else
			html:addClass("infobox-game-blocks--compact")
			gameText
				:tag("span")
					:addClass(CLASS_TOOLTIP)
					:attr("title", Franchise.shortName(block.game))
					:wikitext(block.game)
					:done()
				:wikitext(": ")
			game:wikitext(block.listItems[1])
		end
	end

	return tostring(html), categories
end
function h.parseBlocks(args)
	local categories = ""

	local seenParams = {}
	local blocks = {}
	blocks.compact = false
	for i, game in ipairs(Franchise.enum({ includeSeries = true })) do
		seenParams[game] = true
		local listItems = args[game]
		listItems = listItems and utilsString.trim(listItems)
		listItems = listItems and utilsString.nilIfEmpty(listItems)
		if listItems and string.find(listItems, ", %l") then
			h.warn("Lowercase character detected following comma. Within <code>Template:Infobox Game Blocks</code>, commas are used to separate list items. All list items should be in sentence case. Literal commas can be escaped using {{Template|,}}.")
			categories = categories..CATEGORY_INVALID_ARGS
		end
		if listItems then
			listItems = utilsString.split(listItems, '%s*,%f[^,%d]%s*') -- %f[^,%d] is so we don't split numbers on their thousands separator (e.g., 1,500)
			table.insert(blocks, {
				game = game, 
				listItems = listItems,
			})
		end
		local hasDiv = listItems and listItems[1] and string.find(listItems[1], "<div") -- See [[Minuet of Forest]] "Notes" field, for example
		if listItems and #listItems > 1 or hasDiv then
			blocks.compact = true
		end
		if listItems and listItems[1] and string.find(listItems[1], "plainlist") then
			blocks.compact = true
		end
	end

	for k, v in pairs(args) do
		if not seenParams[k] then
			local errorMessage = string.format("Invalid game <code>%s</code>", k)
			h.warn(errorMessage)
			categories = categories..CATEGORY_INVALID_ARGS
		end
	end
	
	return blocks, categories
end

function p.Title(frame)
	local subpageName = mw.title.getCurrentTitle().subpageText
	local term = Term.fetchTerm(subpageName, "Series")
	return term or utilsString.stripTrailingParentheses(subpageName)
end

function h.warn(msg, ...)
	local utilsError = require("Module:UtilsError")
	local warnMessage = string.format(msg, ...)
	utilsError.warn(warnMessage, {
		includeInstance = false,
	})
end

local templateSpec = function(args)
	local singular = args.singular
	local plural = args.plural
	local params = args.params
	local productionParams = args.productionParams
	local imageSuchAs = args.imageSuchAs

	local spec = {
		format = "block",
		purpose = string.format("[[Guidelines:Articles#Infobox|Infobox]] for [[:Category:%s|%s]].", plural, string.lower(plural)),
		categories = {"Infobox templates"},
		boilerplate = {
			separateRequiredParams = false,	
		},
		paramOrder = {"name", "image", "caption"},
		params = {
			name = {
				desc = "<p>Name to use in the infobox header. Defaults to {{Template|Page Name}}.</p><p>In general, this parameter should be omitted unless the title requires italics.</p>",
				type = "content",
			},
			image = {
				desc = string.format("An image to represent the %s, such as %s.", singular, imageSuchAs),
				type = "wiki-file-name",
			},
			caption = {
				desc = "A caption for the image.",
				type = "content",
			}
		},
	}
	for i, param in ipairs(params or {}) do
		spec.params[param.name] = param
		table.insert(spec.paramOrder, param.name)
	end
	for i, param in ipairs(productionParams or {}) do
		spec.params[param.name] = param
		table.insert(spec.paramOrder, param.name)
	end
	
	return spec
end

local released = {
	name = "released",
	desc = "Release date(s) of the film. Use [[Template:Release]].",
	type = "content",
}

p.Templates = {
	["Infobox Game Blocks"] = {},
	["Infobox Film"] = templateSpec({
		singular = "film",
		plural = "films",
		imageSuchAs = "a release poster or a DVD cover",
		params = {
			{
				name = "director",
				desc = "The director(s) of the film.",
				type = "content",
			},
			{
				name = "producer",
				desc = "The producer(s) of the film.",
				type = "content",
			},
			{
				name = "writer",
				desc = "The writer(s) of the film.",
				type = "content",
			},
			{
				name = "production",
				desc = "The companies producing the film.",
				type = "content",
			},
			{
				name = "distributor",
				desc = "The companies distributing the film.",
				type = "content",
			},
			{
				name = "country",
				desc = "Country or countries of production.",	
			},
			released,
		}
	}),
	["Infobox Television"] = templateSpec({
		singular = "television",
		plural = "television",
		imageSuchAs = "the series' logo or title card",
		params = {
			{
				name = "basedOn",
				type = "string",
				desc = "Comma separated list of [[Data:Franchise|games]] that the series is based on.",
				enum = Franchise.enum(),
				trim = true,
				split = true,
			},
			{
				name = "seasons",
				type = "content",
				desc = "Number of seasons.",
			},
			{
				name = "episodes",
				type = "content",
				desc = "Number of total episodes.",
			},
			{
				name = "company",
				type = "content",
				desc = "Production comapany or companies.",
			},
			{
				name = "distributor",
				type = "content",
				desc = "Distributor(s) of the television series.",
			},
			released,
		}
	})
}

function p.Documentation()
	return {
		Games = {
			desc = "Used by [[:Category:Infobox templates|infobox templates]] to turn comma-separated [[Data:Franchise|game codes]] into lists of games.",
			frameParams = {
				[1] = {
					name = "param",
					desc = "The infobox parameter, usually <code><nowiki>{{{game|}}}</nowiki></code> or <code><nowiki>{{{other|}}}</nowiki></code>.",
				},
			},
			cases = {
				{
					args = {"TLoZ, TAoL, ALttP"},
				},
				{
					args = {"TLoZ (Ran), BoMC, TLoZ (Susumu)"},
				},
				{
					args = {""},
				},
				{
					args = {},
				},
				{
					args = {"invalid game"},
				},
				{
					args = {"OoT, invalid game, TP"},
				},
			}
		},
		Image = {
			desc = "Used by [[:Category:Infobox templates|infobox templates]] to generate an image when [[Template:Media]] is not used.",
			frameParams = {
				[1] = {
					name = "file",
					desc = "The image parameter - a file name.",
				},
				[2] = {
					name = "caption",
					desc = "The caption parameter.",
				},
				size = {
					desc = "Image size in pixels. Sprites are scaled to a maximum of 10 times their original size.",
					default = DEFAULT_IMG_SIZE,
				},
			},
			cases = {
				{
					args = {"File:TWW Great Fairy Figurine Model.png"},
				},
				{
					args = {"File:TWW Great Fairy Figurine Model.png", "Great Fairy Figurine", size = "250px"}
				},
				{
					desc = "Sprites are scaled to a maximum of 10 times their original size.",
					args = {"File:ALttP Apple Sprite.png"},
				},
				{
					desc = "[[Template:Media]] output is rendered as-is",
					args = {"{{Media|Model TWW= TWW Great Fairy Figurine Model.png}}"}
				},
				{
					desc = "Anything other than a file name starting with <code>File:</code> is rendered as-is",
					args = {"{{Plural|Series|Cyber Pico Bloom}} are never seen in-game"},
				},
			},
		},
	}
end

return p