You are browsing a read-only backup copy of Wikitech. The live site can be found at wikitech.wikimedia.org

Module:Colors

From Wikitech-static
Jump to navigation Jump to search

Documentation for this module may be created at Module:Colors/doc (Test casesTest results)

--
-- This module implements helpers for:
--  {{ClusterMap}}
--
local p = {}

local function round( num )
	return math.floor(num + 0.5)
end

--
-- Based on https://en.wikipedia.org/wiki/Module:Color_contrast
--
-- @param number h Hue, from 0 and 360
-- @param number s Saturation, from 0 to 1
-- @param number l Lightness, from 0 to 1
-- @return number r Red, from 0 to 255
-- @return number g Green, from 0 to 255
-- @return number b Blue, from 0 to 255
--
local function hsl2rgb( h, s, l )
	if ( 0 <= h and h < 360 and 0 <= s and s <= 1 and 0 <= l and l <= 1 ) then
		local c = (1 - math.abs(2*l - 1))*s
		local x = c*(1 - math.abs( math.fmod(h/60, 2) - 1) )
		local m = l - c/2

		local r, g, b = m, m, m
		if( 0 <= h and h < 60 ) then
			r = r + c
			g = g + x
		elseif( 60 <= h and h < 120 ) then
			r = r + x
			g = g + c
		elseif( 120 <= h and h < 180 ) then
			g = g + c
			b = b + x
		elseif( 180 <= h and h < 240 ) then
			g = g + x
			b = b + c
		elseif( 240 <= h and h < 300 ) then
			r = r + x
			b = b + c
		elseif( 300 <= h and h < 360 ) then
			r = r + c
			b = b + x
		end
		return round(255*r), round(255*g), round(255*b)
	else
		return 0, 0, 0
	end
end

--
-- @param number h Hue, from 0 and 360
-- @param number s Saturation, from 0 to 100
-- @param number l Lightness, from 0 to 100
-- @param number a Alpha, from 0 to 1 
-- @return string In the form of "rgba( .. )"
--
function p.hsla2rgba(frame)
	local args = frame.args;
	local h = tonumber(args['h'] or '0') or 0
	local s = tonumber(args['s'] or '0') or 0
	local l = tonumber(args['l'] or '0') or 0
	local a = tonumber(args['a'] or '0') or 0

	local r, g, b = hsl2rgb(h, s/100, l/100)

	return 'rgba(' .. r .. ', ' .. g .. ', ' .. b .. ', ' .. a .. ')'
end

--
-- @param number h Hue, from 0 and 360
-- @param number s Saturation, from 0 to 100
-- @param number l Lightness, from 0 to 100
-- @return string In the form of "#..."
--
function p.hsl2hex(frame)
	local args = frame.args;
	local h = tonumber(args['h'] or '0') or 0
	local s = tonumber(args['s'] or '0') or 0
	local l = tonumber(args['l'] or '0') or 0

	local r, g, b = hsl2rgb(h, s/100, l/100)
	
	return '#' .. string.format('%02x', r) .. string.format('%02x', g) .. string.format('%02x', b)
end


return p