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

Материал из Space Station 14 Вики
мНет описания правки
мНет описания правки
(не показана 21 промежуточная версия этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
local getArgs = require('Module:Arguments').getArgs
local getArgs = require('Module:Arguments').getArgs
--------------------------------------------------------------------------------
-- Вспомогательные функции
--------------------------------------------------------------------------------
-- Формирует строку ссылки на изображение
local function formatImage(file, size)
return string.format("[[Файл:%s|%s|link=]]", file, size)
end
-- Возвращает значение аргумента: если nil, то значение по умолчанию; если пустая строка, то пустую строку; иначе само значение
local function resolveArg(input, defaultValue)
if input == nil then
return defaultValue
elseif input == "" then
return ""
else
return input
end
end
-- Обёртка для вызова другого модуля через #invoke
local function invoke(frame, module, method, subMethod, extra, id)
local invocation = string.format("{{#invoke:%s|%s|%s|%s|%s}}", module, method, subMethod, extra, id)
return frame:preprocess(invocation)
end
-- Оборачивает текст в вики-ссылку, если цель задана
local function wrapLink(text, target)
if text == "" then
return ""
else
return string.format("[[%s|%s]]", target, text)
end
end
--------------------------------------------------------------------------------
-- Основная функция модуля
--------------------------------------------------------------------------------


function p.main(frame)
function p.main(frame)
    local args = getArgs(frame)
-- Получаем аргументы шаблона
    local argsWithWhitespace = getArgs(frame, { trim = false, removeBlanks = false })
local args = getArgs(frame)
   
local argsRaw = getArgs(frame, { trim = false, removeBlanks = false })
    local id = args[1] or ""
 
    -- Инициализация данных предмета
    local itemStack = frame:preprocess(string.format('{{#invoke:Prototypes/Хранилище/Предмет|main|framing|stack|%s}}', id))
    local itemContained = frame:preprocess(string.format('{{#invoke:Prototypes/Хранилище/Предмет|main|framing|contained|%s}}', id))
    local itemSlot = frame:preprocess(string.format('{{#invoke:Prototypes/Хранилище/Предмет|main|framing|slot|%s}}', id))
    local itemChem = frame:preprocess(string.format('{{СollapsibleMenu|color=#3e7c82|{{#invoke:Prototypes/Хранилище/Предмет|main|chem|%s}}}}', id))
    local itemName = frame:preprocess("{{#invoke:Entity Lookup|getname|" .. id .. "}}")


    local prefix = args[2] or ""
-- Основные параметры
     local label = args["label"] or itemName
local id      = args[1] or ""
    local size = args["size"] or "32px"
local size     = args["size"] or "32px"
local prefix  = args[2] or ""
local vertical = argsRaw.vertical


     local input_label = argsWithWhitespace.label or argsWithWhitespace.l
-- Получаем данные о предмете через вызовы других модулей
    local label
local itemStack     = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "stack", id)
    if input_label == nil then
local itemContained = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "contained", id)
        label = itemName
local itemSlot      = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "slot", id)
    else
-- Для химии оборачиваем в CollapsibleMenu (из-за ошибки в модуле)
if input_label == "" then
local itemChem = frame:preprocess(string.format("{{СollapsibleMenu|color=#3e7c82|{{#invoke:Prototypes/Хранилище/Предмет|main|chem|%s}}}}", id))
            label = ""
local itemName = frame:preprocess(string.format("{{#invoke:Entity Lookup|getname|%s}}", id))
        else
            label = input_label
        end
    end


    -- Формирование строки изображения с проверкой на пустое значение
-- Обработка ярлыка
    local input_image = argsWithWhitespace.image or argsWithWhitespace.img
local rawLabel = argsRaw.label or argsRaw.l
    local image
local label = rawLabel == nil and itemName or resolveArg(rawLabel, itemName)
    if input_image == nil then
        image = ""
    else
if input_image == "" then
            image = string.format("[[Файл:%s.png|%s]]", id, size)
        else
            image = string.format("[[Файл:%s|%s]]", input_image, size)
        end
    end


    -- Формирование ярлыка с ссылкой, если задана
-- Обработка изображения
    local labelOutput = label
local rawImage = argsRaw.image or argsRaw.img
    if args["link"] then
local image
        local linkTarget = args["link"]
if rawImage == nil then
        if linkTarget == "" then
image = formatImage(id .. ".png", size)
            linkTarget = itemName
else
        end
image = (rawImage ~= "") and formatImage(rawImage, size) or ""
        if label ~= "" then
end
            labelOutput = string.format("[[%s|%s]]", linkTarget, label)
        else
            labelOutput = ""
        end
    end


    -- Сбор информации в зависимости от наличия репозитория
-- Если указан imageTooltip, переопределяем изображение
    local additionalInfo = args["repository"]
if argsRaw.imageTooltip ~= nil then
    if additionalInfo == nil then
image = frame:preprocess(string.format(
        additionalInfo = labelOutput .. " " .. itemStack .. " " .. prefix .. " " .. itemContained .. " " .. itemSlot .. " " .. itemChem
"{{#invoke:Entity Lookup|createimagetooltip|Файл:%s.png|%s|Мета=%s,link=}}",
    else
id, id, size
        additionalInfo =  labelOutput .. " " .. prefix
))
    end
end


    local result = image .. " " .. additionalInfo
-- Обработка ссылки
local rawLink = argsRaw.link
local labelOutput = (rawLink ~= nil) and wrapLink(label, (rawLink == "" and itemName or rawLink)) or label


    -- Формирование вывода через LinkCard, если указан непустой обёртка
-- Формирование описания репозитория
    if args["wrapper"] and args["wrapper"] ~= "" then
local repository = (argsRaw.repository == nil) and prefix or table.concat({ itemContained, itemSlot, itemChem }, " ")
        local pixel = string.match(size, "(%d+)")
        local wrapperInfo
        if args["repository"] then
            wrapperInfo = additionalInfo
        else
            wrapperInfo = label .. prefix
        end


        local imageParam
-- Формирование итогового блока с изображением и описанием
        if args["image"] then
local imagerepository, result
            if args["image"] == "" then
if vertical ~= nil then
                imageParam = ""
imagerepository = string.format(
            else
"<span style='display:inline-flex;flex-direction:column;align-items:center;'>%s<b>%s</b></span>",
                imageParam = args["image"]
image, labelOutput
            end
)
        else
result = table.concat({ imagerepository, itemStack, prefix }, " ")
            imageParam = id .. ".png"
else
        end
imagerepository = string.format("<span>%s%s</span>", image, repository)
result = table.concat({ imagerepository, labelOutput, itemStack, prefix }, " ")
end


        local linkParam = args["link"]
-- Если задан параметр wrapper, формируем LinkCard
        if not linkParam or linkParam == "" then
if argsRaw.wrapper ~= nil then
            linkParam = itemName
local pixel = string.match(size, "(%d+)")
        end
local linkParam = (rawLink ~= nil) and ((rawLink == "" and itemName) or rawLink) or ""
-- Если vertical не задан, добавляем SideStyle=1
local sideStyle = (vertical ~= nil) and "" or "|SideStyle=1"


        return frame:preprocess(string.format("{{LinkCard|name=%s|image=%s|pixel=%s|link=%s|SideStyle=1}}", wrapperInfo, imageParam, pixel, linkParam))
return frame:preprocess(string.format(
    end
"{{LinkCard|name=%s %s %s|pin=%s|image-full=%s|pixel=%s|link=%s%s}}",
labelOutput, itemStack, prefix, repository, image, pixel, linkParam, sideStyle
))
end


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


return p
return p

Версия от 14:39, 7 апреля 2025

Для документации этого модуля может быть создана страница Модуль:Предмет/doc

local p = {}
local getArgs = require('Module:Arguments').getArgs

--------------------------------------------------------------------------------
-- Вспомогательные функции
--------------------------------------------------------------------------------

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

-- Возвращает значение аргумента: если nil, то значение по умолчанию; если пустая строка, то пустую строку; иначе само значение
local function resolveArg(input, defaultValue)
	if input == nil then
		return defaultValue
	elseif input == "" then
		return ""
	else
		return input
	end
end

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

-- Оборачивает текст в вики-ссылку, если цель задана
local function wrapLink(text, target)
	if text == "" then
		return ""
	else
		return string.format("[[%s|%s]]", target, text)
	end
end

--------------------------------------------------------------------------------
-- Основная функция модуля
--------------------------------------------------------------------------------

function p.main(frame)
	-- Получаем аргументы шаблона
	local args = getArgs(frame)
	local argsRaw = getArgs(frame, { trim = false, removeBlanks = false })

	-- Основные параметры
	local id       = args[1] or ""
	local size     = args["size"] or "32px"
	local prefix   = args[2] or ""
	local vertical = argsRaw.vertical

	-- Получаем данные о предмете через вызовы других модулей
	local itemStack     = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "stack", id)
	local itemContained = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "contained", id)
	local itemSlot      = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "slot", id)
	-- Для химии оборачиваем в CollapsibleMenu (из-за ошибки в модуле)
	local itemChem = frame:preprocess(string.format("{{СollapsibleMenu|color=#3e7c82|{{#invoke:Prototypes/Хранилище/Предмет|main|chem|%s}}}}", id))
	local itemName = frame:preprocess(string.format("{{#invoke:Entity Lookup|getname|%s}}", id))

	-- Обработка ярлыка
	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 image
	if rawImage == nil then
		image = formatImage(id .. ".png", size)
	else
		image = (rawImage ~= "") and formatImage(rawImage, size) or ""
	end

	-- Если указан imageTooltip, переопределяем изображение
	if argsRaw.imageTooltip ~= nil then
		image = frame:preprocess(string.format(
			"{{#invoke:Entity Lookup|createimagetooltip|Файл:%s.png|%s|Мета=%s,link=}}",
			id, id, size
		))
	end

	-- Обработка ссылки
	local rawLink = argsRaw.link
	local labelOutput = (rawLink ~= nil) and wrapLink(label, (rawLink == "" and itemName or rawLink)) or label

	-- Формирование описания репозитория
	local repository = (argsRaw.repository == nil) and prefix or table.concat({ itemContained, itemSlot, itemChem }, " ")

	-- Формирование итогового блока с изображением и описанием
	local imagerepository, result
	if vertical ~= nil then
		imagerepository = string.format(
			"<span style='display:inline-flex;flex-direction:column;align-items:center;'>%s<b>%s</b></span>",
			image, labelOutput
		)
		result = table.concat({ imagerepository, itemStack, prefix }, " ")
	else
		imagerepository = string.format("<span>%s%s</span>", image, repository)
		result = table.concat({ imagerepository, labelOutput, itemStack, prefix }, " ")
	end

	-- Если задан параметр wrapper, формируем LinkCard
	if argsRaw.wrapper ~= nil then
		local pixel = string.match(size, "(%d+)")
		local linkParam = (rawLink ~= nil) and ((rawLink == "" and itemName) or rawLink) or ""
		-- Если vertical не задан, добавляем SideStyle=1
		local sideStyle = (vertical ~= nil) and "" or "|SideStyle=1"

		return frame:preprocess(string.format(
			"{{LinkCard|name=%s %s %s|pin=%s|image-full=%s|pixel=%s|link=%s%s}}",
			labelOutput, itemStack, prefix, repository, image, pixel, linkParam, sideStyle
		))
	end

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

return p