Module:Sandbox/BrandonXLF/3

This is an old revision of this page, as edited by BrandonXLF (talk | contribs) at 05:10, 23 July 2022. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

-- Sandbox, do not delete

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

local function getCountry(country)
	local title = mw.title.new(country)
	
	if not title or not title.exists then
		return country
	end
	
	return '[[' .. country .. ']]'
end

local function getTimespan(timespan)
	return ' (' .. timespan .. ')'
end

local function getImage(image)
	local file = nil

	if string.match(image, ".-%.") then
		file = mw.getCurrentFrame():expandTemplate{title = "flagicon image", args = {image}}
	elseif string.match(image, ".-%s%(.-%)") then
		local country, var = string.match(image,"(.-)%s%((.-)%)")
		file = mw.getCurrentFrame():expandTemplate{title = "flagdeco", args = {country, var, noredlink = 'y'}}
	else
		file = mw.getCurrentFrame():expandTemplate{title = "flagdeco", args = {image, noredlink = 'y'}}
	end

	return file
end

function p.main(frame)
	local args = getArgs(frame)
	local hasImages = false
	local entries = {}
	local i = 1

	for i, entry in ipairs(args) do
		local country, timespan, image
		
		for line in args[i]:gmatch('[^\n]+') do
			line = mw.text.trim(line)
			
			local key, val = line:match('^([a-z]*):? *(.*)$')
			
			if key == '' then
				country = getCountry(val)
			elseif key == 'date' then
				timespan = getTimespan(val)
			elseif key == 'flag' then
				image = getImage(val)
			else
				return require('Module:Error').error{'Invalid key ' .. key .. ' in argument ' .. i}
			end
		end
		
		if not country then
			return require('Module:Error').error{'A country is required in argument ' .. i}
		end
		
		if not timespan then
			return require('Module:Error').error{'A date is required in argument ' .. i}
		end
		
		table.insert(entries, {
			country = country,
			timespan = timespan,
			image = image,
		})
	
		if image then
			hasImages = true
		end
	
		i = i + 1
	end
	
	local outTable = mw.html.create('table')
		:css({
			padding = '5px',
			float = args.float or 'left',
			['background-color'] = '#f8f9fa',
			border = '1px solid #aaa',
			width = '20em',
			['font-size'] = '90%'
		})

	outTable:tag('tr')
		:tag('th')
			:attr('colspan', hasImages and 2 or 1)
			:css({
				['text-align'] = 'center',
				['font-size'] = 'larger',
				['font-weight'] = 'bold'
			})
			:wikitext(args.title and args.title or 'Historical affiliations')

	for i, entry in ipairs(entries) do
		local row = outTable:tag('tr')
		
		if entry.image then
			row:tag('td')
				:css('vertical-align', 'top')
				:wikitext(entry.image)
		elseif hasImages then
			row:tag('td')
		end
				
		row:tag('td')
			:css({
				width = '100%',
				['vertical-align'] = 'top'
			})
			:wikitext(entry.country .. entry.timespan)
	end

	return tostring(outTable)
end

return p