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

Материал из Playzone Minecraft Wiki
Перейти к: навигация, поиск
 
м (1 версия импортирована)
 
(нет различий)

Текущая версия на 01:27, 18 января 2017

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

-------------------------------------------------------------------
--- Модуль для отображения инвентарных слотов в Minecraft Wiki.
-------------------------------------------------------------------

local p = {}

-- Список приставок к названиям, обрабатываемых другими модулями.
-- Так будет легче, например, убирать их из целей ссылок.
-- ВНИМАНИЕ: указывайте все варианты склонения по родам и числам.
p.prefixes = {
	'Любой', 'Любая', 'Любое', 'Любые',
	'Повреждённый', 'Повреждённая', 'Повреждённое', 'Повреждённые' -- использование Ё обязательно
}

--- Создание слота
function p.slot(f)
	--- Получение аргументов
	local args = f.args or f
	if f == mw.getCurrentFrame() and args[1] == nil then
		args = f:getParent().args
	end
	
	-- Первый аргумент
	args[1] = mw.text.trim(args[1] or '')
	
	--- Псевдонимы
	-- Вы можете закомментировать следующую строку, если не используете псевдонимы
	local aliases = mw.loadData('Модуль:Инвентарный слот/Псевдонимы')
	
	local modAliases = args["модпсевдонимы"] or ''
	if modAliases ~= '' then
		modAliases = mw.loadData('Модуль:' .. modAliases)
	else
		modAliases = nil
	end
	
	if aliases or modAliases then
		local frames = {}
		for frame in mw.text.gsplit( args[1], '%s*;%s*' ) do
			local frameParts = p.getParts( frame, args["мод"] )
			
			local id = frameParts.name
			if frameParts.mod then
				id = frameParts.mod .. ':' .. id
			end
			
			local alias
			if modAliases and modAliases[id] then
				alias = modAliases[id]
			elseif aliases and aliases[id] then
				alias = aliases[id]
			end
			
			if alias then
				table.insert( frames, p.expandAlias( frameParts, alias ) )
			else
				table.insert( frames, frame )
			end
		end
		
		args[1] = table.concat( frames, ';' )
	end
	
	--- Построение спрайта
	
	-- Параметры
	local sprite
	local ids = mw.loadData([[Модуль:ИнвСпрайт/ID]])["IDы"]
	local modIds = {}
	local back_modIds = {}
	local animated = mw.ustring.find(args[1], ';')
	local pageName = mw.title.getCurrentTitle().text
	local imgClass = args["классизобр"]
	local numStyle = args["стильцифр"]
	
	local body = mw.html.create('span'):css{['vertical-align'] = args["выравн"]}
	
	if animated then
		body:addClass('animated')
	end
	if args["класс"] then
		body:addClass(args["класс"])
	end
		body:addClass('invslot')
	if args["стиль"] then
		body:cssText(args["стиль"])
	end
	
	if (args["умолчание"] or '') ~= '' then
		body:css('background-image', '{{FileUrl|' .. args["умолчание"] .. '.png}}')
	end

    ---спрайты для фона
    local myresult = {}
    table.insert(myresult, '<span>0</span>')
	if (args["умолчаниеCSS"] or '') ~= '' then
        table.insert(myresult, '<span>1</span>')
        local mod=args["Мод"]
		if mod then
            table.insert(myresult, '<span>2</span>')
			local back_modData = back_modIds[mod]
			if not back_modData and mw.title.new('Модуль:ФоновыйСпрайт/' .. mod .. '/ID').exists then
                table.insert(myresult, '<span>3</span>')
				back_modData = mw.loadData('Модуль:ФоновыйСпрайт/' .. mod .. '/ID')
				back_modIds[mod] = back_modData
                local n=mw.text.trim(args["умолчаниеCSS"])
                table.insert(myresult, back_modData[n])
			end
			param = mw.loadData('Модуль:ФоновыйСпрайт/' .. mod)
			---local pos = back_modData["умолчаниеCSS"]
            
            pos=0
			local size = param["разм"]
			local tiles = param["формат"] / size
			local left = pos % tiles * size
			local top = math.floor( pos / tiles ) * size
	
			body:css('background-image', '{{FileUrl|' .. mod .. 'bkgrdCSS.png}}')
			body:css('background-size', 'auto')
			body:css('background-position', '-' .. left .. 'px -' .. top ..'px')
		end		
	end
	
	--- Обработка фреймов
	local first = true
	for frame in mw.text.gsplit(args[1], '%s*;%s*') do
		local item
		if frame ~= '' or frame == '' and animated then
			item = body:tag('span'):addClass('invslot-item')
			if imgClass then
				item:addClass(imgClass)
			end
		end
		
        table.insert(myresult, '<span>' .. frame .. '</span>')
		if frame == '' then
			(item or body):tag('br')
		else
			local category
			local parts = p.getParts(frame, args["мод"])
			local title = parts.title or mw.text.trim(args["назв"] or '')
			local mod = parts.mod
			local name = parts.name
			local num = parts.num
			local description = parts.text
			
			local img, idData
			if mod then
				local modData = modIds[mod]
				if not modData and mw.title.new('Модуль:ИнвСпрайт/' .. mod .. '/ID').exists then
					modData = mw.loadData('Модуль:ИнвСпрайт/' .. mod .. '/ID')["IDы"]
					modIds[mod] = modData
				end
				if modData and modData[name] then
					idData = modData[name]
				else
					img = name .. ' (' .. mod .. ')'
				end
			elseif ids[name] then
				idData = ids[name]
			else
				img = name
			end
			
			local link = args["ссылка"] or ''
			if link == '' then
				if mod then
					link = mod .. '/' .. name
				else
					link = mw.ustring.gsub(name, '^Повреждённ[ыао][йяе] ', '')
				end
			elseif mw.ustring.lower(link) == 'нет' then
				link = nil
			end
			if link == pageName then
				link = nil
			end
			
			local formattedTitle
			local plainTitle
			if title == '' then
				plainTitle = name
			elseif mw.ustring.lower(title) ~= 'нет' then
				plainTitle = mw.ustring.gsub(mw.ustring.gsub(title, '\\\\', '&#92;'), '\\&', '&#38;')
				
				local formatPattern = '&[0-9a-fk-or]'
				if mw.ustring.match(plainTitle, formatPattern) then
					formattedTitle = title
					plainTitle = mw.ustring.gsub(plainTitle, formatPattern, '')
				end
				
				if plainTitle == '' then
					plainTitle = name
				else
					plainTitle =  mw.ustring.gsub(mw.ustring.gsub(plainTitle, '&#92;', '\\'), '&#38;', '&')
				end
			elseif link then
				if img then
					formattedTitle = ''
				else
					plainTitle = ''
				end
			end
			
			item:attr{
				['data-minetip-title'] = formattedTitle,
				['data-minetip-text'] = description
			}
			
			if img then
				-- & is re-escaped because mw.html treats attributes
				-- as plain text, but MediaWiki doesn't
				local escapedTitle = ( plainTitle or '' ):gsub( '&', '&#38;' )
				item:addClass('invslot-item-image')
					:wikitext('[[Файл:Grid ', img, '.png|32x32px|link=', link or '', '|', escapedTitle, ']]')
			else
				if not sprite then
					sprite = require([[Модуль:Спрайт]]).sprite
				end
				local image
				if mod then
					image = (args["таблспрайтов"] or mod or "Inv") .. 'CSS.png'
				end
				if link then
					item:wikitext('[[', link, '|')
				end

				local image, spriteCat;
				if not mod then
				    image, spriteCat = sprite{
					    ["данныеID"] = idData, ["назв"] = plainTitle,
					    ["изобр"] = image, ["настройки"] = 'ИнвСпрайт'
					    }
				else 
				    image, spriteCat = sprite{
					    ["данныеID"] = idData, ["назв"] = plainTitle,
					    ["изобр"] = image, ["настройки"] = 'ИнвСпрайт/' .. mod
					    }
				end
				item:node(image)
				category = spriteCat
			end
			
			if num and num > 1 and num < 1000 then
				if img and link then
					item:wikitext('[[', link, '|')
				end
				local number = item
					:tag('span')
						:addClass('invslot-stacksize')
						:attr{title = plainTitle}
						:wikitext(num)
				if numStyle then
					number:cssText(numStyle)
				end
				if img and link then
					item:wikitext(']]')
				end
			end
			
			if idData and link then
				item:wikitext(']]')
			end
			
			item:wikitext(category)
		end
		
		if first then
			if animated and item then
				item:addClass('active')
			end
			first = false
		end
	end
	
	return table.concat( myresult )
end

function p.expandAlias( frameParts, alias )
	-- If the frame has no parts, we can just return the alias as-is
	--[[if not frameParts.title and not frameParts.mod and not frameParts.num and not frameParts.text then
		return alias
	end--]]
	
	local expandedFrames = {}
	for aliasFrame in mw.text.gsplit(alias, '%s*;%s*') do
		local aliasParts = p.getParts(aliasFrame)
		aliasParts.title = frameParts.title or aliasParts.title or ''
		aliasParts.mod = frameParts.mod or aliasParts.mod or 'Minecraft'
		aliasParts.num = frameParts.num or aliasParts.num or ''
		aliasParts.text = frameParts.text or aliasParts.text or ''
		
		table.insert(expandedFrames, mw.ustring.format(
			'[%s]%s:%s,%s[%s]',
			aliasParts.title, aliasParts.mod, aliasParts.name, aliasParts.num, aliasParts.text
		))
	end
	
	return table.concat(expandedFrames, ';')
end


function p.getParts(frame, mod)
----Функция получает название предмета в формате "[титл]мод:имя[текст],число"
----parts.title = титл, название предмета при наведении
----parts.mod = мод
----parts.name = имя
----parts.text = текст, дополнительный текст при наведении на предмет
----parts.num = число

	local parts = {}
	parts.title = mw.ustring.match(frame, '^%[%s*([^%]]+)%s*%]')
	
    local modPattern
    if mw.ustring.match(frame, '^%[.*%]([a-zA-Zа-яА-Я0-9 _-]+):') then
    modPattern = '^%[.*%]([a-zA-Zа-яА-Я0-9 _-]+):'
    else
    modPattern = '^([a-zA-Zа-яА-Я0-9 _-]+):'
    end

	parts.mod = mw.text.trim(mw.ustring.match(frame, modPattern) or mod or '') ---- Получаем название мода
	
	local vanilla = {v = 1, vanilla = 1, mc = 1, minecraft = 1}
	if parts.mod == '' or vanilla[mw.ustring.lower(parts.mod)] then
		parts.mod = nil
	end

	local _, nameStartV = mw.ustring.find( frame, '^%[[^%]]*%]' )
	local nameStart = ( ({mw.ustring.find( frame, modPattern )})[2] or nameStartV or 0 ) + 1
	if nameStart - 1 == #frame then
		nameStart = 1
	end
	parts.name = mw.text.trim( mw.ustring.sub( frame, nameStart, ( mw.ustring.find( frame, '[,%[]', nameStart ) or 0 ) - 1 ) )
	
	parts.num = math.floor(mw.ustring.match(frame, ',%s*(%d+)') or 0)
	if parts.num == 0 then
		parts.num = nil
	end
	
	parts.text = mw.ustring.match(frame, '%[%s*([^%]]+)%s*%]$')
	
	return parts
end
 
return p