Modulo:Vedi anche/sandbox

Versione del 4 mag 2018 alle 11:36 di Rotpunkt (discussione | contributi) (aggiornato stile documentazione a quello usato in Mediawiki per Lua, +string.format, fix minori)
--[[
* Modulo che implementa i template {{Vedi anche}} e {{Vedi anche sezione}}.
]]

require('Modulo:No globals')

-- Parsifica un argomento del template (rappresenta il titolo di una pagina) e ne restituisce il wikilink.
--
-- @param {string} arg
-- @return {string}
local function parseArg(arg)
	local dest, count

	-- restitusce errore con wikilink a categorie
	if arg:match('^%s*:%s*[Cc][Aa][Tt]') then
		return '<span class="error">(usare il [[Template:Vedi categoria]])</span>'
	end

	-- rimuove eventuali pipe inserite tramite {{!}}
	arg = arg:match('(.*)|') or arg
	-- sostituisce le HTML entity (per esempio &#39; generato da {{PAGENAME}} quando il titolo contiene l'apostrofo)
	arg = mw.text.decode(arg)
	-- sostituisce # con §, se trovato crea un piped wikilink
	dest = arg
	arg, count = arg:gsub('#', ' § ')

	return string.format("'''[[%s%s%s]]'''", dest, count == 1 and '|' or '', arg)
end

-- Costruisce l'HTML per contenere i wikilink alle pagine.
--
-- @param {string} wikitext
-- @param {boolean} withNoprint
-- @return {string}
local function buildHTML(wikitext, withNoprint)
	local tableStyle = {
		['margin-bottom'] = '.5em',
		border = '1px solid #CCC',
		['text-align'] = 'left',
		['font-size'] = '95%',
		background = 'transparent'
	}
	local tableNode = mw.html.create('table')
	tableNode
		:addClass(withNoprint and 'noprint' or nil)
		:css(tableStyle)
		:tag('tr')
			:tag('td')
				:css('padding', '0 .5em')
				:wikitext('[[File:Magnifying glass icon mgx2.svg|20px|class=noviewer|link=]]')
				:done()
			:tag('td')
				:css('width', '100%')
				:wikitext(string.format("''Lo stesso argomento in dettaglio: %s''.", wikitext))
				:done()

	return tostring(tableNode)
end

-- =============================================================================
--                            Funzioni esportate
-- =============================================================================

local p = {}

-- Funzione per il template {{Vedi anche sezione}}.
function p.sezione(frame)
	local arg = frame:getParent().args[1]
	local wlink = arg and string.format("'''[[#%s|%s]]'''", arg, arg) or ''
	return buildHTML('sezione ' .. wlink)
end

-- Funzione per il template {{Vedi anche}}.
function p.main(frame)
	local lastArg, conjunction
	local args = {}

	for _, val in ipairs(frame:getParent().args) do
		table.insert(args, parseArg(val))
		lastArg = val
	end
	if #args > 1 and lastArg then
		conjunction = mw.ustring.lower(lastArg:sub(1, 1)) == 'e' and 'ed' or 'e'
		conjunction = '&#32;' .. conjunction .. '&#32;'
	end

	return buildHTML(mw.text.listToText(args, ',&#32;', conjunction), true)
end

return p