Mudanças entre as edições de "Módulo:Character.Generate"
Ir para navegação
Ir para pesquisar
m |
m |
||
| (2 revisões intermediárias pelo mesmo usuário não estão sendo mostradas) | |||
| Linha 1: | Linha 1: | ||
-- Módulo: | -- Módulo:Character.Generate — função generate() | ||
local p = {} | local p = {} | ||
| Linha 11: | Linha 11: | ||
local requireCharModule = utils.requireCharModule | local requireCharModule = utils.requireCharModule | ||
local collectJsonObjects = utils.collectJsonObjects | local collectJsonObjects = utils.collectJsonObjects | ||
local function ensureFileExists(fileName, fallback) | |||
fileName = trim(fileName or "") | |||
if fileName == "" then | |||
return fallback | |||
end | |||
local title = mw.title.new("Arquivo:" .. fileName) | |||
if title and title.exists then | |||
return fileName | |||
end | |||
return fallback | |||
end | |||
local ATTR_I18N = i18n.ATTR_I18N | local ATTR_I18N = i18n.ATTR_I18N | ||
| Linha 59: | Linha 70: | ||
local nameBox = topbar:tag('div'):addClass('character-name-box') | local nameBox = topbar:tag('div'):addClass('character-name-box') | ||
local avatarImg = | local avatarImg = ensureFileExists(args.avatar, "Franky_ts_medal.png") | ||
nameBox:wikitext(string.format('[[Arquivo:%s|class=topbar-icon|link=|alt=Avatar]]', avatarImg)) | nameBox:wikitext(string.format('[[Arquivo:%s|class=topbar-icon|link=|alt=Avatar]]', avatarImg)) | ||
| Linha 69: | Linha 80: | ||
-- Resolve Tier/Tags em PT (render inicial) | -- Resolve Tier/Tags em PT (render inicial) | ||
-- Prioriza |module= sobre |nome= para carregar o módulo | |||
local moduleKey = trim(args.module or "") | |||
local nomeChar = trim(args.nome or "") | local nomeChar = trim(args.nome or "") | ||
local charData = requireCharModule( | local charModuleName = (moduleKey ~= "" and moduleKey) or nomeChar | ||
local charData = requireCharModule(charModuleName) or {} | |||
local rawTier = trim(frame:preprocess(args.tier or "")) | local rawTier = trim(frame:preprocess(args.tier or "")) | ||
local rawClasse = trim(frame:preprocess(args.classe or "")) | local rawClasse = trim(frame:preprocess(args.classe or "")) | ||
| Linha 246: | Linha 260: | ||
local iconWrap = iconBar:tag('div'):addClass('skill-icon'):attr('data-index', idx):attr('data-nome', | local iconWrap = iconBar:tag('div'):addClass('skill-icon'):attr('data-index', idx):attr('data-nome', | ||
name):attr('data-desc', desc):attr('data-atr', attrs):attr('data-video', | name):attr('data-desc', desc):attr('data-atr', attrs):attr('data-video', | ||
(video ~= "" and fileURL(video) or "")):attr('data-video-preload', 'auto') | (video ~= "" and fileURL(video) or "")):attr('data-video-preload', 'auto'):attr('data-icon-file', | ||
icon):attr('data-video-file', video or "") | |||
-- Level (para "Nível X" no JS) | -- Level (para "Nível X" no JS) | ||
| Linha 273: | Linha 288: | ||
if type(sk.flags) == "table" and #sk.flags > 0 then | if type(sk.flags) == "table" and #sk.flags > 0 then | ||
iconWrap:attr('data-flags', mw.text.jsonEncode(sk.flags)) | iconWrap:attr('data-flags', mw.text.jsonEncode(sk.flags)) | ||
end | |||
-- weapon (arma equipável que modifica atributos/descrição) | |||
if type(sk.weapon) == "table" then | |||
iconWrap:attr('data-weapon', mw.text.jsonEncode(sk.weapon)) | |||
end | end | ||
Edição atual tal como às 17h26min de 2 de dezembro de 2025
A documentação para este módulo pode ser criada em Módulo:Character.Generate/doc
-- Módulo:Character.Generate — função generate()
local p = {}
local utils = require("Módulo:Character.Utils")
local i18n = require("Módulo:Character.i18n")
local trim = utils.trim
local fileURL = utils.fileURL
local normalizeDim = utils.normalizeDim
local makeAttrString = utils.makeAttrString
local requireCharModule = utils.requireCharModule
local collectJsonObjects = utils.collectJsonObjects
local function ensureFileExists(fileName, fallback)
fileName = trim(fileName or "")
if fileName == "" then
return fallback
end
local title = mw.title.new("Arquivo:" .. fileName)
if title and title.exists then
return fileName
end
return fallback
end
local ATTR_I18N = i18n.ATTR_I18N
local FLAGS_I18N = i18n.FLAGS_I18N
local TAB_I18N = i18n.TAB_I18N
local tierPackFrom = i18n.tierPackFrom
local tagsPackFrom = i18n.tagsPackFrom
--------------------------------------------------------------------------------
-- Componente principal
--------------------------------------------------------------------------------
function p.generate(frame)
local parent = frame:getParent() or frame
local args = parent.args or {}
local html = mw.html.create('div')
local box = html:tag('div'):addClass('character-box')
----------------------------------------------------------------------------
-- Background (suporta |background= ou |banner= como fallback)
----------------------------------------------------------------------------
do
local bgParam = trim(frame:preprocess(args.background or ""))
if bgParam == "" then
bgParam = trim(frame:preprocess(args.banner or "")) -- opcional compat
end
if bgParam ~= "" then
box:attr('data-bg-file', bgParam)
local url = fileURL(bgParam)
if url and url ~= "" then
box:attr('data-bg-url', url)
-- fallback inline para certos temas
local style = string.format("--character-bg: url('%s'); background-image: url('%s');", url, url)
local old = box:getAttr('style')
box:attr('style', old and (old .. " " .. style) or style)
end
end
end
----------------------------------------------------------------------------
-- Header
----------------------------------------------------------------------------
local header = box:tag('div'):addClass('character-header')
-- topbar (avatar + nome + tags)
local topbar = header:tag('div'):addClass('character-topbar')
local nameBox = topbar:tag('div'):addClass('character-name-box')
local avatarImg = ensureFileExists(args.avatar, "Franky_ts_medal.png")
nameBox:wikitext(string.format('[[Arquivo:%s|class=topbar-icon|link=|alt=Avatar]]', avatarImg))
local nameGroup = nameBox:tag('div'):addClass('character-name-group')
nameGroup:tag('div'):addClass('character-name'):wikitext(args.nome or "")
-- Class tags (TIER + TAGS, com i18n injetada)
local classTags = nameGroup:tag('div'):addClass('class-tags')
-- Resolve Tier/Tags em PT (render inicial)
-- Prioriza |module= sobre |nome= para carregar o módulo
local moduleKey = trim(args.module or "")
local nomeChar = trim(args.nome or "")
local charModuleName = (moduleKey ~= "" and moduleKey) or nomeChar
local charData = requireCharModule(charModuleName) or {}
local rawTier = trim(frame:preprocess(args.tier or ""))
local rawClasse = trim(frame:preprocess(args.classe or ""))
-- Se vier tokens tipo "tier*", resolve via módulo
if rawTier ~= "" and mw.ustring.lower(rawTier):sub(1, 4) == "tier" then
rawTier = (charData.tier_i18n and charData.tier_i18n.pt) or charData.tier or rawTier
end
if rawClasse ~= "" and mw.ustring.lower(rawClasse):sub(1, 5) == "class" then
local arr = (charData.tags_i18n and charData.tags_i18n.pt) or charData.tags
if type(arr) == "table" then
rawClasse = table.concat(arr, " / ")
end
end
-- Se continuar vazio, puxa do módulo do personagem
if rawTier == "" then
rawTier = (charData.tier_i18n and charData.tier_i18n.pt) or charData.tier or ""
end
if rawClasse == "" then
local arr = (charData.tags_i18n and charData.tags_i18n.pt) or charData.tags
if type(arr) == "table" then
rawClasse = table.concat(arr, " / ")
else
rawClasse = arr or ""
end
end
-- Chip de TIER
local tierDiv
if rawTier ~= "" then
tierDiv = classTags:tag('div'):addClass('class-tag tier'):wikitext(rawTier)
end
-- Injeta i18n do TIER como data-*
do
local tI = charData.tier_i18n
if type(tI) ~= "table" then
-- deduz do texto já resolvido (rawTier) ou do charData.tier
tI = tierPackFrom(rawTier ~= "" and rawTier or (charData.tier or ""))
else
-- completa faltantes usando um seed
local seed = tI.pt or tI.en or tI.es or tI.pl or rawTier or charData.tier or ""
local base = tierPackFrom(seed)
tI = {
pt = tI.pt or base.pt,
en = tI.en or base.en,
es = tI.es or base.es,
pl = tI.pl or base.pl
}
end
if tierDiv then
tierDiv:attr('data-tier-pt', tI.pt or rawTier):attr('data-tier-en', tI.en or tI.pt or rawTier):attr(
'data-tier-es', tI.es or tI.pt or rawTier):attr('data-tier-pl', tI.pl or tI.pt or rawTier)
end
end
-- Injeta i18n das TAGS em JSON no container
do
local tagsI = nil
if type(charData.tags_i18n) == "table" then
-- já tem i18n no módulo → só completa faltantes
local basis = tagsPackFrom(charData.tags_i18n.pt or charData.tags_i18n.en or charData.tags_i18n.es or
charData.tags_i18n.pl or {})
tagsI = {
pt = charData.tags_i18n.pt or basis.pt,
en = charData.tags_i18n.en or basis.en,
es = charData.tags_i18n.es or basis.es,
pl = charData.tags_i18n.pl or basis.pl
}
else
-- constrói i18n a partir da lista simples (pt ou en que o editor já colocou)
local baseList = {}
if type(charData.tags) == "table" then
baseList = charData.tags
elseif type(charData.tags) == "string" then
for entry in mw.text.gsplit(charData.tags, '/', true) do
local t = mw.text.trim(entry or '')
if t ~= '' then
table.insert(baseList, t)
end
end
end
tagsI = tagsPackFrom(baseList)
end
classTags:attr('data-tags-i18n', mw.text.jsonEncode(tagsI))
end
-- Render inicial das TAGS (PT)
do
for entry in mw.text.gsplit(rawClasse, '/', true) do
local clean = mw.text.trim(entry or '')
if clean ~= '' then
classTags:tag('div'):addClass('class-tag'):wikitext(clean)
end
end
end
-- Descrição geral (se houver)
header:tag('div'):addClass('topbar-description'):wikitext(args.desc or "")
----------------------------------------------------------------------------
-- Idioma para tabs (PT padrão + aceita pt-br,en-US,... via |lang=)
----------------------------------------------------------------------------
local rawLang = trim(args.lang or "pt")
rawLang = mw.ustring.lower(rawLang)
local baseLang = rawLang:match("^([a-z][a-z])") or rawLang
-- fallback caso TAB_I18N não exista
local TAB_MAP = TAB_I18N or {
pt = {
skills = "Habilidades",
skins = "Skins",
skins_title = "SKINS & SPOTLIGHTS"
},
en = {
skills = "Skills",
skins = "Skins",
skins_title = "SKINS & SPOTLIGHTS"
},
es = {
skills = "Habilidades",
skins = "Aspectos",
skins_title = "ASPECTOS Y DESTACADOS"
},
pl = {
skills = "Umiejętności",
skins = "Skórki",
skins_title = "SKÓRKI I PREZENTACJE"
}
}
local TAB = TAB_MAP[rawLang] or TAB_MAP[baseLang] or TAB_MAP.pt
----------------------------------------------------------------------------
-- Abas (tabs)
----------------------------------------------------------------------------
local tabs = header:tag('div'):addClass('character-tabs')
tabs:tag('div'):addClass('tab-btn active'):attr('data-tab', 'skills'):wikitext(TAB.skills)
tabs:tag('div'):addClass('tab-btn'):attr('data-tab', 'skins'):wikitext(TAB.skins)
----------------------------------------------------------------------------
-- Aba: Skills
----------------------------------------------------------------------------
local skillsTab = box:tag('div'):addClass('tab-content active'):attr('id', 'skills')
local iconBar = skillsTab:tag('div'):addClass('icon-bar')
local skillsContainer = skillsTab:tag('div'):addClass('skills-container')
local details = skillsContainer:tag('div'):addClass('skills-details')
local descBox = details:tag('div'):addClass('desc-box')
skillsContainer:tag('div'):addClass('video-container'):done()
skillsTab:attr('data-i18n-attrs', mw.text.jsonEncode(ATTR_I18N))
skillsTab:attr('data-i18n-flags', mw.text.jsonEncode(FLAGS_I18N))
if args.lang and trim(args.lang) ~= "" then
skillsTab:attr('data-i18n-default', baseLang)
end
-- Monta ícones de skill a partir de |skills= (sequência de {} JSON)
local skillsPacked = args.skills or ""
local idx = 0
for _, chunk in ipairs(collectJsonObjects(skillsPacked)) do
local ok, sk = pcall(mw.text.jsonDecode, chunk)
if ok and type(sk) == "table" then
local name = trim(sk.name or sk.nome or "")
local icon = trim(sk.icon or "")
local desc = trim(sk.desc or "")
local level = trim(tostring(sk.level or ""))
local pve = trim(sk.powerpve or "")
local pvp = trim(sk.powerpvp or "")
local energy = trim(sk.energy or "")
local cd = trim(sk.cooldown or "")
local video = trim(sk.video or "")
if icon ~= "" then
idx = idx + 1
local attrs = makeAttrString(pve, pvp, energy, cd)
local iconWrap = iconBar:tag('div'):addClass('skill-icon'):attr('data-index', idx):attr('data-nome',
name):attr('data-desc', desc):attr('data-atr', attrs):attr('data-video',
(video ~= "" and fileURL(video) or "")):attr('data-video-preload', 'auto'):attr('data-icon-file',
icon):attr('data-video-file', video or "")
-- Level (para "Nível X" no JS)
if level ~= "" and mw.ustring.upper(level) ~= "NIVEL" then
iconWrap:attr('data-level', level)
end
-- Descrições i18n (quando vierem do Info)
if type(sk.desc_i18n) == "table" then
iconWrap:attr('data-desc-pt', sk.desc_i18n.pt or ""):attr('data-desc-en', sk.desc_i18n.en or "")
:attr('data-desc-es', sk.desc_i18n.es or ""):attr('data-desc-pl', sk.desc_i18n.pl or "")
elseif desc and desc ~= "" then
-- Pelo menos PT
iconWrap:attr('data-desc-pt', desc)
end
-- Subskills: injeta dados no HTML pro Widget ler
if type(sk.subs) == "table" and #sk.subs > 0 then
iconWrap:attr('data-subs', mw.text.jsonEncode(sk.subs))
end
if type(sk.suborder) == "table" and #sk.suborder > 0 then
iconWrap:attr('data-suborder', mw.text.jsonEncode(sk.suborder))
end
-- flags (características: aggro, bridge, wall, quickcast)
if type(sk.flags) == "table" and #sk.flags > 0 then
iconWrap:attr('data-flags', mw.text.jsonEncode(sk.flags))
end
-- weapon (arma equipável que modifica atributos/descrição)
if type(sk.weapon) == "table" then
iconWrap:attr('data-weapon', mw.text.jsonEncode(sk.weapon))
end
-- Imagem do ícone
iconWrap:wikitext(string.format('[[Arquivo:%s|class=skill-icon-img|link=]]', icon))
-- Slot de descrição indexado (o JS usa para sincronizar)
descBox:tag('div'):addClass('skill-desc'):attr('data-index', idx)
end
end
end
----------------------------------------------------------------------------
-- Aba: Skins (carrossel)
----------------------------------------------------------------------------
local skinsTab = box:tag('div'):addClass('tab-content'):attr('id', 'skins')
local cardSkins = skinsTab:tag('div'):addClass('card-skins')
cardSkins:tag('span'):addClass('card-skins-title'):wikitext(TAB.skins_title)
local wrapper = cardSkins:tag('div'):addClass('skins-carousel-wrapper')
wrapper:tag('div'):addClass('skins-arrow left'):wikitext('«')
local carousel = wrapper:tag('div'):addClass('skins-carousel')
local skinsPacked = args.skins or ""
for _, chunk in ipairs(collectJsonObjects(skinsPacked)) do
local ok, sk = pcall(mw.text.jsonDecode, chunk)
if ok and type(sk) == "table" then
-- ... dentro do loop das skins:
local bannerFile = trim(sk.background or "")
local imageFile = trim(sk.sprite or "")
local tooltipRaw = trim(sk.tooltip or "")
-- Título: vem 100% do editor (|name=); não forçamos maiúsculas e não juntamos com nome do personagem
local skinTitle = mw.text.trim(sk.name or "")
-- PT (ou fallback) para render inicial; preserva i18n p/ trocar no JS
local tipPack, chosen = nil, ""
if tooltipRaw:match("^%s*{") then
local ok2, obj2 = pcall(mw.text.jsonDecode, tooltipRaw)
if ok2 and type(obj2) == "table" then
tipPack = obj2
chosen = mw.text.trim(obj2.pt or obj2.en or obj2.es or obj2.pl or "")
end
end
if chosen == "" then
chosen = tooltipRaw
end
-- HTML final do tooltip:
-- 1) Título sem <br>, sem margem (pra não abrir um "buraco")
local titleHtml = skinTitle ~= "" and
('<div class="skin-tooltip-title" style="margin:0">' .. skinTitle .. '</div>') or ""
-- 2) Descrição com '''bold''' respeitado e TODA a linha em <b> (onde obtém)
local bodyHtml = chosen:gsub("'''([^']+)'''", "<b>%1</b>"):gsub("\n", "<br>")
bodyHtml = bodyHtml ~= "" and ('<b>' .. bodyHtml .. '</b>') or ""
local tooltipHtml = titleHtml .. bodyHtml
local skinCard = carousel:tag('div'):addClass('skin-card'):attr('data-skin-tooltip', tooltipHtml)
-- Spotlight do YouTube (parametro |youtube= na Predefinição:Skin)
local yt = trim(sk.youtube or "")
if yt ~= "" then
-- normaliza ID curto pra URL completa (ex.: "dQw4w9WgXcQ" -> "https://youtu.be/dQw4w9WgXcQ")
if not yt:match("^https?://") then
if yt:match("^[%w%-%_]+$") then
yt = "https://youtu.be/" .. yt
else
yt = "https://" .. yt -- fallback besta se vier "www.youtube.com/..."
end
end
skinCard:attr('data-youtube', yt):addClass('is-clickable') -- só pra cursor/estilo (opcional)
:attr('tabindex', '0') -- acessível no teclado
:attr('role', 'button'):attr('aria-label',
'YouTube: ' .. (mw.text.trim(sk.name or '') ~= '' and sk.name or 'skin'))
end
if skinTitle ~= "" then
skinCard:attr('data-skin-title', skinTitle)
end
if tipPack then
skinCard:attr('data-skin-tooltip-i18n', mw.text.jsonEncode(tipPack))
end
-- BANNER (mantém como já está)
local bannerDiv = skinCard:tag('div'):addClass('skin-banner')
if bannerFile ~= "" then
bannerDiv:attr('data-file', bannerFile):wikitext(string.format('[[Arquivo:%s|link=]]', bannerFile))
:attr('style', string.format("background-image:url('%s')", fileURL(bannerFile)))
else
bannerDiv:wikitext("")
end
-- SPRITE (respeita w/h se vierem)
local spriteDiv = skinCard:tag('div'):addClass('skin-sprite')
-- lê w/h do JSON e normaliza
local swp = normalizeDim(sk.w or sk.width)
local shp = normalizeDim(sk.h or sk.height)
-- aplica como inline style no container (sem apagar estilos já existentes)
if swp or shp then
local inline = ""
if swp then
inline = inline .. " width:" .. swp .. ";"
end
if shp then
inline = inline .. " height:" .. shp .. ";"
end
local old = spriteDiv:getAttr('style')
spriteDiv:attr('style', old and (old .. " " .. inline) or inline)
if swp then
spriteDiv:attr('data-sprite-w', swp)
end
if shp then
spriteDiv:attr('data-sprite-h', shp)
end
end
if imageFile ~= "" then
spriteDiv:attr('data-file', imageFile):wikitext(string.format('[[Arquivo:%s|link=]]', imageFile))
else
spriteDiv:wikitext("")
end
end
end
wrapper:tag('div'):addClass('skins-arrow right'):wikitext('»')
----------------------------------------------------------------------------
-- Tier -> classe CSS (visual)
----------------------------------------------------------------------------
do
local key = mw.ustring.lower(rawTier or "")
local tierMap = {
bronze = "tier-bronze",
bronce = "tier-bronze",
silver = "tier-silver",
prata = "tier-silver",
gold = "tier-gold",
ouro = "tier-gold",
diamond = "tier-diamond",
diamante = "tier-diamond"
}
local tierClass = tierMap[key]
if tierClass and tierClass ~= "" then
box:addClass(tierClass)
end
end
----------------------------------------------------------------------------
-- Retorno
----------------------------------------------------------------------------
return tostring(html)
end
return p