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

Материал из Space Station 14 Вики
мНет описания правки
Нет описания правки
 
(не показано 18 промежуточных версий этого же участника)
Строка 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]]", 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
end
return defaultValue
 
elseif input == "" then
local function wrapLink(text, target)
return ""
return (text ~= '' and target and string.format('[[%s|%s]]', target, text) or text)
else
return input
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 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 id = args[1] or ""
-- Лейбл и ссылка
local size = args["size"] or "32px"
local labelRaw = argsRaw.label or argsRaw.l
local prefix = args[2] or ""
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 function invoke(module, method, subMethod, extra, id)
linkTgt = projPrefix .. linkTgt
return frame:preprocess(string.format("{{#invoke:%s|%s|%s|%s|%s}}", module, method, subMethod, extra, id))
end
end


local itemStack    = invoke("Prototypes/Хранилище/Предмет", "main", "framing", "stack", id)
local labelOut = (linkRaw ~= nil) and wrapLink(label, linkTgt) or label
local itemContained = invoke("Prototypes/Хранилище/Предмет", "main", "framing", "contained", id)
local itemSlot      = invoke("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 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)
else
image = resolveArg(formatImage(rawImage, size), formatImage(id .. ".png", size))
end
end


-- Обработка Tooltip. Если указан imageTooltip, переопределяем image
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}}", id, id, size))
string.format(
'{{#invoke:Entity Lookup|createimagetooltip|Файл:%s|%s|Мета=%s,link=}}',
imgFile, id, size
)
)
end
end


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


-- Формирование описания репозитория
-- Основная сборка
local repository = ""
local parts = {}
if argsRaw.repository == nil then
if isVert then
repository = prefix
table.insert(parts,
string.format(
"<span style='display:inline-flex;flex-direction:column;align-items:center;'>%s<b>%s</b></span>",
img, labelOut
)
)
else
else
repository = table.concat({ itemContained, itemSlot, itemChem }, " ")
table.insert(parts,
string.format(
"<span style='display:inline-block;'>%s%s</span>", img, repoStr
)
)
table.insert(parts, labelOut)
end
end


-- Формирование итогового результата
-- Стек предметов
local imagerepository = "<span>".. image .. repository.."</span>"
table.insert(parts,
local result = table.concat({ imagerepository, labelOutput, itemStack, prefix }, " ")
frame:preprocess(
string.format(
'{{#invoke:Prototypes/Хранилище/Предмет|main|framing|stack|%s}}', id
)
)
)
table.insert(parts, prefix)


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


return frame:preprocess("<span>" .. result .. "</span>")
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