Módulo:Escutar
Aparência
| Este módulo é usado em aproximadamente 1 290 páginas e alterações podem ser amplamente notadas. Teste mudanças na subpágina /Testes ou /Exemplo para testes, ou em sua própria página de testes de módulo. Considere discutir mudanças na página de discussão antes de implementá-las. |
| Este módulo depende dos seguintes outros módulos: |
| Este módulo utiliza TemplateStyles: |
Este módulo implementa a predefinição {{Escutar}}.
Uso a partir de wikitexto
É preferível não usar este módulo diretamente a partir de wikitexto. Ele pode ser usado por meio da predefinição {{Escutar}}. Consulte a página da predefinição para obter a documentação.
Uso de módulos Lua
Para usar este módulo a partir de outros módulos Lua, primeiro carregue o módulo.
local mListen = require('Módulo:Escutar')
Você pode então gerar a caixa de escuta usando a função _main.
mListen._main(args)
A variável args deve ser uma tabela contendo os argumentos a serem passados ao módulo. Para ver os diferentes argumentos que podem ser especificados e como eles afetam a saída do módulo, consulte a documentação da predefinição {{Escutar}}.
Categorias de rastreamento/manutenção
local mFileLink = require('Módulo:Link de arquivo')
local mTableTools = require('Módulo:TableTools')
local mSideBox = require('Módulo:Caixa lateral')
local lang = mw.language.new('en')
local p = {}
local function formatLength(length)
-- Formata uma duração em segundos em "(h:)mm:ss" (os minutos são preenchidos com zeros
-- somente se houver horas).
if not length or length == 0 then
return nil
end
-- Adiciona 0,5 para compensar o arredondamento para baixo
local t = lang:getDurationIntervals(length + 0.5, { 'hours', 'minutes', 'seconds' })
local s = t.seconds and string.format('%02d', t.seconds) or '00'
local m = t.minutes or 0
local span = mw.html.create('span'):addClass('duration')
if t.hours then
span
:tag('span')
:addClass('h')
:wikitext(t.hours)
:done()
:wikitext(':')
m = string.format('%02d', m)
end
span
:tag('span')
:addClass('min')
:wikitext(m)
:done()
:wikitext(':')
:tag('span')
:addClass('s')
:wikitext(s)
:done()
return tostring(span)
end
local function renderRow(filename, title, play, alt, description, start, length, hasImage)
-- Renderiza a HTML para uma linha de descrição de arquivo.
if not filename then
return nil
end
length = formatLength(length)
length = length and string.format(' (%s)', length) or ''
local root = mw.html.create('')
root:tag('div')
:addClass('haudio')
:newline()
:tag('div')
:addClass('listen-file-header')
:wikitext(string.format(
'[[:Ficheiro:%s|%s]]%s',
filename,
title or '',
length
))
:done()
:newline()
:tag('div')
:wikitext(play ~= 'no' and mFileLink._main{
file = filename,
size = hasImage and '232px' or '215px',
alt = alt,
start = start
}
or nil
)
:done()
:newline()
:tag('div')
:addClass('description')
:wikitext(description)
:done()
:done()
return tostring(root)
end
local function renderTrackingCategories(isPlain, hasMissing, isEmpty, titleObj)
-- Renderiza todas as categorias de rastreamento produzidas pela predefinição.
-- isPlain, hasMissing e isEmpty são passados através de p._main,
-- e o titleObj é usado apenas para fins de testes.
local cats = {}
local currentTitle = titleObj or mw.title.getCurrentTitle()
if currentTitle.namespace == 0 then
-- Estamos no espaço principal.
if not isEmpty then
cats[#cats + 1] = '!Artigos com microformatos hAudio'
end
if hasMissing then
cats[#cats + 1] = '!Artigos com predefinição escutar vazia'
end
end
if isPlain then
cats[#cats + 1] = '!Páginas com predefinição escutar que usam parâmetro simples'
end
for i, cat in ipairs(cats) do
cats[i] = string.format('[[Categoria:%s]]', cat)
end
return table.concat(cats)
end
function p._main(args)
-- Organiza os argumentos por número.
local isPlain = args.plain == 'yes'
local isEmbedded = args.embed and true
local hasImage = not isPlain and not isEmbedded and args.image ~= 'none'
local numArgs, missingFiles = {}, {}
do
local origNumArgs = mTableTools.numData(args)
origNumArgs[1] = origNumArgs.other -- Substitui args.filename1 etc. por args.filename etc.
origNumArgs = mTableTools.compressSparseArray(origNumArgs)
for i, t in ipairs(origNumArgs) do
-- Verifica se os arquivos existem.
local obj = t.filename and mw.title.makeTitle(-2, t.filename)
if obj and obj.exists then
if t.length == 'yes' or
-- Mostra a duração se a altura do vídeo for menor que 150px
obj.file.width / obj.file.height > (hasImage and 1.547 or 1.434)
then
t.length = obj.file.length
else
t.length = nil
end
numArgs[#numArgs + 1] = t
else
missingFiles[#missingFiles + 1] = t.filename or i
end
end
end
-- Renderiza o aviso
local hasMissing = #missingFiles ~= 0
local previewWarning = ''
if hasMissing then
for i, v in ipairs(missingFiles) do
missingFiles[i] = type(v) == 'string'
and string.format('arquivo "%s" ausente', v)
or string.format('nome de arquivo vazio #%s', v)
end
previewWarning = string.format(
'Página usando [[Predefinição:Escutar]] com %s',
mw.text.listToText(missingFiles)
)
previewWarning = require('Módulo:If preview')._warning({previewWarning})
end
-- Sai mais cedo se não houver nenhum.
if #numArgs == 0 then
return previewWarning .. renderTrackingCategories(isPlain, hasMissing, true)
end
-- Cria os argumentos para {{Caixa lateral}}
local sbArgs = {
metadata = 'no',
position = (isPlain or isEmbedded) and 'left' or args.pos,
style = args.style,
templatestyles = 'Módulo:Escutar/styles.css'
}
-- Argumentos de classe
do
local class = {
'listen',
'noprint'
}
if isPlain then
table.insert(class, 'listen-plain')
end
if isEmbedded then
table.insert(class, 'listen-embedded')
end
if not hasImage then
table.insert(class, 'listen-noimage')
end
if args.pos == 'left' and not isPlain and not isEmbedded then
table.insert(class, 'listen-left')
elseif args.pos == 'center' then
table.insert(class, 'listen-center')
end
sbArgs.class = table.concat(class, ' ')
end
-- Imagem
if not isPlain and not isEmbedded then
if args.image then
sbArgs.image = args.image
else
local images = {
speech = 'Audio-input-microphone.svg',
music = 'Gnome-mime-audio-openclipart.svg',
default = 'Gnome-mime-sound-openclipart.svg'
}
sbArgs.image = mFileLink._main{
file = args.type and images[args.type] or images.default,
size = '65x50px',
location = 'center',
link = '',
alt = ''
}
end
end
-- Texto
do
local header
if args.header then
header = mw.html.create('div')
header:addClass('listen-header')
:wikitext(args.header)
header = tostring(header) .. '\n'
else
header = ''
end
local text = {}
for i, t in ipairs(numArgs) do
text[#text + 1] = renderRow(
t.filename, t.title, t.play, t.alt, t.description, t.start,
t.length, hasImage
)
if numArgs[i + 1] then
text[#text + 1] = '<hr/>'
end
end
sbArgs.text = header .. table.concat(text)
end
-- Abaixo
if not isPlain and not isEmbedded and args.help ~= 'no' then
sbArgs.below = string.format(
'<hr/><i class="selfreference">Problemas ao reproduzir %s? Veja [[Ajuda:Guia de consulta e reprodução/Introdução à mídia|ajuda sobre media]].</i>',
#numArgs == 1 and 'este arquivo' or 'estes arquivos'
)
end
-- Renderiza a caixa lateral.
local sideBox = mSideBox._main(sbArgs)
-- Renderiza as categorias de rastreamento.
local trackingCategories = renderTrackingCategories(isPlain, hasMissing)
return previewWarning .. sideBox .. trackingCategories
end
function p.main(frame)
--local origArgs = frame:getParent().args
local args = {}
for k, v in pairs(frame.args) do-- 'origArgs' foi substituído por 'frame.args' nesta linha
if v ~= '' then
args[k] = v
end
end
return p._main(args)
end
return p