Módulo:IPAc-pt

Origem: Wikipédia, a enciclopédia livre.
-- Este módulo implementa [[Predefinição:IPAc-pt]].

local data = mw.loadData('Módulo:IPAc-pt/data')
local p = {}

-- Container global para rastrear categorias
local categoryHandler = require('Module:Category handler').main
local categories = {}

-- Afeiçoa whitespace dum string
local function trim(s)
	return s:match('^%s*(.-)%s*$')
end

-- Isto implementa [[Predefinição:Nowrap]].
local function makeNowrapSpan(s)
	local span = mw.html.create('span')
		:addClass('nowrap')
		:wikitext(s)
	return tostring(span)
end

local function makePronunciationText(id)
	id = id and string.lower(trim(id))
	if id and id ~= '' and data.pronunciation[id] then
		return data.pronunciation[id].text
	end
end

-- Isto adiciona um ícone tooltip a um rótulo. Implementa [[Predefinição:H:title]].
local function makeTooltip(label, tooltip)
	local span = mw.html.create('span')
		:attr('title', tooltip)
		:wikitext(label)
	return tostring(span)
end

local function formatPhonemeGroup(phonemes)
	if #phonemes > 0 then
		local span = mw.html.create('span')
			:css('border-bottom', '1px dotted')
			:wikitext(table.concat(phonemes))
		return tostring(span)
	else
		return ''
	end
end

local function renderCategories()
	local ret = ''
	ret = categoryHandler{
		[1] = 'yes', -- Adiciona categoria nestes namespaces
		main = 1,
		wikipedia = 1,
		file = 1,
		template = 1,
		help = 1,
		category = 1,
		portal = 1,
		book = 1,
		draft = 1,
		module = 1,
	}
	
	if ret == 'yes' then
		ret = {}
		for cat in pairs(categories) do
			table.insert(ret, string.format('[[Categoria:%s]]', cat))
		end
		table.sort(ret)
		ret = table.concat(ret)
	else
		ret = ''
	end
	return ret
end

function p._main(args)
	local ret = {}
	local i = 0 -- Mantém o controlo de args numerados

	-- Pronúncia
	do
		local pron = {}
		while true do
			i = i + 1
			local pronItem = makePronunciationText(args[i])
			if pronItem then
				pron[#pron + 1] = pronItem
				pron[#pron + 1] = ' '
			else
				break
			end
		end
		if #pron > 0 then
			ret[#ret + 1] = string.format(
				'<small>%s</small>',
				table.concat(pron)
			)
		end
	end

	-- Fonemas
	do
		-- Loop pelos args numerados, ao separá-los em grupos de fonemas
		-- e strings separadores (ambos chamados «palavras» por 
		-- conveniência). Somente sublinhamos grupos de fonemas, não os 
		-- separadores.
		local words = {}
		words[#words + 1] = '/' -- Barra de abertura
		i = i - 1 -- Configurar i novamente, já que foi alterado no loop de pronúncia
		local id
		repeat
			local phonemes = {}
			local isWordEnd = false
			while not isWordEnd do
				i = i + 1
				id = args[i]
				id = id and trim(id)
				if not id then
					isWordEnd = true
					words[#words + 1] = formatPhonemeGroup(phonemes)
				elseif id ~= '' then
					local t = data.phonemes[id]
					if not t then
						-- Foi-nos passada uma id inválida.
						isWordEnd = true
						categories["!Transclusões de IPAc-pt malformatadas"] = true
						words[#words + 1] = formatPhonemeGroup(phonemes)
						words[#words + 1] = makeTooltip(
							string.format(
								"<strong class=\"error\">[input inválido: '%s']</strong>",
								id
								),
							'Símbolo não reconhecido'
						)
					elseif not t.label then
						-- A etiqueta de dados contém dados ruins, então ocorre
						-- erro.
						error(string.format(
							"nenhuma etiqueta foi encontrado para a id'%s'",
							tostring(id)
						))
					elseif t.tooltip then
						-- Estamos a lidar com um fonema regular.
						phonemes[#phonemes + 1] = makeTooltip(
							t.label,
							t.tooltip
						)
					else
						-- Estamos a lidar com um separador.
						isWordEnd = true
						words[#words + 1] = formatPhonemeGroup(phonemes)
						words[#words + 1] = t.label						
					end
				end
			end
		until not id
		words[#words + 1] = '/' -- Barra de fechadura

		-- Junta as palavras num link para a ajuda de IPA.
		local span = mw.html.create('span')
			-- Suprime popups Navegação e Previsão de Páginas (aka Hovercards)
			:addClass('IPA nopopups noexcerpt')
			:wikitext(string.format(
				'[[Wikipédia:AFI para português e galego|%s]]',
				table.concat(words)
			))
		
		ret[#ret + 1] = tostring(span)
	end
	
	-- Audio link
	do
		local file = args.audio and trim(args.audio) or args['áudio'] and trim(args['áudio'])
		if file and file ~= '' then
			if args[1] and string.lower(trim(args[1])) == 'pt' then
				categories["!Páginas que incluem pronúncias gravadas (português europeu)"] = true
			elseif args[1] and string.lower(trim(args[1])) == 'br' then
				categories["!Páginas que incluem pronúncias gravadas (português brasileiro)"] = true
			else
				categories["!Páginas que incluem pronúncias gravadas (português)"] = true
			end
			
			ret[#ret + 1] = mw.getCurrentFrame():expandTemplate{
				title = 'Predefinição:IPA audio link', args = { file } }
		end
	end
	
	-- Nowrap e categorias
	ret = makeNowrapSpan(table.concat(ret)) .. renderCategories()

	-- Redefine a tabela de categorias caso reproduzamos novamente.
	categories = {}

	return ret
end

function p.main(frame)
	return p._main(frame:getParent().args)
end

return p