« Module:Infobox » : différence entre les versions

De kookipedia
Aller à la navigation Aller à la recherche
(merge hlist here)
 
Aucun résumé des modifications
 
(Une version intermédiaire par le même utilisateur non affichée)
Ligne 1 : Ligne 1 :
local p = {}
local p = {}
local args = {}
local wikiLang = 'fr'
local origArgs = {}
 
local root
local localdata = {}-- données concernant les paramètres passés au modèle
local empty_row_categories = {}
 
local category_in_empty_row_pattern = '%[%[%s*[Cc][Aa][Tt][Ee][Gg][Oo][Rr][Yy]%s*:[^]]*]]'
-- données concernant la page où est affichée l'infobox
local has_rows = false
local page = mw.title.getCurrentTitle()
local lists = {
 
plainlist_t = {
local maincolor, secondcolor, thirdcolor = 'var(--background-color-interactive-subtle, #f8f9fa)', 'var(--background-color-interactive-subtle, #f8f9fa)', 'var(--color-emphasized, #000000)'
patterns = {
-- l'objet principal à retourner
'^plainlist$',
local infobox = mw.html.create('div')
'%splainlist$',
 
'^plainlist%s',
-- objets secondaires à retourner
'%splainlist%s'
local maintenance = '' -- chaîne retournée avec le module : cats de maintenance
},
local externaltext = '' -- par exemple coordonnées en titre
found = false,
-- modules importés
styles = 'Plainlist/styles.css'
local wd = require 'Module:Wikidata'
},
local yesno = require 'Module:Yesno'
hlist_t = {
local valueexpl = wd.translate("activate-query")
patterns = {
 
'^hlist$',
-- maintenance des images dupliquées
'%shlist$',
local usedImages = {}
'^hlist%s',
 
'%shlist%s'
local i18n = {
},
['see doc'] = 'Documentation du modèle',
found = false,
['edit'] = 'modifier',
styles = 'Hlist/styles.css'
['edit code'] = 'modifier le code',
}
['edit item'] = 'modifier Wikidata',
['tracking cat'] = "Page utilisant des données de Wikidata",
['invalid block type'] = "Bloc de données invalide dans le module d'infobox",
['default cat'] = "Maintenance des infobox",
}
}


local function has_list_class(args_to_check)
local function expandQuery(query)
for _, list in pairs(lists) do
if not query.entity then
if not list.found then
query.entity = localdata.item
for _, arg in pairs(args_to_check) do
end
for _, pattern in ipairs(list.patterns) do
if not query.conjtype then
if mw.ustring.find(arg or '', pattern) then
query.conjtype = 'comma'
list.found = true
end
break
local claims = wd.getClaims(query)
end
if (not claims) then
end
return nil
if list.found then break end
end
 
return wd.formatAndCat(query), wd.getgendernum(claims) -- valeur  et code indiquant le genre/nombre pour accorder le libellé
end
 
local function getWikidataValue(params, wikidataparam)
-- Récupère la valeur Wikidata pour la valeur, soit dans le paramètre "wikidata" soit dans le paramètre "property"
if not localdata.item then
return nil
end
 
if params.blockers then -- blockers are local parameters that disable the wikidata query
local blockers = params.blockers
if (type(blockers) == 'string') then
blockers = {blockers}
end
for i, blocker in ipairs(blockers) do
if localdata[blocker] then
return nil
end
end
end
end
end
end
end


local function fixChildBoxes(sval, tt)
local v, valgendernum -- la valeur à retourner, et le genre/nombre de de valeurs (pour l'accord grammatical)
local function notempty( s ) return s and s:match( '%S' ) end
 
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
wikidataparam = 'wikidata'
end
if params.property and not params[wikidataparam] then params[wikidataparam] = {property = params.property} end
if notempty(sval) then
if params[wikidataparam] then
local marker = '<span class=special_infobox_marker>'
if type(params[wikidataparam]) == 'function' then
local s = sval
v, valgendernum = params[wikidataparam](localdata.item)
-- start moving templatestyles and categories inside of table rows
elseif type(params[wikidataparam]) == 'table' then
local slast = ''
v, valgendernum = expandQuery(params[wikidataparam])
while slast ~= s do
else
slast = s
v, valgendernum = params[wikidataparam]
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
-- end moving templatestyles and categories inside of table rows
end
s = mw.ustring.gsub(s, '(<%s*[Tt][Rr])', marker .. '%1')
if not v then
s = mw.ustring.gsub(s, '(</[Tt][Rr]%s*>)', '%1' .. marker)
return nil
if s:match(marker) then
end
s = mw.ustring.gsub(s, marker .. '%s*' .. marker, '')
s = mw.ustring.gsub(s, '([\r\n]|-[^\r\n]*[\r\n])%s*' .. marker, '%1')
if(type(valgendernum) == 'number') then
s = mw.ustring.gsub(s, marker .. '%s*([\r\n]|-)', '%1')
if(valgendernum > 1) then
s = mw.ustring.gsub(s, '(</[Cc][Aa][Pp][Tt][Ii][Oo][Nn]%s*>%s*)' .. marker, '%1')
valgendernum = 'p'
s = mw.ustring.gsub(s, '(<%s*[Tt][Aa][Bb][Ll][Ee][^<>]*>%s*)' .. marker, '%1')
else
s = mw.ustring.gsub(s, '^(%{|[^\r\n]*[\r\n]%s*)' .. marker, '%1')
valgendernum = 's'
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
end
if s:match(marker) then
end
local subcells = mw.text.split(s, marker)
s = ''
return v, valgendernum
for k = 1, #subcells do
end
if k == 1 then
 
s = s .. subcells[k] .. '</' .. tt .. '></tr>'
local function getValue(val, params)
elseif k == #subcells then
if type(val) == 'string' then
local rowstyle = ' style="display:none"'
return localdata[val]
if notempty(subcells[k]) then rowstyle = '' end
elseif type(val) == 'function' then
s = s .. '<tr' .. rowstyle ..'><' .. tt .. ' colspan=2>\n' ..
return val(localdata, localdata.item, params)
subcells[k]
elseif type(val) == 'table' then
elseif notempty(subcells[k]) then
for i, j in pairs(val) do -- si plusieurs paramètres possibles (legacy de vieux code), prendre le premier non vide
if (k % 2) == 0 then
if localdata[j] then
s = s .. subcells[k]
return localdata[j]
else
s = s .. '<tr><' .. tt .. ' colspan=2>\n' ..
subcells[k] .. '</' .. tt .. '></tr>'
end
end
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
end
end


-- Cleans empty tables
local function addMaintenanceCat(cat, sortkey)
local function cleanInfobox()
if page.namespace ~= 0 then
root = tostring(root)
return ''
if has_rows == false then
end
root = mw.ustring.gsub(root, '<table[^<>]*>%s*</table>', '')
if cat then
local sortkeycode
if sortkey then sortkeycode = '|' .. sortkey else sortkeycode = '' end
maintenance = maintenance .. '[[Category:'.. cat .. sortkeycode .. ']]'
end
end
end
end


-- Returns the union of the values of two tables, as a sequence.
function p.separator(params)
local function union(t1, t2)
local style = params['separator style'] or {}
style.height = style.height or '2px'
style['background-color'] = style['background-color'] or maincolor
 
return mw.html.create('hr'):css( style )
end
 
--[=[
Construit le code du bloc de titre de l'infobox


local vals = {}
Paramètres (liste partielle) :
for k, v in pairs(t1) do
- value : Moyen d'obtenir le titre via getValue (nom de paramètre de modèle ou fonction).
vals[v] = true
- textdefaultvalue : Valeur par défaut du titre.
- icon : Pictogramme d'infobox (voir [[Projet:Infobox/Pictogramme]]).
- italic : Indique si le titre doit être affiché en italique.
  Si italic=true, le paramètre "titre en italique" de l'infobox peut forcer la désactivation.
- setdisplaytitle : Indique si le titre de l'article doit être mis en forme comme celui de l'infobox.
  Si setdisplaytitle=true, le paramètre "titre article en italique" de l'infobox peut forcer la désactivation.
]=]
function p.buildtitle(params)
local text = getValue(params.value, params) or params.textdefaultvalue or getWikidataValue(params) or page.prefixedText
local lang = localdata['langue du titre'] or ''
if lang ~= '' then
local langueFunction = require( 'Module:Langue' ).langue
text = langueFunction( { lang, text } )
end
end
for k, v in pairs(t2) do
local subtext = getValue(params.subtitle) or  getWikidataValue(params, 'wikidatasubtitle') or params.subtitledefaultvalue
vals[v] = true
if subtext and (subtext ~= text) then
text = text .. '<br /><small>' .. subtext .. '</small>'
end
end
local ret = {}
local icon = params.icon or ''
for k, v in pairs(vals) do
if icon ~= '' and icon ~= 'defaut' then
table.insert(ret, k)
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
return ret
local classes = 'entete ' .. icon
end


-- Returns a table containing the numbers of the arguments that exist
local italic = params.italic and yesno(localdata['titre en italique'] or '', true, true)
-- for the specified prefix. For example, if the prefix was 'data', and
if italic then
-- 'data1', 'data2', and 'data5' exist, it would return {1, 2, 5}.
classes = classes .. ' italique'
local function getArgNums(prefix)
end
local nums = {}
if params.setdisplaytitle and yesno(localdata['titre article en italique'] or '', true, true) then
for k, v in pairs(args) do
local formatTitleModule = require( 'Module:Formatage du titre' )
local num = tostring(k):match('^' .. prefix .. '([1-9]%d*)$')
text = text .. formatTitleModule.setDisplayTitle{ args = {
if num then table.insert(nums, tonumber(num)) end
lang = lang,
italic = italic,
options = 'noreplace',
} }
end
end
table.sort(nums)
return nums
end


-- Adds a row to the infobox, with either a header cell
-- overwrites with those provided in the module
-- or a label/data cell combination.
local style = {}
local function addRow(rowArgs)
style['background-color'] = maincolor
style['color'] = thirdcolor
if rowArgs.header and rowArgs.header ~= '_BLANK_' then
if params.style then
has_rows = true
for i, j in pairs(params.style) do
has_list_class({ rowArgs.rowclass, rowArgs.class, args.headerclass })
style[i] = j
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
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 title = mw.html.create('div')
:addClass(classes)
:css(style)
:tag('div')
:wikitext(text)
:allDone()
return title
end
end
p.buildTitle = p.buildtitle
function p.buildnavigator(params)


local function renderTitle()
-- définition du style
if not args.title then return end
local classes = "overflow infobox-navigateur " .. (params.class or '')
local style = params.style or {}


has_rows = true
if params.separated then -- options pour ajouter une ligne de séparation au dessus
has_list_class({args.titleclass})
classes = classes .. ' bordered'
style['border-top'] = '1px solid' .. maincolor
root
end
: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()
-- ajustement des paramètres de données
if not args.above then return end
params.previousval = params.previousval or params.previousparameter -- nom de paramètre obsolète
params.nextval = params.nextval or params.nextparameter


has_rows = true
if params.previousproperty then
has_list_class({ args.aboveclass })
params.previouswikidata = {property = params.previousproperty}
end
root
if params.nextproperty then
:tag('tr')
params.nextwikidata = {property = params.nextproperty}
:tag('th')
end
: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
local previousval = getValue(params.previousval, params) or getWikidataValue(params, 'previouswikidata')
has_list_class({ args.belowclass })
local nextval = getValue(params.nextval, params) or getWikidataValue(params, 'nextwikidata')
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 previousval  == '-' then previousval  = nil end
if subheaderArgs.data and
    if nextval  == '-' then nextval  = nil end
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')
local navigator
dataCell
if params.inner then -- pour celles qui sont à l'intérieur d'une table
:attr('colspan', '2')
navigator = mw.html.create('tr'):tag('th'):attr('colspan', 2)
:addClass('infobox-subheader')
style['font-weight'] = style['font-weight'] or 'normal'
:addClass(subheaderArgs.class)
:cssText(subheaderArgs.datastyle)
:cssText(subheaderArgs.rowcellstyle)
:wikitext(fixChildBoxes(subheaderArgs.data, 'td'))
else
else
table.insert(empty_row_categories, subheaderArgs.data or '')
navigator = mw.html.create('div')
end
 
if previousval or nextval then
navigator
:addClass(classes)
:css(style)
:tag('div')
:addClass('prev_bloc')
:wikitext(previousval)
:done()
:tag('div')
:addClass('next_bloc')
:wikitext(nextval)
:done()
:allDone()
return navigator
end
end
return nil
end
end
p.buildNavigator = p.buildnavigator


local function renderSubheaders()
function p.buildimages(params)
if args.subheader then
local images = {}
args.subheader1 = args.subheader
local upright, link, caption, classe, alt, size  -- size is deprecated
if type(params.imageparameters) == 'string' then
params.imageparameters = {params.imageparameters}
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
params.imageparameters = {}
end
for j, k in ipairs(params.imageparameters) do
table.insert(images, localdata[k])
end
end
if args.subheaderrowclass then
-- Images de Wikidata
args.subheaderrowclass1 = args.subheaderrowclass
local iswikidataimage, iswikidatacaption = false
if #images == 0 and localdata.item then
if params.property then
params.wikidata = {entity = localdata.item, property = params.property}
end
if params.wikidata then
local wdq = params.wikidata
wdq.excludespecial = true
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
maintenance = maintenance .. wd.addTrackingCat(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'})
iswikidatacaption = caption ~= nil
end
images[i] = image.mainsnak.datavalue.value
iswikidataimage = true
end
end
end
end
end
local subheadernums = getArgNums('subheader')
 
for k, num in ipairs(subheadernums) do
if #images == 0 and getValue(params.captionparameter) ~= nil then
addSubheaderRow({
addMaintenanceCat("Infobox avec une légende locale sans image")
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
end
-- Images par défaut
if #images == 0 then
if params.maintenancecat then
addMaintenanceCat(params.maintenancecat, params.sortkey)
end
if params.defaultimages then
images = params.defaultimages
if type(images) == 'string' then
images = {images}
end
upright = params.defaultimageupright
caption = params.defaultimagecaption
link = params.defaultimagelink
classe = params.defaultimageclass
if not classe and ( images[1] == 'Defaut.svg' or images[1] == 'Defaut 2.svg' ) then
classe = 'skin-invert notheme'
end
alt = params.defaultimagealt
if not alt and ( images[1] == 'Defaut.svg' or images[1] == 'Defaut 2.svg' ) then
alt = 'une illustration sous licence libre serait bienvenue'
end
end
end
if #images == 0 then
return nil
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
classe = classe or getValue( params.classparameter) or params.defaultclass
alt = alt or getValue( params.altparameter) or params.defaultalt
 
if iswikidataimage and not iswikidatacaption and getValue(params.captionparameter) ~= nil then
addMaintenanceCat("Infobox avec une légende locale et une image sur Wikidata")
end
 
-- 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.*', '')
widthonly = tonumber(widthonly)
if type(widthonly) ~= 'number' or widthonly > 280 then
addMaintenanceCat("Infobox avec une image trop grande")
end
 
if tonumber(sizevalue) then
size = tostring( tonumber(sizevalue) ) .. 'px'
end
end
 
if tonumber(upright) then
upright = tostring( tonumber(upright) )
end
 
local style = params.style or {padding ='2px 0',}
 
-- Partie image
 
local imagesString = ''
for i,image in pairs(images) do
if image == '-' then
return
end
imagesString = imagesString ..  '[[Fichier:' .. image .. '|frameless'
if size then
imagesString = imagesString .. '|' .. size -- not a mistake, parameter is unnamed
end
if classe then
imagesString = imagesString .. '|class=' .. classe
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 .. ']]'


local function addImageRow(imageArgs)
if usedImages[image] then
addMaintenanceCat('Infobox avec plusieurs images identiques')
end
usedImages[image] = true
end


if imageArgs.data and
local image = mw.html.create('div')
imageArgs.data:gsub(category_in_empty_row_pattern, ''):match('^%S') then
:addClass("images")
:css(style)
:wikitext(imagesString)


has_rows = true
-- Partie légende
has_list_class({ imageArgs.rowclass, imageArgs.class })
local captionobj
if caption then
local row = root:tag('tr')
captionobj = mw.html.create('div')
row:addClass(imageArgs.rowclass)
:wikitext(caption)
:css(params.legendstyle or {})
:addClass("legend")
:done()
end


local dataCell = row:tag('td')
-- séparateur
dataCell
local separator
:attr('colspan', '2')
if params.separator then
:addClass('infobox-image')
separator = p.separator(params)
:addClass(imageArgs.class)
:cssText(imageArgs.datastyle)
:wikitext(fixChildBoxes(imageArgs.data, 'td'))
else
table.insert(empty_row_categories, imageArgs.data or '')
end
end
return mw.html.create('div')
:node(image)
:node(captionobj)
:node(separator)
:done()
end
end
p.buildImages = p.buildimages


local function renderImages()
function p.buildtext(params)
if args.image then
local classes = params.class or ''
args.image1 = args.image
local style = {
['text-align'] = 'center',
['font-weight'] = 'bold'
}
if params.style then
for i, j in pairs(params.style) do
style[i] = j
end
end
end
if args.caption then
local text = getValue(params.value, params) or getWikidataValue(params) or params.defaultvalue
args.caption1 = args.caption
if text == '-' then
return
end
end
local imagenums = getArgNums('image')
if not text then
for k, num in ipairs(imagenums) do
if params.maintenancecat then
local caption = args['caption' .. tostring(num)]
addMaintenanceCat(params.maintenancecat, params.sortkey)
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
end
addImageRow({
return nil
data = tostring(data),
end
-- @deprecated next; target .infobox-<name> .infobox-image
-- séparateur
datastyle = args.imagestyle,
local separator
class = args.imageclass,
if params.separator then
rowclass = args['imagerowclass' .. tostring(num)]
separator = p.separator(params)
})
end
end
local formattedtext = mw.html.create('p')
:addClass(classes)
:css(style)
:wikitext(text)
:node(separator)
:done()
return formattedtext
end
end
p.buildText = p.buildtext


-- When autoheaders are turned on, preprocesses the rows
function p.buildrow(params)
local function preprocessRows()
local classes = params.class or ''
if not args.autoheaders then return end
local style = params.style or {}
local valueClass = params.valueClass or ''
local valueStyle = params.valueStyle or {}
local value, gendernum = getValue(params.value, params)
if(type(gendernum) == 'number') then
if(gendernum > 1) then
gendernum = 'p'
else
gendernum = 's'
end
end
local rownums = union(getArgNums('header'), getArgNums('data'))
if type(params.wikidata) == 'table' then
table.sort(rownums)
params.wikidata.wikidatalang = localdata.wikidatalang
local lastheader
if (value == valueexpl) then
for k, num in ipairs(rownums) do
value = nil
if args['header' .. tostring(num)] then
params.wikidata.expl = false
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
end
end
if lastheader then
if (not value) then
args['header' .. tostring(lastheader)] = nil
value, gendernum = getWikidataValue(params, 'wikidata')
end
if not value then
value = params.defaultvalue
end
if value == '-' then
return nil
end
if not gendernum then
gendernum = 's' --singulier indéfini
end
end
end


-- Gets the union of the header and data argument numbers,
if not value then
-- and renders them all in order
if params.maintenancecat then
local function renderRows()
addMaintenanceCat(params.maintenancecat, params.sortkey)
end
return nil
end


local rownums = union(getArgNums('header'), getArgNums('data'))
local label = params.label
table.sort(rownums)
if type(label) == 'string' then label = {default = label} end
for k, num in ipairs(rownums) do
addRow({
if type(label) == 'table' then -- Accord en genre et en nombre
header = args['header' .. tostring(num)],
local onlynum = {default = 'default', s = 's', ms = 's', fs = 's', p = 'p', mp = 'p', fp = 'p', mixtep = 'p'} -- Accord seulement en nombre par défaut
label = args['label' .. tostring(num)],
data = args['data' .. tostring(num)],
label['s'] = label['s'] or params.singularlabel or label['default'] or label['ms']
datastyle = args.datastyle,
label['p'] = label['p'] or params.plurallabel or label['mp']
class = args['class' .. tostring(num)],
rowclass = args['rowclass' .. tostring(num)],
label = label[gendernum] or label[onlynum[gendernum]] or label.default
-- @deprecated next; target .infobox-<name> rowclass
end
rowstyle = args['rowstyle' .. tostring(num)],
rowcellstyle = args['rowcellstyle' .. tostring(num)]
if type(label) == 'function' then
})
label = label(localdata, localdata.item)
end
end
end


local function renderNavBar()
-- format
if not args.name then return end
local formattedvalue = mw.html.create('div')
:wikitext('\n' .. value) -- Le '\n' est requis lorsque value est une liste commençant par '*' ou '#'


has_rows = true
if (params.hidden == true)then
root
formattedvalue
:tag('tr')
:attr({class="NavContent", style="display: none; text-align: left;"})
:tag('td')
formattedvalue = mw.html.create('div')
:attr('colspan', '2')
:attr({class="NavFrame", title="[Afficher]/[Masquer]", style="border: none; padding: 0;"})
:addClass('infobox-navbar')
:node(formattedvalue)
:wikitext(require('Module:Navbar')._navbar{
end
args.name,
formattedvalue = mw.html.create('td')
mini = 1,
:node(formattedvalue)
})
:addClass(valueClass)
end
:css(valueStyle)
:allDone()


local function renderItalicTitle()
local formattedlabel
local italicTitle = args['italic title'] and mw.ustring.lower(args['italic title'])
if label then
if italicTitle == '' or italicTitle == 'force' or italicTitle == 'yes' then
formattedlabel = mw.html.create('th')
root:wikitext(require('Module:Italic title')._main({}))
:attr('scope', 'row')
:wikitext(label)
:done()
end
end
local row = mw.html.create('tr')
:addClass(classes)
:css(style)
:node(formattedlabel)
:node(formattedvalue)
:done()
return row
end
end
p.buildRow = p.buildrow


-- Categories in otherwise empty rows are collected in empty_row_categories.
function p.buildsuccession(params)
-- This function adds them to the module output. It is not affected by
if not params.value then
-- args.decat because this module should not prevent module-external categories
return nil
-- from rendering.
local function renderEmptyRowCategories()
for _, s in ipairs(empty_row_categories) do
root:wikitext(s)
end
end
end


-- Render tracking categories. args.decat == turns off tracking categories.
--local style = params.style or {}
local function renderTrackingCategories()
--style['text-align'] = style['text-align'] or 'center'
if args.decat == 'yes' then return end
--style['color'] = style['color'] or '#000000'
if args.child == 'yes' then
--style['background-color'] = style['background-color'] or '#F9F9F9'
if args.title then
 
root:wikitext(
local rowI = mw.html.create('tr')
'[[Category:Pages using embedded infobox templates with the title parameter]]'
 
)
local styleI = {}
end
local colspan = '2'
elseif #(getArgNums('data')) == 0 and mw.title.getCurrentTitle().namespace == 0 then
styleI['padding'] = '1px'
root:wikitext('[[Category:Articles using infobox templates with no data rows]]')
local cellI = mw.html.create('td')
:attr({colspan = colspan})
:attr({align = 'center'})
:css(styleI)
 
local styleT = {
margin = '0px',
['background-color'] = 'transparent',
color = 'inherit',
width = '100%'
}
local 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 style = {}
local arrowLeft = '[[Fichier:Arrleft.svg|13px|alt=Précédent|link=]]'
local arrowRight = '[[Fichier:Arrright.svg|13px|alt=Suivant|link=]]'
 
if color ~= 'default' then
style['background-color'] = color
end
end
end


--[=[
local styleTrans = {}
Loads the templatestyles for the infobox.
 
local values = params.value
local before = values['before']
local center = values['center']
local after = values['after']


TODO: FINISH loading base templatestyles here rather than in
local widthCenter
MediaWiki:Common.css. There are 4-5000 pages with 'raw' infobox tables.
local widthCell = '44%'
See [[Mediawiki_talk:Common.css/to_do#Infobox]] and/or come help :).
if center then
When we do this we should clean up the inline CSS below too.
widthCenter = '28%'
Will have to do some bizarre conversion category like with sidebar.
widthCell = '29%'
end


]=]
local formattedbefore
local function loadTemplateStyles()
if before then
local frame = mw.getCurrentFrame()
formattedbefore = mw.html.create('td')
:attr({valign = 'middle'})
local hlist_templatestyles = ''
:attr({align = 'left'})
if lists.hlist_t.found then
:attr({width = '5%'})
hlist_templatestyles = frame:extensionTag{
:css(style)
name = 'templatestyles', args = { src = lists.hlist_t.styles }
: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 plainlist_templatestyles = ''
local formattedcenter
if lists.plainlist_t.found then
formattedcenter = mw.html.create('td')
plainlist_templatestyles = frame:extensionTag{
:attr({width = '1%'})
name = 'templatestyles', args = { src = lists.plainlist_t.styles }
:css(styleTrans)
}
: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
-- See function description
local base_templatestyles = frame:extensionTag{
name = 'templatestyles', args = { src = 'Module:Infobox/styles.css' }
}


local templatestyles = ''
local formattedafter
if args['templatestyles'] then
if after then
templatestyles = frame:extensionTag{
formattedafter = mw.html.create('td')
name = 'templatestyles', args = { src = args['templatestyles'] }
:attr({align = 'right'})
}
:attr({valign = 'middle'})
:attr({width = widthCell})
:css(style)
:wikitext(after)
:done()
row:node(formattedafter)
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
end
 
local child_templatestyles = ''
row:done()
if args['child templatestyles'] then
tabC:node(row)
child_templatestyles = frame:extensionTag{
tabC:done()
name = 'templatestyles', args = { src = args['child templatestyles'] }
cellI:node(tabC)
}
cellI:done()
rowI:node(cellI)
rowI:allDone()
 
return rowI
end
p.buildSuccession = p.buildsuccession
 
function p.buildrow1col(params)
 
if not params.value then
return nil
end
end
 
local grandchild_templatestyles = ''
--local style = params.style or {}
if args['grandchild templatestyles'] then
--style['text-align'] = style['text-align'] or 'center'
grandchild_templatestyles = frame:extensionTag{
--style['color'] = style['color'] or '#000000'
name = 'templatestyles', args = { src = args['grandchild templatestyles'] }
--style['background-color'] = style['background-color'] or '#F9F9F9'
}
local classes = params.class
local rowcolor
if params.color == 'secondcolor' then
rowcolor = secondcolor
else
rowcolor = params.color
end
end
 
return table.concat({
local style = {}
-- hlist -> plainlist -> base is best-effort to preserve old Common.css ordering.
style['padding'] = '4px'
-- this ordering is not a guarantee because the rows of interest invoking
style['text-align'] = 'center'
-- each class may not be on a specific page
style['background-color'] = rowcolor or 'var(--couleur-fond-boite-grise, #f9f9f9)'
hlist_templatestyles,
style['color'] = 'var(--color-emphasized, #000000)'
plainlist_templatestyles,
 
base_templatestyles,
local text = params.value
templatestyles,
 
child_templatestyles,
local colspan ='2'
grandchild_templatestyles
 
})
local formattedlabel
formattedlabel = mw.html.create('th')
:attr({colspan = colspan})
:css(style)
:wikitext(text)
:done()
 
local row = mw.html.create('tr')
:addClass(classes)
:css(style)
:node(formattedlabel)
:done()
 
return row
end
end
p.buildRow1Col = p.buildrow1col
function p.buildtable(params)
local tab = mw.html.create('table'):css(params.style or {})
local rows = params.rows
-- expand parameters so that we have a list of tables
local i = 1
while (i <= #rows) do
local l = rows[i]
if type(l) == 'function' then
l = l(localdata, localdata.item)
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


-- common functions between the child and non child cases
local style = params.titlestyle or {}
local function structure_infobox_common()
style['text-align'] = style['text-align'] or 'center'
renderSubheaders()
style['color'] = style['color'] or thirdcolor
renderImages()
style['background-color'] = style['background-color'] or maincolor
preprocessRows()
renderRows()
renderBelowRow()
renderNavBar()
renderItalicTitle()
renderEmptyRowCategories()
renderTrackingCategories()
cleanInfobox()
end


-- Specify the overall layout of the infobox, with special settings if the
local colspan ='2'
-- infobox is used as a 'child' inside another infobox.
title = mw.html.create('caption')
local function _infobox()
:attr({colspan = colspan})
if args.child ~= 'yes' then
:css(style)
root = mw.html.create('table')
:wikitext(text)
:done()
end


root
if title then
:addClass(args.subbox == 'yes' and 'infobox-subbox' or 'infobox')
tab:node(title)
:addClass(args.bodyclass)
end
-- @deprecated next; target .infobox-<name>
:cssText(args.bodystyle)
has_list_class({ args.bodyclass })


renderTitle()
for i, j in pairs (rows) do
renderAboveRow()
tab:node(j)
else
end
root = mw.html.create()


root
if params.separator then
:wikitext(args.title)
local separator = p.separator(params)
tab:node(separator)
end
end
structure_infobox_common()
tab:allDone()
return tab
return loadTemplateStyles() .. root
end
end
p.buildTable = p.buildtable


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


-- Assign the parameters with the given prefixes to the args table, in order, in
-- paramètre d'affichage
-- batches of the step size specified. This is to prevent references etc. from
local maplist = getValue(params.maps)
-- appearing in the wrong order. The prefixTable should be an array containing
local pointtype = params.pointtype
-- tables, each of which has two possible fields, a "prefix" string and a
local maptype = params.maptype -- choisit le type de carte le plus approprié (relief, administratif, etc.)
-- "depend" table. The function always parses parameters containing the "prefix"
if type(maplist) == 'function' then
-- string, but only parses parameters in the "depend" table if the prefix
maplist = maplist(localdata, localdata.item)
-- parameter is present and non-blank.
end
local function preprocessArgs(prefixTable, step)
local width = tonumber(params.width) or 280
if type(prefixTable) ~= 'table' then
if width > 280 then
error("Non-table value detected for the prefix table", 2)
addMaintenanceCat("Infobox avec une image trop grande")
return 'image trop grande, la largeur doit être inférieure ou égale à 280px'
end
end
if type(step) ~= 'number' then
 
error("Invalid step value detected", 2)
-- récupération des données locales
local pointtable = {}
local globe = params.globe
if params.latitude then
local lat, long
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
if lat then
table.insert(pointtable, {latitude = lat, longitude = long})
end
end
end


-- Get arguments without a number suffix, and check for bad input.
-- récupération des données wikidata
for i,v in ipairs(prefixTable) do
local function processWDval(claim, displayformat)
if type(v) ~= 'table' or type(v.prefix) ~= "string" or
if not claim then
(v.depend and type(v.depend) ~= 'table') then
return nil
error('Invalid input detected to preprocessArgs prefix table', 2)
end
end
preprocessSingleArg(v.prefix)
local val = wd.formatSnak( claim.mainsnak )
-- Only parse the depend parameter if the prefix parameter is present
return {latitude = val.latitude, longitude = val.longitude, globe = val.globe, marker = displayformat.marker}
-- and not blank.
end
if args[v.prefix] and v.depend then
 
for j, dependValue in ipairs(v.depend) do
local function getWDvals(query)
if type(dependValue) ~= 'string' then
query.excludespecial = true
error('Invalid "depend" parameter value detected in preprocessArgs')
query.numval = query.numval or 1
end
query.entity = query.entity or localdata.item
preprocessSingleArg(dependValue)
local claims = wd.getClaims(query)
if (not claims) then
return
end
for i, claim in ipairs(claims) do
claim = processWDval(claim, query)
table.insert(pointtable, claim)
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
end
end


-- Get arguments with number suffixes.
if (not pointtable) or (#pointtable == 0) then
local a = 1 -- Counter variable.
return nil
local moreArgumentsExist = true
end
while moreArgumentsExist == true do
 
moreArgumentsExist = false
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 }
for i = a, a + step - 1 do
if params.params and type(params.params) == 'table' then -- paramètres additionnels
for j,v in ipairs(prefixTable) do
for i, j in pairs(params.params) do
local prefixArgName = v.prefix .. tostring(i)
newparams[i] = j
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
end
a = a + step
end
end
return require('Module:Carte').multimap(newparams)
end
end
p.buildMap = p.buildmap


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


preprocessSingleArg('autoheaders')
function p.buildfooter(params)
preprocessSingleArg('child')
if not params then
preprocessSingleArg('bodyclass')
params = {}
preprocessSingleArg('subbox')
end
preprocessSingleArg('bodystyle')
 
preprocessSingleArg('title')
local classes = 'navbar noprint bordered navigation-not-searchable ' .. (params.class or '')
preprocessSingleArg('titleclass')
local style = params.style or {}
preprocessSingleArg('titlestyle')
style['border-top'] = style['border-top'] or '1px solid ' .. maincolor
preprocessSingleArg('above')
 
preprocessSingleArg('aboveclass')
local backlinkstr = '[' .. tostring( mw.uri.fullUrl( page.prefixedText, 'veaction=edit&section=0' ) ) .. ' ' .. i18n['edit'] .. ']'
preprocessSingleArg('abovestyle')
.. ' - [' .. tostring( mw.uri.fullUrl( page.prefixedText, 'action=edit&section=0' ) ) .. ' ' .. i18n['edit code'] .. ']'
preprocessArgs({
 
{prefix = 'subheader', depend = {'subheaderstyle', 'subheaderrowclass'}}
local itemlinkstr
}, 10)
if localdata.item and localdata.item ~= '-' then
preprocessSingleArg('subheaderstyle')
itemlinkstr = '[[d:' .. localdata.item .. '|' .. i18n['edit item'] .. ']]'
preprocessSingleArg('subheaderclass')
end
preprocessArgs({
local editstr = backlinkstr
{prefix = 'image', depend = {'caption', 'imagerowclass'}}
if itemlinkstr then
}, 10)
editstr = editstr .. ' - ' .. itemlinkstr
preprocessSingleArg('captionstyle')
end
preprocessSingleArg('imagestyle')
local editlinkspan = mw.html.create('span')
preprocessSingleArg('imageclass')
:css({['text-align'] = "left"})
preprocessArgs({
:addClass('plainlinks')
{prefix = 'header'},
:wikitext(editstr)
{prefix = 'data', depend = {'label'}},
:done()
{prefix = 'rowclass'},
local doclinkstr = '[[Fichier:Info Simple.svg|12px|link=' .. localdata.templatename .. '|' .. i18n['see doc'] .. ']]'
{prefix = 'rowstyle'},
-- si ce lien ne marche pas toujours, il faut ajouter un variable pour le nom de l'infobox récupéré par le frame
{prefix = 'rowcellstyle'},
local doclinkspan = mw.html.create('span')
{prefix = 'class'}
:css({['text-align'] = "right"})
}, 50)
:wikitext(doclinkstr)
preprocessSingleArg('headerclass')
:done()
preprocessSingleArg('headerstyle')
 
preprocessSingleArg('labelstyle')
local footer = mw.html.create('p')
preprocessSingleArg('datastyle')
:addClass(classes)
preprocessSingleArg('below')
:css(style)
preprocessSingleArg('belowclass')
:node(editlinkspan)
preprocessSingleArg('belowstyle')
:node(doclinkspan)
preprocessSingleArg('name')
return footer
-- 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.buildFooter = p.buildfooter


-- If called via #invoke, use the args passed into the invoking template.
function p.buildblock(block)
-- Otherwise, for testing purposes, assume args are being passed directly in.
if type(block) == 'function' then
function p.infobox(frame)
block = block( localdata )
if frame == mw.getCurrentFrame() then
end
origArgs = frame:getParent().args
 
else
local blocktypes = { -- list of functions for block buildings
origArgs = frame
['invalid'] = p.buildinvalidblock,
['external text'] = p.buildexternaltext,
['footer'] = p.buildfooter,
['images'] = p.buildimages,
['map']= p.buildmap,
['mixed'] = p.buildrow,
['navigator'] = p.buildnavigator,
['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
end
return blocktypes[block.type](block)
parseDataParameters()
return _infobox()
end
end
p.buildBlock = p.buildblock
function p.build()
localdata = require( 'Module:Infobox/Localdata' )
if type( localdata.item ) == 'table' then
localdata.item = localdata.item.id
end
-- assign rank to the infobox, "secondary" means special formatting like no displaytitle for coordinates
local infoboxrank = 'main' -- main infobox of the page, with coordinates displayed in title etc.
if page.namespace ~= 0 then
infoboxrank = 'secondary'
end
-- if infobox is linked to another item: rank = secondary
if localdata.item then
local itemlink = mw.wikibase.sitelink(localdata.item)
local pagetitle = page.prefixedText
if (itemlink or '') ~= pagetitle then
infoboxrank = 'secondary'
end
end
localdata.infoboxrank = infoboxrank


-- For calling via #invoke within a template
-- load infobox module page
function p.infoboxTemplate(frame)
local moduledata = require('Module:Infobox/' .. localdata.modulename)
origArgs = {}
moduledata.name = localdata.modulename
for k,v in pairs(frame.args) do origArgs[k] = mw.text.trim(v) end
parseDataParameters()
-- maintenance categories given by the module page
if moduledata.categories then
for i, j in pairs(moduledata.categories) do
if (type(j) == 'string') then addMaintenanceCat(j) end
if (type(j) == 'table') then addMaintenanceCat(j[1],j[2]) end
end
end
return _infobox()
-- defines main color
maincolor = localdata['couleur infobox'] or localdata['couleur boîte'] or localdata['couleur boite'] 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 == 6 or #maincolor == 3 ) and maincolor:match( '^%x+$' ) then
maincolor = '#' .. maincolor
end
if thirdcolor == 'oui' or thirdcolor == 'true' then
thirdcolor = '#000'
elseif thirdcolor == 'non' or thirdcolor == 'false' then
thirdcolor = '#fff'
end
 
-- classes
local classes = mw.getCurrentFrame():expandTemplate{ title = 'Classes début infobox', args = { version = '3' } }
classes = classes .. ' large ' .. (moduledata.class or '')
 
-- style
local style = moduledata.style or {}
 
-- build infobox
infobox :addClass(classes)
: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

Dernière version du 19 septembre 2024 à 16:41

Module pour la création d'infobox à partir d'un sous-module de paramétrage de l'infobox, de paramètres passés à un modèle et, le cas échéant, de données de Wikidata.

build(frame)

Fonction à utiliser depuis un modèle, elle ne prend qu'un paramètre direct, nom, le nom du sous-module où est définie la structure de l'infobox. Par exemple Modèle:Infobox Tapis persan contient {{#invoke:Infobox|build|nom=Tapis persan}}, indiquant qu'il faut utiliser Module:Infobox/Tapis persan. Les paramètres passés au modèles sont disponibles dans le Module:Infobox/Localdata, qui peut être appelé depuis les sous-modules. Les classes css des infobox (actuellement infobox_v3 et noarchive) sont gérées par Modèle:Classes début infobox.

La structure de l'infobox est définie par une table contenue dans un sous-module, et dont le format est :

{
 maincolor = '#XXXXXX' -- couleur à utiliser par défaut pour les titres et les sous titre
 parts = {} -- les différentes sous-parties de l'infobox
}

La partie parts contient elle-même des tables, ou des fonctions utilisant les variables localdata et item pour créer des tables. Pour une liste des types de données acceptés, et des conseils pratiques, voir Aide:Infobox en Lua.

Modèle:Projet Scribunto


local p = {}
local wikiLang = 'fr'

local localdata = {}-- données concernant les paramètres passés au modèle

-- données concernant la page où est affichée l'infobox
local page = mw.title.getCurrentTitle()

local maincolor, secondcolor, thirdcolor = 'var(--background-color-interactive-subtle, #f8f9fa)', 'var(--background-color-interactive-subtle, #f8f9fa)', 'var(--color-emphasized, #000000)'
-- l'objet principal à retourner
local infobox = mw.html.create('div')

-- objets secondaires à retourner
local maintenance = '' -- chaîne retournée avec le module : cats de maintenance
local externaltext = '' -- par exemple coordonnées en titre
-- modules importés
local wd = require 'Module:Wikidata'
local yesno = require 'Module:Yesno'
local valueexpl = wd.translate("activate-query")

-- maintenance des images dupliquées
local usedImages = {}

local i18n = {
	['see doc'] = 'Documentation du modèle',
	['edit'] = 'modifier',
	['edit code'] = 'modifier le code',
	['edit item'] = 'modifier Wikidata',
	['tracking cat'] = "Page utilisant des données de Wikidata",
	['invalid block type'] = "Bloc de données invalide dans le module d'infobox",
	['default cat'] = "Maintenance des infobox",
}

local function expandQuery(query)
	if not query.entity then
		query.entity = localdata.item
	end
	if not query.conjtype then
		query.conjtype = 'comma'
	end
	local claims = wd.getClaims(query)
	if (not claims) then
		return nil
	end

	return wd.formatAndCat(query), wd.getgendernum(claims) -- valeur  et code indiquant le genre/nombre pour accorder le libellé
end

local function getWikidataValue(params, wikidataparam)
	-- Récupère la valeur Wikidata pour la valeur, soit dans le paramètre "wikidata" soit dans le paramètre "property"
	if not localdata.item then
		return nil
	end

	if params.blockers then -- blockers are local parameters that disable the wikidata query
		local blockers = params.blockers
		if (type(blockers) == 'string') then
			blockers = {blockers}
		end
		for i, blocker in ipairs(blockers) do
			if localdata[blocker] then
				return nil
			end
		end
	end

	local v, valgendernum -- la valeur à retourner, et le genre/nombre de de valeurs (pour l'accord grammatical)

	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
		wikidataparam = 'wikidata'
	end
	
	if params.property and not params[wikidataparam] then params[wikidataparam] = {property = params.property} end
	
	if params[wikidataparam] then
		if type(params[wikidataparam]) == 'function' then
			v, valgendernum = params[wikidataparam](localdata.item)
		elseif type(params[wikidataparam]) == 'table' then
			v, valgendernum = expandQuery(params[wikidataparam])
		else
			v, valgendernum = params[wikidataparam]
		end
	end
	if not v then
		return nil
	end
	
	if(type(valgendernum) == 'number') then
		if(valgendernum > 1) then
			valgendernum = 'p'
		else
			valgendernum = 's'
		end
	end
	
	return v, valgendernum
end

local function getValue(val, params)
	if type(val) == 'string' then
		return localdata[val]
	elseif type(val) == 'function' then
		return val(localdata, localdata.item, params)
	elseif type(val) == 'table' then
		for i, j in pairs(val) do -- si plusieurs paramètres possibles (legacy de vieux code), prendre le premier non vide
			if localdata[j] then
				return localdata[j]
			end
		end
	end
end

local function addMaintenanceCat(cat, sortkey)
	if page.namespace ~= 0 then
		return ''
	end
	if cat then
		local sortkeycode
		if sortkey then sortkeycode = '|' .. sortkey else sortkeycode = '' end
		maintenance = maintenance .. '[[Category:'.. cat .. sortkeycode .. ']]'
	end
end

function p.separator(params)
	local style = params['separator style'] or {}
	style.height = style.height or '2px'
	style['background-color'] = style['background-color'] or maincolor

	return mw.html.create('hr'):css( style )
end

--[=[
Construit le code du bloc de titre de l'infobox

Paramètres (liste partielle) :
- value : Moyen d'obtenir le titre via getValue (nom de paramètre de modèle ou fonction).
- textdefaultvalue : Valeur par défaut du titre.
- icon : Pictogramme d'infobox (voir [[Projet:Infobox/Pictogramme]]).
- italic : Indique si le titre doit être affiché en italique.
  Si italic=true, le paramètre "titre en italique" de l'infobox peut forcer la désactivation.
- setdisplaytitle : Indique si le titre de l'article doit être mis en forme comme celui de l'infobox.
  Si setdisplaytitle=true, le paramètre "titre article en italique" de l'infobox peut forcer la désactivation.
]=]
function p.buildtitle(params)
	local text = getValue(params.value, params) or params.textdefaultvalue or getWikidataValue(params) or page.prefixedText
	local lang = localdata['langue du titre'] or ''
	if lang ~= '' then
		local langueFunction = require( 'Module:Langue' ).langue
		text = langueFunction( { lang, text } )
	end
	local subtext = getValue(params.subtitle) or  getWikidataValue(params, 'wikidatasubtitle') or params.subtitledefaultvalue
	if subtext and (subtext ~= text) then
		text = text .. '<br /><small>' .. subtext .. '</small>'
	end
	local icon = params.icon or ''
	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
	local classes = 'entete ' .. icon

	local italic = params.italic and yesno(localdata['titre en italique'] or '', true, true)
	if italic then
		classes = classes .. ' italique'
	end
	if params.setdisplaytitle and yesno(localdata['titre article en italique'] or '', true, true) then
		local formatTitleModule = require( 'Module:Formatage du titre' )
		text = text .. formatTitleModule.setDisplayTitle{ args = {
			lang = lang,
			italic = italic,
			options = 'noreplace',
		} }
	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(classes)
		:css(style)
		:tag('div')
			:wikitext(text)
		:allDone()
	return title
end
p.buildTitle = p.buildtitle

function p.buildnavigator(params)

	-- définition du style
	local classes = "overflow infobox-navigateur " .. (params.class or '')
	local style = params.style or {}

	if params.separated then -- options pour ajouter une ligne de séparation au dessus
		classes = classes .. ' bordered'
		style['border-top'] = '1px solid' .. maincolor
	end

	-- ajustement des paramètres de données
	params.previousval = params.previousval or params.previousparameter -- nom de paramètre obsolète
	params.nextval = params.nextval or params.nextparameter

	if params.previousproperty then
		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 nextval = getValue(params.nextval, params) or getWikidataValue(params, 'nextwikidata')

    if previousval  == '-' then previousval  = nil end
    if nextval  == '-' then nextval  = nil end

	local navigator
	if params.inner then -- pour celles qui sont à l'intérieur d'une table
		navigator = mw.html.create('tr'):tag('th'):attr('colspan', 2)
		style['font-weight'] = style['font-weight'] or 'normal'
	else
		navigator = mw.html.create('div')
	end

	if previousval or nextval then
		navigator
			:addClass(classes)
			:css(style)
			:tag('div')
				:addClass('prev_bloc')
				:wikitext(previousval)
				:done()
			:tag('div')
				:addClass('next_bloc')
				:wikitext(nextval)
				:done()
			:allDone()
		return navigator
	end
	return nil
end
p.buildNavigator = p.buildnavigator

function p.buildimages(params)
	local images = {}
	local upright, link, caption, classe, alt, size  -- size is deprecated
	if type(params.imageparameters) == 'string' then
		params.imageparameters = {params.imageparameters}
	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
		params.imageparameters = {}
	end
	for j, k in ipairs(params.imageparameters) do
		table.insert(images, localdata[k])
	end
	-- Images de Wikidata
	local iswikidataimage, iswikidatacaption = false
	if #images == 0 and localdata.item then
		if params.property then
			params.wikidata = {entity = localdata.item, property = params.property}
		end
		if params.wikidata then
			local wdq = params.wikidata
			wdq.excludespecial = true
			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
				maintenance = maintenance .. wd.addTrackingCat(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'})
						iswikidatacaption = caption ~= nil
					end
					images[i] = image.mainsnak.datavalue.value
					iswikidataimage = true
				end
			end
		end
	end

	if #images == 0 and getValue(params.captionparameter) ~= nil then
		addMaintenanceCat("Infobox avec une légende locale sans image")
	end
	-- Images par défaut
	if #images == 0 then
		if params.maintenancecat then
			addMaintenanceCat(params.maintenancecat, params.sortkey)
		end
		if params.defaultimages then
			images = params.defaultimages
			if type(images) == 'string' then
				images = {images}
			end
			upright = params.defaultimageupright
			caption = params.defaultimagecaption
			link = params.defaultimagelink
			classe = params.defaultimageclass
			if not classe and ( images[1] == 'Defaut.svg' or images[1] == 'Defaut 2.svg' ) then
				classe = 'skin-invert notheme'
			end
			alt = params.defaultimagealt
			if not alt and ( images[1] == 'Defaut.svg' or images[1] == 'Defaut 2.svg' ) then
				alt = 'une illustration sous licence libre serait bienvenue'
			end
		end
	end
	if #images == 0 then
		return nil
	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
	classe = classe or getValue( params.classparameter) or params.defaultclass
	alt = alt or getValue( params.altparameter) or params.defaultalt

	if iswikidataimage and not iswikidatacaption and getValue(params.captionparameter) ~= nil then
		addMaintenanceCat("Infobox avec une légende locale et une image sur Wikidata")
	end

	-- 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.*', '')
		widthonly = tonumber(widthonly)
		if type(widthonly) ~= 'number' or widthonly > 280 then
			addMaintenanceCat("Infobox avec une image trop grande")
		end

		if tonumber(sizevalue) then
			size = tostring( tonumber(sizevalue) ) .. 'px'
		end
	end

	if tonumber(upright) then
		upright = tostring( tonumber(upright) )
	end

	local style = params.style or {padding ='2px 0',}

	-- Partie image

	local imagesString = ''
	for i,image in pairs(images) do
		if image == '-' then
			return
		end
		imagesString = imagesString ..  '[[Fichier:' .. image .. '|frameless'
		if size then
			imagesString = imagesString .. '|' .. size -- not a mistake, parameter is unnamed
		end
		if classe then
			imagesString = imagesString .. '|class=' .. classe
		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 .. ']]'

		if usedImages[image] then
			addMaintenanceCat('Infobox avec plusieurs images identiques')
		end
		usedImages[image] = true
	end

	local image = mw.html.create('div')
		:addClass("images")
		:css(style)
		:wikitext(imagesString)

	-- Partie légende
	local captionobj
	if caption then
		captionobj = mw.html.create('div')
			:wikitext(caption)
			:css(params.legendstyle or {})
			:addClass("legend")
			:done()
	end

	-- séparateur
	local separator
	if params.separator then
		separator = p.separator(params)
	end
	return mw.html.create('div')
		:node(image)
		:node(captionobj)
		:node(separator)
		:done()
end
p.buildImages = p.buildimages

function p.buildtext(params)
	local classes = params.class or ''
	local style = {
		['text-align'] = 'center',
		['font-weight'] = 'bold'
	}
	if params.style then
		for i, j in pairs(params.style) do
			style[i] = j
		end
	end
	local text = getValue(params.value, params) or getWikidataValue(params) or params.defaultvalue
	if text == '-' then
		return
	end
	if not text then
		if params.maintenancecat then
			addMaintenanceCat(params.maintenancecat, params.sortkey)
		end
		return nil
	end
	-- séparateur
	local separator
	if params.separator then
		separator = p.separator(params)
	end
	local formattedtext = mw.html.create('p')
		:addClass(classes)
		:css(style)
		:wikitext(text)
		:node(separator)
		:done()
	return formattedtext
end
p.buildText = p.buildtext

function p.buildrow(params)
	local classes = params.class or ''
	local style = params.style or {}
	local valueClass = params.valueClass or ''
	local valueStyle = params.valueStyle or {}
	local value, gendernum = getValue(params.value, params)
	if(type(gendernum) == 'number') then
		if(gendernum > 1) then
			gendernum = 'p'
		else
			gendernum = 's'
		end 
	end
	
	if type(params.wikidata) == 'table' then
		params.wikidata.wikidatalang = localdata.wikidatalang
		if (value == valueexpl) then
			value = nil
			params.wikidata.expl = false
		end
	end
	if (not value) then
		value, gendernum = getWikidataValue(params, 'wikidata')
	end
	
	if not value then
		value = params.defaultvalue
	end
	if value == '-' then
		return nil
	end
	if not gendernum then
		gendernum = 's' --singulier indéfini
	end

	if not value then
		if params.maintenancecat then
			addMaintenanceCat(params.maintenancecat, params.sortkey)
		end
		return nil
	end

	local label = params.label
	if type(label) == 'string' then label = {default = label} end
	
	if type(label) == 'table' then -- Accord en genre et en nombre
		local onlynum = {default = 'default', s = 's', ms = 's', fs = 's', p = 'p', mp = 'p', fp = 'p', mixtep = 'p'} -- Accord seulement en nombre par défaut
		
		label['s'] = label['s'] or params.singularlabel or label['default'] or label['ms']
		label['p'] = label['p'] or params.plurallabel or label['mp']
		
		label = label[gendernum] or label[onlynum[gendernum]] or label.default
	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
	if label then
		formattedlabel = mw.html.create('th')
			:attr('scope', 'row')
			:wikitext(label)
			:done()
	end
	local row = mw.html.create('tr')
		:addClass(classes)
		:css(style)
		:node(formattedlabel)
		:node(formattedvalue)
		:done()

	return row
end
p.buildRow = p.buildrow

function p.buildsuccession(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 rowI = mw.html.create('tr')

	local styleI = {}
	local colspan = '2'
	styleI['padding'] = '1px'
	local cellI = mw.html.create('td')
			:attr({colspan = colspan})
			:attr({align = 'center'})
			:css(styleI)

	local styleT = {
		margin = '0px',
		['background-color'] = 'transparent',
		color = 'inherit',
		width = '100%'
	}
	local 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 style = {}
	local arrowLeft = '[[Fichier:Arrleft.svg|13px|alt=Précédent|link=]]'
	local arrowRight = '[[Fichier:Arrright.svg|13px|alt=Suivant|link=]]'

	if color ~= 'default' then
		style['background-color'] = color
	end

	local styleTrans = {}

	local values = params.value
	local before = values['before']
	local center = values['center']
	local after = values['after']

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

	local formattedcenter
	formattedcenter = mw.html.create('td')
		:attr({width = '1%'})
		:css(styleTrans)
		: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

	local formattedafter
	if after then
		formattedafter = mw.html.create('td')
			:attr({align = 'right'})
			:attr({valign = 'middle'})
			:attr({width = widthCell})
			:css(style)
			:wikitext(after)
			:done()
		row:node(formattedafter)
		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
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 classes = 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 'var(--couleur-fond-boite-grise, #f9f9f9)'
	style['color'] = 'var(--color-emphasized, #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')
		:addClass(classes)
		:css(style)
		:node(formattedlabel)
		:done()

	return row
end
p.buildRow1Col = p.buildrow1col

function p.buildtable(params)
	local tab = mw.html.create('table'):css(params.style or {})

	local rows = params.rows

	-- expand parameters so that we have a list of tables
	local i = 1

	while (i <= #rows) do
		local l = rows[i]
		if type(l) == 'function' then
			l = l(localdata, localdata.item)
		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'
		title = mw.html.create('caption')
			:attr({colspan = colspan})
			:css(style)
			:wikitext(text)
			:done()
	end

	if title then
		tab:node(title)
	end

	for i, j in pairs (rows) do
		tab:node(j)
	end

	if params.separator then
		local separator = p.separator(params)
		tab:node(separator)
	end
	tab:allDone()
	return tab
end
p.buildTable = p.buildtable

function p.buildinvalidblock(args)
	addMaintenanceCat(i18n['default cat'])
	local text = ''
	if type(args) ~= 'table' then
		text = "Les blocs d'infobox doivent être des tables"
	else
		text = i18n["invalid block type"] .. ' : ' .. (args.type or '??')
	end
	return text
end
p.buildInvalidBlock = p.buildinvalidblock

function p.buildmap(params)

	-- paramètre d'affichage
	local maplist = getValue(params.maps)
	local pointtype = params.pointtype
	local maptype = params.maptype -- choisit le type de carte le plus approprié (relief, administratif, etc.)
	if type(maplist) == 'function' then
		maplist = maplist(localdata, localdata.item)
	end
	local width = tonumber(params.width) or 280
	if width > 280 then
		addMaintenanceCat("Infobox avec une image trop grande")
		return 'image trop grande, la largeur doit être inférieure ou égale à 280px'
	end

	-- récupération des données locales
	local pointtable = {}
	local globe = params.globe
	if params.latitude then
		local lat, long
		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
		if lat then
			table.insert(pointtable, {latitude = lat, longitude = long})
		end
	end

	-- récupération des données wikidata
	local function processWDval(claim, displayformat)
		if not claim then
			return nil
		end
		local val = wd.formatSnak( claim.mainsnak )
		return {latitude = val.latitude, longitude = val.longitude, globe = val.globe, marker = displayformat.marker}
	end

	local function getWDvals(query)
		query.excludespecial = true
		query.numval = query.numval or 1
		query.entity = query.entity or localdata.item
		local claims = wd.getClaims(query)
		if (not claims) then
			return
		end
		for i, claim in ipairs(claims) do
			claim = processWDval(claim, query)
			table.insert(pointtable, claim)
		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

	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
p.buildMap = p.buildmap

function p.buildexternaltext(params)
	local value = getValue(params.value)
	if value and (type(value) == 'string') then
		externaltext = externaltext .. value
	end
end
p.buildExternalText = p.buildexternaltext

function p.buildfooter(params)
	if not params then
		params = {}
	end

	local classes = 'navbar noprint bordered navigation-not-searchable ' .. (params.class or '')
	local style = params.style or {}
	style['border-top'] = style['border-top'] or '1px solid ' .. maincolor

	local backlinkstr = '[' .. tostring( mw.uri.fullUrl( page.prefixedText, 'veaction=edit&section=0' ) ) .. ' ' .. i18n['edit'] .. ']'
		.. ' - [' .. tostring( mw.uri.fullUrl( page.prefixedText, 'action=edit&section=0' ) ) .. ' ' .. i18n['edit code'] .. ']'

	local itemlinkstr
	if localdata.item and localdata.item ~= '-' then
		itemlinkstr = '[[d:' .. localdata.item .. '|' .. 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(classes)
		:css(style)
		:node(editlinkspan)
		:node(doclinkspan)
	return footer
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,
		['navigator'] = p.buildnavigator,
		['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' )
	if type( localdata.item ) == 'table' then
		localdata.item = localdata.item.id
	end

	-- assign rank to the infobox, "secondary" means special formatting like no displaytitle for coordinates
	local infoboxrank = 'main' -- main infobox of the page, with coordinates displayed in title etc.
	if page.namespace ~= 0 then
		infoboxrank = 'secondary'
	end
	-- if infobox is linked to another item: rank = secondary
	if localdata.item then
		local itemlink = mw.wikibase.sitelink(localdata.item)
		local pagetitle = page.prefixedText
		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
	
	-- maintenance categories given by the module page
	if moduledata.categories then
		for i, j in pairs(moduledata.categories) do
			if (type(j) == 'string') then addMaintenanceCat(j) end
			if (type(j) == 'table') then addMaintenanceCat(j[1],j[2]) end
		end
	end
	
	-- defines main color
	maincolor = localdata['couleur infobox'] or localdata['couleur boîte'] or localdata['couleur boite'] 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 == 6 or #maincolor == 3 ) and maincolor:match( '^%x+$' ) then
		maincolor = '#' .. maincolor
	end
	if thirdcolor == 'oui' or thirdcolor == 'true' then
		thirdcolor = '#000'
	elseif thirdcolor == 'non' or thirdcolor == 'false' then
		thirdcolor = '#fff'
	end

	-- classes
	local classes = mw.getCurrentFrame():expandTemplate{ title = 'Classes début infobox', args = { version = '3' } }
	classes = classes .. ' large ' .. (moduledata.class or '')

	-- style
	local style = moduledata.style or {}

	-- build infobox
	infobox	:addClass(classes)
			: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

return p