Модуль:Песочница/Seryo93/Infobox military conflict

Поделись знанием:
< Модуль:Песочница
Это текущая версия страницы, сохранённая Seryo93 (обсуждение | вклад) в 08:55, 30 октября 2016. Вы просматриваете постоянную ссылку на эту версию.

(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

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

require('Module:No globals')

local IMCframe

local infoboxStyle = {
	header_raw = 'background-color:lightsteelblue;text-align:center;',
	sub_header_raw = 'background-color:#DDDDDD;text-align:center;font-style:oblique;',
	image_box_raw = 'text-align:center;',
	internal_border = '1px dotted #aaa;',
	section_border = '1px solid #aaa;'
}

infoboxStyle.header_bar = 'style="' .. infoboxStyle.header_raw .. '"'
infoboxStyle.sub_header_bar = 'style="' .. infoboxStyle.sub_header_raw .. '"'
infoboxStyle.image_box = 'style="' .. infoboxStyle.image_box_raw .. '"'

local IsMultipart = false

local commonsTemplateWikitext

local IMC = {}
IMC.__index = IMC

function IMC:renderPerCombatant(builder, headerText, prefix, suffix)
	    prefix = prefix or ''
        --end
	suffix = suffix or ''
	local colspans = {}
	
	-- This may result in colspans[1] getting set twice, but
	-- this is no big deal. The second set will be correct.
	local lastCombatant = 1
	
	for i = 1,self.combatants do
		if self.args[prefix .. i .. suffix] then
			colspans[lastCombatant] = i - lastCombatant
			lastCombatant = i
		end
	end

	local jointText = self.args[prefix .. (self.combatants + 1) .. suffix]
	
	if headerText and (colspans[1] or jointText) then
		builder:tag('tr')
			:tag('th')
				:attr('colspan', self.combatants)
				:cssText(infoboxStyle.header_raw)
				:wikitext(headerText)
	end

	-- The only time colspans[1] wouldn't be set is if no
	-- combatant has a field with the given prefix and suffix.
	if colspans[1] then
		-- Since each found argument set the colspan for the previous
		-- one, the final one wasn't set above, so set it now.
		colspans[lastCombatant] = self.combatants - lastCombatant + 1
		builder = builder:tag('tr')
		for i = 1,self.combatants do
			-- At this point, colspans[i] will be set for i=1 unconditionally, and for
			-- any other value of i where self.args[prefix .. i .. suffix] is set.
			if colspans[i] then
				builder:tag('td')
					-- don't bother emitting colspan="1"
					:attr('colspan', colspans[i] ~= 1 and colspans[i] or nil)
					:css('width', math.floor(100 / self.combatants * colspans[i] + 0.5) .. '%')
					-- no border on the right of the rightmost column
					:css('border-right', i ~= lastCombatant and infoboxStyle.internal_border or nil)
					-- no padding on the left of the leftmost column
					:css('padding-left', i ~= 1 and '0.25em' or nil)
					-- don't show the border if we're directly under a header
					:css('border-top', not headerText and infoboxStyle.internal_border or nil)
					:newline()
					:wikitext(self.args[prefix .. i .. suffix])
			end
		end
	end

	if jointText then
		builder:tag('tr')
			:tag('td')
				:attr('colspan', self.combatants)
				:css('text-align', 'center')
				-- don't show the border if we're directly under a header
				:css('border-top', (not headerText or colspans[1]) and infoboxStyle.internal_border or nil)
				:newline()
				:wikitext(jointText)
	end
end

function IMC:renderCombatantsSubtable(builder)
	
	builder = builder:tag('table')
		:css('width', '100%')
		:css('margin', 0)
		:css('padding', 0)
		:css('border', 0)

	self:renderPerCombatant(builder, self.args.combatants_header or 'Противники', 'combatant')
	-- can be un-hardcoded once gerrit:165108 is merged
	for _,v in ipairs{'a','b','c','d'} do
		self:renderPerCombatant(builder, nil, 'combatant', v)
	end
	
	self:renderPerCombatant(builder, 'Командующие', 'commander')
	if IsMultipart == false then
		for _,v in ipairs{'a','b','c','d'} do
			self:renderPerCombatant(builder, nil, 'commander', v)
		end
	end
	self:renderPerCombatant(builder, 'Силы сторон', 'strength')
	if IsMultipart == false then
		for _,v in ipairs{'a','b','c','d'} do
			self:renderPerCombatant(builder, nil, 'strength', v)
		end
	end
	self:renderPerCombatant(builder, 'Потери', 'casualties')
	if IsMultipart == false then
		for _,v in ipairs{'a','b','c','d'} do
			self:renderPerCombatant(builder, nil, 'casualties', v)
		end
	end
	builder:done():done()
end

function IMC:render()
	local builder = mw.html.create()
	if self.args.campaignbox then
		builder = builder:tag('table')
			:css('float', 'right')
			:css('clear', 'right')
			:css('background', 'transparent')
			:css('margin', 0)
			:css('padding', 0)
			:tag('tr'):tag('td')
	end
	builder = builder:tag('table')
		:addClass('infobox vevent')

	builder:tag('tr')
		:tag('th')
			:addClass('summary')
			:attr('colspan', '2')
			:cssText(infoboxStyle.header_raw)
			:wikitext(self.args['конфликт'] or self.args.conflict or mw.title.getCurrentTitle().text)
	if self.args.partof or self.args['часть'] then
		builder:tag('tr')
			:tag('td')
				:attr('colspan', '2')
				:cssText(infoboxStyle.sub_header_raw)
				:wikitext('Основной конфликт&#58;' .. (self.args.partof or self.args['часть']))
	end
	if self.args.image or self.args['изображение'] then
		builder:tag('tr')
			:tag('td')
				attr('colspan', 2)
				:cssText(infoboxStyle.image_box_raw)
				:wikitext(IMCframe:expandTemplate{ title = 'Форматирование изображения', args = { (self.args.image or self.args['изображение']), '300px'} })
				:newline()
				:wikitext(self.args.caption or self.args['подпись'])
	end
	
	
	if self.args.date or self.args['дата'] then
		builder:tag('tr')
			:tag('th')
				:css('padding-right', '1em')
				:wikitext('Дата')
			:done()
			:tag('td')
				:newline()
                :wikitext(self.args['дата'] or self.args.date)
	end
    if self.args['место'] or self.args.place then
	builder = builder:tag('tr')
		:tag('th')
			:css('padding-right', '1em')
			:wikitext('Место')
		:done()
		:tag('td')
			:tag('span')
				:addClass('location')
				:newline()
				:wikitext(self.args['место'] or self.args.place)
			:done()
    end
	if self.args['координаты'] or self.args.coordinates then
		builder:wikitext('<br />' .. self.args.coordinates)
	end
	if self.args.casus or self.args['причина'] then
		builder:tag('tr')
			:tag('th')
				:css('padding-right', '1em')
				:wikitext('Причина')
			:done()
			:tag('td')
				:newline()
                :wikitext(self.args.casus or self.args['причина'])
	end
	builder = builder:done():done()
	
	if self.args['статус'] or self.args.status or self.args['итог'] or self.args.result then
		builder:tag('tr')
			:tag('th')
				:css('padding-right', '1em')
				:newline()
				:wikitext((self.args['статус'] or self.args.status) and 'Статус' or 'Итог')
			:done()
			:tag('td')
				:newline()
				:wikitext(self.args['статус'] or self.args.status or self.args['итог'] or self.args.result)
	end

	if self.args['изменения'] or self.args.territory then
		builder:tag('tr')
			:tag('th')
				:css('padding-right', '1em')
				:wikitext('Изменения')
			:done()
			:tag('td')
				:newline()
				:wikitext(self.args.territory or self.args['изменения'])
	end
	self:renderCombatantsSubtable(builder:tag('tr'):tag('td'):attr('width', '100%'):attr('colspan', '2'):attr('cellpadding','0'):attr('cellspacing', '0'):cssText('width: 100%; border-spacing: 0; border-collapse: collapse; padding: 0;'))
	
	if self.args['overall_casualties'] or self.args['общие_потери'] then
		builder:tag('tr')
			:tag('th')
			    :addClass('summary')
				:attr('colspan', '2')
				:cssText(infoboxStyle.header_raw)
				:wikitext("Общие потери")
			:tag('tr')
			:tag('td')
				:attr('colspan', '2')
				:newline()
				:wikitext(self.args['overall_casualties'] or self.args['общие_потери'])
	end
		builder:tag('tr')
			:tag('td')
				:attr('colspan', '2')
				:css('border-top', infoboxStyle.internal_border)
				:wikitext(IMCframe:expandTemplate{title  = 'примечания', args = { '', 'height', group='~' }})
	if not (commonsTemplateWikitext ==('' or nil)) then
		builder:tag('tr')
			:tag('td')
				:attr('colspan', '2')
				--:css('border-top', infoboxStyle.internal_border)
				:css('background', '#dddddd')
                :css('text-align', 'center')
				:wikitext(commonsTemplateWikitext)
	end
	builder = builder:done()
	return builder
end

function IMC.new(frame, args)
	if not args then
		args = require('Module:Arguments').getArgs(frame, {wrappers = {'Template:Вооружённый конфликт', 'Template:Вооружённый конфликт/temp'}})
	end
	local obj = {
		frame = frame,
		args = args
	}
	
	IMCframe = frame
    
    if (args.multipart or args['многосторонний']) == ('1' or 'да' or 'true' or 'yes') then
    	IsMultipart = true
    end
	
	commonsTemplateWikitext = frame:expandTemplate{ title = 'commonslink2', args = { args['викисклад'], 'Аудио, фото, видео', icon_size = '12px' } }

	-- until gerrit:165108 is merged, there's still a cap on combatants, but as soon as it merges, we can update this little bit of code to uncap it
	-- also, don't try to make this more efficient, or references could be in the wrong order
	obj.combatants = 2
	for _,v in ipairs{'', 'a', 'b', 'c', 'd', 'а', 'б', 'в', 'г'} do
		for i = 1,5 do
		-- русификация динамических параметров (combatantXY↔противникXY)
			if args['противник' .. i .. v] then args['combatant' .. i .. v] = args['противник' .. i .. v] end
			if args['командир' .. i .. v] then args['commander' .. i .. v] = args['командир' .. i .. v] end
			if args['силы' .. i .. v] then args['strength' .. i .. v] = args['силы' .. i .. v] end
			if args['потери' .. i .. v] then args['casualties' .. i .. v] = args['потери' .. i .. v] end
			for _,p in ipairs{'combatant', 'commander', 'strength', 'casualties'} do
				if IsMultipart == true then
					-- русификация динамических параметров (parameter1b↔параметр1б)
					if args[p .. i .. 'а'] then args[p .. i .. 'a'] = args[p .. i .. 'а'] end
					if args[p .. i .. 'б'] then args[p .. i .. 'b'] = args[p .. i .. 'б'] end
					if args[p .. i .. 'в'] then args[p.. i .. 'c'] = args[p .. i .. 'в'] end
					if args[p .. i .. 'г'] then args[p .. i .. 'd'] = args[p .. i .. 'г'] end
				else
					args[p..'1a'] = args[p..'3']
					args[p..'2a'] = args[p..'4']						
				end
			end
		-- счёт противников
				if IsMultipart == true then
					if args['combatant' .. i .. v]  then
						obj.combatants = math.max(obj.combatants, i)
					end
				end
			end
		end
		if IsMultipart == false then
			args.combatant1b, args.combatant1c, args.combatant3, args.combatant4, args.combatant5, args.commander3, args.commander4, args.commander5, args.casualties3, args.casualties4, args.casualties5 = nil
		end

	return setmetatable(obj, IMC)
end

local p = {}

function p.main(frame)
	return IMC.new(frame):render()
end

return p