Jump to content

Module:Infobox: Difference between revisions

From ADI Digital Archives
Created page with "-- This module implements {{documentation}}. -- Get required modules. local getArgs = require('Module:Arguments').getArgs -- Get the config table. local cfg = mw.loadData('Module:Documentation/config') local p = {} -- Often-used functions. local ugsub = mw.ustring.gsub local format = mw.ustring.format ---------------------------------------------------------------------------- -- Helper functions -- -- These are defined as local functions, but are made available in..."
 
mNo edit summary
 
Line 1: Line 1:
-- This module implements {{documentation}}.
-- Get required modules.
local getArgs = require('Module:Arguments').getArgs
-- Get the config table.
local cfg = mw.loadData('Module:Documentation/config')
local p = {}
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 yesno = require("Module:Yesno")
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'
},
found = false,
styles = 'Hlist/styles.css'
}
}


-- Often-used functions.
local function has_list_class(args_to_check)
local ugsub = mw.ustring.gsub
for _, list in pairs(lists) do
local format = mw.ustring.format
if not list.found then
 
for _, arg in pairs(args_to_check) do
----------------------------------------------------------------------------
for _, pattern in ipairs(list.patterns) do
-- Helper functions
if mw.ustring.find(arg or '', pattern) then
--
list.found = true
-- These are defined as local functions, but are made available in the p
break
-- table for testing purposes.
end
----------------------------------------------------------------------------
end
 
if list.found then break end
local function message(cfgKey, valArray, expectType)
end
--[[
end
-- Gets a message from the cfg table and formats it if appropriate.
-- The function raises an error if the value from the cfg table is not
-- of the type expectType. The default type for expectType is 'string'.
-- If the table valArray is present, strings such as $1, $2 etc. in the
-- message are substituted with values from the table keys [1], [2] etc.
-- For example, if the message "foo-message" had the value 'Foo $2 bar $1.',
-- message('foo-message', {'baz', 'qux'}) would return "Foo qux bar baz."
--]]
local msg = cfg[cfgKey]
expectType = expectType or 'string'
if type(msg) ~= expectType then
error('message: type error in message cfg.' .. cfgKey .. ' (' .. expectType .. ' expected, got ' .. type(msg) .. ')', 2)
end
if not valArray then
return msg
end
 
local function getMessageVal(match)
match = tonumber(match)
return valArray[match] or error('message: no value found for key $' .. match .. ' in message cfg.' .. cfgKey, 4)
end
end
return ugsub(msg, '$([1-9][0-9]*)', getMessageVal)
end
end


p.message = message
local function fixChildBoxes(sval, tt)
 
local function notempty( s ) return s and s:match( '%S' ) end
local function makeWikilink(page, display)
if display then
if notempty(sval) then
return format('[[%s|%s]]', page, display)
local marker = '<span class=special_infobox_marker>'
local s = sval
-- start moving templatestyles and categories inside of table rows
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 format('[[%s]]', page)
return sval
end
end
end
end


p.makeWikilink = makeWikilink
-- Cleans empty tables
 
local function cleanInfobox()
local function makeCategoryLink(cat, sort)
root = tostring(root)
local catns = mw.site.namespaces[14].name
if has_rows == false then
return makeWikilink(catns .. ':' .. cat, sort)
root = mw.ustring.gsub(root, '<table[^<>]*>%s*</table>', '')
end
end
end


p.makeCategoryLink = makeCategoryLink
-- Returns the union of the values of two tables, as a sequence.
local function union(t1, t2)


local function makeUrlLink(url, display)
local vals = {}
return format('[%s %s]', url, display)
for k, v in pairs(t1) do
end
vals[v] = true
 
end
p.makeUrlLink = makeUrlLink
for k, v in pairs(t2) do
 
vals[v] = true
local function makeToolbar(...)
end
local ret = {}
local ret = {}
local lim = select('#', ...)
for k, v in pairs(vals) do
if lim < 1 then
table.insert(ret, k)
return nil
end
end
for i = 1, lim do
return ret
ret[#ret + 1] = select(i, ...)
end
end
-- 'documentation-toolbar'
return format(
'<span class="%s">(%s)</span>',
message('toolbar-class'),
table.concat(ret, ' &#124; ')
)
end
 
p.makeToolbar = makeToolbar


----------------------------------------------------------------------------
-- Returns a table containing the numbers of the arguments that exist
-- Argument processing
-- for the specified prefix. For example, if the prefix was 'data', and
----------------------------------------------------------------------------
-- 'data1', 'data2', and 'data5' exist, it would return {1, 2, 5}.
 
local function getArgNums(prefix)
local function makeInvokeFunc(funcName)
local nums = {}
return function (frame)
for k, v in pairs(args) do
local args = getArgs(frame, {
local num = tostring(k):match('^' .. prefix .. '([1-9]%d*)$')
valueFunc = function (key, value)
if num then table.insert(nums, tonumber(num)) end
if type(value) == 'string' then
value = value:match('^%s*(.-)%s*$') -- Remove whitespace.
if key == 'heading' or value ~= '' then
return value
else
return nil
end
else
return value
end
end
})
return p[funcName](args)
end
end
table.sort(nums)
return nums
end
end


----------------------------------------------------------------------------
-- Adds a row to the infobox, with either a header cell
-- Entry points
-- or a label/data cell combination.
----------------------------------------------------------------------------
local function addRow(rowArgs)
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 and not yesno(args.decat) then
root:wikitext(
'[[Category:Pages using infobox templates with ignored data cells]]'
)
end
elseif rowArgs.data and rowArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
has_rows = true
has_list_class({ rowArgs.rowclass, rowArgs.class })
local row = root:tag('tr')
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


function p.nonexistent(frame)
local dataCell = row:tag('td')
if mw.title.getCurrentTitle().subpageText == 'testcases' then
dataCell
return frame:expandTemplate{title = 'module test cases notice'}
: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
else
return p.main(frame)
table.insert(empty_row_categories, rowArgs.data or '')
end
end
end
end


p.main = makeInvokeFunc('_main')
local function renderTitle()
if not args.title then return end


function p._main(args)
has_rows = true
--[[
has_list_class({args.titleclass})
-- This function defines logic flow for the module.
-- @args - table of arguments passed by the user
--]]
local env = p.getEnvironment(args)
local root = mw.html.create()
root
root
:wikitext(p._getModuleWikitext(args, env))
:tag('caption')
:wikitext(p.protectionTemplate(env))
:addClass('infobox-title')
:wikitext(p.sandboxNotice(args, env))
:addClass(args.titleclass)
:tag('div')
-- @deprecated next; target .infobox-<name> .infobox-title
-- 'documentation-container'
:cssText(args.titlestyle)
:addClass(message('container'))
:wikitext(args.title)
:attr('role', 'complementary')
:attr('aria-labelledby', args.heading ~= '' and 'documentation-heading' or nil)
:attr('aria-label', args.heading == '' and 'Documentation' or nil)
:newline()
:tag('div')
-- 'documentation'
:addClass(message('main-div-classes'))
:newline()
:wikitext(p._startBox(args, env))
:wikitext(p._content(args, env))
:tag('div')
-- 'documentation-clear'
:addClass(message('clear'))
:done()
:newline()
:done()
:wikitext(p._endBox(args, env))
:done()
:wikitext(p.addTrackingCategories(env))
-- 'Module:Documentation/styles.css'
return mw.getCurrentFrame():extensionTag (
'templatestyles', '', {src=cfg['templatestyles']
}) .. tostring(root)
end
end


----------------------------------------------------------------------------
local function renderAboveRow()
-- Environment settings
if not args.above then return end
----------------------------------------------------------------------------


function p.getEnvironment(args)
has_rows = true
--[[
has_list_class({ args.aboveclass })
-- Returns a table with information about the environment, including title
-- objects and other namespace- or path-related data.
-- @args - table of arguments passed by the user
--
-- Title objects include:
-- env.title - the page we are making documentation for (usually the current title)
-- env.templateTitle - the template (or module, file, etc.)
-- env.docTitle - the /doc subpage.
-- env.sandboxTitle - the /sandbox subpage.
-- env.testcasesTitle - the /testcases subpage.
--
-- Data includes:
-- env.protectionLevels - the protection levels table of the title object.
-- env.subjectSpace - the number of the title's subject namespace.
-- env.docSpace - the number of the namespace the title puts its documentation in.
-- env.docpageBase - the text of the base page of the /doc, /sandbox and /testcases pages, with namespace.
-- env.compareUrl - URL of the Special:ComparePages page comparing the sandbox with the template.
--
-- All table lookups are passed through pcall so that errors are caught. If an error occurs, the value
-- returned will be nil.
--]]
local env, envFuncs = {}, {}
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


-- Set up the metatable. If triggered we call the corresponding function in the envFuncs table. The value
local function renderBelowRow()
-- returned by that function is memoized in the env table so that we don't call any of the functions
if not args.below then return end
-- more than once. (Nils won't be memoized.)
setmetatable(env, {
__index = function (t, key)
local envFunc = envFuncs[key]
if envFunc then
local success, val = pcall(envFunc)
if success then
env[key] = val -- Memoise the value.
return val
end
end
return nil
end
})


function envFuncs.title()
has_rows = true
-- The title object for the current page, or a test page passed with args.page.
has_list_class({ args.belowclass })
local title
local titleArg = args.page
root
if titleArg then
:tag('tr')
title = mw.title.new(titleArg)
:tag('td')
else
:attr('colspan', '2')
title = mw.title.getCurrentTitle()
:addClass('infobox-below')
end
:addClass(args.belowclass)
return title
-- @deprecated next; target .infobox-<name> .infobox-below
end
:cssText(args.belowstyle)
:wikitext(fixChildBoxes(args.below,'td'))
end


function envFuncs.templateTitle()
local function addSubheaderRow(subheaderArgs)
--[[
if subheaderArgs.data and
-- The template (or module, etc.) title object.
subheaderArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
-- Messages:
has_rows = true
-- 'sandbox-subpage' --> 'sandbox'
has_list_class({ subheaderArgs.rowclass, subheaderArgs.class })
-- 'testcases-subpage' --> 'testcases'
--]]
local row = root:tag('tr')
local subjectSpace = env.subjectSpace
row:addClass(subheaderArgs.rowclass)
local title = env.title
local subpage = title.subpageText
if subpage == message('sandbox-subpage') or subpage == message('testcases-subpage') or (subpage == message('doc-subpage') and mw.title.getCurrentTitle().namespace == env.docSpace) then
return mw.title.makeTitle(subjectSpace, title.baseText)
else
return mw.title.makeTitle(subjectSpace, title.text)
end
end


function envFuncs.docTitle()
local dataCell = row:tag('td')
--[[
dataCell
-- Title object of the /doc subpage.
:attr('colspan', '2')
-- Messages:
:addClass('infobox-subheader')
-- 'doc-subpage' --> 'doc'
:addClass(subheaderArgs.class)
--]]
:cssText(subheaderArgs.datastyle)
local title = env.title
:cssText(subheaderArgs.rowcellstyle)
local docname = args[1] -- User-specified doc page.
:wikitext(fixChildBoxes(subheaderArgs.data, 'td'))
local docpage
else
if docname then
table.insert(empty_row_categories, subheaderArgs.data or '')
docpage = docname
else
docpage = env.docpageBase .. '/' .. message('doc-subpage')
end
return mw.title.new(docpage)
end
function envFuncs.sandboxTitle()
--[[
-- Title object for the /sandbox subpage.
-- Messages:
-- 'sandbox-subpage' --> 'sandbox'
--]]
return mw.title.new(env.docpageBase .. '/' .. message('sandbox-subpage'))
end
function envFuncs.testcasesTitle()
--[[
-- Title object for the /testcases subpage.
-- Messages:
-- 'testcases-subpage' --> 'testcases'
--]]
return mw.title.new(env.docpageBase .. '/' .. message('testcases-subpage'))
end
end
end


function envFuncs.protectionLevels()
local function renderSubheaders()
-- The protection levels table of the title object.
if args.subheader then
return env.title.protectionLevels
args.subheader1 = args.subheader
end
end
 
if args.subheaderrowclass then
function envFuncs.subjectSpace()
args.subheaderrowclass1 = args.subheaderrowclass
-- The subject namespace number.
return mw.site.namespaces[env.title.namespace].subject.id
end
end
 
local subheadernums = getArgNums('subheader')
function envFuncs.docSpace()
for k, num in ipairs(subheadernums) do
-- The documentation namespace number. For most namespaces this is the
addSubheaderRow({
-- same as the subject namespace. However, pages in the Article, File,
data = args['subheader' .. tostring(num)],
-- MediaWiki or Category namespaces must have their /doc, /sandbox and
-- @deprecated next; target .infobox-<name> .infobox-subheader
-- /testcases pages in talk space.
datastyle = args.subheaderstyle,
local subjectSpace = env.subjectSpace
rowcellstyle = args['subheaderstyle' .. tostring(num)],
if subjectSpace == 0 or subjectSpace == 6 or subjectSpace == 8 or subjectSpace == 14 then
class = args.subheaderclass,
return subjectSpace + 1
rowclass = args['subheaderrowclass' .. tostring(num)]
else
})
return subjectSpace
end
end
end
end


function envFuncs.docpageBase()
local function addImageRow(imageArgs)
-- The base page of the /doc, /sandbox, and /testcases subpages.
-- For some namespaces this is the talk page, rather than the template page.
local templateTitle = env.templateTitle
local docSpace = env.docSpace
local docSpaceText = mw.site.namespaces[docSpace].name
-- Assemble the link. docSpace is never the main namespace, so we can hardcode the colon.
return docSpaceText .. ':' .. templateTitle.text
end
function envFuncs.compareUrl()
-- Diff link between the sandbox and the main template using [[Special:ComparePages]].
local templateTitle = env.templateTitle
local sandboxTitle = env.sandboxTitle
if templateTitle.exists and sandboxTitle.exists then
local compareUrl = mw.uri.canonicalUrl(
'Special:ComparePages',
{ page1 = templateTitle.prefixedText, page2 = sandboxTitle.prefixedText}
)
return tostring(compareUrl)
else
return nil
end
end
 
return env
end


----------------------------------------------------------------------------
if imageArgs.data and
-- Auxiliary templates
imageArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
----------------------------------------------------------------------------


p.getModuleWikitext = makeInvokeFunc('_getModuleWikitext')
has_rows = true
has_list_class({ imageArgs.rowclass, imageArgs.class })
local row = root:tag('tr')
row:addClass(imageArgs.rowclass)


function p._getModuleWikitext(args, env)
local dataCell = row:tag('td')
local currentTitle = mw.title.getCurrentTitle()
dataCell
if currentTitle.contentModel ~= 'Scribunto' then return end
:attr('colspan', '2')
pcall(require, currentTitle.prefixedText) -- if it fails, we don't care
:addClass('infobox-image')
local moduleWikitext =  package.loaded["Module:Module wikitext"]
:addClass(imageArgs.class)
if moduleWikitext then
:cssText(imageArgs.datastyle)
return moduleWikitext.main()
:wikitext(fixChildBoxes(imageArgs.data, 'td'))
else
table.insert(empty_row_categories, imageArgs.data or '')
end
end
end
end


function p.sandboxNotice(args, env)
local function renderImages()
--[=[
if args.image then
-- Generates a sandbox notice for display above sandbox pages.
args.image1 = args.image
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
--
-- Messages:
-- 'sandbox-notice-image' --> '[[File:Sandbox.svg|50px|alt=|link=]]'
-- 'sandbox-notice-blurb' --> 'This is the $1 for $2.'
-- 'sandbox-notice-diff-blurb' --> 'This is the $1 for $2 ($3).'
-- 'sandbox-notice-pagetype-template' --> '[[Wikipedia:Template test cases|template sandbox]] page'
-- 'sandbox-notice-pagetype-module' --> '[[Wikipedia:Template test cases|module sandbox]] page'
-- 'sandbox-notice-pagetype-other' --> 'sandbox page'
-- 'sandbox-notice-compare-link-display' --> 'diff'
-- 'sandbox-notice-testcases-blurb' --> 'See also the companion subpage for $1.'
-- 'sandbox-notice-testcases-link-display' --> 'test cases'
-- 'sandbox-category' --> 'Template sandboxes'
-- 'module-sandbox-category' --> 'Module sandboxes'
-- 'other-sandbox-category' --> 'Sandboxes outside of template or module namespace'
--]=]
local title = env.title
local sandboxTitle = env.sandboxTitle
local templateTitle = env.templateTitle
local subjectSpace = env.subjectSpace
if not (subjectSpace and title and sandboxTitle and templateTitle
and mw.title.equals(title, sandboxTitle)) then
return nil
end
end
-- Build the table of arguments to pass to {{ombox}}. We need just two fields, "image" and "text".
if args.caption then
local omargs = {}
args.caption1 = args.caption
omargs.image = message('sandbox-notice-image')
-- Get the text. We start with the opening blurb, which is something like
-- "This is the template sandbox for [[Template:Foo]] (diff)."
local text = '__EXPECTUNUSEDTEMPLATE__'
local pagetype, sandboxCat
if subjectSpace == 10 then
pagetype = message('sandbox-notice-pagetype-template')
sandboxCat = message('sandbox-category')
elseif subjectSpace == 828 then
pagetype = message('sandbox-notice-pagetype-module')
sandboxCat = message('module-sandbox-category')
else
pagetype = message('sandbox-notice-pagetype-other')
sandboxCat = message('other-sandbox-category')
end
end
local templateLink = makeWikilink(templateTitle.prefixedText)
local imagenums = getArgNums('image')
local compareUrl = env.compareUrl
for k, num in ipairs(imagenums) do
if compareUrl then
local caption = args['caption' .. tostring(num)]
local compareDisplay = message('sandbox-notice-compare-link-display')
local data = mw.html.create():wikitext(args['image' .. tostring(num)])
local compareLink = makeUrlLink(compareUrl, compareDisplay)
if caption then
text = text .. message('sandbox-notice-diff-blurb', {pagetype, templateLink, compareLink})
data
else
:tag('div')
text = text .. message('sandbox-notice-blurb', {pagetype, templateLink})
: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
-- Get the test cases page blurb if the page exists. This is something like
end
-- "See also the companion subpage for [[Template:Foo/testcases|test cases]]."
 
local testcasesTitle = env.testcasesTitle
-- When autoheaders are turned on, preprocesses the rows
if testcasesTitle and testcasesTitle.exists then
local function preprocessRows()
if testcasesTitle.contentModel == "Scribunto" then
if not args.autoheaders then return end
local testcasesLinkDisplay = message('sandbox-notice-testcases-link-display')
local testcasesRunLinkDisplay = message('sandbox-notice-testcases-run-link-display')
local rownums = union(getArgNums('header'), getArgNums('data'))
local testcasesLink = makeWikilink(testcasesTitle.prefixedText, testcasesLinkDisplay)
table.sort(rownums)
local testcasesRunLink = makeWikilink(testcasesTitle.talkPageTitle.prefixedText, testcasesRunLinkDisplay)
local lastheader
text = text .. '<br />' .. message('sandbox-notice-testcases-run-blurb', {testcasesLink, testcasesRunLink})
for k, num in ipairs(rownums) do
else
if args['header' .. tostring(num)] then
local testcasesLinkDisplay = message('sandbox-notice-testcases-link-display')
if lastheader then
local testcasesLink = makeWikilink(testcasesTitle.prefixedText, testcasesLinkDisplay)
args['header' .. tostring(lastheader)] = nil
text = text .. '<br />' .. message('sandbox-notice-testcases-blurb', {testcasesLink})
end
lastheader = num
elseif args['data' .. tostring(num)] and
args['data' .. tostring(num)]:gsub(
category_in_empty_row_pattern, ''
):match('^%S') then
local data = args['data' .. tostring(num)]
if data:gsub(category_in_empty_row_pattern, ''):match('%S') then
lastheader = nil
end
end
end
end
end
if lastheader then
-- Add the sandbox to the sandbox category.
args['header' .. tostring(lastheader)] = nil
omargs.text = text .. makeCategoryLink(sandboxCat)
end
end


-- 'documentation-clear'
-- Gets the union of the header and data argument numbers,
return '<div class="' .. message('clear') .. '"></div>'
-- and renders them all in order
.. require('Module:Message box').main('ombox', omargs)
local function renderRows()
end


function p.protectionTemplate(env)
local rownums = union(getArgNums('header'), getArgNums('data'))
-- Generates the padlock icon in the top right.
table.sort(rownums)
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
for k, num in ipairs(rownums) do
-- Messages:
addRow({
-- 'protection-template' --> 'pp-template'
header = args['header' .. tostring(num)],
-- 'protection-template-args' --> {docusage = 'yes'}
label = args['label' .. tostring(num)],
local protectionLevels = env.protectionLevels
data = args['data' .. tostring(num)],
if not protectionLevels then
datastyle = args.datastyle,
return nil
class = args['class' .. tostring(num)],
end
rowclass = args['rowclass' .. tostring(num)],
local editProt = protectionLevels.edit and protectionLevels.edit[1]
-- @deprecated next; target .infobox-<name> rowclass
local moveProt = protectionLevels.move and protectionLevels.move[1]
rowstyle = args['rowstyle' .. tostring(num)],
if editProt then
rowcellstyle = args['rowcellstyle' .. tostring(num)]
-- The page is edit-protected.
})
return require('Module:Protection banner')._main{
message('protection-reason-edit'), small = true
}
elseif moveProt and moveProt ~= 'autoconfirmed' then
-- The page is move-protected but not edit-protected. Exclude move
-- protection with the level "autoconfirmed", as this is equivalent to
-- no move protection at all.
return require('Module:Protection banner')._main{
action = 'move', small = true
}
else
return nil
end
end
end
end


----------------------------------------------------------------------------
local function renderNavBar()
-- Start box
if not args.name then return end
----------------------------------------------------------------------------


p.startBox = makeInvokeFunc('_startBox')
has_rows = true
root
:tag('tr')
:tag('td')
:attr('colspan', '2')
:addClass('infobox-navbar')
:wikitext(require('Module:Navbar')._navbar{
args.name,
mini = 1,
})
end


function p._startBox(args, env)
local function renderItalicTitle()
--[[
local italicTitle = args['italic title'] and mw.ustring.lower(args['italic title'])
-- This function generates the start box.
if italicTitle == '' or italicTitle == 'force' or italicTitle == 'yes' then
-- @args - a table of arguments passed by the user
root:wikitext(require('Module:Italic title')._main({}))
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
--
-- The actual work is done by p.makeStartBoxLinksData and p.renderStartBoxLinks which make
-- the [view] [edit] [history] [purge] links, and by p.makeStartBoxData and p.renderStartBox
-- which generate the box HTML.
--]]
env = env or p.getEnvironment(args)
local links
local content = args.content
if not content or args[1] then
-- No need to include the links if the documentation is on the template page itself.
local linksData = p.makeStartBoxLinksData(args, env)
if linksData then
links = p.renderStartBoxLinks(linksData)
end
end
-- Generate the start box html.
local data = p.makeStartBoxData(args, env, links)
if data then
return p.renderStartBox(data)
else
-- User specified no heading.
return nil
end
end
end
end


function p.makeStartBoxLinksData(args, env)
-- Categories in otherwise empty rows are collected in empty_row_categories.
--[[
-- This function adds them to the module output. It is not affected by
-- Does initial processing of data to make the [view] [edit] [history] [purge] links.
-- args.decat because this module should not prevent module-external categories
-- @args - a table of arguments passed by the user
-- from rendering.
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
local function renderEmptyRowCategories()
--
for _, s in ipairs(empty_row_categories) do
-- Messages:
root:wikitext(s)
-- 'view-link-display' --> 'view'
-- 'edit-link-display' --> 'edit'
-- 'history-link-display' --> 'history'
-- 'purge-link-display' --> 'purge'
-- 'module-preload' --> 'Template:Documentation/preload-module-doc'
-- 'docpage-preload' --> 'Template:Documentation/preload'
-- 'create-link-display' --> 'create'
--]]
local subjectSpace = env.subjectSpace
local title = env.title
local docTitle = env.docTitle
if not title or not docTitle then
return nil
end
if docTitle.isRedirect then
docTitle = docTitle.redirectTarget
end
end
end


-- Create link if /doc doesn't exist.
-- Render tracking categories. args.decat == turns off tracking categories.
local preload = args.preload
local function renderTrackingCategories()
if not preload then
if yesno(args.decat) then return end
if subjectSpace == 828 then -- Module namespace
if args.child == 'yes' then
preload = message('module-preload')
if args.title then
else
root:wikitext(
preload = message('docpage-preload')
'[[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
return {
title = title,
docTitle = docTitle,
-- View, display, edit, and purge links if /doc exists.
viewLinkDisplay = message('view-link-display'),
editLinkDisplay = message('edit-link-display'),
historyLinkDisplay = message('history-link-display'),
purgeLinkDisplay = message('purge-link-display'),
preload = preload,
createLinkDisplay = message('create-link-display')
}
end
end


function p.renderStartBoxLinks(data)
--[=[
--[[
Loads the templatestyles for the infobox.
-- Generates the [view][edit][history][purge] or [create][purge] links from the data table.
 
-- @data - a table of data generated by p.makeStartBoxLinksData
TODO: FINISH loading base templatestyles here rather than in
--]]
MediaWiki:Common.css. There are 4-5000 pages with 'raw' infobox tables.
local docTitle = data.docTitle
See [[Mediawiki_talk:Common.css/to_do#Infobox]] and/or come help :).
-- yes, we do intend to purge the template page on which the documentation appears
When we do this we should clean up the inline CSS below too.
local purgeLink = makeWikilink("Special:Purge/" .. data.title.prefixedText, data.purgeLinkDisplay)
Will have to do some bizarre conversion category like with sidebar.
 
]=]
local function loadTemplateStyles()
local frame = mw.getCurrentFrame()
if docTitle.exists then
local hlist_templatestyles = ''
local viewLink = makeWikilink(docTitle.prefixedText, data.viewLinkDisplay)
if lists.hlist_t.found then
local editLink = makeWikilink("Special:EditPage/" .. docTitle.prefixedText, data.editLinkDisplay)
hlist_templatestyles = frame:extensionTag{
local historyLink = makeWikilink("Special:PageHistory/" .. docTitle.prefixedText, data.historyLinkDisplay)
name = 'templatestyles', args = { src = lists.hlist_t.styles }
return "&#91;" .. viewLink .. "&#93; &#91;" .. editLink .. "&#93; &#91;" .. historyLink .. "&#93; &#91;" .. purgeLink .. "&#93;"
}
else
local createLink = makeUrlLink(docTitle:canonicalUrl{action = 'edit', preload = data.preload}, data.createLinkDisplay)
return  "&#91;" .. createLink .. "&#93; &#91;" .. purgeLink .. "&#93;"
end
end
return ret
end
local plainlist_templatestyles = ''
 
if lists.plainlist_t.found then
function p.makeStartBoxData(args, env, links)
plainlist_templatestyles = frame:extensionTag{
--[=[
name = 'templatestyles', args = { src = lists.plainlist_t.styles }
-- Does initial processing of data to pass to the start-box render function, p.renderStartBox.
}
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
-- @links - a string containing the [view][edit][history][purge] links - could be nil if there's an error.
--
-- Messages:
-- 'documentation-icon-wikitext' --> '[[File:Test Template Info-Icon - Version (2).svg|50px|link=|alt=]]'
-- 'template-namespace-heading' --> 'Template documentation'
-- 'module-namespace-heading' --> 'Module documentation'
-- 'file-namespace-heading' --> 'Summary'
-- 'other-namespaces-heading' --> 'Documentation'
-- 'testcases-create-link-display' --> 'create'
--]=]
local subjectSpace = env.subjectSpace
if not subjectSpace then
-- Default to an "other namespaces" namespace, so that we get at least some output
-- if an error occurs.
subjectSpace = 2
end
end
local data = {}
-- Heading
-- See function description
local heading = args.heading -- Blank values are not removed.
local base_templatestyles = frame:extensionTag{
if heading == '' then
name = 'templatestyles', args = { src = 'Module:Infobox/styles.css' }
-- Don't display the start box if the heading arg is defined but blank.
}
return nil
 
end
local templatestyles = ''
if heading then
if args['templatestyles'] then
data.heading = heading
templatestyles = frame:extensionTag{
elseif subjectSpace == 10 then -- Template namespace
name = 'templatestyles', args = { src = args['templatestyles'] }
data.heading = message('documentation-icon-wikitext') .. ' ' .. message('template-namespace-heading')
}
elseif subjectSpace == 828 then -- Module namespace
data.heading = message('documentation-icon-wikitext') .. ' ' .. message('module-namespace-heading')
elseif subjectSpace == 6 then -- File namespace
data.heading = message('file-namespace-heading')
else
data.heading = message('other-namespaces-heading')
end
end
-- Heading CSS
local child_templatestyles = ''
local headingStyle = args['heading-style']
if args['child templatestyles'] then
if headingStyle then
child_templatestyles = frame:extensionTag{
data.headingStyleText = headingStyle
name = 'templatestyles', args = { src = args['child templatestyles'] }
else
}
-- 'documentation-heading'
data.headingClass = message('main-div-heading-class')
end
end
-- Data for the [view][edit][history][purge] or [create] links.
local grandchild_templatestyles = ''
if links then
if args['grandchild templatestyles'] then
-- 'mw-editsection-like plainlinks'
grandchild_templatestyles = frame:extensionTag{
data.linksClass = message('start-box-link-classes')
name = 'templatestyles', args = { src = args['grandchild templatestyles'] }
data.links = links
}
end
end
return data
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


function p.renderStartBox(data)
-- common functions between the child and non child cases
-- Renders the start box html.
local function structure_infobox_common()
-- @data - a table of data generated by p.makeStartBoxData.
renderSubheaders()
local sbox = mw.html.create('div')
renderImages()
sbox
preprocessRows()
-- 'documentation-startbox'
renderRows()
:addClass(message('start-box-class'))
renderBelowRow()
:newline()
renderNavBar()
:tag('span')
renderItalicTitle()
:addClass(data.headingClass)
renderEmptyRowCategories()
:attr('id', 'documentation-heading')
renderTrackingCategories()
:cssText(data.headingStyleText)
cleanInfobox()
:wikitext(data.heading)
local links = data.links
if links then
sbox:tag('span')
:addClass(data.linksClass)
:attr('id', data.linksId)
:wikitext(links)
end
return tostring(sbox)
end
end


----------------------------------------------------------------------------
-- Specify the overall layout of the infobox, with special settings if the
-- Documentation content
-- infobox is used as a 'child' inside another infobox.
----------------------------------------------------------------------------
local function _infobox()
if args.child ~= 'yes' then
root = mw.html.create('table')


p.content = makeInvokeFunc('_content')
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 })


function p._content(args, env)
renderTitle()
-- Displays the documentation contents
renderAboveRow()
-- @args - a table of arguments passed by the user
else
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
root = mw.html.create()
env = env or p.getEnvironment(args)
 
local docTitle = env.docTitle
root
local content = args.content
:wikitext(args.title)
if not content and docTitle and docTitle.exists then
content = args._content or mw.getCurrentFrame():expandTemplate{title = docTitle.prefixedText}
end
end
-- The line breaks below are necessary so that "=== Headings ===" at the start and end
structure_infobox_common()
-- of docs are interpreted correctly.
return '\n' .. (content or '') .. '\n'
return loadTemplateStyles() .. root
end
end


p.contentTitle = makeInvokeFunc('_contentTitle')
-- If the argument exists and isn't blank, add it to the argument table.
 
-- Blank arguments are treated as nil to match the behaviour of ParserFunctions.
function p._contentTitle(args, env)
local function preprocessSingleArg(argName)
env = env or p.getEnvironment(args)
if origArgs[argName] and origArgs[argName] ~= '' then
local docTitle = env.docTitle
args[argName] = origArgs[argName]
if not args.content and docTitle and docTitle.exists then
return docTitle.prefixedText
else
return ''
end
end
end
end


----------------------------------------------------------------------------
-- Assign the parameters with the given prefixes to the args table, in order, in
-- End box
-- batches of the step size specified. This is to prevent references etc. from
----------------------------------------------------------------------------
-- appearing in the wrong order. The prefixTable should be an array containing
 
-- tables, each of which has two possible fields, a "prefix" string and a
p.endBox = makeInvokeFunc('_endBox')
-- "depend" table. The function always parses parameters containing the "prefix"
 
-- string, but only parses parameters in the "depend" table if the prefix
function p._endBox(args, env)
-- parameter is present and non-blank.
--[=[
local function preprocessArgs(prefixTable, step)
-- This function generates the end box (also known as the link box).
if type(prefixTable) ~= 'table' then
-- @args - a table of arguments passed by the user
error("Non-table value detected for the prefix table", 2)
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
--  
--]=]
-- Get environment data.
env = env or p.getEnvironment(args)
local subjectSpace = env.subjectSpace
local docTitle = env.docTitle
if not subjectSpace or not docTitle then
return nil
end
end
if type(step) ~= 'number' then
-- Check whether we should output the end box at all. Add the end
error("Invalid step value detected", 2)
-- box by default if the documentation exists or if we are in the
-- user, module or template namespaces.
local linkBox = args['link box']
if linkBox == 'off'
or not (
docTitle.exists
or subjectSpace == 2
or subjectSpace == 828
or subjectSpace == 10
)
then
return nil
end
end


-- Assemble the link box.
-- Get arguments without a number suffix, and check for bad input.
local text = ''
for i,v in ipairs(prefixTable) do
if linkBox then
if type(v) ~= 'table' or type(v.prefix) ~= "string" or
text = text .. linkBox
(v.depend and type(v.depend) ~= 'table') then
else
error('Invalid input detected to preprocessArgs prefix table', 2)
text = text .. (p.makeDocPageBlurb(args, env) or '') -- "This documentation is transcluded from [[Foo]]."
end
if subjectSpace == 2 or subjectSpace == 10 or subjectSpace == 828 then
preprocessSingleArg(v.prefix)
-- We are in the user, template or module namespaces.
-- Only parse the depend parameter if the prefix parameter is present
-- Add sandbox and testcases links.
-- and not blank.
-- "Editors can experiment in this template's sandbox and testcases pages."
if args[v.prefix] and v.depend then
text = text .. (p.makeExperimentBlurb(args, env) or '') .. '<br />'
for j, dependValue in ipairs(v.depend) do
if not args.content and not args[1] then
if type(dependValue) ~= 'string' then
-- "Please add categories to the /doc subpage."
error('Invalid "depend" parameter value detected in preprocessArgs')
-- Don't show this message with inline docs or with an explicitly specified doc page,
end
-- as then it is unclear where to add the categories.
preprocessSingleArg(dependValue)
text = text .. (p.makeCategoriesBlurb(args, env) or '')
end
end
text = text .. ' ' .. (p.makeSubpagesBlurb(args, env) or '') --"Subpages of this template"
end
end
end
end
local box = mw.html.create('div')
-- 'documentation-metadata'
box:attr('role', 'note')
:addClass(message('end-box-class'))
-- 'plainlinks'
:addClass(message('end-box-plainlinks'))
:wikitext(text)
:done()


return '\n' .. tostring(box)
-- Get arguments with number suffixes.
end
local a = 1 -- Counter variable.
 
local moreArgumentsExist = true
function p.makeDocPageBlurb(args, env)
while moreArgumentsExist == true do
--[=[
moreArgumentsExist = false
-- Makes the blurb "This documentation is transcluded from [[Template:Foo]] (edit, history)".
for i = a, a + step - 1 do
-- @args - a table of arguments passed by the user
for j,v in ipairs(prefixTable) do
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
local prefixArgName = v.prefix .. tostring(i)
--
if origArgs[prefixArgName] then
-- Messages:
-- Do another loop if any arguments are found, even blank ones.
-- 'edit-link-display' --> 'edit'
moreArgumentsExist = true
-- 'history-link-display' --> 'history'
preprocessSingleArg(prefixArgName)
-- 'transcluded-from-blurb' -->
end
-- 'The above [[Wikipedia:Template documentation|documentation]]
-- Process the depend table if the prefix argument is present
-- is [[Help:Transclusion|transcluded]] from $1.'
-- and not blank, or we are processing "prefix1" and "prefix" is
-- 'module-preload' --> 'Template:Documentation/preload-module-doc'
-- present and not blank, and if the depend table is present.
-- 'create-link-display' --> 'create'
if v.depend and (args[prefixArgName] or (i == 1 and args[v.prefix])) then
-- 'create-module-doc-blurb' -->
for j,dependValue in ipairs(v.depend) do
-- 'You might want to $1 a documentation page for this [[Wikipedia:Lua|Scribunto module]].'
local dependArgName = dependValue .. tostring(i)
--]=]
preprocessSingleArg(dependArgName)
local docTitle = env.docTitle
end
if not docTitle then
end
return nil
end
end
end
if docTitle.exists then
a = a + step
-- /doc exists; link to it.
local docLink = makeWikilink(docTitle.prefixedText)
local editDisplay = message('edit-link-display')
local editLink = makeWikilink("Special:EditPage/" .. docTitle.prefixedText, editDisplay)
local historyDisplay = message('history-link-display')
local historyLink = makeWikilink("Special:PageHistory/" .. docTitle.prefixedText, historyDisplay)
return message('transcluded-from-blurb', {docLink})
.. ' '
.. makeToolbar(editLink, historyLink)
.. '<br />'
elseif env.subjectSpace == 828 then
-- /doc does not exist; ask to create it.
local createUrl = docTitle:canonicalUrl{action = 'edit', preload = message('module-preload')}
local createDisplay = message('create-link-display')
local createLink = makeUrlLink(createUrl, createDisplay)
return message('create-module-doc-blurb', {createLink})
.. '<br />'
end
end
end
end


function p.makeExperimentBlurb(args, env)
-- Parse the data parameters in the same order that the old {{infobox}} did, so
--[[
-- that references etc. will display in the expected places. Parameters that
-- Renders the text "Editors can experiment in this template's sandbox (edit | diff) and testcases (edit) pages."
-- depend on another parameter are only processed if that parameter is present,
-- @args - a table of arguments passed by the user
-- to avoid phantom references appearing in article reference lists.
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
local function parseDataParameters()
--
-- Messages:
-- 'sandbox-link-display' --> 'sandbox'
-- 'sandbox-edit-link-display' --> 'edit'
-- 'compare-link-display' --> 'diff'
-- 'module-sandbox-preload' --> 'Template:Documentation/preload-module-sandbox'
-- 'template-sandbox-preload' --> 'Template:Documentation/preload-sandbox'
-- 'sandbox-create-link-display' --> 'create'
-- 'mirror-edit-summary' --> 'Create sandbox version of $1'
-- 'mirror-link-display' --> 'mirror'
-- 'mirror-link-preload' --> 'Template:Documentation/mirror'
-- 'sandbox-link-display' --> 'sandbox'
-- 'testcases-link-display' --> 'testcases'
-- 'testcases-edit-link-display'--> 'edit'
-- 'template-sandbox-preload' --> 'Template:Documentation/preload-sandbox'
-- 'testcases-create-link-display' --> 'create'
-- 'testcases-link-display' --> 'testcases'
-- 'testcases-edit-link-display' --> 'edit'
-- 'module-testcases-preload' --> 'Template:Documentation/preload-module-testcases'
-- 'template-testcases-preload' --> 'Template:Documentation/preload-testcases'
-- 'experiment-blurb-module' --> 'Editors can experiment in this module's $1 and $2 pages.'
-- 'experiment-blurb-template' --> 'Editors can experiment in this template's $1 and $2 pages.'
--]]
local subjectSpace = env.subjectSpace
local templateTitle = env.templateTitle
local sandboxTitle = env.sandboxTitle
local testcasesTitle = env.testcasesTitle
local templatePage = templateTitle.prefixedText
if not subjectSpace or not templateTitle or not sandboxTitle or not testcasesTitle then
return nil
end
-- Make links.
local sandboxLinks, testcasesLinks
if sandboxTitle.exists then
local sandboxPage = sandboxTitle.prefixedText
local sandboxDisplay = message('sandbox-link-display')
local sandboxLink = makeWikilink(sandboxPage, sandboxDisplay)
local sandboxEditDisplay = message('sandbox-edit-link-display')
local sandboxEditLink = makeWikilink("Special:EditPage/" .. sandboxPage, sandboxEditDisplay)
local compareUrl = env.compareUrl
local compareLink
if compareUrl then
local compareDisplay = message('compare-link-display')
compareLink = makeUrlLink(compareUrl, compareDisplay)
end
sandboxLinks = sandboxLink .. ' ' .. makeToolbar(sandboxEditLink, compareLink)
else
local sandboxPreload
if subjectSpace == 828 then
sandboxPreload = message('module-sandbox-preload')
else
sandboxPreload = message('template-sandbox-preload')
end
local sandboxCreateUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = sandboxPreload}
local sandboxCreateDisplay = message('sandbox-create-link-display')
local sandboxCreateLink = makeUrlLink(sandboxCreateUrl, sandboxCreateDisplay)
local mirrorSummary = message('mirror-edit-summary', {makeWikilink(templatePage)})
local mirrorPreload = message('mirror-link-preload')
local mirrorUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = mirrorPreload, summary = mirrorSummary}
if subjectSpace == 828 then
mirrorUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = templateTitle.prefixedText, summary = mirrorSummary}
end
local mirrorDisplay = message('mirror-link-display')
local mirrorLink = makeUrlLink(mirrorUrl, mirrorDisplay)
sandboxLinks = message('sandbox-link-display') .. ' ' .. makeToolbar(sandboxCreateLink, mirrorLink)
end
if testcasesTitle.exists then
local testcasesPage = testcasesTitle.prefixedText
local testcasesDisplay = message('testcases-link-display')
local testcasesLink = makeWikilink(testcasesPage, testcasesDisplay)
local testcasesEditUrl = testcasesTitle:canonicalUrl{action = 'edit'}
local testcasesEditDisplay = message('testcases-edit-link-display')
local testcasesEditLink = makeWikilink("Special:EditPage/" .. testcasesPage, testcasesEditDisplay)
-- for Modules, add testcases run link if exists
if testcasesTitle.contentModel == "Scribunto"  and testcasesTitle.talkPageTitle and testcasesTitle.talkPageTitle.exists then
local testcasesRunLinkDisplay = message('testcases-run-link-display')
local testcasesRunLink = makeWikilink(testcasesTitle.talkPageTitle.prefixedText, testcasesRunLinkDisplay)
testcasesLinks = testcasesLink .. ' ' .. makeToolbar(testcasesEditLink, testcasesRunLink)
else
testcasesLinks = testcasesLink .. ' ' .. makeToolbar(testcasesEditLink)
end
else
local testcasesPreload
if subjectSpace == 828 then
testcasesPreload = message('module-testcases-preload')
else
testcasesPreload = message('template-testcases-preload')
end
local testcasesCreateUrl = testcasesTitle:canonicalUrl{action = 'edit', preload = testcasesPreload}
local testcasesCreateDisplay = message('testcases-create-link-display')
local testcasesCreateLink = makeUrlLink(testcasesCreateUrl, testcasesCreateDisplay)
testcasesLinks = message('testcases-link-display') .. ' ' .. makeToolbar(testcasesCreateLink)
end
local messageName
if subjectSpace == 828 then
messageName = 'experiment-blurb-module'
else
messageName = 'experiment-blurb-template'
end
return message(messageName, {sandboxLinks, testcasesLinks})
end


function p.makeCategoriesBlurb(args, env)
preprocessSingleArg('autoheaders')
--[[
preprocessSingleArg('child')
-- Generates the text "Please add categories to the /doc subpage."
preprocessSingleArg('bodyclass')
-- @args - a table of arguments passed by the user
preprocessSingleArg('subbox')
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
preprocessSingleArg('bodystyle')
-- Messages:
preprocessSingleArg('title')
-- 'doc-link-display' --> '/doc'
preprocessSingleArg('titleclass')
-- 'add-categories-blurb' --> 'Please add categories to the $1 subpage.'
preprocessSingleArg('titlestyle')
--]]
preprocessSingleArg('above')
local docTitle = env.docTitle
preprocessSingleArg('aboveclass')
if not docTitle then
preprocessSingleArg('abovestyle')
return nil
preprocessArgs({
end
{prefix = 'subheader', depend = {'subheaderstyle', 'subheaderrowclass'}}
local docPathLink = makeWikilink(docTitle.prefixedText, message('doc-link-display'))
}, 10)
return message('add-categories-blurb', {docPathLink})
preprocessSingleArg('subheaderstyle')
preprocessSingleArg('subheaderclass')
preprocessArgs({
{prefix = 'image', depend = {'caption', 'imagerowclass'}}
}, 10)
preprocessSingleArg('captionstyle')
preprocessSingleArg('imagestyle')
preprocessSingleArg('imageclass')
preprocessArgs({
{prefix = 'header'},
{prefix = 'data', depend = {'label'}},
{prefix = 'rowclass'},
{prefix = 'rowstyle'},
{prefix = 'rowcellstyle'},
{prefix = 'class'}
}, 50)
preprocessSingleArg('headerclass')
preprocessSingleArg('headerstyle')
preprocessSingleArg('labelstyle')
preprocessSingleArg('datastyle')
preprocessSingleArg('below')
preprocessSingleArg('belowclass')
preprocessSingleArg('belowstyle')
preprocessSingleArg('name')
-- different behaviour for italics if blank or absent
args['italic title'] = origArgs['italic title']
preprocessSingleArg('decat')
preprocessSingleArg('templatestyles')
preprocessSingleArg('child templatestyles')
preprocessSingleArg('grandchild templatestyles')
end
end


function p.makeSubpagesBlurb(args, env)
-- If called via #invoke, use the args passed into the invoking template.
--[[
-- Otherwise, for testing purposes, assume args are being passed directly in.
-- Generates the "Subpages of this template" link.
function p.infobox(frame)
-- @args - a table of arguments passed by the user
if frame == mw.getCurrentFrame() then
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
origArgs = frame:getParent().args
-- Messages:
-- 'template-pagetype' --> 'template'
-- 'module-pagetype' --> 'module'
-- 'default-pagetype' --> 'page'
-- 'subpages-link-display' --> 'Subpages of this $1'
--]]
local subjectSpace = env.subjectSpace
local templateTitle = env.templateTitle
if not subjectSpace or not templateTitle then
return nil
end
local pagetype
if subjectSpace == 10 then
pagetype = message('template-pagetype')
elseif subjectSpace == 828 then
pagetype = message('module-pagetype')
else
else
pagetype = message('default-pagetype')
origArgs = frame
end
end
local subpagesLink = makeWikilink(
'Special:PrefixIndex/' .. templateTitle.prefixedText .. '/',
parseDataParameters()
message('subpages-link-display', {pagetype})
)
return _infobox()
return message('subpages-blurb', {subpagesLink})
end
end


----------------------------------------------------------------------------
-- For calling via #invoke within a template
-- Tracking categories
function p.infoboxTemplate(frame)
----------------------------------------------------------------------------
origArgs = {}
 
for k,v in pairs(frame.args) do origArgs[k] = mw.text.trim(v) end
function p.addTrackingCategories(env)
--[[
parseDataParameters()
-- Check if {{documentation}} is transcluded on a /doc or /testcases page.
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
-- Messages:
return _infobox()
-- 'display-strange-usage-category' --> true
-- 'doc-subpage' --> 'doc'
-- 'testcases-subpage' --> 'testcases'
-- 'strange-usage-category' --> 'Wikipedia pages with strange ((documentation)) usage'
--
-- /testcases pages in the module namespace are not categorised, as they may have
-- {{documentation}} transcluded automatically.
--]]
local title = env.title
local subjectSpace = env.subjectSpace
if not title or not subjectSpace then
return nil
end
local subpage = title.subpageText
if message('display-strange-usage-category', nil, 'boolean')
and (
subpage == message('doc-subpage')
or subjectSpace ~= 828 and subpage == message('testcases-subpage')
)
then
return makeCategoryLink(message('strange-usage-category'))
end
return ''
end
end
return p
return p

Latest revision as of 17:46, 19 January 2026


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 yesno = require("Module:Yesno")
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'
		},
		found = false,
		styles = 'Hlist/styles.css'
	}
}

local function has_list_class(args_to_check)
	for _, list in pairs(lists) do
		if not list.found then
			for _, arg in pairs(args_to_check) do
				for _, pattern in ipairs(list.patterns) do
					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)
	local function notempty( s ) return s and s:match( '%S' ) end
	
	if notempty(sval) then
		local marker = '<span class=special_infobox_marker>'
		local s = sval
		-- start moving templatestyles and categories inside of table rows
		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
		return sval
	end
end

-- Cleans empty tables
local function cleanInfobox()
	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
	for k, v in pairs(t2) do
		vals[v] = true
	end
	local ret = {}
	for k, v in pairs(vals) do
		table.insert(ret, k)
	end
	return ret
end

-- Returns a table containing the numbers of the arguments that exist
-- for the specified prefix. For example, if the prefix was 'data', and
-- 'data1', 'data2', and 'data5' exist, it would return {1, 2, 5}.
local function getArgNums(prefix)
	local nums = {}
	for k, v in pairs(args) do
		local num = tostring(k):match('^' .. prefix .. '([1-9]%d*)$')
		if num then table.insert(nums, tonumber(num)) end
	end
	table.sort(nums)
	return nums
end

-- Adds a row to the infobox, with either a header cell
-- or a label/data cell combination.
local function addRow(rowArgs)
	
	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 and not yesno(args.decat) then
			root:wikitext(
				'[[Category:Pages using infobox templates with ignored data cells]]'
			)
		end
	elseif rowArgs.data and rowArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
		has_rows = true
		has_list_class({ rowArgs.rowclass, rowArgs.class })
		
		local row = root:tag('tr')
		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

		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

local function renderTitle()
	if not args.title then return end

	has_rows = true
	has_list_class({args.titleclass})
	
	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

local function renderSubheaders()
	if args.subheader then
		args.subheader1 = args.subheader
	end
	if args.subheaderrowclass then
		args.subheaderrowclass1 = args.subheaderrowclass
	end
	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
		table.insert(empty_row_categories, imageArgs.data or '')
	end
end

local function renderImages()
	if args.image then
		args.image1 = args.image
	end
	if args.caption then
		args.caption1 = args.caption
	end
	local imagenums = getArgNums('image')
	for k, num in ipairs(imagenums) do
		local caption = args['caption' .. tostring(num)]
		local data = mw.html.create():wikitext(args['image' .. tostring(num)])
		if caption then
			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

-- When autoheaders are turned on, preprocesses the rows
local function preprocessRows()
	if not args.autoheaders then return end
	
	local rownums = union(getArgNums('header'), getArgNums('data'))
	table.sort(rownums)
	local lastheader
	for k, num in ipairs(rownums) do
		if args['header' .. tostring(num)] then
			if lastheader then
				args['header' .. tostring(lastheader)] = nil
			end
			lastheader = num
		elseif args['data' .. tostring(num)] and
			args['data' .. tostring(num)]:gsub(
				category_in_empty_row_pattern, ''
			):match('^%S') then
			local data = args['data' .. tostring(num)]
			if data:gsub(category_in_empty_row_pattern, ''):match('%S') then
				lastheader = nil
			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'))
	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

local function renderNavBar()
	if not args.name then return end

	has_rows = true
	root
		:tag('tr')
			:tag('td')
				:attr('colspan', '2')
				:addClass('infobox-navbar')
				:wikitext(require('Module:Navbar')._navbar{
					args.name,
					mini = 1,
				})
end

local function renderItalicTitle()
	local italicTitle = args['italic title'] and mw.ustring.lower(args['italic title'])
	if italicTitle == '' or italicTitle == 'force' or italicTitle == 'yes' then
		root:wikitext(require('Module:Italic title')._main({}))
	end
end

-- Categories in otherwise empty rows are collected in empty_row_categories.
-- This function adds them to the module output. It is not affected by
-- args.decat because this module should not prevent module-external categories
-- from rendering.
local function renderEmptyRowCategories()
	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 yesno(args.decat) 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
	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
	
	local grandchild_templatestyles = ''
	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

-- common functions between the child and non child cases
local function structure_infobox_common()
	renderSubheaders()
	renderImages()
	preprocessRows()
	renderRows()
	renderBelowRow()
	renderNavBar()
	renderItalicTitle()
	renderEmptyRowCategories()
	renderTrackingCategories()
	cleanInfobox()
end

-- Specify the overall layout of the infobox, with special settings if the
-- infobox is used as a 'child' inside another infobox.
local function _infobox()
	if args.child ~= 'yes' then
		root = mw.html.create('table')

		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

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

-- Assign the parameters with the given prefixes to the args table, in order, in
-- batches of the step size specified. This is to prevent references etc. from
-- appearing in the wrong order. The prefixTable should be an array containing
-- tables, each of which has two possible fields, a "prefix" string and a
-- "depend" table. The function always parses parameters containing the "prefix"
-- string, but only parses parameters in the "depend" table if the prefix
-- parameter is present and non-blank.
local function preprocessArgs(prefixTable, step)
	if type(prefixTable) ~= 'table' then
		error("Non-table value detected for the prefix table", 2)
	end
	if type(step) ~= 'number' then
		error("Invalid step value detected", 2)
	end

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

-- Parse the data parameters in the same order that the old {{infobox}} did, so
-- that references etc. will display in the expected places. Parameters that
-- depend on another parameter are only processed if that parameter is present,
-- to avoid phantom references appearing in article reference lists.
local function parseDataParameters()

	preprocessSingleArg('autoheaders')
	preprocessSingleArg('child')
	preprocessSingleArg('bodyclass')
	preprocessSingleArg('subbox')
	preprocessSingleArg('bodystyle')
	preprocessSingleArg('title')
	preprocessSingleArg('titleclass')
	preprocessSingleArg('titlestyle')
	preprocessSingleArg('above')
	preprocessSingleArg('aboveclass')
	preprocessSingleArg('abovestyle')
	preprocessArgs({
		{prefix = 'subheader', depend = {'subheaderstyle', 'subheaderrowclass'}}
	}, 10)
	preprocessSingleArg('subheaderstyle')
	preprocessSingleArg('subheaderclass')
	preprocessArgs({
		{prefix = 'image', depend = {'caption', 'imagerowclass'}}
	}, 10)
	preprocessSingleArg('captionstyle')
	preprocessSingleArg('imagestyle')
	preprocessSingleArg('imageclass')
	preprocessArgs({
		{prefix = 'header'},
		{prefix = 'data', depend = {'label'}},
		{prefix = 'rowclass'},
		{prefix = 'rowstyle'},
		{prefix = 'rowcellstyle'},
		{prefix = 'class'}
	}, 50)
	preprocessSingleArg('headerclass')
	preprocessSingleArg('headerstyle')
	preprocessSingleArg('labelstyle')
	preprocessSingleArg('datastyle')
	preprocessSingleArg('below')
	preprocessSingleArg('belowclass')
	preprocessSingleArg('belowstyle')
	preprocessSingleArg('name')
	-- different behaviour for italics if blank or absent
	args['italic title'] = origArgs['italic title']
	preprocessSingleArg('decat')
	preprocessSingleArg('templatestyles')
	preprocessSingleArg('child templatestyles')
	preprocessSingleArg('grandchild templatestyles')
end

-- If called via #invoke, use the args passed into the invoking template.
-- Otherwise, for testing purposes, assume args are being passed directly in.
function p.infobox(frame)
	if frame == mw.getCurrentFrame() then
		origArgs = frame:getParent().args
	else
		origArgs = frame
	end
	
	parseDataParameters()
	
	return _infobox()
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