Модуль:Предмет: различия между версиями

мНет описания правки
Нет описания правки
 
(не показано 9 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
local getArgs = require('Module:Arguments').getArgs
local getArgs = require('Module:Arguments').getArgs
local JsonPaths = require('Module:JsonPaths')


-- Формирует строку ссылки на изображение
local function trim(value)
local function formatImage(file, size)
return mw.text.trim(value or '')
    return string.format("[[Файл:%s|%s|link=]]", file, size)
end
end


-- Возвращает значение аргумента: если nil, то значение по умолчанию; если пустая строка, то пустую строку; иначе само значение
local function formatImage(file, size, link)
local function resolveArg(input, defaultValue)
return string.format('[[Файл:%s|%s|link=%s]]', file, size, link)
    if input == nil then
        return defaultValue
    elseif input == "" then
        return ""
    else
        return input
    end
end
end


-- Обёртка для вызова другого модуля через #invoke
local function wrapLink(text, target)
local function invoke(frame, module, method, subMethod, extra, id)
return (text ~= '' and target and string.format('[[%s|%s]]', target, text) or text)
    local invocation = string.format("{{#invoke:%s|%s|%s|%s|%s}}", module, method, subMethod, extra, id)
    return frame:preprocess(invocation)
end
end


-- Оборачивает текст в вики-ссылку, если цель задана
function p.main(frame)
local function wrapLink(text, target)
local argsRaw = getArgs(frame, { trim = false, removeBlanks = false })
    if text == "" then
local args = {}
        return ""
for k, v in pairs(argsRaw) do
    else
if v ~= '' then
        return string.format("[[%s|%s]]", target, text)
args[k] = v
    end
end
end
end


--------------------------------------------------------------------------------
local id = args[1] or ''
-- Основная функция модуля
local size = args.size or '32px'
--------------------------------------------------------------------------------
local prefix = args[2] or ''
local isRepo = argsRaw.repository ~= nil
local isWrap = argsRaw.wrapper ~= nil
local isVert = argsRaw.vertical ~= nil


function p.main(frame)
-- Если id найден в JsonPaths, префиксы проекта нужны
    -- Получаем аргументы шаблона
local hasId = (JsonPaths.has(id) == true)
    local args = getArgs(frame)
local projPrefix = hasId and JsonPaths.prefix() or ''
    local argsRaw = getArgs(frame, { trim = false, removeBlanks = false })
local projPrefixFile = hasId and JsonPaths.prefixFile() or ''


    -- Основные параметры
-- Получение имени
    local id      = args[1] or ""
local nameStr = frame:preprocess(
    local size    = args["size"] or "32px"
string.format('{{#invoke:Entity Lookup|getname|%s}}', id)
    local prefix  = args[2] or ""
)
    local vertical = argsRaw.vertical


    -- Режим репозитория: дополнительные данные только при необходимости
-- Лейбл и ссылка
    local repositoryMode = argsRaw.repository ~= nil
local labelRaw = argsRaw.label or argsRaw.l
    local repository = prefix
local label = (labelRaw == nil and nameStr) or (labelRaw == '' and '' or labelRaw)
    local itemContained, itemSlot, itemChem
local linkRaw = argsRaw.link
    if repositoryMode then
local linkTgt = linkRaw == nil and '' or (linkRaw == '' and nameStr or linkRaw)
        -- Получаем данные о вложенных предметах, слоте и химии
        itemContained = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "contained", id)
        itemSlot      = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "slot", id)
        -- Для химии оборачиваем в CollapsibleMenu (из-за ошибки в модуле)
        itemChem      = frame:preprocess(string.format(
            "{{СollapsibleMenu|color=#3e7c82|{{#invoke:Prototypes/Хранилище/Предмет|main|chem|%s}}}}", id
        ))
        repository = table.concat({ itemContained, itemSlot, itemChem }, " ")
    end


    -- Получаем имя предмета
if linkTgt ~= '' and projPrefix ~= '' then
    local itemName = frame:preprocess(string.format("{{#invoke:Entity Lookup|getname|%s}}", id))
linkTgt = projPrefix .. linkTgt
end


    -- Обработка ярлыка
local labelOut = (linkRaw ~= nil) and wrapLink(label, linkTgt) or label
    local rawLabel = argsRaw.label or argsRaw.l
    local label = rawLabel == nil and itemName or resolveArg(rawLabel, itemName)


    -- Обработка изображения
-- Изображение
    local rawImage = argsRaw.image or argsRaw.img
local imgFile = argsRaw.image or argsRaw.img or (id .. '.png')
    local image
if imgFile ~= '' and projPrefixFile ~= '' then
    if rawImage == nil then
imgFile = projPrefixFile .. imgFile
        image = formatImage(id .. ".png", size)
end
    else
        image = (rawImage ~= "") and formatImage(rawImage, size) or ""
    end


    -- Переопределение изображения через imageTooltip
local img = imgFile ~= '' and formatImage(imgFile, size, linkTgt) or ''
    if argsRaw.imageTooltip ~= nil then
if argsRaw.imageTooltip then
        image = frame:preprocess(string.format(
img = frame:preprocess(
            "{{#invoke:Entity Lookup|createimagetooltip|Файл:%s.png|%s|Мета=%s,link=}}",
string.format(
            id, id, size
'{{#invoke:Entity Lookup|createimagetooltip|Файл:%s|%s|Мета=%s,link=}}',
        ))
imgFile, id, size
    end
)
)
end


    -- Обработка ссылки
-- Репозиторий
    local rawLink = argsRaw.link
local repoStr = ''
    local labelOutput = (rawLink ~= nil)
if isRepo then
        and wrapLink(label, (rawLink == "" and itemName or rawLink))
local parts = {}
        or label
for _, slot in ipairs({ 'contained', 'slot', 'chem' }) do
table.insert(parts,
frame:preprocess(
string.format(
'{{#invoke:Prototypes/Хранилище/Предмет|main|framing|%s|%s}}',
slot, id
)
)
)
end
repoStr = table.concat(parts, ' ')
end


    -- Формирование вывода
-- Основная сборка
    local imagerepository, result
local parts = {}
    if vertical ~= nil then
if isVert then
        -- Вертикальное отображение
table.insert(parts,
        imagerepository = string.format(
string.format(
            "<span style='display:inline-flex;flex-direction:column;align-items:center;'>%s<b>%s</b></span>",
"<span style='display:inline-flex;flex-direction:column;align-items:center;'>%s<b>%s</b></span>",
            image, labelOutput
img, labelOut
        )
)
        result = table.concat({ imagerepository, prefix }, " ")
)
    else
else
        -- Горизонтальное отображение
table.insert(parts,
        imagerepository = string.format("<span style='display:inline-block;'>%s%s</span>", image, repository)
string.format(
        result = table.concat({ imagerepository, labelOutput, prefix }, " ")
"<span style='display:inline-block;'>%s%s</span>", img, repoStr
    end
)
)
table.insert(parts, labelOut)
end


    -- Обёртка LinkCard
-- Стек предметов
    if argsRaw.wrapper ~= nil then
table.insert(parts,
        local pixel = string.match(size, "(%d+)")
frame:preprocess(
        local linkParam = (rawLink ~= nil) and ((rawLink == "" and itemName) or rawLink) or ""
string.format(
        local sideStyle = (vertical ~= nil) and "" or "|SideStyle=1"
'{{#invoke:Prototypes/Хранилище/Предмет|main|framing|stack|%s}}', id
)
)
)
table.insert(parts, prefix)


        return frame:preprocess(string.format(
-- Обёртка LinkCard
            "{{LinkCard|name=%s %s %s|pin=%s|image-full=%s|pixel=%s|link=%s%s}}",
if isWrap then
            labelOutput, prefix, repository, image, pixel, linkParam, sideStyle
local side = isVert and '' or '|горизонт_стиль=1'
        ))
local card = string.format(
    end
'{{LinkCard|название=%s %s %s|пин=%s|изображение=%s|ссылка=%s%s}}',
labelOut,
frame:preprocess(string.format(
'{{#invoke:Prototypes/Хранилище/Предмет|main|framing|stack|%s}}', id
)),
prefix,
repoStr,
img,
linkTgt,
side
)
return frame:preprocess(card)
end


    return frame:preprocess(string.format("<span>%s</span>", result))
return frame:preprocess('<span>' .. table.concat(parts, ' ') .. '</span>')
end
end


return p
return p