Module:Infobox : Tameẓla gar ileqman

Si Wikipedia, tasanayt tilellit.
Contenu supprimé Contenu ajouté
Aucun résumé des modifications
Ssefsu tasiwelt 63748 sɣur Issimo 15 (Meslay)
Ajerriḍ 1: Ajerriḍ 1:
--
-- This module implements {{Infobox}}
--
local p = {}
local p = {}
local infobox = mw.html.create('div')
local pagename = mw.title.getCurrentTitle().prefixedText
local wikidata = require('Module:Wikidata')
local linguistic = require('Module:Linguistique')
local infoboxname, infoboxmodule
local maintenance = '' -- chaîne retournée avec le module : cats de maintenance
local externaltext = '' -- par exemple coordonnées en titre
local localdata = {} -- aramètres du modèle dans l'article
local maincolor -- la couleur par défaut des titres, sous-titres etc.i


local navbar = require('Module:Navbar')._navbar
local i18n = {
['see doc'] = 'Documentation du modèle',
['edit infobox'] = 'modifier l\'infobox',
['edit item'] = 'modifier Wikidata'
}


local args = {}
local function addwikidatacat(prop)
local origArgs
maintenance = maintenance .. '[[Catégorie:Page utilisant des données de Wikidata/' .. string.upper(prop) .. ']]'
local root

local function union(t1, t2)
-- Returns the union of the values of two tables, as a sequence.
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
end


local function getWikidataValue(params, wikidataparam)
local function getArgNums(prefix)
-- 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 praramètre "property"
-- for the specified prefix. For example, if the prefix was 'data', and
if not item then
-- 'data1', 'data2', and 'data5' exist, it would return {1, 2, 5}.
return nil
local nums = {}
end
for k, v in pairs(args) do
local value
local num = tostring(k):match('^' .. prefix .. '([1-9]%d*)$')
if num then table.insert(nums, tonumber(num)) 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
end
wikidataparam = 'wikidata'
table.sort(nums)
end
return nums
if params[wikidataparam] then
if type(params[wikidataparam]) == 'function' then
value = params[wikidataparam](item)
else
value = params[wikidataparam]
end
elseif params.property then
value = wikidata.formatStatements({item = item, property = params.property}) --ne pas mettre wiidata_formatAndCat directement à cause de buildimages
if value then
addwikidatacat(params.property)
end
end
return value
end
end


local function getvalue(val, params)
local function addRow(rowArgs)
-- Adds a row to the infobox, with either a header cell
if type(val) == 'string' then
-- or a label/data cell combination.
return localdata[val]
if rowArgs.header then
elseif type(val) == 'function' then
root
return val(localdata, item, params)
:tag('tr')
end
:addClass(rowArgs.rowclass)
:cssText(rowArgs.rowstyle)
:attr('id', rowArgs.rowid)
:tag('th')
:attr('colspan', 2)
:attr('id', rowArgs.headerid)
:addClass(rowArgs.class)
:addClass(args.headerclass)
:css('text-align', 'center')
:cssText(args.headerstyle)
:wikitext(rowArgs.header)
elseif rowArgs.data then
local row = root:tag('tr')
row:addClass(rowArgs.rowclass)
row:cssText(rowArgs.rowstyle)
row:attr('id', rowArgs.rowid)
if rowArgs.label then
row
:tag('th')
:attr('scope', 'row')
:attr('id', rowArgs.labelid)
:cssText(args.labelstyle)
:wikitext(rowArgs.label)
:done()
end
local dataCell = row:tag('td')
if not rowArgs.label then
dataCell
:attr('colspan', 2)
:css('text-align', 'center')
end
dataCell
:attr('id', rowArgs.dataid)
:addClass(rowArgs.class)
:cssText(rowArgs.datastyle)
:newline()
:wikitext(rowArgs.data)
end
end
end

local function addmaintenancecat(cat, sortkey)
local function renderTitle()
if mw.title.getCurrentTitle().namespace ~= 0 then
if not args.title then return end
return

end
root
if cat then
:tag('caption')
maintenance = maintenance .. '[[Category:' .. cat .. '|' .. (sortkey or infoboxname) .. ']]'
:addClass(args.titleclass)
end
:cssText(args.titlestyle)
:wikitext(args.title)
end
end


local function buildtitle(params)
local function renderAboveRow()
if not args.above then return end
local text = getvalue(params.value, params) or params.textdefaultvalue or getWikidataValue(params) or mw.title.getCurrentTitle().text
local subtext = getvalue(params.subtitle) or getWikidataValue(params, 'wikidatasubtitle') or params.subtitledefaultvalue
root
if subtext and (subtext ~= text) then
:tag('tr')
text = text .. '<br /><small>' .. subtext .. '</small>'
:tag('th')
end
:attr('colspan', 2)
local class = params.class or "entete"
:addClass(args.aboveclass)
local style = params.style or {}
:css('text-align', 'center')
if not style['background-color'] then
:css('font-size', '125%')
style['background-color'] = maincolor
:css('font-weight', 'bold')
end
:cssText(args.abovestyle)
local title = mw.html.create('p')
:wikitext(args.above)
:addClass(class)
:css(style)
:wikitext(text)
:done()
return title
end
end


local function buildnavbox(params)
local function renderBelowRow()
if not args.below then return end
local class = "overflow nav " .. (params.class or '')
local style = params.style or {['border-width'] = '1px'}
root
if not style['border-color']
:tag('tr')
then style['border-color'] = maincolor
:tag('td')
end
:attr('colspan', '2')
local previousval = localdata[params.previousparameter]
:addClass(args.belowclass)
local nextval = localdata[params.nextparameter]
:css('text-align', 'center')
local navbox =
:cssText(args.belowstyle)
mw.html.create('p')
:newline()
:addClass(class)
:wikitext(args.below)
:css(style)
:tag('span')
:addClass('prev_bloc')
:wikitext(previousval)
:done()
:tag('span')
:addClass('next_bloc')
:wikitext(nextval)
:done()
:done()
return navbox
end
end


local function buildimages(params)
local function renderSubheaders()
if args.subheader then
local images = {}
args.subheader1 = args.subheader
if type(params.imageparameters) == 'string' then
end
params.imageparameters = {params.imageparameters}
if args.subheaderrowclass then
end
args.subheaderrowclass1 = args.subheaderrowclass
if not params.imageparameters then -- s'il n'y a pa de paramètre image, continuer, peut-être y-a-t-il une image par défaut définie dans le module d'infobox
end
params.imageparameters = {}
local subheadernums = getArgNums('subheader')
end
for j, k in ipairs(params.imageparameters) do
for k, num in ipairs(subheadernums) do
addRow({
table.insert(images, localdata[k])
data = args['subheader' .. tostring(num)],
end
datastyle = args.subheaderstyle or args['subheaderstyle' .. tostring(num)],
if #images == 0 and item then
class = args.subheaderclass,
if params.property then
rowclass = args['subheaderrowclass' .. tostring(num)]
images = wikidata.getClaims{item= item, property = params.property} or {}
})
if #images > 0 then addwikidatacat(params.property) end
end
if params.wikidata 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
end
if ((not images) or (#images == 0)) and params.defaultimages then
images = params.defaultimages
if type(images) == 'string' then
images = {images}
end
end
if (not images) or #images == 0 then
if params.maintenancecat then
local maintenancecat = getvalue(params.maintenancecat, params)
addmaintenancecat(maintenancecat, params.sortkey)
end
return
end
-- extrait les images des valeurs Wikidata
if type(images[1]) == 'table' then
for i, j in pairs(images) do
if j.mainsnak.snaktype ~= 'value' then
return
end
if i > (params.numval) then
images[i] = nil
else
images[i] = j.mainsnak.datavalue.value
end
end
end
local captiontext = localdata[params.captionparameter] or params.defaultcaption
if type(captiontext) == 'function' then
captiontext = captiontext(localdata)
end
local style = params.style or {padding ='5px 0'}

-- Partie image

local imagesString = ''
for i,image in pairs(images) do
if image == '-' then
return
end
imagesString = imagesString .. '[[Fichier:' .. image .. '|frameless'
if #images == 1 then
imagesString = imagesString .. '|center'
end
if image.upright then
imagesString = imagesString .. '|upright=' .. image.upright
else
imagesString = imagesString .. '|upright=' .. ( 1 / #images )
end
imagesString = imagesString .. ']]'
end
end

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

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

return image, caption
end
end


local function buildtext(params)
local function renderImages()
if args.image then
local class = params.class or ''
args.image1 = args.image
local style = params.style or {}
end
if not style['text-align'] then
if args.caption then
style['text-align'] = 'center'
args.caption1 = args.caption
end
end
if not style['padding'] then
local imagenums = getArgNums('image')
style['padding'] = '10px'
for k, num in ipairs(imagenums) do
end
local caption = args['caption' .. tostring(num)]
if not style['font-weight'] then
local data = mw.html.create():wikitext(args['image' .. tostring(num)])
style['font-weight'] = 'bold'
if caption then
end
data
local text = getvalue(params.value, params) or getWikidataValue(params) or params.defaultvalue
:tag('div')
if text == '-' then
:cssText(args.captionstyle)
return
:wikitext(caption)
end
end
if not text then
addRow({
addmaintenancecat(params.maintenancecat, params.sortkey)
data = tostring(data),
return nil
datastyle = args.imagestyle,
end
class = args.imageclass,
local formattedtext = mw.html.create('p')
rowclass = args['imagerowclass' .. tostring(num)]
:addClass(class)
})
:css(style)
end
:wikitext(text)
:done()
return formattedtext
end
end


local function buildmixedrow(params)
local function renderRows()
-- Gets the union of the header and data argument numbers,
local class = params.class or ''
-- and renders them all in order using addRow.
local style = params.style or {}
local rownums = union(getArgNums('header'), getArgNums('data'))
local value = getvalue(params.value, params)
table.sort(rownums)
for k, num in ipairs(rownums) do
if not value then
addRow({
value = getWikidataValue(params) or params.defaultvalue
header = args['header' .. tostring(num)],
end
label = args['label' .. tostring(num)],
data = args['data' .. tostring(num)],
local label = params.label
datastyle = args.datastyle,
if not value then
class = args['class' .. tostring(num)],
addmaintenancecat(params.maintenancecat, params.sortkey)
rowclass = args['rowclass' .. tostring(num)],
return nil
rowstyle = args['rowstyle' .. tostring(num)],
end
dataid = args['dataid' .. tostring(num)],
if value == '-' then
labelid = args['labelid' .. tostring(num)],
return
headerid = args['headerid' .. tostring(num)],
end
rowid = args['rowid' .. tostring(num)]
-- formatting
})
-- Le '\n' est requis lorsque value est une liste commençant par '*' ou '#'
end
local formattedvalue = mw.html.create('div')
:wikitext('\n' .. value)
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)
:allDone()
local formattedlabel = mw.html.create('th')
:attr('scope', 'row')
:wikitext(label)
:done()

local row = mw.html.create('tr')
:addClass(class)
:css(style)
:node(formattedlabel)
:node(formattedvalue)
:done()
return row
end
local function buildtable(params)
local tab = mw.html.create('table')
local title
if params.title then
local text
if type(params.title) == 'string' then -- raccourci moche mais pratique : n'utiliser qu'une chaîne pour le titre
text = params.title
params.title = {}
else
text = params.title.value or error('no value provided for this title')
end
local style = params.title.style or {['text-align'] = 'center', color = '000000'}
if not style['background-color'] then
style['background-color'] = maincolor
end
local colspan = params.title.colspan or '2'
title = mw.html.create('caption')
:attr({colspan = 2})
:css(style)
:wikitext(text)
:done()
end
local rows = {} -- does not add the rows directly to tab: check if some rows are non empty beoforehand so that we do not add a title if there are no data to show
for k, l in pairs(params.rows) do
if type(l) == 'function' then --accepte les fonctions qui retournent des tables
l = l(localdata, item)
end
if type(l) == 'nil' then
--ne rien faire (quand la valeur est originellemenet une fonctin elle peut retourner nil)
elseif type(l) ~= 'table' then
return error('les lignes d\'infobox ("rows") doivent être des tables, est ' .. type(l))
elseif l.type == 'mixed' then
local row = buildmixedrow(l)
if row then
table.insert(rows, row)
end
elseif l.type == 'external text' then
externaltext = externaltext .. l.value()
elseif l.type then
return error('type de ligne inconnue dans l\'infobox : ' .. l.type)
else
return error('veuillez spécifier un type pour toutes les lignes d\'infobox')
end
end
if title and (#rows > 0) then
tab:node(title)
end
if #rows > 0 then
for i, j in pairs (rows) do
tab:node(j)
end
end
tab:allDone()
return tab
end
end


local function renderNavBar()

if not args.name then return end
local function buildsinglemap(map, maptype, width, latitude, longitude, pointimage, caption) -- fonction d'aige pour buildmap
if map == '-' then
root
return
:tag('tr')
end
:tag('td')
local mapdata = require('Module:Données cartes')[string.lower(map or '')]
:attr('colspan', '2')
if not mapdata or not mapdata.images then
:css('text-align', 'right')
addmaintenancecat('Page avec des données de géolocalisation non supportée')
:wikitext(navbar{
return "carte non supportée: " .. map
args.name,
end
mini = 1,
local name = mapdata.name or '?'
})
-- analyse linguistique pour le texte de la carte
local datagender = mapdata.genre or ''
local gender = string.sub(datagender, 1, 1) -- les données cartes sont du format ms pour masucline singulier
local number = string.sub(datagender, 2, 2)
local determiner = mapdata.determiner
if not determiner and gender == 'm' or gender == 'ms' or gender == 'mp' then
determiner = true -- on dit "carte "de" France mais "du" Japon
end
local ofstring = linguistic.of(name, gender, number, determiner) -- restitue "de France" ou "du Japon"
--
local pointsize = tostring(8)
local pointheight, pointwidth
if mapdata.projection == 'Projection équirectangulaire' then
pointheight = 100 * (latitude - mapdata.top) / (mapdata.bottom - mapdata.top)
pointwidth = 100 * (longitude - mapdata.left) / (mapdata.right - mapdata.left)
else
return "système cartographique non supporté"
end
if (pointheight > 100) or (pointwidth) > 100 or (pointheight < 0) or (pointwidth < 0) then
addmaintenancecat('Article avec une géolocalisation hors-carte') return 'lat: ' .. latitude .. '//' .. pointheight
end
local htmlheight = tostring(pointheight) .. '%'
local htmlwidth = tostring(pointwidth) .. '%'

local pointdiv = mw.html.create('div')
:css{position = 'absolute', border = 'none', top = htmlheight, left = htmlwidth}
:tag('div')
:css{position = 'absolute', top = '-4px', left = '-4px', ['line-height'] = '0'}
:wikitext('[[Image:' .. pointimage .. '|8px]]')
:done()
local mapname = mapdata.name
local file
if type(mapdata.images) == 'string' then
file = mapdata.images
else
file = mapdata.images[maptype] or mapdata.images[1] or mapdata.images['default']
end
local alt = 'voir sur la carte ' .. ofstring
local map = mw.html.create('div')
:css{['text-align'] = 'center'}
:addClass("geobox")
:wikitext('<small>Géolocalisation sur la carte ' .. ofstring .. '</small>')
:tag('table')
:addClass('DebutCarte')
:attr({border="0", cellspacing="0", cellpadding="0"})
:css({margin = '0', border = 'none', padding = '0'})
:tag('tr')
:tag('td')
:tag('div')
:css({position= 'relative', margin = "auto",})
:wikitext('[[Fichier:' .. file .. '|' .. width .. '|' .. alt .. ']]' )
:node(pointdiv)
:done()
:done()
:done()
:done()
return map
end
end


local function buildmap(params)
local function renderItalicTitle()
local italicTitle = args['italic title'] and mw.ustring.lower(args['italic title'])
if italicTitle == '' or italicTitle == 'force' or italicTitle == 'yes' then
local maplist = params.maps
root:wikitext(mw.getCurrentFrame():expandTemplate({title = 'italic title'}))
if type(maplist) == 'function' then
end
maplist = maplist(localdata, item)
end
if not maplist then
return nil
end
local width = params.width or 280
if type(width) ~= 'number' then
width = 280
maintenance = addmaintenancecat('Erreur d\'Infobox/Format d\'image invalide')
end
if width > 280 then
addmaintenancecat('Erreur d\'Infobox/Image trop grande')
return 'image trop grande, la largeur doit être inférieure ou égale à 280px'
end
width = tostring(280) .. 'px'
local div = mw.html.create('div'):addClass('img_toogle')
local pointimage = params.pointimage
if not pointimage then
pointimage = 'Point carte.svg'
end
local maptype = params.maptype -- choisit le type de carte le plus approprié (relief, administratif, etc.)
local latitude, longitude
if type(params.latitude) == 'function' then
latitude, longitude = params.latitude(localdata, item), params.longitude(localdata, item)
else
latitude, longitude = tonumber(localdata[params.latitude]), tonumber(localdata[params.longitude])
end
if (not latitude or not longitude) and item and params.wikidata then
if not type(params.wikidata) == 'function'
then return error('valeur wikidata incorrecte pour la géolocalisation')
end
local val = params.wikidata(localdata, item)
if not val then return nil end
if (not type(val) == 'table') then
return error("mauvaise requête pour les coordonnées de géolocalisation")
end
val = val[1]
if val.mainsnak.snaktype == 'value' then
latitude, longitude = val.mainsnak.datavalue.value.latitude, val.mainsnak.datavalue.value.longitude
end
end
if not latitude or not longitude then
return nil
end
for i, map in pairs(maplist) do
local newmap = buildsinglemap( mw.ustring.lower(map), maptype, width, latitude, longitude, pointimage, caption)
div:node(newmap)
end
return div
end
end


local function buildfooter(params)
local function renderTrackingCategories()
if args.decat ~= 'yes' then
if not params then params = {} end
if #(getArgNums('data')) == 0 and mw.title.getCurrentTitle().namespace == 0 then
root:wikitext('[[Category:Articles which use infobox templates with no data rows]]')
local class = 'navbar noprint ' .. (params.class or '')
end
local style = params.style or {}
if args.child == 'yes' and args.title then
if not style['border-top-style'] then
root:wikitext('[[Category:Pages which use embedded infobox templates with the title parameter]]')
style['border-top-style'] = 'solid'
end
end
end
if not style['border-width'] then
style['border-width'] = '1px'
end
if not style['border-color'] then
style['border-color'] = maincolor
end
if not style['font-size'] then
style['font-size'] = '80%'
end
local backlinkstr = '[' .. tostring( mw.uri.fullUrl( pagename, '&action=edit&section=0' ) ) .. ' ' .. i18n['edit infobox'] .. ']'

local itemlinkstr
if item then
itemlinkstr = '[[d:' .. 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 = '[[Image:Gtk-dialog-info.svg|12px|link=' .. infoboxname .. '|' .. i18n['see doc'] .. ']]'
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


function p._build(localinfoboxmodule)
local function _infobox()
-- analyse le module d'infobox
local style = localinfoboxmodule.style or {}
local class = localinfoboxmodule.class or "infobox_v3"
local parts = localinfoboxmodule.parts
maincolor = localinfoboxmodule.maincolor or "#E1E1E1"
local footerparams = localinfoboxmodule.footer or {}
infobox:css(style)
infobox:addClass(class)

for i, j in pairs(parts) do
if type(j) ~= 'table' then
return error("les éléments du module doivent être des tables (est ".. type(j) .. ')')
elseif j.type == 'title' then
infobox:node(buildtitle(j))
elseif j.type == 'images' then
local image, caption = buildimages(j)
infobox:node(image):node(caption)
elseif j.type == 'text' then
infobox:node(buildtext(j))
elseif j.type == 'map' then
infobox:node(buildmap(j))
elseif j.type == 'navbox' then
infobox:node(buildnavbox(j))
elseif j.type == 'table' then
infobox:node(buildtable(j))
end
end
local div = mw.html.create('div')
infobox:node(div):node(tab)
infobox
:node(buildfooter(footerparams))
:done()
return tostring(infobox) .. externaltext, maintenance
end

function p.build(frame)
-- set variables
infoboxname = 'Module:Infobox/' .. frame.args.nom
localinfoboxmodule = require(infoboxname)
-- get the localinfoboxmodule parameter values and clen them up
for i, j in pairs(frame:getParent().args) do
if j and mw.text.trim(j) ~= '' then
localdata[i] = j
end
end
-- Specify the overall layout of the infobox, with special settings
-- Specify the overall layout of the infobox, with special settings
-- if the infobox is used as a 'child' inside another infobox.
-- if the infobox is used as a 'child' inside another infobox.
Ajerriḍ 595: Ajerriḍ 273:


local function preprocessSingleArg(argName)
local function preprocessSingleArg(argName)
-- fetch wikidata item and assign it to the item global variable
-- 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.
if localdata.wikidata == 'non' then
if origArgs[argName] and origArgs[argName] ~= '' then
item = nil
args[argName] = origArgs[argName]
elseif (not localdata.wikidata) or (localdata.wikidata == '') then
end
item = mw.wikibase.getEntityObject()
else
item = mw.wikibase.getEntityObject() -- todo: fetch arbitrary item and check for errors
end
-- build infobox
return p._build(localinfoboxmodule)
end
end


local function preprocessArgs(prefixTable, step)
-- 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.
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
moreArgumentsExist = true -- Do another loop if any arguments are found, even blank ones.
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
function p.infobox(frame)
-- If called via #invoke, use the args passed into the invoking template.
-- Otherwise, for testing purposes, assume args are being passed directly in.
if frame == mw.getCurrentFrame() then
origArgs = frame:getParent().args
else
origArgs = frame
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.
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 = 'class'},
{prefix = 'dataid'},
{prefix = 'labelid'},
{prefix = 'headerid'},
{prefix = 'rowid'}
}, 50)
preprocessSingleArg('headerclass')
preprocessSingleArg('headerstyle')
preprocessSingleArg('labelstyle')
preprocessSingleArg('datastyle')
preprocessSingleArg('below')
preprocessSingleArg('belowclass')
preprocessSingleArg('belowstyle')
preprocessSingleArg('name')
args['italic title'] = origArgs['italic title'] -- different behaviour if blank or absent
preprocessSingleArg('decat')
return _infobox()
end
return p
return p

Lqem n wass 12 Ɣuct 2016 à 17:53

La documentation pour ce module peut être créée à Module:Infobox/doc

--
-- This module implements {{Infobox}}
--
 
local p = {}

local navbar = require('Module:Navbar')._navbar

local args = {}
local origArgs
local root

local function union(t1, t2)
    -- Returns the union of the values of two tables, as a sequence.
    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

local function getArgNums(prefix)
    -- 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 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

local function addRow(rowArgs)
    -- Adds a row to the infobox, with either a header cell
    -- or a label/data cell combination.
    if rowArgs.header then
        root
            :tag('tr')
                :addClass(rowArgs.rowclass)
                :cssText(rowArgs.rowstyle)
                :attr('id', rowArgs.rowid)
                :tag('th')
                    :attr('colspan', 2)
                    :attr('id', rowArgs.headerid)
                    :addClass(rowArgs.class)
                    :addClass(args.headerclass)
                    :css('text-align', 'center')
                    :cssText(args.headerstyle)
                    :wikitext(rowArgs.header)
    elseif rowArgs.data then
        local row = root:tag('tr')
        row:addClass(rowArgs.rowclass)
        row:cssText(rowArgs.rowstyle)
        row:attr('id', rowArgs.rowid)
        if rowArgs.label then
            row
                :tag('th')
                    :attr('scope', 'row')
                    :attr('id', rowArgs.labelid)
                    :cssText(args.labelstyle)
                    :wikitext(rowArgs.label)
                    :done()
        end
        
        local dataCell = row:tag('td')
        if not rowArgs.label then 
            dataCell
                :attr('colspan', 2)
                :css('text-align', 'center') 
        end
        dataCell
            :attr('id', rowArgs.dataid)
            :addClass(rowArgs.class)
            :cssText(rowArgs.datastyle)
            :newline()
            :wikitext(rowArgs.data)
    end
end

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

    root
        :tag('caption')
            :addClass(args.titleclass)
            :cssText(args.titlestyle)
            :wikitext(args.title)
end

local function renderAboveRow()
    if not args.above then return end
    
    root
        :tag('tr')
            :tag('th')
                :attr('colspan', 2)
                :addClass(args.aboveclass)
                :css('text-align', 'center')
                :css('font-size', '125%')
                :css('font-weight', 'bold')
                :cssText(args.abovestyle)
                :wikitext(args.above)
end

local function renderBelowRow()
    if not args.below then return end
    
    root
        :tag('tr')
            :tag('td')
                :attr('colspan', '2')
                :addClass(args.belowclass)
                :css('text-align', 'center')
                :cssText(args.belowstyle)
                :newline()
                :wikitext(args.below)
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
        addRow({
            data = args['subheader' .. tostring(num)],
            datastyle = args.subheaderstyle or args['subheaderstyle' .. tostring(num)],
            class = args.subheaderclass,
            rowclass = args['subheaderrowclass' .. tostring(num)]
        })
    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')
                    :cssText(args.captionstyle)
                    :wikitext(caption)
        end
        addRow({
            data = tostring(data),
            datastyle = args.imagestyle,
            class = args.imageclass,
            rowclass = args['imagerowclass' .. tostring(num)]
        })
    end
end

local function renderRows()
    -- Gets the union of the header and data argument numbers,
    -- and renders them all in order using addRow.
    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)],
            rowstyle = args['rowstyle' .. tostring(num)],
            dataid = args['dataid' .. tostring(num)],
            labelid = args['labelid' .. tostring(num)],
            headerid = args['headerid' .. tostring(num)],
            rowid = args['rowid' .. tostring(num)]
        })
    end
end

local function renderNavBar()
    if not args.name then return end
    
    root
        :tag('tr')
            :tag('td')
                :attr('colspan', '2')
                :css('text-align', 'right')
                :wikitext(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(mw.getCurrentFrame():expandTemplate({title = 'italic title'}))
    end
end

local function renderTrackingCategories()
    if args.decat ~= 'yes' then
        if #(getArgNums('data')) == 0 and mw.title.getCurrentTitle().namespace == 0 then
            root:wikitext('[[Category:Articles which use infobox templates with no data rows]]')
        end
        if args.child == 'yes' and args.title then
            root:wikitext('[[Category:Pages which use embedded infobox templates with the title parameter]]')
        end
    end
end

local function _infobox()
    -- Specify the overall layout of the infobox, with special settings
    -- if the infobox is used as a 'child' inside another infobox.
    if args.child ~= 'yes' then
        root = mw.html.create('table')
        
        root
            :addClass('infobox')
            :addClass(args.bodyclass)
            
            if args.subbox == 'yes' then
                root
                    :css('padding', '0')
                    :css('border', 'none')
                    :css('margin', '-3px')
                    :css('width', 'auto')
                    :css('min-width', '100%')
                    :css('font-size', '100%')
                    :css('clear', 'none')
                    :css('float', 'none')
                    :css('background-color', 'transparent')
            else
                root
                    :css('width', '22em')
            end
        root
            :cssText(args.bodystyle)
    
        renderTitle()
        renderAboveRow()
    else
        root = mw.html.create()
        
        root
            :wikitext(args.title)
    end

    renderSubheaders()
    renderImages() 
    renderRows() 
    renderBelowRow()  
    renderNavBar()
    renderItalicTitle()
    renderTrackingCategories()
    
    return tostring(root)
end

local function preprocessSingleArg(argName)
    -- 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.
    if origArgs[argName] and origArgs[argName] ~= '' then
        args[argName] = origArgs[argName]
    end
end

local function preprocessArgs(prefixTable, step)
    -- 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.
    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
                    moreArgumentsExist = true -- Do another loop if any arguments are found, even blank ones.
                    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
 
function p.infobox(frame)
    -- If called via #invoke, use the args passed into the invoking template.
    -- Otherwise, for testing purposes, assume args are being passed directly in.
    if frame == mw.getCurrentFrame() then
        origArgs = frame:getParent().args
    else
        origArgs = frame
    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.
    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 = 'class'},
        {prefix = 'dataid'},
        {prefix = 'labelid'},
        {prefix = 'headerid'},
        {prefix = 'rowid'}
    }, 50)
    preprocessSingleArg('headerclass')
    preprocessSingleArg('headerstyle')
    preprocessSingleArg('labelstyle')
    preprocessSingleArg('datastyle')
    preprocessSingleArg('below')
    preprocessSingleArg('belowclass')
    preprocessSingleArg('belowstyle')
    preprocessSingleArg('name')
    args['italic title'] = origArgs['italic title'] -- different behaviour if blank or absent
    preprocessSingleArg('decat')
 
    return _infobox()
end
 
return p