Перейти к содержанию

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

Материал из LemonCraft Wiki
Нет описания правки
Нет описания правки
 
(не показаны 3 промежуточные версии этого же участника)
Строка 322: Строка 322:
class = 'class="' .. class .. '"'
class = 'class="' .. class .. '"'
end
end
local lclass = args["ярлык класс"] or ''
local lclass = args["ярлыккласс"] or ''
if lclass ~= '' then
if lclass ~= '' then
lclass = 'class="' .. lclass .. '"'
lclass = '|class="' .. lclass .. '"'
end
end
Строка 330: Строка 331:
return table.concat {
return table.concat {
"|-\n! ", mw.ustring.gsub(label, "^%l", mw.ustring.upper),
"|-\n! ", mw.ustring.gsub(label, "^%l", mw.ustring.upper),
"\n", lclass, "| ", class, " |\n",
"\n| ", class, " |1\n",
data
data
}
}

Текущая версия от 10:49, 24 апреля 2025

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

local p = {}

-- Создаёт карточку
function p.infobox(f)
	local args = f
	if f == mw.getCurrentFrame() then
		args = require( 'Модуль:ProcessArgs' ).merge( true )
	else
		f = mw.getCurrentFrame()
	end
	local titleObject = mw.title.getCurrentTitle()
	local title = args['название'] or titleObject.subpageText
	local subtitle = args["подзаголовок"] or ""
	local externalClass = args["класс"] or ""
	
	local titleArea = args["шапка"]
	if not titleArea then
		if subtitle == '' then
			titleArea = title
		else
			titleArea = title .. '<br><span class="infobox-subtitle">' .. subtitle .. '</span>'
		end
	end
	
	local mod = args["мод"]
	if mod then
		local mods = mw.loadData("Модуль:Модификации")
		mod = mods[mod] or mod
	end

	local imageArea = args["изображения"]
	if not imageArea then
		local images = {}
		local invImages = {}
		local defaultImageSize = args["умолчразмеризобр"] or '160px'
		local defaultImageClass = args["умолчклассизобр"]
		args["изображение1"] = args["изображение1"] or args["изображение"] or 'назв'
		args["изобр1описание"] = args["изобр1описание"] or args["изоброписание"]
		args["изобр1разм"]  = args["изобр1разм"] or args["изобрразм"]
		args["изобр1класс"]  = args["изобр1класс"] or args["изобркласс"]
		args["инвизображение1"] = args["инвизображение1"] or args["инвизображение"] or 'назв'
		args['группа1'] = args['группа1'] or args['группа']
		args['групп1разм'] = args['групп1разм'] or args['группразм']
		args['групп1класс'] = args['групп1класс'] or args['группкласс']
		args['групп1описание'] = args['групп1описание'] or args['группописание'] or ''
		
		local imgCount = {}
		local invImgCount = {}
		local groupCount = {}
		local groupImgList = {}
		for k, v in pairs( args ) do
			if type( k ) == "string" and k ~= "ряды" then
				local image, num = mw.ustring.match(k, '^(изображение)(%d+)$' )
				local invImage, invNum = mw.ustring.match(k, '^(инвизображение)(%d+)$' )
				local group, groupNum = mw.ustring.match(k, '^(группа)(%d+)$' )
				local groupImg, groupImgNum = mw.ustring.match(k, '^(%d+)-(%d+)$' )
				if mw.ustring.lower(v) ~= 'нет' then
					if image then
						table.insert( imgCount, tonumber( num ) )
					elseif invImage then
						table.insert( invImgCount, tonumber( invNum ) )
					elseif group then
						table.insert( groupCount, tonumber( groupNum ) )
						if not groupImgList['группа' .. groupNum] then
							groupImgList['группа' .. groupNum] = {}
						end
					elseif groupImg then
						if not groupImgList['группа' .. groupImg] then
							groupImgList['группа' .. groupImg] = {}
						end
						table.insert( groupImgList['группа' .. groupImg], tonumber( groupImgNum ) )
					end
				end
			end
		end
		
		local animate
		if #groupCount > 0 then
			table.sort( groupCount )
			local tabber = {}
			for k, v in ipairs( groupCount ) do
				local group = args['группа' .. v]
				local groupSize = args['групп' .. v .. 'разм'] or defaultImageSize
				local groupClass = args['групп' .. v .. 'класс'] or defaultImageClass
				local groupCaption = args['групп' .. v .. 'описание'] or ''
				local groupImages = {}
				
				table.sort( groupImgList['группа' .. v] )
				for _, w in ipairs( groupImgList['группа' .. v] ) do
					local image = args[v .. '-' .. w]
					local size = args[v .. '-' .. w .. 'разм'] or args['*-' .. w .. 'разм'] or groupSize
					local class = args[v .. '-' .. w .. 'класс'] or args['*-' .. w .. 'класс'] or groupClass
					local caption = args[v .. '-' .. w .. 'описание'] or args['*-' .. w .. 'описание'] or ''
					
					if image:match( ';' ) then
						if not animate then
							animate = require( 'Модуль:Анимация' ).animate
						end
						image = animate{ image, size, nil, class }
					else
						image = '[[Файл:' .. image .. '|' .. size .. '|class=' .. ( class or '' ) .. ']]'
					end
					
					if caption ~= '' then
						caption = '<div class="infobox-imagecaption">\n' .. caption .. '\n</div>'
					end
					
					table.insert( groupImages, '<div>' .. image .. caption .. '</div>' )
				end

				if groupCaption ~= '' then
					groupCaption = '<div class="infobox-imagecaption">\n' .. groupCaption .. '\n</div>'
				end
				
				table.insert( tabber, '|-|' .. group .. '=\n' .. table.concat( groupImages, '\n' ) .. groupCaption )
			end
			table.insert( images, '<div>' .. f:extensionTag( 'tabber', table.concat( tabber, '\n' ) ) .. '</div>' )
		end
		
		table.sort( imgCount )
		local animate
		for k, v in ipairs( imgCount ) do
			local image = args['изображение' .. v]
			local size = args['изобр' .. v .. 'разм'] or defaultImageSize
			local class = args['изобр' .. v .. 'класс'] or defaultImageClass
			local caption = args['изобр' .. v .. 'описание']
			
			if mw.ustring.lower(image) == 'назв' or image == 'title' then
				local filename
				if mod then
					filename = title .. ' (' .. mod .. ').png'
				elseif titleObject.isSubpage then
					filename = title .. ' (' .. titleObject.baseText .. ').png'
				else
					filename = title .. '.png'
				end
				local imageTitle = mw.title.new( 'Файл:' .. filename )
				if imageTitle and imageTitle.exists then
					image = '[[Файл:' .. filename .. '|' .. size .. '|class=' .. (class or '') .. ']]'
				elseif titleObject.namespace == 0 then
					image = '[[Файл:No image.svg|' .. size .. '|link=Файл:' .. filename .. '|Загрузить ' .. filename .. ']]'
				else
					image = '[[Файл:No image.svg|' .. size .. '|link=|Изображение отсутствует]]'
				end
			elseif image:match(';') then
				if not animate then
					animate = require( 'Модуль:Анимация' ).animate
				end
				image = animate{ image, size, nil, class }
			else
				image = '[[Файл:' .. image .. '|' .. size .. '|class=' .. (class or '') .. ']]'
			end
			
			if caption and mw.ustring.lower(caption) ~= 'нет' then
				caption = '<div class="infobox-imagecaption">' .. caption .. '</div>'
			else
				caption = ''
			end
			
			table.insert( images, '<div>' .. image .. caption .. '</div>' )
		end
		images = table.concat( images, '\n' )
		
		if #invImgCount > 0 then
			table.sort( invImgCount )
			local grid
			for k, v in ipairs( invImgCount ) do
				local image = args['инвизображение' .. v]
				if mw.ustring.lower(image) == 'назв' or image == 'title' then
					local imageExists
					if mod then
						local tryLoadData = require([[Модуль:Специальные утилиты]]).tryLoadData
						local modInvIds = tryLoadData([[Модуль:ИнвСпрайт/]] .. mod)
						local modAliases = tryLoadData([[Модуль:Инвентарный слот/Псевдонимы/]] .. mod)
						if modAliases and modAliases[title] or modInvIds and modInvIds["IDы"][title] then
							imageExists = true
						else
							local imageTitle = mw.title.new('Файл:Grid ' .. title .. ' (' .. mod .. ').png')
							imageExists = imageTitle and imageTitle.exists
						end
					else
						local invEnglish = mw.loadData([[Модуль:Инвентарный слот/Англоязычные названия]])
						local invIds = mw.loadData( [[Модуль:ИнвСпрайт]] )["IDы"]
						local invAliases = mw.loadData([[Модуль:Инвентарный слот/Псевдонимы]])
						if invAliases[title] or invEnglish[title] or invIds[title] then
							imageExists = true
						else
							local imageTitle = mw.title.new( 'Файл:Grid ' .. title .. '.png' )
							mw.log(imageTitle)
							imageExists = imageTitle and imageTitle.exists
						end
					end
					if imageExists then
						image = title
					else
						image = false
					end
				end
				
				if image == '----' then
					table.insert( invImages, '</div><div style="padding-top:.5em">' )
				elseif image then
					if not grid then
						grid = require( 'Модуль:Инвентарный слот' ).slot
					end
					table.insert( invImages, grid{ image, ['ссылка'] = 'нет', ['мод'] = mod } )
				end
			end
			
			if grid and #invImages > 0 then
				invImages = '<div class="infobox-invimages"><div>' .. table.concat( invImages, '' ) .. '</div></div>'
			else
				invImages = ''
			end
		else
			invImages = ''
		end
		
		if images ~= '' or invImages ~= '' then
			imageArea = images .. '\n' .. invImages
		else
			imageArea = 'нет'
		end
	end
	if imageArea and mw.ustring.lower(imageArea) ~= 'нет' then
		imageArea = '<div class="infobox-imagearea">' .. imageArea .. '</div>'
	else
		imageArea = ''
	end
	
	local extraText = args["доптекст"]
	if extraText and mw.ustring.lower(extraText) ~= 'нет' then
		extraText = '<div class="infobox-extratext">' .. extraText .. '</div>'
	else
		extraText = ''
	end
	
	local serverIcon = args['иконка'] or 'нет'
	if serverIcon and mw.ustring.lower(serverIcon) ~= 'нет' then
		local size = '32px';
		local filename = title .. '_Icon.png'
		local imageTitle = mw.title.new( 'Файл:' .. filename )
		if imageTitle and imageTitle.exists then
			serverIconImage = '[[Файл:' .. filename .. '|' .. size .. '|class=' .. (class or '') .. ']]'
		elseif titleObject.namespace == 0 then
			serverIconImage = '[[Файл:No image.svg|' .. size .. '|link=Файл:' .. filename .. '|Загрузить ' .. filename .. ']]'
		else
			serverIconImage = '[[Файл:No image.svg|' .. size .. '|link=|Изображение отсутствует]]'
		end
		
		if caption and mw.ustring.lower(caption) ~= 'нет' then
			caption = '<div class="infobox-imagecaption">' .. caption .. '</div>'
		else
			caption = ''
		end
		
		serverIcon = '<div class="infobox-servericon">' .. serverIconImage .. '</div>';
	else
		serverIcon = ''
	end
	
	local imageAreaExpanded = imageArea .. '' .. serverIcon .. '' .. extraText
	
	local footer = args["подвал"]
	if footer then
		footer = '| class="infobox-footer" colspan="2" | ' .. footer
	end

	local styles = { args["стиль"] }
	local width = args["ширина"]
	if width then
		if not width:match("px$") then
			-- временно, для совместимости
			width = width .. 'px'
		end
		styles[#styles+1] = "width:" .. width
	end
	local style = ""
	if #styles > 0 then
		style = ' style="' .. table.concat(styles, ";") .. '"'
	end
	
	local rows = args["ряды"] or ''
	if type(rows) == "table" then
		local sRows = {}
		for _, row in ipairs(rows) do
			table.insert(sRows, row["заголовок"] and p.header(row) or p.row(row))
		end
		rows = table.concat(sRows, '\n')
	end
	
	local html = {
		'<div class="infobox notaninfobox '.. externalClass ..'"' .. style .. '>',
			'<div class="infobox-title">' .. titleArea .. '</div>',
			imageAreaExpanded,
			'{| class="infobox-rows" cellspacing="1" cellpadding="4"',
			'|-',
			rows,
			footer or '',
			'|}',
		'</div>'
	}
	
	if args["цвет"] then
		table.insert(html, "[[Категория:Страницы с вызовом устаревших параметров]]")
	end
	
	return table.concat( html, '\n' )
end

-- Создаёт ряд карточки. Предназначена для использования только в модулях
-- В шаблонах используйте {{Ряд карточки}}
function p.row(args)
	local label = args[1] or args["ярлык"]
	local data = args[2] or args["поле"]
	if not data then
		data = label
		label = nil
	end
	local class = args["класс"] or ''
	if class ~= '' then
		class = 'class="' .. class .. '"'
	end
	
	local lclass = args["ярлыккласс"] or ''
	if lclass ~= '' then
		lclass = '|class="' .. lclass .. '"'
	end
	
	if label then
		return table.concat {
			"|-\n! ", mw.ustring.gsub(label, "^%l", mw.ustring.upper),
			"\n| ", class, " |1\n",
			data
		}
	else
		return table.concat {
			"| ", class, " colspan=2 |\n",
			data
		}
	end
end

-- Создаёт заголовок карточки. Предназначена для использования только в модулях
-- В шаблонах используйте {{Заголовок карточки}}
function p.header(args)
	local header = args[1] or args["заголовок"]
	
	-- Стили строки
	local collapsible = ""
	if args["складываемый"] then
		collapsible = " collapsible" .. (args["сложить"] and " collapsed" or "")
	end
	
	-- Стили столбца
	local class = args["класс"] or "infobox-title"
	local style = args["стиль"] or ""
	if style ~= '' then
		style = 'style="' .. style .. '"'
	end
	
	return table.concat {
		'|- class="collapsible-rows', collapsible,
		'"\n| colspan=2 class="infobox-header ', class, '" |\n',
		header
	}
end

return p