Module:4chan User ID

From Soyjak Wiki, the free ensoyclopedia
Jump to navigationJump to search

-- Adapted from https://s.4cdn.org/js/extension.1158.js
bit32 = require( 'bit32' )
local templatestyles = 'Module:4chan_User_ID/styles.css'
local function hash(uid)
	local i = 0
	local tbl = {string.byte(uid, 1, #uid)}
	for t = 1, #tbl do
		i = bit32.lshift(i, 5) - i + tbl[t]
	end
	return i
end
local function generateColor(uid)
	local arr = {}
	local hash_sum = hash(uid)
	arr[1] = bit32.band(bit32.rshift(hash_sum, 24), 255) --R
	arr[2] = bit32.band(bit32.rshift(hash_sum, 16), 255) --G
	arr[3] = bit32.band(bit32.rshift(hash_sum, 8), 255) --B
	arr[4] = arr[1] * 0.299 + arr[2] * 0.587 + arr[3] * 0.114 > 125 --If greyscale value is above a certain threshold
	return arr
end
local function render(uid)
	local span = mw.html.create( 'span' )
	local color = generateColor(uid)
	local text_color
	if color[4] then
		text_color = 'black'
	else
		text_color = 'white'
	end
	span
		:wikitext( uid )
		:attr( 'class', 'uid' )
		:css('background-color', "rgb("..tostring(color[1])..","..tostring(color[2])..","..tostring(color[3])..")")
		:css('color', text_color)
		:css('border-radius', "6px")
		:css('padding', "0 5px")
		:css('font-size', "0.8em")
		:css('cursor', "pointer")
	return tostring( span )
end

local p = {}

function p.main( frame )
    return frame:extensionTag{ name = 'templatestyles', args = { src = templatestyles} } .. render(tostring(frame.args[1]):gsub("^%s*(.-)%s*$", "%1"))
end

return p