Module:Gradient

From MuttWiki
Jump to navigationJump to search

This module provides support for generating text gradients. It contains the following functions:

rgb[edit source]

{{#invoke:Gradient|rgb|<from>|<to>|<text>}}
  • from: A 6-digit hex code for the start colour. No starting #.
  • to: A 6-digit hex code for the end colour. No starting #.
  • text: The text to apply the gradient effect to. Plain text only.

Example: {{#invoke:Gradient|rgb|FF0000|0000FF|Hello world!}}Hello world!

multi[edit source]

{{#invoke:Gradient|multi|<colours>|<text>}}
  • colours: A comma-separated list of 6-digit hex codes. No starting #s.
  • text: The text to apply the gradient effect to. Plain text only.

Example: {{#invoke:Gradient|multi|FF0000,FFFF00,00FF00,00FFFF,0000FF,FF00FF|Hello world!}}Hello world!


local p={}

function parse_colour(c)
	return
		tonumber(string.sub(c,1,2),16),
		tonumber(string.sub(c,3,4),16),
		tonumber(string.sub(c,5,6),16)
end
function fmt_colour(r,g,b)
	return string.format("%02x%02x%02x",math.floor(r+0.5),math.floor(g+0.5),math.floor(b+0.5))
end

function p.rgb(frame)
	local r,g,b = parse_colour(frame.args[1])
	local r2,g2,b2 = parse_colour(frame.args[2])
	local text = frame.args[3]
	local n = mw.ustring.len(text)
	local out = ""
	local dr,dg,db = (r2-r)/n, (g2-g)/n, (b2-b)/n
	for i=1,n do
		local ch = mw.ustring.codepoint(text,i,i)
		out = out.."<span style='color: #"..fmt_colour(r,g,b)..";'>"..mw.text.nowiki(mw.ustring.char(ch)).."</span>"
		r=r+dr
		g=g+dg
		b=b+db
	end
	return out
end

function lerp_multi(a,t)
	local n = #a - 1
	t = t*n
	local i = math.floor(t)+1
	return a[i] + (a[i+1]-a[i])*(t-math.floor(t))
end

function strsplit(str,sep)
	local out={}
	while true do
		local i,j=string.find(str,sep,1,true)
		if i==nil then
			table.insert(out,str)
			return out
		else
			local part=string.sub(str,1,i-1)
			table.insert(out,part)
			str=string.sub(str,j+1)
		end
	end
end

function p.multi(frame)
	local cstrs = strsplit(frame.args[1],",")
	local ra,ga,ba = {},{},{}
	for i=1,#cstrs do
		local r,g,b = parse_colour(cstrs[i])
		table.insert(ra,r)
		table.insert(ga,g)
		table.insert(ba,b)
	end
	local text = frame.args[2]
	local n = mw.ustring.len(text)
	local t = 0
	local dt = 1.0/n
	local out=""
	for i=1,n do
		local r = lerp_multi(ra,t)
		local g = lerp_multi(ga,t)
		local b = lerp_multi(ba,t)
		local ch = mw.ustring.codepoint(text,i,i)
		out = out.."<span style='color: #"..fmt_colour(r,g,b)..";'>"..mw.text.nowiki(mw.ustring.char(ch)).."</span>"
		t=t+dt
	end
	return out
end

return p