Module:Tricolor

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Lua

CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules


Logic for {{Tricolor}}.

Usage

[edit]
{{Module:Tricolor|tricolor}}
local tricolor = require('Module:Tricolor')._tricolor


Code

--[[
Tricolor module to implement Template:Tricolor.

Colour definitions and existing combinations are in Module:Bicolor/data.

We can load the data efficiently with:

	local c = mw.loadData( "Module:Bicolor/data" )

Creating the definitions like this offers us tables indexed by number or by colour name,
and combinations as a sequence or an indexed set for efficient testing
--]]

require('strict')

local c = mw.loadData("Module:Bicolor/data")
local colors = c.colors
local colorcount = c.colorcount
local colorvalues = c.colorvalues
local colortitles = c.colortitles

local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')

local p = {}

local function cat_box(args)
	local topic = args[1]
	
	-- TODO: get subcats of Category:Combinations of 3 colors
	local combo_categories = {}
	local existent_colors = {}
	for _, cat in pairs(combo_categories) do
		local cols = mw.text.split(string.lower(cat), ', ')
		if #cols == 3 and colorvalues[cols[1]] and colorvalues[cols[2]] and colorvalues[cols[3]] then
			table.insert(
				existent_colors,
				{
					[1] = {['name'] = cols[1], ['value'] = colorvalues[cols[1]], ['title'] = colortitles[cols[1]]},
					[2] = {['name'] = cols[2], ['value'] = colorvalues[cols[2]], ['title'] = colortitles[cols[2]]},
					[3] = {['name'] = cols[3], ['value'] = colorvalues[cols[3]], ['title'] = colortitles[cols[3]]},
					['cat'] = cat
				}
			)
		end
	end
	
	local out = {}
	for _, cols in pairs(existent_colors) do
		table.insert(out, table.concat({
			'<span class="tricbox" style="background:' .. cols[1]['value'] .. '" title="' .. cols[1]['title'] .. '"></span>',
			'<span class="tricbox" style="background:' .. cols[2]['value'] .. '" title="' .. cols[2]['title'] .. '"></span>',
			'<span class="tricbox" style="background:' .. cols[3]['value'] .. '" title="' .. cols[3]['title'] .. '"></span>',
			'&#8239;', -- NNBSP (U+202F) prefix
			'[[:Category:',
			cols['cat'],
			' ',
			topic,
			'|',
			cols['cat'],
			']]'
		}))
	end
	return table.concat(out, ' ')
end

function p._tricolor(args)
	args[1] = args[1] or ''
	local cattext = 'Tricolor ' .. args[1]
	local display = {
		mw.getCurrentFrame():preprocess('<templatestyles src="Tricolor/styles.css" />'),
		'<div class="catlinks tric-outer">',
		'<div class="tric-head">[[:Category:' .. cattext .. '|' .. cattext .. ']]</div>',
		'<div class="tric-inner">' .. cat_box(args) .. '</div>',
		'</div>'
	}
	return table.concat(display)
end

function p.tricolor(frame)
	return p._tricolor(getArgs(frame))
end

return p