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

Материал из Space Station 14 Вики
мНет описания правки
Нет описания правки
 
(не показано 14 промежуточных версий этого же участника)
Строка 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)
-- Вспомогательные функции
return mw.text.trim(value or '')
--------------------------------------------------------------------------------
 
-- Формирует строку ссылки на изображение
local function formatImage(file, size)
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 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)
local function wrapLink(text, target)
if text == "" then
return (text ~= '' and target and string.format('[[%s|%s]]', target, text) or text)
return ""
else
return string.format("[[%s|%s]]", target, text)
end
end
end
--------------------------------------------------------------------------------
-- Основная функция модуля
--------------------------------------------------------------------------------


function p.main(frame)
function p.main(frame)
-- Получаем аргументы шаблона
local args = getArgs(frame)
local argsRaw = getArgs(frame, { trim = false, removeBlanks = false })
local argsRaw = getArgs(frame, { trim = false, removeBlanks = false })
local args = {}
for k, v in pairs(argsRaw) do
if v ~= '' then
args[k] = v
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


-- Основные параметры
-- Если id найден в JsonPaths, префиксы проекта нужны
local id       = args[1] or ""
local hasId = (JsonPaths.has(id) == true)
local size    = args["size"] or "32px"
local projPrefix = hasId and JsonPaths.prefix() or ''
local prefix   = args[2] or ""
local projPrefixFile = hasId and JsonPaths.prefixFile() or ''
local vertical = argsRaw.vertical


-- Получаем данные о предмете через вызовы других модулей
-- Получение имени
local itemStack    = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "stack", id)
local nameStr = frame:preprocess(
local itemContained = invoke(frame, "Prototypes/Хранилище/Предмет", "main", "framing", "contained", id)
string.format('{{#invoke:Entity Lookup|getname|%s}}', 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 labelRaw = argsRaw.label or argsRaw.l
local label = rawLabel == nil and itemName or resolveArg(rawLabel, itemName)
local label = (labelRaw == nil and nameStr) or (labelRaw == '' and '' or labelRaw)
local linkRaw = argsRaw.link
local linkTgt = linkRaw == nil and '' or (linkRaw == '' and nameStr or linkRaw)


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


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


-- Обработка ссылки
local img = imgFile ~= '' and formatImage(imgFile, size, linkTgt) or ''
local rawLink = argsRaw.link
if argsRaw.imageTooltip then
local labelOutput = (rawLink ~= nil) and wrapLink(label, (rawLink == "" and itemName or rawLink)) or label
img = frame:preprocess(
string.format(
'{{#invoke:Entity Lookup|createimagetooltip|Файл:%s|%s|Мета=%s,link=}}',
imgFile, id, size
)
)
end


-- Формирование описания репозитория
-- Репозиторий
local repository = (argsRaw.repository == nil) and prefix or table.concat({ itemContained, itemSlot, itemChem }, " ")
local repoStr = ''
if isRepo then
local parts = {}
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
imagerepository = string.format(
table.insert(parts,
"<span style='display:inline-flex;flex-direction:column;align-items:center;'>%s<b>%s</b></span>",
string.format(
image, labelOutput
"<span style='display:inline-flex;flex-direction:column;align-items:center;'>%s<b>%s</b></span>",
img, labelOut
)
)
)
result = table.concat({ imagerepository, itemStack, prefix }, " ")
else
else
imagerepository = string.format("<span>%s%s</span>", image, repository)
table.insert(parts,
result = table.concat({ imagerepository, labelOutput, itemStack, prefix }, " ")
string.format(
"<span style='display:inline-block;'>%s%s</span>", img, repoStr
)
)
table.insert(parts, labelOut)
end
end


-- Если задан параметр wrapper, формируем 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(
-- Если vertical не задан, добавляем SideStyle=1
'{{#invoke:Prototypes/Хранилище/Предмет|main|framing|stack|%s}}', id
local sideStyle = (vertical ~= nil) and "" or "|SideStyle=1"
)
)
)
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, itemStack, prefix, repository, image, pixel, linkParam, sideStyle
local side = isVert and '' or '|горизонт_стиль=1'
))
local card = string.format(
'{{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
end


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


return p
return p

Текущая версия от 22:51, 24 марта 2026

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

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

local function trim(value)
	return mw.text.trim(value or '')
end

local function formatImage(file, size, link)
	return string.format('[[Файл:%s|%s|link=%s]]', file, size, link)
end

local function wrapLink(text, target)
	return (text ~= '' and target and string.format('[[%s|%s]]', target, text) or text)
end

function p.main(frame)
	local argsRaw = getArgs(frame, { trim = false, removeBlanks = false })
	local args = {}
	for k, v in pairs(argsRaw) do
		if v ~= '' then
			args[k] = v
		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

	-- Если id найден в JsonPaths, префиксы проекта нужны
	local hasId = (JsonPaths.has(id) == true)
	local projPrefix = hasId and JsonPaths.prefix() or ''
	local projPrefixFile = hasId and JsonPaths.prefixFile() or ''

	-- Получение имени
	local nameStr = frame:preprocess(
		string.format('{{#invoke:Entity Lookup|getname|%s}}', id)
	)

	-- Лейбл и ссылка
	local labelRaw = argsRaw.label or argsRaw.l
	local label = (labelRaw == nil and nameStr) or (labelRaw == '' and '' or labelRaw)
	local linkRaw = argsRaw.link
	local linkTgt = linkRaw == nil and '' or (linkRaw == '' and nameStr or linkRaw)

	if linkTgt ~= '' and projPrefix ~= '' then
		linkTgt = projPrefix .. linkTgt
	end

	local labelOut = (linkRaw ~= nil) and wrapLink(label, linkTgt) or label

	-- Изображение
	local imgFile = argsRaw.image or argsRaw.img or (id .. '.png')
	if imgFile ~= '' and projPrefixFile ~= '' then
		imgFile = projPrefixFile .. imgFile
	end

	local img = imgFile ~= '' and formatImage(imgFile, size, linkTgt) or ''
	if argsRaw.imageTooltip then
		img = frame:preprocess(
			string.format(
				'{{#invoke:Entity Lookup|createimagetooltip|Файл:%s|%s|Мета=%s,link=}}',
				imgFile, id, size
			)
		)
	end

	-- Репозиторий
	local repoStr = ''
	if isRepo then
		local parts = {}
		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 parts = {}
	if isVert then
		table.insert(parts,
			string.format(
				"<span style='display:inline-flex;flex-direction:column;align-items:center;'>%s<b>%s</b></span>",
				img, labelOut
			)
		)
	else
		table.insert(parts,
			string.format(
				"<span style='display:inline-block;'>%s%s</span>", img, repoStr
			)
		)
		table.insert(parts, labelOut)
	end

	-- Стек предметов
	table.insert(parts,
		frame:preprocess(
			string.format(
				'{{#invoke:Prototypes/Хранилище/Предмет|main|framing|stack|%s}}', id
			)
		)
	)
	table.insert(parts, prefix)

	-- Обёртка LinkCard
	if isWrap then
		local side = isVert and '' or '|горизонт_стиль=1'
		local card = string.format(
			'{{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('<span>' .. table.concat(parts, ' ') .. '</span>')
end

return p