Module:Infobox: Difference between revisions

From The Satanic Wiki
Jump to navigation Jump to search
No edit summary
Tag: Reverted
No edit summary
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
local p = {}
local p = {}
local wikiLang = 'fr'
local args = {}
 
local origArgs = {}
local item = nil -- l'élément Wikidata lié
local root
local localdata = {}-- données concernant les paramètres passés au modèle
local empty_row_categories = {}
local page = { -- données concernant la page où est affichée l'infobox
local category_in_empty_row_pattern = '%[%[%s*[Cc][Aa][Tt][Ee][Gg][Oo][Rr][Yy]%s*:[^]]*]]'
name = mw.title.getCurrentTitle().prefixedText,
local has_rows = false
namespace = mw.title.getCurrentTitle().namespace
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 maincolor, secondcolor, thirdcolor = '#E1E1E1', '#E1E1E1', '#000000'
-- l'objet principal à retourner
local infobox = mw.html.create('div')


-- objets secondaires à retourner
local function has_list_class(args_to_check)
local maintenance = '' -- chaîne retournée avec le module : cats de maintenance
for _, list in pairs(lists) do
local externaltext = '' -- par exemple coordonnées en titre
if not list.found then
-- modules importés
for _, arg in pairs(args_to_check) do
local linguistic = require "Module:Linguistique"
for _, pattern in ipairs(list.patterns) do
local wd = require 'Module:Wikidata'
if mw.ustring.find(arg or '', pattern) then
local yesno = require 'Module:Yesno'
list.found = true
local valueexpl = wd.translate("activate-query")
break
end
end
if list.found then break end
end
end
end
end


local i18n = {
local function fixChildBoxes(sval, tt)
['see doc'] = 'Documentation du modèle',
local function notempty( s ) return s and s:match( '%S' ) end
['edit'] = 'modifier',
['edit code'] = 'modifier le code',
if notempty(sval) then
['edit item'] = 'modifier Wikidata',
local marker = '<span class=special_infobox_marker>'
['tracking cat'] = "Page utilisant des données de Wikidata",
local s = sval
['invalid block type'] = "Bloc de données invalide dans le module d'infobox",
-- start moving templatestyles and categories inside of table rows
['default cat'] = "Maintenance des infobox",
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


local function addWikidataCat(prop)
-- Cleans empty tables
maintenance = maintenance .. wd.addTrackingCat(prop)
local function cleanInfobox()
root = tostring(root)
if has_rows == false then
root = mw.ustring.gsub(root, '<table[^<>]*>%s*</table>', '')
end
end
end


local function expandQuery(query)
-- Returns the union of the values of two tables, as a sequence.
local value, number -- valeur à retourner, nombre de valeurs pour accorder le libellé
local function union(t1, t2)
if not query.entity then
 
query.entity = localdata.item
local vals = {}
for k, v in pairs(t1) do
vals[v] = true
end
end
if not query.conjtype then
for k, v in pairs(t2) do
query.conjtype = 'comma'
vals[v] = true
end
end
local claims = wd.getClaims(query)
local ret = {}
if (not claims) then
for k, v in pairs(vals) do
return nil
table.insert(ret, k)
end
end
return wd.formatAndCat(query), #claims -- pour l'accord au pluriel
return ret
end
end


local function getWikidataValue(params, wikidataparam)
-- Returns a table containing the numbers of the arguments that exist
-- Récupère la valeur Wikidata pour la valeur, soit dans le paramètre "wikidata" soit dans le paramètre "property"
-- for the specified prefix. For example, if the prefix was 'data', and
if not localdata.item then
-- 'data1', 'data2', and 'data5' exist, it would return {1, 2, 5}.
return nil
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
end
table.sort(nums)
return nums
end


if params.blockers then -- blockers are local parameters that disable the wikidata query
-- Adds a row to the infobox, with either a header cell
local blockers = params.blockers
-- or a label/data cell combination.
if (type(blockers) == 'string') then
local function addRow(rowArgs)
blockers = {blockers}
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
for i, blocker in ipairs(blockers) do
elseif rowArgs.data and rowArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
if localdata[blocker] then
has_rows = true
return nil
has_list_class({ rowArgs.rowclass, rowArgs.class })
end
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
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
end
local function renderTitle()
if not args.title then return end


local v, valnum -- la valeur à retourner, et le nombre de de valeurs (pour l'accord grammatical)
has_rows = true
has_list_class({args.titleclass})
if not wikidataparam then -- par défaut la valeur wikidata est dans le paramètre "wikidata" mais dans les structures composées comme "title", il y a plusieurs paramètres wikidata
root
wikidataparam = 'wikidata'
:tag('caption')
end
:addClass('infobox-title')
:addClass(args.titleclass)
-- @deprecated next; target .infobox-<name> .infobox-title
:cssText(args.titlestyle)
:wikitext(args.title)
end


if params[wikidataparam] then
local function renderAboveRow()
if type(params[wikidataparam]) == 'function' then
if not args.above then return end
v, valnum = params[wikidataparam](localdata.item)
elseif type(params[wikidataparam]) == 'table' then
v, valnum = expandQuery(params[wikidataparam])
else
v, valnum = params[wikidataparam]
end
end
if not v then
return nil
end
v = linguistic.ucfirst(v)
return v, valnum
end


local function getValue(val, params)
has_rows = true
if type(val) == 'string' then
has_list_class({ args.aboveclass })
return localdata[val]
elseif type(val) == 'function' then
root
return val(localdata, localdata.item, params)
:tag('tr')
elseif type(val) == 'table' then
:tag('th')
for i, j in pairs(val) do -- si plusieurs paramètres possibles (legacy de vieux code), prendre le premier non vide
:attr('colspan', '2')
if localdata[j] then
:addClass('infobox-above')
return localdata[j]
:addClass(args.aboveclass)
end
-- @deprecated next; target .infobox-<name> .infobox-above
end
:cssText(args.abovestyle)
end
:wikitext(fixChildBoxes(args.above,'th'))
end
end


local function addMaintenanceCat(cat, sortkey)
local function renderBelowRow()
if page.namespace ~= 0 then
if not args.below then return end
return ''
end
if cat then
maintenance = maintenance .. '[[Category:' .. cat .. '|' .. (sortkey or page.name) .. ']]'
end
end


function p.separator(params)
has_rows = true
local style = params['separator style'] or {}
has_list_class({ args.belowclass })
style.height = style.height or '2px'
style['background-color'] = style['background-color'] or maincolor
return mw.html.create('hr'):css( style )
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
end


--[=[
local function addSubheaderRow(subheaderArgs)
Construit le code du bloc de titre de l'infobox
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)


Paramètres (liste partielle) :
local dataCell = row:tag('td')
- value : Moyen d'obtenir le titre via getValue (nom de paramètre de modèle ou fonction).
dataCell
- textdefaultvalue : Valeur par défaut du titre.
:attr('colspan', '2')
- icon : Pictogramme d'infobox (voir [[Projet:Infobox/Pictogramme]]).
:addClass('infobox-subheader')
- italic : Indique si le titre doit être affiché en italique.
:addClass(subheaderArgs.class)
  Si italic=true, le paramètre "titre en italique" de l'infobox peut forcer la désactivation.
:cssText(subheaderArgs.datastyle)
- setdisplaytitle : Indique si le titre de l'article doit être mis en forme comme celui de l'infobox.
:cssText(subheaderArgs.rowcellstyle)
  Si setdisplaytitle=true, le paramètre "titre article en italique" de l'infobox peut forcer la désactivation.
:wikitext(fixChildBoxes(subheaderArgs.data, 'td'))
]=]
else
function p.buildtitle(params)
table.insert(empty_row_categories, subheaderArgs.data or '')
local text = getValue(params.value, params) or params.textdefaultvalue or  getWikidataValue(params) or mw.title.getCurrentTitle().text
local lang = localdata['langue du titre'] or ''
if lang ~= '' then
local langueFunction = require( 'Module:Langue' ).langue
text = langueFunction( { lang, text } )
end
end
local subtext = getValue(params.subtitle) or  getWikidataValue(params, 'wikidatasubtitle') or params.subtitledefaultvalue
end
if subtext and (subtext ~= text) then
 
text = text .. '<br /><small>' .. subtext .. '</small>'
local function renderSubheaders()
end
if args.subheader then
local icon = params.icon or ''
args.subheader1 = args.subheader
if icon ~= '' and icon ~= 'defaut' then
text = text .. mw.getCurrentFrame():extensionTag('templatestyles', '', {src = 'Infobox/Pictogramme/' .. mw.text.trim(icon) .. '.css'})
if not params.large then
icon = 'icon ' .. icon
end
end
end
local class = 'entete ' .. icon
if args.subheaderrowclass then
args.subheaderrowclass1 = args.subheaderrowclass
local italic = params.italic and yesno(localdata['titre en italique'] or '', true, true)
if italic then
class = class .. ' italique'
end
end
if params.setdisplaytitle and yesno(localdata['titre article en italique'] or '', true, true) then
local subheadernums = getArgNums('subheader')
local formatTitleModule = require( 'Module:Formatage du titre' )
for k, num in ipairs(subheadernums) do
text = text .. formatTitleModule.setDisplayTitle{ args = {
addSubheaderRow({
lang = lang,
data = args['subheader' .. tostring(num)],
italic = italic,
-- @deprecated next; target .infobox-<name> .infobox-subheader
options = 'noreplace',
datastyle = args.subheaderstyle,
} }
rowcellstyle = args['subheaderstyle' .. tostring(num)],
class = args.subheaderclass,
rowclass = args['subheaderrowclass' .. tostring(num)]
})
end
end
-- overwrites with those provided in the module
local style = {}
style['background-color'] = maincolor
style['color'] = thirdcolor
if params.style then
for i, j in pairs(params.style) do
style[i] = j
end
end
local title = mw.html.create('div')
:addClass(class)
:css(style)
:tag('div')
:wikitext(text)
:allDone()
return title
end
end
p.buildTitle = p.buildtitle


function p.buildnavbox(params)
local function addImageRow(imageArgs)
-- définition du style
local class = "overflow nav " .. (params.class or '')
local style = params.style or {}


if params.separated then -- options pour ajouter une ligne de séparation au dessus
if imageArgs.data and
class = class .. ' bordered'
imageArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
style['border-top'] = '1px solid' .. maincolor
end


-- ajustement des paramètres de données
has_rows = true
params.previousval = params.previousval or params.previousparameter -- nom de paramètre obsolète
has_list_class({ imageArgs.rowclass, imageArgs.class })
params.nextval = params.nextval or params.nextparameter
local row = root:tag('tr')
if params.previousproperty then
row:addClass(imageArgs.rowclass)
params.previouswikidata = {property = params.previousproperty}
end
if params.nextproperty then
params.nextwikidata = {property = params.nextproperty}
end


local previousval = getValue(params.previousval, params) or getWikidataValue(params, 'previouswikidata')
local dataCell = row:tag('td')
local nextval = getValue(params.nextval, params) or getWikidataValue(params, 'nextwikidata')
dataCell
:attr('colspan', '2')
local navbox
:addClass('infobox-image')
if params.inner then -- pour celles qui sont à l'intérieur d'une table
:addClass(imageArgs.class)
navbox = mw.html.create('tr'):tag('th'):attr('colspan', 2)
:cssText(imageArgs.datastyle)
style['font-weight'] = style['font-weight'] or 'normal'
:wikitext(fixChildBoxes(imageArgs.data, 'td'))
else
else
navbox = mw.html.create('div')
table.insert(empty_row_categories, imageArgs.data or '')
end
end
if previousval or nextval then
navbox
:addClass(class)
:css(style)
:tag('div')
:addClass('prev_bloc')
:wikitext(previousval)
:done()
:tag('div')
:addClass('next_bloc')
:wikitext(nextval)
:done()
:allDone()
return navbox
end
return nil
end
end
p.buildNavbox = p.buildnavbox


function p.buildimages(params)
local function renderImages()
local images = {}
if args.image then
local upright, link, caption, alt, size  -- size is deprecated
args.image1 = args.image
if type(params.imageparameters) == 'string' then
params.imageparameters = {params.imageparameters}
end
end
if not params.imageparameters then -- s'il n'y a pas de paramètre image, continuer, peut-être y a-t-il une image par défaut définie dans le module d'infobox
if args.caption then
params.imageparameters = {}
args.caption1 = args.caption
end
end
for j, k in ipairs(params.imageparameters) do
local imagenums = getArgNums('image')
table.insert(images, localdata[k])
for k, num in ipairs(imagenums) do
end
local caption = args['caption' .. tostring(num)]
-- Images de Wikidata
local data = mw.html.create():wikitext(args['image' .. tostring(num)])
if #images == 0 and localdata.item then
if caption then
if params.property then
data
params.wikidata = {entity = localdata.item, property = params.property}
:tag('div')
end
:addClass('infobox-caption')
if params.wikidata then
-- @deprecated next; target .infobox-<name> .infobox-caption
local wdq = params.wikidata
:cssText(args.captionstyle)
wdq.excludespecial = true
:wikitext(caption)
if type(wdq) == 'table' then
wdq.entity = wdq.entity or localdata.item
wdq.numval = wdq.numval or params.numval or 1
images = wd.getClaims(wdq)
end
if type(wdq) == 'function' then
images = params.wikidata()
if type(images) == 'string' then
return images
end --c'est probablement une erreur dans la requête => afficher le message
end
if (not images) then
images = {}
end
if (#images > 0) and (params.wikidata.property) then
addWikidataCat(params.wikidata.property)
end
 
if type(images[1]) == 'table' then
for i, image in pairs(images) do
if image.mainsnak.snaktype ~= 'value' then
return
end
if #images == 1 then -- si une seule image, on utilise la légende (si deux plusieurs images, comment mettre en forme ?)
caption = wd.getFormattedQualifiers(images[i], {'P2096'}, {isinlang = wikiLang}) or wd.getFormattedQualifiers(images[i], {'P805'})
end
images[i] = image.mainsnak.datavalue.value
end
end
end
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
end


-- Images par défaut
-- When autoheaders are turned on, preprocesses the rows
if #images == 0 then
local function preprocessRows()
if params.maintenancecat then
if not args.autoheaders then return end
addMaintenanceCat(params.maintenancecat, params.sortkey)
end
local rownums = union(getArgNums('header'), getArgNums('data'))
if params.defaultimages then
table.sort(rownums)
images = params.defaultimages
local lastheader
if type(images) == 'string' then
for k, num in ipairs(rownums) do
images = {images}
if args['header' .. tostring(num)] then
if lastheader then
args['header' .. tostring(lastheader)] = nil
end
end
upright = params.defaultimageupright
lastheader = num
caption = params.defaultimagecaption
elseif args['data' .. tostring(num)] and
link = params.defaultimagelink
args['data' .. tostring(num)]:gsub(
alt = params.defaultimagealt
category_in_empty_row_pattern, ''
if not alt and ( images[1] == 'Defaut.svg' or images[1] == 'Defaut 2.svg' ) then
):match('^%S') then
alt = 'une illustration sous licence libre serait bienvenue'
local data = args['data' .. tostring(num)]
if data:gsub(category_in_empty_row_pattern, ''):match('%S') then
lastheader = nil
end
end
end
end
end
end
if #images == 0 then
if lastheader then
return nil
args['header' .. tostring(lastheader)] = nil
end
end
end
upright = upright or getValue(params.uprightparameter) or params.defaultupright or "1.2"
link = link or getValue(params.linkparameter) or params.defaultlink
caption = caption or getValue(params.captionparameter) or params.defaultcaption
alt = alt or getValue( params.altparameter) or params.defaultalt
 
-- taille avec "size" (obsolète)
size = size or getValue(params.sizeparameter) or params.defaultsize -- deprecated
if size then
local sizevalue = size:gsub('px$', '')


local widthonly = mw.ustring.gsub(sizevalue, 'x.*', '')
-- Gets the union of the header and data argument numbers,
widthonly = tonumber(widthonly)
-- and renders them all in order
if type(widthonly) ~= 'number' or widthonly > 280 then
local function renderRows()
addMaintenanceCat("taille d'image invalide")
end


if tonumber(sizevalue) then
local rownums = union(getArgNums('header'), getArgNums('data'))
size = tostring( tonumber(sizevalue) / #images ) .. 'px'
table.sort(rownums)
end
for k, num in ipairs(rownums) do
end
addRow({
header = args['header' .. tostring(num)],
if tonumber(upright) then
label = args['label' .. tostring(num)],
upright = tostring( tonumber(upright) / #images )
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


local style = params.style or {padding ='2px 0',}
local function renderNavBar()
if not args.name then return end


-- Partie image
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 imagesString = ''
local function renderItalicTitle()
for i,image in pairs(images) do
local italicTitle = args['italic title'] and mw.ustring.lower(args['italic title'])
if image == '-' then
if italicTitle == '' or italicTitle == 'force' or italicTitle == 'yes' then
return
root:wikitext(require('Module:Italic title')._main({}))
end
imagesString = imagesString .. '[[Fichier:' .. image .. '|frameless'
if size then
imagesString = imagesString .. '|' .. size -- not a mistake, parameter is unnamed
end
if alt then
imagesString = imagesString .. '|alt=' .. alt
end
if link then
imagesString = imagesString .. '|link=' .. link
end
if upright then
imagesString = imagesString .. '|upright=' .. upright
elseif #images > 1 and not size then
imagesString = imagesString .. '|upright=' .. ( 1 / #images )
end
if image:sub(-4):lower() == '.svg' then
imagesString = imagesString .. '|lang=' .. wikiLang
end
imagesString = imagesString .. ']]'
end
end
end


local image = mw.html.create('div')
-- Categories in otherwise empty rows are collected in empty_row_categories.
:addClass("images")
-- This function adds them to the module output. It is not affected by
:css(style)
-- args.decat because this module should not prevent module-external categories
:wikitext(imagesString)
-- from rendering.
 
local function renderEmptyRowCategories()
-- Partie légende
for _, s in ipairs(empty_row_categories) do
local captionobj
root:wikitext(s)
if caption then
captionobj = mw.html.create('div')
:wikitext(caption)
:css(params.legendstyle or {})
:addClass("legend")
:done()
end
end
-- séparateur
local separator
if params.separator then
separator = separator(params)
end
return mw.html.create('div')
:node(image)
:node(captionobj)
:node(separator)
:done()
end
end
p.buildImages = p.buildimages


function p.buildtext(params)
-- Render tracking categories. args.decat == turns off tracking categories.
local class = params.class or ''
local function renderTrackingCategories()
local style = {
if args.decat == 'yes' then return end
['text-align'] = 'center',
if args.child == 'yes' then
['font-weight'] = 'bold'
if args.title then
}
root:wikitext(
if params.style then
'[[Category:Pages using embedded infobox templates with the title parameter]]'
for i, j in pairs(params.style) do
)
style[i] = j
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
local text = getValue(params.value, params) or getWikidataValue(params) or params.defaultvalue
if text == '-' then
return
end
if not text then
addMaintenanceCat(params.maintenancecat, params.sortkey)
return nil
end
local formattedtext = mw.html.create('p')
:addClass(class)
:css(style)
:wikitext(text)
:done()
return formattedtext
end
end
p.buildText = p.buildtext


function p.buildrow(params)
--[=[
local class = params.class or ''
Loads the templatestyles for the infobox.
local style = params.style or {}
local valueClass = params.valueClass or ''
local valueStyle = params.valueStyle or {}
local value, number =  getValue(params.value, params)
if (value == valueexpl) then
value = nil
params.wikidata.expl = false
end
if (not value) then
value, number =  getWikidataValue(params, 'wikidata')
end
if (not value) and (params.property) then
value, number = expandQuery{ property = params.property, ucfirst = params.ucfirst }
end
if not value then
value = params.defaultvalue
end
if value == '-' then
return nil
end
if not number then
number = 0 -- == indéfini
end


if not value then
TODO: FINISH loading base templatestyles here rather than in
if params.maintenancecat then
MediaWiki:Common.css. There are 4-5000 pages with 'raw' infobox tables.
local maintenancecat = getValue(params.maintenancecat, params)
See [[Mediawiki_talk:Common.css/to_do#Infobox]] and/or come help :).
addMaintenanceCat(maintenancecat, params.sortkey)
When we do this we should clean up the inline CSS below too.
end
Will have to do some bizarre conversion category like with sidebar.
return nil
end


local label = params.label
]=]
if number > 1 and (params.plurallabel) then
local function loadTemplateStyles()
label = params.plurallabel
local frame = mw.getCurrentFrame()
elseif number == 1 and (params.singularlabel) then
label = params.singularlabel
end
if type(label) == 'function' then
label = label(localdata, localdata.item)
end
 
-- format
local formattedvalue = mw.html.create('div')
:wikitext('\n' .. value) -- Le '\n' est requis lorsque value est une liste commençant par '*' ou '#'
if (params.hidden == true)then
formattedvalue
:attr({class="NavContent", style="display: none; text-align: left;"})
formattedvalue = mw.html.create('div')
:attr({class="NavFrame", title="[Afficher]/[Masquer]", style="border: none; padding: 0;"})
:node(formattedvalue)
end
formattedvalue =  mw.html.create('td')
:node(formattedvalue)
:addClass(valueClass)
:css(valueStyle)
:allDone()
local formattedlabel
local hlist_templatestyles = ''
if label then
if lists.hlist_t.found then
formattedlabel = mw.html.create('th')
hlist_templatestyles = frame:extensionTag{
:attr('scope', 'row')
name = 'templatestyles', args = { src = lists.hlist_t.styles }
:wikitext(label)
}
:done()
end
end
local row = mw.html.create('tr')
:addClass(class)
:css(style)
:node(formattedlabel)
:node(formattedvalue)
:done()
return row
local plainlist_templatestyles = ''
end
if lists.plainlist_t.found then
p.buildRow = p.buildrow
plainlist_templatestyles = frame:extensionTag{
 
name = 'templatestyles', args = { src = lists.plainlist_t.styles }
function p.buildsuccession(params)
}
if not params.value then
return nil
end
end
--local style = params.style or {}
--style['text-align'] = style['text-align'] or 'center'
--style['color'] = style['color'] or '#000000'
--style['background-color'] = style['background-color'] or '#F9F9F9'
local rowI = mw.html.create('tr')
-- See function description
local base_templatestyles = frame:extensionTag{
local styleI = {}
name = 'templatestyles', args = { src = 'Module:Infobox/styles.css' }
local colspan = '2'
}
styleI['padding'] = '1px'
cellI = mw.html.create('td')
:attr({colspan = colspan})
:attr({align = 'center'})
:css(styleI)
local styleT = {}
styleT['margin'] = '0px'
styleT['background-color'] = 'transparent'
styleT['width'] = '100%'
tabC = mw.html.create('table')
:attr({cellspacing = '0'})
:addClass('navigation-not-searchable')
:css(styleT)
local row = mw.html.create('tr')


local color = params.color
local templatestyles = ''
 
if args['templatestyles'] then
local style = {}
templatestyles = frame:extensionTag{
local arrowLeft
name = 'templatestyles', args = { src = args['templatestyles'] }
local arrowRight
}
if color == 'default' then
arrowLeft = '[[Fichier:Arrleft.svg|13px|alt=Précédent|link=]]'
arrowRight = '[[Fichier:Arrright.svg|13px|alt=Précédent|link=]]'
else
arrowLeft = '[[Fichier:Arrleft.svg|13px|alt=Suivant|link=]]'
arrowRight = '[[Fichier:Arrright.svg|13px|alt=Suivant|link=]]'
style['background-color'] = color
end
end
local styleTrans = {}
local child_templatestyles = ''
 
if args['child templatestyles'] then
local values = params.value
child_templatestyles = frame:extensionTag{
local before = values['before']
name = 'templatestyles', args = { src = args['child templatestyles'] }
local center = values['center']
}
local after = values['after']
local widthCell = '44%'
if center then
widthCenter = '28%'
widthCell = '29%'
end
local formattedbefore
if before then
formattedbefore = mw.html.create('td')
:attr({valign = 'middle'})
:attr({align = 'left'})
:attr({width = '5%'})
:css(style)
:wikitext(arrowLeft)
:done()
row:node(formattedbefore)
formattedbefore = mw.html.create('td')
:attr({width = '1%'})
:css(style)
:wikitext('')
:done()
row:node(formattedbefore)
formattedbefore = mw.html.create('td')
:attr({align = 'left'})
:attr({valign = 'middle'})
:attr({width = widthCell})
:css(style)
:wikitext(before)
:done()
row:node(formattedbefore)
else
formattedbefore = mw.html.create('td')
:attr({valign = 'middle'})
:attr({align = 'left'})
:attr({width = '5%'})
:css(styleTrans)
:wikitext('')
:done()
row:node(formattedbefore)
formattedbefore = mw.html.create('td')
:attr({width = '1%'})
:css(styleTrans)
:wikitext('')
:done()
row:node(formattedbefore)
formattedbefore = mw.html.create('td')
:attr({align = 'left'})
:attr({valign = 'middle'})
:attr({width = widthCell})
:css(styleTrans)
:wikitext('')
:done()
row:node(formattedbefore)
end
end
local formattedcenter
local grandchild_templatestyles = ''
formattedcenter = mw.html.create('td')
if args['grandchild templatestyles'] then
:attr({width = '1%'})
grandchild_templatestyles = frame:extensionTag{
:css(styleTrans)
name = 'templatestyles', args = { src = args['grandchild templatestyles'] }
:wikitext('')
}
:done()
row:node(formattedcenter)
if center then
formattedcenter = mw.html.create('td')
:attr({align = 'center'})
:attr({valign = 'middle'})
:attr({width = widthCenter})
:css(style)
:wikitext(center)
:done()
row:node(formattedcenter)
formattedcenter = mw.html.create('td')
:attr({width = '1%'})
:css(styleTrans)
:wikitext('')
:done()
row:node(formattedcenter)
end
end
local formattedafter
return table.concat({
if after then
-- hlist -> plainlist -> base is best-effort to preserve old Common.css ordering.
formattedafter = mw.html.create('td')
-- this ordering is not a guarantee because the rows of interest invoking
:attr({align = 'right'})
-- each class may not be on a specific page
:attr({valign = 'middle'})
hlist_templatestyles,
:attr({width = widthCell})
plainlist_templatestyles,
:css(style)
base_templatestyles,
:wikitext(after)
templatestyles,
:done()
child_templatestyles,
row:node(formattedafter)
grandchild_templatestyles
formattedbefore = mw.html.create('td')
})
:attr({width = '1%'})
:css(style)
:wikitext('')
:done()
row:node(formattedbefore)
formattedafter = mw.html.create('td')
:attr({align = 'right'})
:attr({valign = 'middle'})
:attr({width = '5%'})
:css(style)
:wikitext(arrowRight)
:done()
row:node(formattedafter)
else
formattedafter = mw.html.create('td')
:attr({align = 'right'})
:attr({valign = 'middle'})
:attr({width = widthCell})
:css(styleTrans)
:wikitext('')
:done()
row:node(formattedafter)
formattedbefore = mw.html.create('td')
:attr({width = '1%'})
:css(styleTrans)
:wikitext('')
:done()
row:node(formattedbefore)
formattedafter = mw.html.create('td')
:attr({align = 'right'})
:attr({valign = 'middle'})
:attr({width = '5%'})
:css(styleTrans)
:wikitext('')
:done()
row:node(formattedafter)
end
row:done()
tabC:node(row)
tabC:done()
cellI:node(tabC)
cellI:done()
rowI:node(cellI)
rowI:allDone()
return rowI
end
end
p.buildSuccession = p.buildsuccession
function p.buildrow1col(params)
if not params.value then
return nil
end
--local style = params.style or {}
--style['text-align'] = style['text-align'] or 'center'
--style['color'] = style['color'] or '#000000'
--style['background-color'] = style['background-color'] or '#F9F9F9'
local class = params.class
local rowcolor
if params.color == 'secondcolor' then
rowcolor = secondcolor
else
rowcolor = params.color
end
local style = {}
style['padding'] = '4px'
style['text-align'] = 'center'
style['background-color'] = rowcolor or '#F9F9F9'
style['color'] = '#000000'
local text = params.value
local colspan ='2'
local formattedlabel
formattedlabel = mw.html.create('th')
:attr({colspan = colspan})
:css(style)
:wikitext(text)
:done()


local row = mw.html.create('tr')
-- common functions between the child and non child cases
:addClass(class)
local function structure_infobox_common()
:css(style)
renderSubheaders()
:node(formattedlabel)
renderImages()
:done()
preprocessRows()
renderRows()
return row
renderBelowRow()
renderNavBar()
renderItalicTitle()
renderEmptyRowCategories()
renderTrackingCategories()
cleanInfobox()
end
end
p.buildRow1Col = p.buildrow1col


function p.buildtable(params)
-- Specify the overall layout of the infobox, with special settings if the
local tab = mw.html.create('table'):css(params.style or {})
-- infobox is used as a 'child' inside another infobox.
local function _infobox()
if args.child ~= 'yes' then
root = mw.html.create('table')


local rows = params.rows
root
:addClass(args.subbox == 'yes' and 'infobox-subbox' or 'infobox')
-- expand parameters so that we have a list of tables
:addClass(args.bodyclass)
local i = 1
-- @deprecated next; target .infobox-<name>
:cssText(args.bodystyle)
has_list_class({ args.bodyclass })


while (i <= #rows) do
renderTitle()
local l = rows[i]
renderAboveRow()
if type(l) == 'function' then
else
l = l(localdata, localdata.item)
root = mw.html.create()
end
if (type(l) == 'table') and (l.type == 'multi') then
table.remove(rows, i) 
for j, row in ipairs(l.rows) do
table.insert(rows, i + j - 1, row)
end
elseif type(l) == 'nil' then
table.remove(rows, i)
elseif type(l) ~= 'table' then
return error('les lignes d\'infobox ("rows") doivent être des tables, est ' .. type(l))
else
i = i + 1
end
end
 
-- CREATE ROW
local expandedrows = {}
for k, row in ipairs(rows) do
local v = p.buildblock(row)
if v then
table.insert(expandedrows, v)
end
end
if (#expandedrows == 0) then
return nil
end
rows = expandedrows
 
-- ADD TITLE
local title
if params.title or params.singulartitle or params.pluraltitle then
local text
if #rows > 1 and params.pluraltitle then
text = params.pluraltitle
elseif #rows == 1 and params.singulartitle then
text = params.singulartitle
else
text = params.title
end
 
local style = params.titlestyle or {}
style['text-align'] = style['text-align'] or 'center'
style['color'] = style['color'] or thirdcolor
style['background-color'] = style['background-color'] or maincolor


local colspan ='2'
root
title = mw.html.create('caption')
:wikitext(args.title)
:attr({colspan = colspan})
:css(style)
:wikitext(text)
:done()
end
if title then
tab:node(title)
end
end
structure_infobox_common()
for i, j in pairs (rows) do
return loadTemplateStyles() .. root
tab:node(j)
end
if params.separator then
local separator = p.separator(params)
tab:node(separator)
end
tab:allDone()
return tab
end
end
p.buildTable = p.buildtable


function p.buildinvalidblock(args)
-- If the argument exists and isn't blank, add it to the argument table.
addMaintenanceCat(defaultcat)
-- Blank arguments are treated as nil to match the behaviour of ParserFunctions.
local text = ''
local function preprocessSingleArg(argName)
if type(args) ~= 'table' then
if origArgs[argName] and origArgs[argName] ~= '' then
text = "Les blocs d'infobox doivent être des tables"
args[argName] = origArgs[argName]
else
text = i18n["invalid block type"] .. ' : ' .. (args.type or '??')
end
end
return text
end
end
p.buildInvalidBlock = p.buildinvalidblock
function p.buildmap(params)


-- paramètre d'affichage
-- Assign the parameters with the given prefixes to the args table, in order, in
local maplist = getValue(params.maps)
-- batches of the step size specified. This is to prevent references etc. from
local pointtype = params.pointtype
-- appearing in the wrong order. The prefixTable should be an array containing
local maptype = params.maptype -- choisit le type de carte le plus approprié (relief, administratif, etc.)
-- tables, each of which has two possible fields, a "prefix" string and a
if type(maplist) == 'function' then
-- "depend" table. The function always parses parameters containing the "prefix"
maplist = maplist(localdata, localdata.item)
-- 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
end
local width = tonumber(params.width) or 280
if type(step) ~= 'number' then
if width > 280 then
error("Invalid step value detected", 2)
addMaintenanceCat("Erreur d'Infobox/Image trop grande")
return 'image trop grande, la largeur doit être inférieure ou égale à 280px'
end
end


-- récupération des données locales
-- Get arguments without a number suffix, and check for bad input.
local pointtable = {}
for i,v in ipairs(prefixTable) do
local globe = params.globe
if type(v) ~= 'table' or type(v.prefix) ~= "string" or
if params.latitude then
(v.depend and type(v.depend) ~= 'table') then
local lat, long
error('Invalid input detected to preprocessArgs prefix table', 2)
if type(params.latitude) == 'function' then
lat, long = params.latitude(localdata, localdata.item), params.longitude(localdata, localdata.item)
else
lat, long = localdata[params.latitude], localdata[params.longitude]
end
end
if lat then
preprocessSingleArg(v.prefix)
table.insert(pointtable, {latitude = lat, longitude = long})
-- 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
end
end


-- récupération des données wikidata
-- Get arguments with number suffixes.
local function processWDval(claim, displayformat)
local a = 1 -- Counter variable.
if not claim then
local moreArgumentsExist = true
return nil
while moreArgumentsExist == true do
end
moreArgumentsExist = false
local val = wd.formatSnak( claim.mainsnak )
for i = a, a + step - 1 do
return {latitude = val.latitude, longitude = val.longitude, globe = val.globe, marker = displayformat.marker}
for j,v in ipairs(prefixTable) do
end
local prefixArgName = v.prefix .. tostring(i)
if origArgs[prefixArgName] then
local function getWDvals(query)
-- Do another loop if any arguments are found, even blank ones.
query.excludespecial = true
moreArgumentsExist = true
query.numval = query.numval or 1
preprocessSingleArg(prefixArgName)
query.entity = query.entity or localdata.item
end
local claims = wd.getClaims(query)
-- Process the depend table if the prefix argument is present
if (not claims) then
-- and not blank, or we are processing "prefix1" and "prefix" is
return
-- present and not blank, and if the depend table is present.
end
if v.depend and (args[prefixArgName] or (i == 1 and args[v.prefix])) then
for i, claim in ipairs(claims) do
for j,dependValue in ipairs(v.depend) do
claim = processWDval(claim, query)
local dependArgName = dependValue .. tostring(i)
table.insert(pointtable, claim)
preprocessSingleArg(dependArgName)
end
end
end
end
if (#pointtable == 0) and localdata.item and params.wikidata and (params.wikidata ~= '-') then
for i, query in ipairs(params.wikidata) do
if type(query) == 'function' then
query = query()
end
if query then
getWDvals(query)
end
end
end
end
a = a + step
end
end
if (not pointtable) or (#pointtable == 0) then
return nil
end
local newparams = {maplist = maplist, pointtype = pointtype, maptype = maptype, width = width, item = localdata.item, pointtable = pointtable, globe = globe, marker=params.marker, default_zoom=params.default_zoom, ids = params.ids, markercolor = params.markercolor, shapecolor = params.shapecolor }
if params.params and type(params.params) == 'table' then -- paramètres additionnels
for i, j in pairs(params.params) do
newparams[i] = j
end
end
return require('Module:Carte').multimap(newparams)
end
end
p.buildMap = p.buildmap


function p.buildexternaltext(params)
-- Parse the data parameters in the same order that the old {{infobox}} did, so
local value = getValue(params.value)
-- that references etc. will display in the expected places. Parameters that
if value and (type(value) == 'string') then
-- depend on another parameter are only processed if that parameter is present,
externaltext = externaltext .. value
-- to avoid phantom references appearing in article reference lists.
end
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
end
p.buildExternalText = p.buildexternaltext


function p.buildfooter(params)
-- If called via #invoke, use the args passed into the invoking template.
if not params then
-- Otherwise, for testing purposes, assume args are being passed directly in.
params = {}
function p.infobox(frame)
if frame == mw.getCurrentFrame() then
origArgs = frame:getParent().args
else
origArgs = frame
end
end
local class = 'navbar noprint bordered ' .. (params.class or '')
parseDataParameters()
local style = params.style or {}
style['border-top'] = style['border-top'] or '1px solid ' .. maincolor
local backlinkstr = '[' .. tostring( mw.uri.fullUrl( page.name, 'veaction=edit&section=0' ) ) .. ' ' .. i18n['edit'] .. ']'
return _infobox()
.. ' - [' .. tostring( mw.uri.fullUrl( page.name, 'action=edit&section=0' ) ) .. ' ' .. i18n['edit code'] .. ']'
 
local itemlinkstr
if localdata.item then
itemlinkstr = '[[d:' .. localdata.item.id .. '|' .. i18n['edit item'] .. ']]'
end
local editstr = backlinkstr
if itemlinkstr then
editstr = editstr .. ' - ' .. itemlinkstr
end
local editlinkspan =  mw.html.create('span')
:css({['text-align'] = "left"})
:addClass('plainlinks')
:wikitext(editstr)
:done()
local doclinkstr = '[[Fichier:Info Simple.svg|12px|link=' .. localdata.templatename .. '|' .. i18n['see doc'] .. ']]'
-- si ce lien ne marche pas toujours, il faut ajouter un variable pour le nom de l'infobox récupéré par le frame
local doclinkspan = mw.html.create('span')
:css({['text-align'] = "right"})
:wikitext(doclinkstr)
:done()
local footer = mw.html.create('p')
:addClass(class)
:css(style)
:node(editlinkspan)
:node(doclinkspan)
return footer
end
end
p.buildFooter = p.buildfooter
function p.buildblock(block)
if type(block) == 'function' then
block = block( localdata )
end
local blocktypes = { -- list of functions for block buildings
['invalid'] = p.buildinvalidblock,
['external text'] = p.buildexternaltext,
['footer'] = p.buildfooter,
['images'] = p.buildimages,
['map']= p.buildmap,
['mixed'] = p.buildrow,
['navbox'] = p.buildnavbox,
['table'] = p.buildtable,
['row'] = p.buildrow,
['row1col'] = p.buildrow1col,
['succession'] = p.buildsuccession,
['text'] = p.buildtext,
['title'] = p.buildtitle,
}
if type(block) ~= 'table' or (not block.type) or (not blocktypes[block.type]) then
return blocktypes['invalid'](block)
end
return blocktypes[block.type](block)
end
p.buildBlock = p.buildblock
function p.build()
localdata = require( 'Module:Infobox/Localdata' )
item = localdata.item


-- assign rank to the infobox, "secondary" means special formatting like no displaytitle for coordinates
-- For calling via #invoke within a template
local infoboxrank = 'main' -- main infobox of the page, with coordinates displayed in title etc.
function p.infoboxTemplate(frame)
if page.namespace ~= 0 then
origArgs = {}
infoboxrank = 'secondary'
for k,v in pairs(frame.args) do origArgs[k] = mw.text.trim(v) end
end
-- if infobox is linked to another item: rank = secondary
if localdata.item then
local itemlink = mw.wikibase.sitelink(localdata.item.id)
local pagetitle = mw.title.getCurrentTitle().text
if (itemlink or '') ~= pagetitle then
infoboxrank = 'secondary'
end
end
localdata.infoboxrank = infoboxrank
 
-- load infobox module page
local moduledata = require('Module:Infobox/' .. localdata.modulename)
moduledata.name = localdata.modulename
-- defines main color
maincolor = localdata['couleur infobox'] or localdata['couleur boîte'] or moduledata.maincolor or maincolor
secondcolor = moduledata.secondcolor or secondcolor
thirdcolor = localdata['texte noir'] or localdata['couleur texte'] or moduledata.thirdcolor or thirdcolor
if maincolor:match( '^%x%x%x%x%x%x$' ) or maincolor:match( '^%x%x%x$' ) then
maincolor = '#' .. maincolor
end
if thirdcolor:match ('oui') or thirdcolor:match( 'true' ) then
thirdcolor = '#000'
end
if thirdcolor:match ('non') or thirdcolor:match( 'false' ) then
thirdcolor = '#fff'
end
-- class
local class = 'infobox infobox_v3 large'
if moduledata.class then
class = class .. ' ' .. moduledata.class
end
-- style
parseDataParameters()
local style = moduledata.style or {}
-- build infobox
return _infobox()
infobox :addClass(class)
:css(style)
for i, j in pairs( moduledata.parts ) do
infobox:node( p.buildblock(j) )
end
infobox :node(p.buildfooter(moduledata.footer))
:done()
 
return tostring(infobox) .. externaltext, maintenance
end
end
return p
return p

Latest revision as of 05:11, 10 March 2023

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

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'
		},
		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 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 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
	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