Módulo:Testes/Gkiyoshinishimoto/Message box

Origem: Wikipédia, a enciclopédia livre.
Documentação do módulo[ver] [editar] [histórico] [purgar]

Este é um metamódulo que implementa as predefinições de caixa de mensagem {{Teste/Gkiyoshinishimoto/Mbox}}, {{Teste/Gkiyoshinishimoto/Ambox}}, {{Teste/Gkiyoshinishimoto/Cmbox}}, {{Teste/Gkiyoshinishimoto/Fmbox}}, {{Teste/Gkiyoshinishimoto/Imbox}}, {{Teste/Gkiyoshinishimoto/Ombox}}, e {{Teste/Gkiyoshinishimoto/Tmbox}}. Ele destina-se a ser usado em módulos Lua e não deve ser usado diretamente em páginas wiki. Se você quiser usar a funcionalidade deste módulo em uma página wiki, por favor use as predefinições de caixas de mensagens individuais.

Uso[editar código-fonte]

Para usar este módulo a partir de outro módulo Lua, primeiro você precisa carregá-lo.

local messageBox = require('Módulo:Testes/Gkiyoshinishimoto/Message box')

Para criar uma caixa de mensagem, use a função main. São necessários dois parâmetros: o primeiro é o tipo de caixa (como uma string) e o segundo é uma tabela contendo os parâmetros da caixa de mensagem.

local box = messageBox.main( boxType, {
    param1 = param1,
    param2 = param2,
    -- Mais parâmetros ...
})

Existem sete tipos de caixas disponíveis:

Tipo de caixa Predefinição Propósito
mbox {{Teste/Gkiyoshinishimoto/Mbox}} Para que caixas de mensagens sejam usadas em vários espaços nomeados
ambox {{Teste/Gkiyoshinishimoto/Ambox}} Para caixas de mensagens de artigos
cmbox {{Teste/Gkiyoshinishimoto/Cmbox}} Para caixas de mensagens de categorias
fmbox {{Teste/Gkiyoshinishimoto/Fmbox}} Para caixas de mensagens da interface
imbox {{Teste/Gkiyoshinishimoto/Imbox}} Para caixas de mensagens dos espaços nomeados de arquivos
tmbox {{Teste/Gkiyoshinishimoto/Tmbox}} Para caixas de mensagens de páginas de discussão
ombox {{Teste/Gkiyoshinishimoto/Ombox}} Para caixas de mensagens em outros espaços nomeados

Consulte a página da predefinição de cada tipo de caixa para os parâmetros disponíveis.

Uso a partir de "#invoke"[editar código-fonte]

Assim como a função main, este módulo possui funções separadas para cada tipo de caixa. Elas são acessadas ​​usando o código {{#invoke:Testes/Gkiyoshinishimoto/Message box|mbox|...}}, {{#invoke:Testes/Gkiyoshinishimoto/Message box|ambox|...}}, etc. Elas funcionarão quando chamadas de a partir de outros módulos, mas acessam o código usado para processar argumentos passados a partir de "#invoke" e, portanto, chamá-las será menos eficiente do que chamar main.

Detalhes técnicos[editar código-fonte]

O módulo usa o mesmo código básico para cada uma das predefinições listadas acima; as diferenças entre cada uma delas são configuradas usando os dados em Módulo:Testes/Gkiyoshinishimoto/Message box/configuration. Aqui estão as várias opções de configuração e o que elas significam:

  • types – uma tabela contendo dados usados pelo parâmetro de tipo da caixa de mensagem. As chaves da tabela são os valores que podem ser passados para o parâmetro de tipo, e os valores da tabela são tabelas contendo a classe e a imagem usada por aquele tipo.
  • default – o tipo a ser usado se nenhum valor for passado para o parâmetro de tipo ou se um valor inválido for especificado.
  • showInvalidTypeError – se deve mostrar um erro se o valor passado para o parâmetro de tipo for inválido.
  • allowBlankParams – normalmente os valores em branco são retirados dos parâmetros passados para o módulo. No entanto, os espaços em branco são preservados para os parâmetros incluídos na tabela "AllowBlankParams".
  • allowSmall – se uma versão pequena da caixa de mensagem pode ser produzida com "small=yes".
  • smallParam – um nome personalizado para o parâmetro da pequena. Por exemplo, se definido como "left", você poderá produzir uma pequena caixa de mensagem usando "small=left".
  • smallClass – a classe a ser usada para caixas de mensagens pequenas.
  • substCheck – se deve realizar uma verificação secundária ou não.
  • classes – um arranjo de classes para usar com a caixa de mensagem.
  • imageEmptyCell – se deve usar uma célula <td>...</td> vazia se não houver nenhum conjunto de imagens. Isso é usado para preservar o espaçamento de caixas de mensagens com largura inferior a 100% da tela.
  • imageEmptyCellStyle – se as células vazias de imagem devem ser estilizadas.
  • imageCheckBlank – se "image=blank" resulta na exibição de nenhuma imagem.
  • imageSmallSize – normalmente, as imagens usadas em caixas de mensagens pequenas são definidas para 30x30px. Isso define um tamanho personalizado.
  • imageCellDiv – se deve incluir a imagem em um "div" impondo um tamanho máximo de imagem.
  • useCollapsibleTextFields – se deve usar campos de texto que podem ser recolhidos, ou seja, "problema", "correção", "conversa", etc. Atualmente usado apenas em "ambox".
  • imageRightNone – se "imageright=none" resulta na exibição de nenhuma imagem no lado direito da caixa de mensagem.
  • sectionDefault – o nome padrão para o parâmetro "section". Depende de useCollapsibleTextFields.
  • allowMainspaceCategories – permite categorização no espaço nomeado principal.
  • templateCategory – o nome de uma categoria a ser colocada na página da predefinição.
  • templateCategoryRequireName – se o parâmetro name é necessário para mostrar a categoria da predefinição.
  • templateErrorCategory – o nome da categoria de erro a ser usada na página da predefinição.
  • templateErrorParamsToCheck – um arranjo de nomes de parâmetros a serem verificados. Se algum estiver ausente, templateErrorCategory será aplicado à página da predefinição.

require('strict')
local getArgs
local yesno = require('Módulo:Testes/Gkiyoshinishimoto/Yesno')
local lang = mw.language.getContentLanguage()

local CONFIG_MODULE = 'Módulo:Testes/Gkiyoshinishimoto/Message box/configuration'
local DEMOSPACES = {talk = 'tmbox', image = 'imbox', file = 'imbox', category = 'cmbox', article = 'ambox', main = 'ambox'}

--------------------------------------------------------------------------------
-- Funções auxiliares
--------------------------------------------------------------------------------

local function getTitleObject(...)
	-- Obtém o objeto de título, passando a função por "pcall"
	-- caso estejamos acima do limite de contagem de funções caras.
	local success, title = pcall(mw.title.new, ...)
	if success then
		return title
	end
end

local function union(t1, t2)
	-- Retorna a união de dois arranjos ('arrays').
	local vals = {}
	for i, v in ipairs(t1) do
		vals[v] = true
	end
	for i, v in ipairs(t2) do
		vals[v] = true
	end
	local ret = {}
	for k in pairs(vals) do
		table.insert(ret, k)
	end
	table.sort(ret)
	return ret
end

local function getArgNums(args, prefix)
	local nums = {}
	for k, v in pairs(args) do
		local num = mw.ustring.match(tostring(k), '^' .. prefix .. '([1-9]%d*)$')
		if num then
			table.insert(nums, tonumber(num))
		end
	end
	table.sort(nums)
	return nums
end

--------------------------------------------------------------------------------
-- Definição de classe de caixa
--------------------------------------------------------------------------------

local MessageBox = {}
MessageBox.__index = MessageBox

function MessageBox.new(boxType, args, cfg)
	args = args or {}
	local obj = {}

	-- Define o objeto de título e o espaço nomeado.
	obj.title = getTitleObject(args.page) or mw.title.getCurrentTitle()

	-- Define a configuração para o nosso tipo de caixa.
	obj.cfg = cfg[boxType]
	if not obj.cfg then
		local ns = obj.title.namespace
		-- boxType é "mbox" ou entrada inválida
		if args.demospace and args.demospace ~= '' then
			-- implementa o parâmetro "demospace" de "mbox"
			local demospace = string.lower(args.demospace)
			if DEMOSPACES[demospace] then
				-- usa a predefinição ('template') de "DEMOSPACES"
				obj.cfg = cfg[DEMOSPACES[demospace]]
			elseif string.find( demospace, 'talk' ) then
				-- "demo" como uma página de discussão
				obj.cfg = cfg.tmbox
			else
				-- padrão para "ombox"
				obj.cfg = cfg.ombox
			end
		elseif ns == 0 then
			obj.cfg = cfg.ambox -- espaço nomeado principal
		elseif ns == 6 then
			obj.cfg = cfg.imbox -- espaço nomeado de arquivo (ficheiro)
		elseif ns == 14 then
			obj.cfg = cfg.cmbox -- espaço nomeado de categoria
		else
			local nsTable = mw.site.namespaces[ns]
			if nsTable and nsTable.isTalk then
				obj.cfg = cfg.tmbox -- qualquer espaço nomeado de discussão
			else
				obj.cfg = cfg.ombox -- outros espaços nomeados ou entrada inválida
			end
		end
	end

	-- Define os argumentos e remove todos os argumentos em branco, exceto os
	-- listados em "cfg.allowBlankParams".
	do
		local newArgs = {}
		for k, v in pairs(args) do
			if v ~= '' then
				newArgs[k] = v
			end
		end
		for i, param in ipairs(obj.cfg.allowBlankParams or {}) do
			newArgs[param] = args[param]
		end
		obj.args = newArgs
	end

	-- Define a estrutura interna de dados.
	obj.categories = {}
	obj.classes = {}
	-- Para o carregamento "preguiçoso" de [[Módulo:Testes/Gkiyoshinishimoto/Category handler]].
	obj.hasCategories = false

	return setmetatable(obj, MessageBox)
end

function MessageBox:addCat(ns, cat, sort)
	if not cat then
		return nil
	end
	if sort then
		cat = string.format('[[Categoria:%s|%s]]', cat, sort)
	else
		cat = string.format('[[Categoria:%s]]', cat)
	end
	self.hasCategories = true
	self.categories[ns] = self.categories[ns] or {}
	table.insert(self.categories[ns], cat)
end

function MessageBox:addClass(class)
	if not class then
		return nil
	end
	table.insert(self.classes, class)
end

function MessageBox:setParameters()
	local args = self.args
	local cfg = self.cfg

	-- Obtém os dados de tipo.
	self.type = args.type
	local typeData = cfg.types[self.type]
	self.invalidTypeError = cfg.showInvalidTypeError
		and self.type
		and not typeData
	typeData = typeData or cfg.types[cfg.default]
	self.typeClass = typeData.class
	self.typeImage = typeData.image

	-- Localiza se a caixa foi substituída incorretamente.
	self.isSubstituted = cfg.substCheck and args.subst == 'SUBST'

	-- Descobre se estamos usando uma caixa de mensagem pequena.
	self.isSmall = cfg.allowSmall and (
		cfg.smallParam and args.small == cfg.smallParam
		or not cfg.smallParam and yesno(args.small)
	)

	-- Adiciona atributos, classes e estilos.
	self.id = args.id
	self.name = args.name
	if self.name then
		self:addClass('box-' .. string.gsub(self.name,' ','_'))
	end
	if yesno(args.plainlinks) ~= false then
		self:addClass('plainlinks')
	end
	for _, class in ipairs(cfg.classes or {}) do
		self:addClass(class)
	end
	if self.isSmall then
		self:addClass(cfg.smallClass or 'mbox-small')
	end
	self:addClass(self.typeClass)
	self:addClass(args.class)
	self.style = args.style
	self.attrs = args.attrs

	-- Define o estilo do texto.
	self.textstyle = args.textstyle

	-- Descobre se estamos na página de predefinição ou não. Esta funcionalidade 
	-- só é usada se "useCollapsibleTextFields" estiver definido ou se ambos 
	-- "cfg.templateCategory" e "cfg.templateCategoryRequireName" estiverem definidos.
	self.useCollapsibleTextFields = cfg.useCollapsibleTextFields
	if self.useCollapsibleTextFields
		or cfg.templateCategory
		and cfg.templateCategoryRequireName
	then
		if self.name then
			local templateName = mw.ustring.match(
				self.name,
				'^[pP][rR][eE][dD][eE][fF][iI][nN][iI][çÇ][ãÃ][oO][%s_]*:[%s_]*(.*)$'
			) or self.name
			templateName = 'Predefinição:' .. templateName
			self.templateTitle = getTitleObject(templateName)
		end
		self.isTemplatePage = self.templateTitle
			and mw.title.equals(self.title, self.templateTitle)
	end
	
	-- Processa dados para campos de texto recolhíveis. No momento esses
	-- são apenas usados em {{Teste/Gkiyoshinishimoto/Ambox}}.
	if self.useCollapsibleTextFields then
		-- Obtém o valor de "self.issue".
		if self.isSmall and args.smalltext then
			self.issue = args.smalltext
		else
			local sect
			if args.sect == '' then
				sect = 'Esta ' .. (cfg.sectionDefault or 'página') -- Pode ser necessário mudar 'Esta ' para 'Est' e 'página' para 'a página'.
			elseif type(args.sect) == 'string' then
				sect = 'Esta ' .. args.sect -- Pode ser necessário mudar 'Esta ' para 'Est'.
			end
			local issue = args.issue
			issue = type(issue) == 'string' and issue ~= '' and issue or nil
			local text = args.text
			text = type(text) == 'string' and text or nil
			local issues = {}
			table.insert(issues, sect)
			table.insert(issues, issue)
			table.insert(issues, text)
			self.issue = table.concat(issues, ' ')
		end

		-- Obtém o valor de "self.talk".
		local talk = args.talk
		-- Mostra as ligações ('links') de discussão na página de predefinição  
		-- ou nas subpáginas de predefinição se o parâmetro "talk" estiver em branco.
		if talk == ''
			and self.templateTitle
			and (
				mw.title.equals(self.templateTitle, self.title)
				or self.title:isSubpageOf(self.templateTitle)
			)
		then
			talk = '#'
		elseif talk == '' then
			talk = nil
		end
		if talk then
			-- Se o valor "talk" for uma página de discussão, cria uma ligação 
			-- ('link') para essa página. Se não, assume que é um cabeçalho de 
			-- seção e cria uma ligação ('link') para a página de discussão da  
			-- página atual com esse cabeçalho de seção.
			local talkTitle = getTitleObject(talk)
			local talkArgIsTalkPage = true
			if not talkTitle or not talkTitle.isTalkPage then
				talkArgIsTalkPage = false
				talkTitle = getTitleObject(
					self.title.text,
					mw.site.namespaces[self.title.namespace].talk.id
				)
			end
			if talkTitle and talkTitle.exists then
                local talkText
                if self.isSmall then
                    local talkLink = talkArgIsTalkPage and talk or (talkTitle.prefixedText .. '#' .. talk)
                    talkText = string.format('([[%s|discussão]])', talkLink)
                else
                    talkText = 'As discussões relevantes podem ser encontradas em'
                    if talkArgIsTalkPage then
                        talkText = string.format(
                            '%s [[%s|%s]].',
                            talkText,
                            talk,
                            talkTitle.prefixedText
                        )
                    else
                        talkText = string.format(
                            '%s a [[%s#%s|página de discussão]].',
                            talkText,
                            talkTitle.prefixedText,
                            talk
                        )
                    end
                end
				self.talk = talkText
			end
		end

		-- Obtém outros valores.
		self.fix = args.fix ~= '' and args.fix or nil
		local date
		if args.date and args.date ~= '' then
			date = args.date
		elseif args.date == '' and self.isTemplatePage then
			date = lang:formatDate('F Y')
		end
		if date then
			self.date = string.format(" <span class='date-container'><i>(<span class='date'>%s</span>)</i></span>", date)
		end
		self.info = args.info
		if yesno(args.removalnotice) then
			self.removalNotice = cfg.removalNotice
		end
	end

	-- Define o campo de texto não recolhível. No momento, isso é usado por todos 
	-- os tipos de caixa, exceto "ambox", e também por "ambox" quando "small=yes".
	if self.isSmall then
		self.text = args.smalltext or args.text
	else
		self.text = args.text
	end

	-- Define a linha abaixo.
	self.below = cfg.below and args.below

	-- Configurações gerais de imagem.
	self.imageCellDiv = not self.isSmall and cfg.imageCellDiv
	self.imageEmptyCell = cfg.imageEmptyCell

	-- Configurações de imagem à esquerda.
	local imageLeft = self.isSmall and args.smallimage or args.image
	if cfg.imageCheckBlank and imageLeft ~= 'blank' and imageLeft ~= 'none'
		or not cfg.imageCheckBlank and imageLeft ~= 'none'
	then
		self.imageLeft = imageLeft
		if not imageLeft then
			local imageSize = self.isSmall
				and (cfg.imageSmallSize or '30x30px')
				or '40x40px'
			self.imageLeft = string.format('[[Ficheiro:%s|%s|link=|alt=]]', self.typeImage
				or 'Imbox notice.png', imageSize)
		end
	end

	-- Configurações de imagem à direita.
	local imageRight = self.isSmall and args.smallimageright or args.imageright
	if not (cfg.imageRightNone and imageRight == 'none') then
		self.imageRight = imageRight
	end
	
	-- Define "templatestyles"
	self.base_templatestyles = cfg.templatestyles
	self.templatestyles = args.templatestyles
end

function MessageBox:setMainspaceCategories()
	local args = self.args
	local cfg = self.cfg

	if not cfg.allowMainspaceCategories then
		return nil
	end

	local nums = {}
	for _, prefix in ipairs{'cat', 'category', 'all'} do
		args[prefix .. '1'] = args[prefix]
		nums = union(nums, getArgNums(args, prefix))
	end

	-- O seguinte é aproximadamente equivalente à antiga {{Teste/Gkiyoshinishimoto/Ambox/category}}.
	local date = args.date
	date = type(date) == 'string' and date
	local preposition = 'from' -- talvez "de"
	for _, num in ipairs(nums) do
		local mainCat = args['cat' .. tostring(num)]
			or args['category' .. tostring(num)]
		local allCat = args['all' .. tostring(num)]
		mainCat = type(mainCat) == 'string' and mainCat
		allCat = type(allCat) == 'string' and allCat
		if mainCat and date and date ~= '' then
			local catTitle = string.format('%s %s %s', mainCat, preposition, date)
			self:addCat(0, catTitle)
			catTitle = getTitleObject('Categoria:' .. catTitle)
			if not catTitle or not catTitle.exists then
				self:addCat(0, '!Artigos com parâmetro de data inválido em predefinições')
			end
		elseif mainCat and (not date or date == '') then
			self:addCat(0, mainCat)
		end
		if allCat then
			self:addCat(0, allCat)
		end
	end
end

function MessageBox:setTemplateCategories()
	local args = self.args
	local cfg = self.cfg

	-- Adiciona as categorias de predefinição ('template').
	if cfg.templateCategory then
		if cfg.templateCategoryRequireName then
			if self.isTemplatePage then
				self:addCat(10, cfg.templateCategory)
			end
		elseif not self.title.isSubpage then
			self:addCat(10, cfg.templateCategory)
		end
	end

	-- Adiciona as categorias de erro de predefinição ('template').
	if cfg.templateErrorCategory then
		local templateErrorCategory = cfg.templateErrorCategory
		local templateCat, templateSort
		if not self.name and not self.title.isSubpage then
			templateCat = templateErrorCategory
		elseif self.isTemplatePage then
			local paramsToCheck = cfg.templateErrorParamsToCheck or {}
			local count = 0
			for i, param in ipairs(paramsToCheck) do
				if not args[param] then
					count = count + 1
				end
			end
			if count > 0 then
				templateCat = templateErrorCategory
				templateSort = tostring(count)
			end
			if self.categoryNums and #self.categoryNums > 0 then
				templateCat = templateErrorCategory
				templateSort = 'C'
			end
		end
		self:addCat(10, templateCat, templateSort)
	end
end

function MessageBox:setAllNamespaceCategories()
	-- Define as categorias para todos os espaços nomeados.
	if self.invalidTypeError then
		local allSort = (self.title.namespace == 0 and 'Main:' or '') .. self.title.prefixedText
		self:addCat('all', '!Parâmetro de message box que precisa de conserto', allSort)
	end
	if self.isSubstituted then
		self:addCat('all', '!Páginas com predefinições substituídas incorretamente')
	end
end

function MessageBox:setCategories()
	if self.title.namespace == 0 then
		self:setMainspaceCategories()
	elseif self.title.namespace == 10 then
		self:setTemplateCategories()
	end
	self:setAllNamespaceCategories()
end

function MessageBox:renderCategories()
	if not self.hasCategories then
		-- Nenhuma categoria adicionada, não há necessidade de passá-las para o 
		-- manipulador de categorias, portanto, se fosse invocado, retornaria a 
		-- sequência ('string') vazia. Então, criamos um atalho e retornamos a  
		-- sequência ('string') vazia.
		return ""
	end
	-- Converte tabelas de categorias em sequências ('strings') e as passa
	-- por meio de [[Módulo:Testes/Gkiyoshinishimoto/Category handler]].
	return require('Módulo:Testes/Gkiyoshinishimoto/Category handler')._main{
		main = table.concat(self.categories[0] or {}),
		template = table.concat(self.categories[10] or {}),
		all = table.concat(self.categories.all or {}),
		nocat = self.args.nocat,
		page = self.args.page
	}
end

function MessageBox:export()
	local root = mw.html.create()

	-- Adiciona o erro de verificação de substituição.
	if self.isSubstituted and self.name then
		root:tag('b')
			:addClass('error')
			:wikitext(string.format(
				'A predefinição <code>%s[[Predefinição:%s|%s]]%s</code> foi substituída incorretamente.',
				mw.text.nowiki('{{'), self.name, self.name, mw.text.nowiki('}}')
			))
	end

	local frame = mw.getCurrentFrame()
	root:wikitext(frame:extensionTag{
		name = 'templatestyles',
		args = { src = self.base_templatestyles },
	})
	-- Adiciona suporte para uma única folha de  "templatestyles" personalizada. 
	-- Não documentado conforme a necessidade deve ser limitado e muitas 
	-- predefinições ('templates') usando "mbox" são substituídas; nós não  
	-- queremos espalhar folhas de  "templatestyles" em locais arbitrários
	if self.templatestyles then
		root:wikitext(frame:extensionTag{
			name = 'templatestyles',
			args = { src = self.templatestyles },
		})
	end

	-- Cria a tabela de caixa.
	local boxTable = root:tag('table')
	boxTable:attr('id', self.id or nil)
	for i, class in ipairs(self.classes or {}) do
		boxTable:addClass(class or nil)
	end
	boxTable
		:cssText(self.style or nil)
		:attr('role', 'presentation')

	if self.attrs then
		boxTable:attr(self.attrs)
	end

	-- Adiciona a imagem à esquerda.
	local row = boxTable:tag('tr')
	if self.imageLeft then
		local imageLeftCell = row:tag('td'):addClass('mbox-image')
		if self.imageCellDiv then
			-- Se estivermos usando um "div", redefine "imageLeftCell" para que 
			-- a imagem fique dentro dele. "Divs" usa "style="width: 52px;"", 
			-- que limita a largura da imagem a 52px. Se alguma imagem em um "div" 
			-- for mais larga do que isso, ela pode se sobrepor ao texto ou causar  
			-- outros problemas de exibição.
			imageLeftCell = imageLeftCell:tag('div'):addClass('mbox-image-div')
		end
		imageLeftCell:wikitext(self.imageLeft or nil)
	elseif self.imageEmptyCell then
		-- Algumas caixas de mensagem definem uma célula vazia se nenhuma 
		-- imagem for especificada e  outras não. O antigo código de 
		-- predefinição em predefinições onde células vazias são especificadas 
		-- dá a seguinte dica: "Sem imagem. Célula com alguma largura ou  
		-- preenchimento necessário para que a célula de texto tenha 100% de largura."
		row:tag('td')
			:addClass('mbox-empty-cell')
	end

	-- Adiciona o texto.
	local textCell = row:tag('td'):addClass('mbox-text')
	if self.useCollapsibleTextFields then
		-- A caixa de mensagem usa parâmetros de texto avançados que permitem 
		-- que as coisas sejam recolhíveis. No momento, somente  "ambox" usa isso.
		textCell:cssText(self.textstyle or nil)
		local textCellDiv = textCell:tag('div')
		textCellDiv
			:addClass('mbox-text-span')
			:wikitext(self.issue or nil)
		if (self.talk or self.fix) then
			textCellDiv:tag('span')
				:addClass('hide-when-compact')
				:wikitext(self.talk and (' ' .. self.talk) or nil)
				:wikitext(self.fix and (' ' .. self.fix) or nil)
		end
		textCellDiv:wikitext(self.date and (' ' .. self.date) or nil)
		if self.info and not self.isSmall then
			textCellDiv
				:tag('span')
				:addClass('hide-when-compact')
				:wikitext(self.info and (' ' .. self.info) or nil)
		end
		if self.removalNotice then
			textCellDiv:tag('span')
				:addClass('hide-when-compact')
				:tag('i')
					:wikitext(string.format(" (%s)", self.removalNotice))
		end
	else
		-- Formatação de texto padrão - vale tudo.
		textCell
			:cssText(self.textstyle or nil)
			:wikitext(self.text or nil)
	end

	-- Adiciona a imagem à direita.
	if self.imageRight then
		local imageRightCell = row:tag('td'):addClass('mbox-imageright')
		if self.imageCellDiv then
			-- Se estivermos usando um "div", redefine "imageRightCell" para 
			-- que a imagem fique dentro dele.
			imageRightCell = imageRightCell:tag('div'):addClass('mbox-image-div')
		end
		imageRightCell
			:wikitext(self.imageRight or nil)
	end

	-- Adiciona a linha abaixo.
	if self.below then
		boxTable:tag('tr')
			:tag('td')
				:attr('colspan', self.imageRight and '3' or '2')
				:addClass('mbox-text')
				:cssText(self.textstyle or nil)
				:wikitext(self.below or nil)
	end

	-- Adiciona mensagem de erro para parâmetros de tipo inválido.
	if self.invalidTypeError then
		root:tag('div')
			:addClass('mbox-invalid-type')
			:wikitext(string.format(
				'Esta caixa de mensagem está usando um parâmetro "type=%s" inválido e precisa ser consertado.',
				self.type or ''
			))
	end

	-- Adiciona categorias.
	root:wikitext(self:renderCategories() or nil)

	return tostring(root)
end

--------------------------------------------------------------------------------
-- Exportações
--------------------------------------------------------------------------------

local p, mt = {}, {}

function p._exportClasses()
	-- Para testes.
	return {
		MessageBox = MessageBox
	}
end

function p.main(boxType, args, cfgTables)
	local box = MessageBox.new(boxType, args, cfgTables or mw.loadData(CONFIG_MODULE))
	box:setParameters()
	box:setCategories()
	return box:export()
end

function mt.__index(t, k)
	return function (frame)
		if not getArgs then
			getArgs = require('Módulo:Testes/Gkiyoshinishimoto/Arguments').getArgs
		end
		return t.main(k, getArgs(frame, {trim = false, removeBlanks = false}))
	end
end

return setmetatable(p, mt)