Saltar para o conteúdo

Módulo:Infobox3cols/Testes

Origem: Wikipédia, a enciclopédia livre.
--
-- This module implements {{Infobox3cols}}
--
-- The initial version was created by modifying [[Module:Infobox]]
--
 
local p = {}

local navbar = require('Módulo: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,suffix)
    -- 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 .. '([0-9]%d*)' .. suffix .. '$')
        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', 4)
                    :attr('id', rowArgs.headerid)
                    :addClass(rowArgs.class)
                    :addClass(args.headerclass or args['cabeçalho-classe'])
                    :css('text-align', 'center')
                    :cssText(args.headerstyle or args['cabeçalho-estilo'])
                    :cssText(rowArgs.rowcellstyle)
                    :wikitext(rowArgs.header)
    elseif rowArgs.label then
        if rowArgs.data then
            local row = root:tag('tr')
            row:addClass(rowArgs.rowclass)
            row:cssText(rowArgs.rowstyle)
            row:attr('id', rowArgs.rowid)
            row
                :tag('th')
                    :attr('scope', 'row')
                    :attr('id', rowArgs.labelid)
                    :cssText(args.labelstyle or args['rótulo-estilo'])
                    :cssText(rowArgs.rowcellstyle)
                    :wikitext(rowArgs.label)
                    :done()
        
            local dataCell = row:tag('td')
            dataCell
                :attr('colspan', 3)
                :attr('id', rowArgs.dataid)
                :addClass(rowArgs.class)
                :cssText(rowArgs.datastyle)
                :cssText(rowArgs.rowcellstyle)
                :newline()
                :wikitext(rowArgs.data)
        elseif rowArgs.dataa or rowArgs.datab then
            local row = root:tag('tr')
            row:addClass(rowArgs.rowclass)
            row:cssText(rowArgs.rowstyle)
            row:attr('id', rowArgs.rowid)
            row
                :tag('th')
                    :attr('scope', 'row')
                    :attr('id', rowArgs.labelid)
                    :cssText(args.labelstyle or args['rótulo-estilo'])
                    :cssText(rowArgs.rowcellstyle)
                    :wikitext(rowArgs.label)
                    :done()

            local dataCella = row:tag('td')
            dataCella
                :attr('id', rowArgs.dataaid)
                :addClass(rowArgs.classa)
                :cssText(rowArgs.dataastyle)
                :cssText(rowArgs.rowcellstyle)
                :newline()
                :wikitext(rowArgs.dataa)
            if rowArgs.renderb then
                local dataCellb = row:tag('td')
                dataCellb
                    :attr('id', rowArgs.databid)
                    :addClass(rowArgs.classb)
                    :cssText(rowArgs.databstyle)
                    :cssText(rowArgs.rowcellstyle)
                    :newline()
                    :wikitext(rowArgs.datab)
            end
            if rowArgs.renderc then
                local dataCellc = row:tag('td')
                dataCellc
                    :attr('id', rowArgs.datacid)
                    :addClass(rowArgs.classc)
                    :cssText(rowArgs.datacstyle)
                    :cssText(rowArgs.rowcellstyle)
                    :newline()
                    :wikitext(rowArgs.datac)
            end
        end
    elseif rowArgs.data then
        local row = root:tag('tr')
        row:addClass(rowArgs.rowclass)
        row:cssText(rowArgs.rowstyle)
        row:attr('id', rowArgs.rowid)
                    
        local dataCell = row:tag('td')
        dataCell
            :attr('colspan', 4)
            :attr('id', rowArgs.dataid)
            :addClass(rowArgs.class)
            :css('text-align', 'center') 
            :cssText(rowArgs.datastyle)
            :cssText(rowArgs.rowcellstyle)
            :newline()
            :wikitext(rowArgs.data)
    end
end

local function renderTitle()
	local argsTitle = args.title or args['título']
    if not argsTitle then return end

    root
        :tag('caption')
            :addClass(args.titleclass or args['título-classe'])
            :cssText(args.titlestyle or args['título-estilo'])
            :wikitext(args.title or args['título'])
end

local function renderAboveRow()
	local argsAbove = args.above or args.acima
    if not argsAbove then return end
    
    root
        :tag('tr')
            :tag('th')
                :attr('colspan', 4)
                :addClass(args.aboveclass or args['acima-classe'])
                :css('text-align', 'center')
                :css('font-size', '125%')
                :css('font-weight', 'bold')
                :cssText(args.abovestyle or args['acima-estilo'])
                :wikitext(args.above or args.acima)
end

local function renderBelowRow()
	local argsBelow = args.below or args.abaixo
    if not argsBelow then return end
    
    root
        :tag('tr')
            :tag('td')
                :attr('colspan', 4)
                :addClass(args.belowclass or args['abaixo-classe'])
                :css('text-align', 'center')
                :cssText(args.belowstyle or args['abaixo-estilo'])
                :newline()
                :wikitext(args.below or args.acima)
end

local function renderSubheaders()
    if args.subheader then
        args.subheader1 = args.subheader
    end
    if args['subcabeçalho'] then
        args['subcabeçalho1'] = args['subcabeçalho']
    end
    if args.subheaderrowclass then
        args.subheaderrowclass1 = args.subheaderrowclass
    end
    if args['subcabeçalho-linha-classe'] then
        args['subcabeçalho-linha-classe1'] = args['subcabeçalho-linha-classe']
    end
    local subheadernums = union(getArgNums('subheader',''), getArgNums('subcabeçalho', ''))
    for k, num in ipairs(subheadernums) do
        addRow({
            data = args['subheader' .. tostring(num)] or args['subcabeçalho' .. tostring(num)],
            datastyle = args.subheaderstyle or args['subcabeçalho-estilo'] or args['subheaderstyle' .. tostring(num)] or args['subcabeçalho-estilo' .. tostring(num)],
            class = args.subheaderclass or args['subcabeçalho-classe'],
            rowclass = args['subheaderrowclass' .. tostring(num)] or args['subcabeçalho-linha-classe' .. tostring(num)]
        })
    end
end

local function renderImages()
    if args.image then
        args.image1 = args.image
    end
    if args.imagem then
        args.imagem1 = args.imagem
    end
    if args.caption then
        args.caption1 = args.caption
    end
    if args.legenda then
        args.legenda1 = args.legenda
    end
    local imagenums = union(getArgNums('image',''), getArgNums('imagem',''))
    for k, num in ipairs(imagenums) do
        local caption = args['caption' .. tostring(num)] or args['legenda' .. tostring(num)]
        local data = mw.html.create():wikitext(args['image' .. tostring(num)] or args['imagem' .. tostring(num)])
        if caption then
            data
                :tag('div')
                    :cssText(args.captionstyle or args['legenda-estilo'])
                    :wikitext(caption)
        end
        addRow({
            data = tostring(data),
            datastyle = args.imagestyle or args['imagem-estilo'],
            class = args.imageclass or args['imagem-classe'],
            rowclass = args['imagerowclass' .. tostring(num)] or args['imagem-linha-classe' .. 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','[ab]?'))
    table.sort(rownums)
    rownums = union(rownums, getArgNums('cabeçalho',''))
    table.sort(rownums)
    rownums = union(rownums, getArgNums('dados', '[ab]?'))
    local datab_count = #(union(getArgNums('data', 'b'), getArgNums('dados','b')))
    local datac_count = #(union(getArgNums('data', 'c'), getArgNums('dados','c')))

    table.sort(rownums)
    for k, num in ipairs(rownums) do
        addRow({
            renderb = datab_count > 0,
            renderc = datac_count > 0,
            header = args['header' .. tostring(num)] or args['cabeçalho' .. tostring(num)],
            label = args['label' .. tostring(num)] or args['rótulo' .. tostring(num)],
            data = args['data' .. tostring(num)] or args['dados' .. tostring(num)],
            datastyle = args.datastyle or args['dados-estilo'],
            class = args['class' .. tostring(num)] or args['classe' .. tostring(num)],
            dataa = args['data' .. tostring(num) .. 'a'] or args['dados' .. tostring(num) .. 'a'],
            dataastyle = args.datastylea or args['dados-estiloa'],
            classa = args['class' .. tostring(num) .. 'a'] or args['classe' .. tostring(num) .. 'a'],
            datab = args['data' .. tostring(num) .. 'b'] or args['dados' .. tostring(num) .. 'b'],
            databstyle = args.datastyleb or args['dados-estilob'],
            classb = args['class' .. tostring(num) .. 'b'] or args['classe' .. tostring(num) .. 'b'],
            datac = args['data' .. tostring(num) .. 'c'] or args['dados' .. tostring(num) .. 'c'],
            datacstyle = args.datastylec or args['dados-estiloc'],
            classc = args['class' .. tostring(num) .. 'c'] or args['classe' .. tostring(num) .. 'c'],
            rowclass = args['rowclass' .. tostring(num)] or args['linha-classe' .. tostring(num)],
            rowstyle = args['rowstyle' .. tostring(num)] or args['linha-estilo' .. tostring(num)],
            rowcellstyle = args['rowcellstyle' .. tostring(num)] or args['linha-célula-estilo' .. tostring(num)],
            dataid = args['dataid' .. tostring(num)] or args['dados-id' .. tostring(num)],
            dataaid = args['dataid' .. tostring(num) .. 'a'] or args['dados-id' .. tostring(num) .. 'a'],
            dataaib = args['dataid' .. tostring(num) .. 'b'] or args['dados-id' .. tostring(num) .. 'b'],
            dataaic = args['dataid' .. tostring(num) .. 'c'] or args['dados-id' .. tostring(num) .. 'c'],
            labelid = args['labelid' .. tostring(num)] or args['rótulo-id' .. tostring(num)],
            headerid = args['headerid' .. tostring(num)] or args['cabeçalho-id' .. tostring(num)],
            rowid = args['rowid' .. tostring(num)] or args['linha-id' .. tostring(num)]
        })
    end
end

local function renderNavBar()
	local argsName = args.name or args.nome
    if not argsName then return end
    
    root
        :tag('tr')
            :tag('td')
                :attr('colspan', '4')
                :css('text-align', 'right')
                :wikitext(navbar{
                    args.name or args.nome,
                    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 == 'forçar' or italicTitle == 'yes' or italicTitle == 'sim' then
        root:wikitext(mw.getCurrentFrame():expandTemplate({title = 'título em itálico'}))
    end
end

local function renderTrackingCategories()
    if args.decat ~= 'yes' and args.decat ~= 'sim' and args.descat ~= 'yes' and args.descat ~= 'sim' then
        if #(getArgNums('data','[abc]?')) == 0 and #(getArgNums('dados','[abc]?')) == 0 and mw.title.getCurrentTitle().namespace == 0 then
            root:wikitext('[[Categoria:!Artigos que usam predefinições de infocaixa sem linhas de dados]]')
        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.

    root = mw.html.create('table')
        
    root
        :addClass('infobox')
        :addClass(args.bodyclass or args['corpo-classe'])
    if args.child == 'yes' or args.child == 'sim' or args.filha == 'yes' or args.filha == 'sim' or args.subbox == 'yes' or args.subbox == 'sim' or args.subcaixa == 'yes' or args.subcaixa == 'sim' then
        root
            :css('padding', '0')
            :css('border', 'none')
            :css('margin', (args.subbox == 'yes') and '-3px' or (args.subbox == 'sim') and '-3px' or (args.subcaixa == 'yes') and '-3px' or (args.subcaixa == 'sim') and '-3px' or 'auto')
            :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 or args['corpo-estilo'])
    
    renderTitle()
    renderAboveRow()
    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("Valor que não é uma tabela detetado para a tabela prefix", 2)
    end
    if type(step) ~= 'number' then
        error("Valor inváido para step detetado", 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('Input inválido detetado para tabela prefix de preprocessArgs', 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('Valor inválido para parâmetro "depend" detatado em preprocessArgs')
                end
                preprocessSingleArg(dependValue)
            end
        end
    end

    -- Get arguments with number suffixes.
    local a = 0 -- 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) .. (v.suffix or '')
                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) .. (v.dependsuffix or '')
                        preprocessSingleArg(dependArgName)
                    end
                end
            end
        end
        a = a + step
    end
end
 
-- Parse the data parameters in the same order that the old {{infobox}} did, so
-- that references etc. will display in the expected places. Parameters that
-- depend on another parameter are only processed if that parameter is present,
-- to avoid phantom references appearing in article reference lists.
local function parseDataParameters()
	preprocessSingleArg('child')
    preprocessSingleArg('filha')
    preprocessSingleArg('bodyclass')
    preprocessSingleArg('corpo-classe')
    preprocessSingleArg('subbox')
    preprocessSingleArg('subcaixa')
    preprocessSingleArg('bodystyle')
    preprocessSingleArg('corpo-estilo')
    preprocessSingleArg('title')
    preprocessSingleArg('título')
    preprocessSingleArg('titleclass')
    preprocessSingleArg('título-classe')
    preprocessSingleArg('titlestyle')
    preprocessSingleArg('título-estilo')
    preprocessSingleArg('above')
    preprocessSingleArg('acima')
    preprocessSingleArg('aboveclass')
    preprocessSingleArg('acima-classe')
    preprocessSingleArg('abovestyle')
    preprocessSingleArg('acima-estilo')
    preprocessArgs({
        {prefix = 'subheader', depend = {'subheaderstyle', 'subcabeçalho-estilo', 'subheaderrowclass', 'subcabeçalho-linha-classe'}}
    }, 10)
    preprocessArgs({
        {prefix = 'subcabeçalho', depend = {'subheaderstyle', 'subcabeçalho-estilo', 'subheaderrowclass', 'subcabeçalho-linha-classe'}}
    }, 10)
    preprocessSingleArg('subheaderstyle')
    preprocessSingleArg('subcabeçalho-estilo')
    preprocessSingleArg('subheaderclass')
    preprocessSingleArg('subcabeçalho-classe')
    preprocessSingleArg('image')
    preprocessSingleArg('imagem')
    preprocessSingleArg('caption')
    preprocessSingleArg('legenda')
    preprocessArgs({
        {prefix = 'image', depend = {'caption', 'legenda', 'imagerowclass', 'imagem-linha-classe'}}
    }, 10)
    preprocessArgs({
        {prefix = 'imagem', depend = {'caption', 'legenda', 'imagerowclass', 'imagem-linha-classe'}}
    }, 10)
    preprocessSingleArg('captionstyle')
    preprocessSingleArg('legenda-estilo')
    preprocessSingleArg('imagestyle')
    preprocessSingleArg('imagem-estilo')
    preprocessSingleArg('imageclass')
    preprocessSingleArg('imagem-classe')
    preprocessArgs({
        {prefix = 'header'},
        {prefix = 'data', depend = {'label', 'rótulo'}},
        {prefix = 'data', suffix = 'a', depend = {'label', 'rótulo'}},
        {prefix = 'data', suffix = 'a', depend = {'data', 'dados'}, dependsuffix='c'},
        {prefix = 'data', suffix = 'b', depend = {'label', 'rótulo'}},
        {prefix = 'data', suffix = 'b', depend = {'data', 'dados'}, dependsuffix='c'},
        {prefix = 'rowclass'},
        {prefix = 'rowstyle'},
        {prefix = 'rowcellstyle'},
        {prefix = 'class'},
        {prefix = 'dataid'},
        {prefix = 'labelid'},
        {prefix = 'headerid'},
        {prefix = 'rowid'}
    }, 50)
        preprocessArgs({
        {prefix = 'cabeçalho'},
        {prefix = 'dados', depend = {'label', 'rótulo'}},
        {prefix = 'dados', suffix = 'a', depend = {'label', 'rótulo'}},
        {prefix = 'dados', suffix = 'a', depend = {'data', 'dados'}, dependsuffix='c'},
        {prefix = 'dados', suffix = 'b', depend = {'label', 'rótulo'}},
        {prefix = 'dados', suffix = 'b', depend = {'data', 'dados'}, dependsuffix='c'},
        {prefix = 'linha-classe'},
        {prefix = 'linha-estilo'},
        {prefix = 'linha-célula-estilo'},
        {prefix = 'classe'},
        {prefix = 'dados-id'},
        {prefix = 'rótulo-id'},
        {prefix = 'cabeçalho-id'},
        {prefix = 'linha-id'}
    }, 50)
    preprocessSingleArg('headerclass')
    preprocessSingleArg('cabeçalho-classe')
    preprocessSingleArg('headerstyle')
    preprocessSingleArg('cabeçalho-estilo')
    preprocessSingleArg('labelstyle')
    preprocessSingleArg('rótulo-estilo')
    preprocessSingleArg('datastyle')
    preprocessSingleArg('dados-estilo')
    preprocessSingleArg('datastylea')
    preprocessSingleArg('dados-estiloa')
    preprocessSingleArg('datastyleb')
    preprocessSingleArg('dados-estilob')
    preprocessSingleArg('datastylec')
    preprocessSingleArg('dados-estiloc')
    preprocessSingleArg('below')
    preprocessSingleArg('abaixo')
    preprocessSingleArg('belowclass')
    preprocessSingleArg('abaixo-classe')
    preprocessSingleArg('belowstyle')
    preprocessSingleArg('abaixo-estilo')
    preprocessSingleArg('name')
    preprocessSingleArg('nome')
    args['italic title'] = origArgs['italic title'] or origArgs['título itálico'] -- different behaviour if blank or absent
    preprocessSingleArg('decat')
    preprocessSingleArg('descat')
end

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

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

-- Shortcut for making child infoboxes via #invoke.
function p.child(frame)
	return p.infoboxTemplate(frame, {child = "yes"})
end

return p