Wiki DC Comics
Advertisement

-- HF significa High Frequency.
-- Este módulo aumenta o IC incorporado
local HF = mw.InfoboxBuilderHF
 
----------------------------
-- Bibliotecas de funções --
----------------------------
-- Parâmetros de invocação de Parses, abrange espaços em branco e remove espaços em branco
HF.getArgs = require('Dev:Arguments').getArgs

-- Uma vez que isso só deve ser avaliado uma vez por visualização de página, agora é global
_G.vars = { Pagename = mw.title.getCurrentTitle().text }

-----------------------
-- Bibliotecas de dados --
-----------------------
-- Tabelas de dados para contribuintes comuns de pessoal
local StaffNames = require( 'Módulo:Correção de Funcionários' )
-- Tabelas de dados para nomes de editoras comuns
local CompanyNames = require( 'Module:CompanyCorrection' )

------------------------------------------------
-- Funções locais (usadas apenas neste Módulo) --
------------------------------------------------
function invokeInt(funcName)
  -- Este invólucro permite a invocação de uma função interna a partir de um quadro.
  -- Em outras palavras, ele se traduz de uma Predefinição: para uma função interna.
	return function (frame)
		local args = HF.getArgs(frame, { trim = true, removeBlanks = true })
		return HF[funcName](args, vars)
	end
end

----------------------------------------------------------
-- Funções públicas (chamadas a partir de um modelo ou artigo) --
----------------------------------------------------------

-- Adiciona um botão de Ajuda ao título / canto de uma Infobox.
-- (Não implementa uma predefinição específica. Chamado de invocar.)
HF.TitleHelpButton = invokeInt('_TitleHelpButton')

-- Adiciona um botão de Ajuda ao rótulo de um campo Infobox.
-- (Não implementa uma predefinição específica. Chamado de invocar.)
HF.HelpButton = invokeInt('_HelpButton')

-- Toma uma lista (ou matriz) de itens em um campo que está em uma única linha
-- e separado por um delimitador, e faz algo com eles.
-- (Não implementa uma predefinição específica. Chamado de invocar.)
HF.Iterator = invokeInt('_Iterator')

---------------------------------------------------------
-- Funções internas (usadas neste e em outros módulos) --
---------------------------------------------------------
-- elimina o espaço em branco da frente e da parte de trás de uma string
function HF.trim(s)
  if type(s) == 'string' then
    return (s:gsub("^%s*(.-)%s*$", '%1'))
  else
    return false
  end
end

-- Eu acho que isso é para preenchimento com zeros
function HF.AddZeros( s, len )
  local output = ""

  local sLength = string.len( tostring( s ) )
  local diff = tonumber( len ) - tonumber( sLength )

  if diff > 0 then
    for i = 1, diff do
      output = output .. "0"
    end
  end

  output = output .. s

  return output
end

-- Isso cria um link externo.
function HF.ExternalLink( target, label, plain )
  local output = string.format('[%s %s]', target, label)

  if plain == true then
    output = string.format('<span class="plainlinks">%s</span>', output)
  end  

  return output
end

-- Isso cria um link para uma categoria, além de colocá-lo nessa categoria.
-- `sortkey` e `label` são opcionais
-- Se não houver `label` dado, ele só irá colocá-lo na categoria,
-- qual é o que é para HF.Category.
function HF.CategoryLink( category, sortkey, label )
  if not HF.isempty( label ) then
    return HF.LinkToCategory( category, label ) ..
        HF.Category( category, sortkey )
  else 
    return HF.Category( category, sortkey )
  end
end

-- Adiciona uma categoria
-- `sortkey` é opcional
function HF.Category( category, sortkey )
    if sortkey == nil then sortkey = '' else sortkey = '|' .. sortkey end
    return string.format('[['..'Categoria:%s%s]]', category, sortkey)
end

--Adiciona um link para uma Categoria
function HF.LinkToCategory( category, label )
    return string.format('[[:'..'Categoria:%s|%s]]', category, 
        label or 'Categoria:' .. category )
end

-- Adiciona um link interno
-- `label` é opcional
function HF.Link( link, text )
    if not HF.isempty( text ) then
        return string.format('[['..'%s|%s]]', link, text)
    else
        return string.format('[['..'%s]]', link)
    end
end

-- Verifica se existe um artigo existente no alvo.
-- Se houver, cria um link.
-- Se não houver, basta escrever o nome do alvo como texto.
-- Se for passado um link, ele não executará essa verificação e apenas escreverá o link.
function HF.KillNewLinks( object )
    if object:match("^%[%[(.*)%]%]$") then
        return object
    elseif mw.title.new( object ).exists == true then
        return HF.Link( object )
    else
        return object
    end
end

-- Verifica se existe uma categoria existente no alvo.
-- Se houver, cria um link.
-- Se não houver, basta escrever o nome do alvo como texto.
function HF.KillNewCatLinks( object )
    if mw.title.new( object, 'Categoria' ).exists == true then
        return HF.Link( ':Categoria:'..object, object )
    else
        return object
    end
end

-- Verifica se existe uma categoria existente no alvo.
-- Se houver, cria um link.
-- Se não houver, basta escrever o nome do alvo como texto.
function HF.KillNewCategories( object )
    if mw.title.new( object, 'Categoria' ).exists == true then
        return HF.Category( object, object, object)
    else
        return object
    end
end

function HF._HelpButton( args )
  if HF.isempty( args.buttonsize ) then args.buttonsize = "10px" end
	local link = string.format(
		'[['..'File:Information-silk.png|%s|link=Clique aqui para obter ajuda com este campo#%s]] %s',
		args.buttonsize,
		args.Section or args.Label or '',
		args.Label or ''
	)
  return link
end

function HF._TitleHelpButton( args )
  if HF.isempty( args.buttonsize ) then args.buttonsize = "16px" end
	local link = string.format(
		'[['..'Arquivo:Help.png|%s|link=%s#%s|%s]]',
		args.buttonsize,
		args.Link or 'Ajuda:Campos da Predefinição',
		args.Section or args.Label or '',
		args.Label or ''
	)
  return '<span class="title-help-button">'..link..'</span>'
end

function HF.ContributorNameCorrection( name )
  if type( StaffNames[ string.lower( name ) ] ) == "string" then
    return StaffNames[ string.lower( name ) ]
  else
    return name
  end
end
 
function HF.CompanyNameCorrection( name )
  if type( CompanyNames[ string.lower( name ) ] ) == "string" then
    return CompanyNames[ string.lower( name ) ]
  else
    return name
  end
end

function HF._Iterator( args )
    local text = args['text'] or args[1] or nil
    local delimiter = args['delimiter'] or args[2] or ';'
    local contributorrole = args['role'] or nil
    local check = args['check'] or nil
    local storage = mw.text.split( text, delimiter )
    local output = {}

    for i, item in ipairs( storage ) do
        item = HF.trim(item)
        check = HF.trim(check)
        if not string.match(item, '%S') then break end
        if check == 'company' then
            if type(item) == 'string' and 
              CompanyNames:in_database( item ) then
                table.insert( output,
                    HF.KillNewLinks( CompanyNames:normalize(item) ) ..
                    CompanyNames:cat_staff( item )
                )
            else
                table.insert( output,  item )
            end
        elseif check == 'staff' then
            table.insert(
                output,
                StaffNames:link( item ) ..
                StaffNames:cat_role( item, contributorrole )
            )
        elseif check == 'featured' then
            table.insert(
                output,
                HF.Category( item .. ' Titles') ..
                HF.Link( item )
            )
        elseif check == 'featured_publisher' then
            table.insert(
                output,
                HF.Category( CompanyNames:normalize(item) .. ' Titles') ..
                HF.KillNewLinks( CompanyNames:normalize(item) )
            )
        elseif check == 'category' then 
            table.insert(output, HF.KillNewCategories( item ))
        elseif check == 'categorylinkonly' then 
            table.insert(output, HF.KillNewCatLinks( item ))
        elseif check == 'noredlink' then 
            table.insert(output, HF.KillNewLinks( item ))
        elseif check == 'jobtitles' then 
            if mw.title.new( item..'s', 'Categoria' ).exists == true then
                table.insert(output, HF.CategoryLink( item..'s', item, item) )
            else
                table.insert(output, item)
            end
        else
            table.insert(output, item)
        end
    end
    return table.concat(output, ' · ')
end

HF.TrimOverflow = invokeInt('_TrimOverflow')

function HF._TrimOverflow( args )
    local input = args[1]
    local breakat = args['TrimBreak'] or ' '
    local limit = args['TrimLimit'] or 1000
    local morelabel = args['TrimMoreLabel'] or 'more...'
    local lesslabel = args['TrimLessLabel'] or 'less...'
    if not input then return nil end
    if mw.ustring.len( input ) > limit then
        local primary   = mw.ustring.sub( input, 1, limit )
        local secondary = mw.ustring.sub( input, limit )
        local shiftatbreak = ''
        if not args['TrimBreak'] and string.find(primary, '·') then breakat = '·'
        elseif not args['TrimBreak'] and string.find(primary, ';') then breakat = ';'
        elseif not args['TrimBreak'] and string.find(primary, ' ') then breakat = ' '
        end
        
        primary, shiftatbreak = mw.ustring.match( primary, '(.*)'..breakat..'(.*)$')
        secondary = shiftatbreak .. secondary
        local morebox = mw.html.create('div')
            :addClass('expansion-tag')
            :addClass('mw-collapsible')
            :addClass('mw-collapsed')
            :attr('data-expandtext',morelabel)
            :attr('data-collapsetext',lesslabel)
            :wikitext(secondary):allDone()
        return primary .. tostring(morebox)
    else
        return input
    end
end

-------------------------------------------------
-- Saída (enviá-lo de volta ao que chamou)--
-------------------------------------------------
return HF
Advertisement