Abrir menu principal

Mudanças

Módulo:URL

2 892 bytes adicionados, 09h29min de 21 de abril de 2021
Criação do Módulo URL
--
-- Este módulo implementa a {{URL}}
--
-- Veja unidade de testes em [[Módulo:URL/testes]]

local p = {}

function trim(s)
return (mw.ustring.gsub(s, "^%s*(.-)%s*$", "%1"))
end

function safeUri(s)
local success, uri = pcall(function()
return mw.uri.new(s)
end)
if success then
return uri
end
end

function p._url(url, text)
url = trim(url or '')
text = trim(text or '')

if url == '' then
if text == '' then
return mw.getCurrentFrame():expandTemplate{ title = 'tlx', args = { 'URL', "''exemplo.com''", "''texto de exibição opicional''" } }
else
return text
end
end

-- Se a URL contiver espaços descodificados, codificá-los, porque o MediaWiki, caso contrário, pode interpretar um espaço como o fim da URL
url = mw.ustring.gsub(url, '%s', function(s) return mw.uri.encode(s, 'PATH') end)

-- Se houver uma string de consulta vazia ou fragmento id, removê-lo, uma vez que irá fazer com que mw.uri.new lançe um erro
url = mw.ustring.gsub(url, '#$', '')
url = mw.ustring.gsub(url, '%?$', '')

-- If it's an HTTP[S] URL without the double slash, fix it.
url = mw.ustring.gsub(url, '^[Hh][Tt][Tt][Pp]([Ss]?):(/?)([^/])', 'http%1://%3')

-- Lidar com URLs da Wikidata do formato http://
url = mw.ustring.gsub(url, '^[Hh][Tt][Tt][Pp]([Ss]?)://', 'http%1://')

local uri = safeUri(url)

-- Lidar com URLs sem protocolo e com URLs que são relativo a protocolo,
-- ex.: www.exemplo.com/foo or www.exemplo.com:8080/foo, e //www.exemplo.com/foo
if uri and (not uri.protocol or (uri.protocol and not uri.host)) and url:sub(1, 2) ~= '//' then
url = 'http://' .. url
uri = safeUri(url)
end

if text == '' then
if uri then
if uri.path == '/' then uri.path = '' end

local port = ''
if uri.port then port = ':' .. uri.port end

text = mw.ustring.lower(uri.host or '') .. port .. (uri.relativePath or '')
else -- A URL é mal-formado, então apenas mostrar o que quer que foi aprovada em
text = url
end
end

-- Adicionar <wbr> depois da sequências _/.-#
text = mw.ustring.gsub(text,"(/+)","<wbr/>%1") -- Esta entrada DEVE ser a primeira. "<wbr/>" tem uma "/" nele, você sabe.
text = mw.ustring.gsub(text,"(%.+)","<wbr/>%1")
-- texto = mw.ustring.gsub(text,"(%-+)","<wbr/>%1") -- DISATIVADO por agora
text = mw.ustring.gsub(text,"(%#+)","<wbr/>%1")
text = mw.ustring.gsub(text,"(_+)","<wbr/>%1")

return mw.ustring.format('<span class="url">[%s %s]</span>', url, text)
end

function p.url(frame)
local templateArgs = frame.args
local url = templateArgs[1] or ''
local text = templateArgs[2] or ''
return p._url(url, text)
end

return p