Module:Color
Jump to navigation
Jump to search
This Module is used by the Template:Color and produces color-boxes of the given names.
The available color names can be seen and expanded at Module:Color/codes, the according ids at Module:Color/ids.
local p = {}
local colorCodes = mw.loadData( 'Module:Color/codes' )
local colorIds = mw.loadData( 'Module:Color/ids' )
local function findColorName(colorId)
for name, id in pairs(colorIds) do
if id == colorId then
return name
end
end
return ''
end
function p.colors( f )
local args = f:getParent().args
local colorBlocks = {}
local size = 20
local colorNameLower = ''
local colorId = 0
local colorCode = ''
local unknownId = 256
--This slices one parameter into a variable number of parameters with a comma as a delimiter.
--This allows the list to be called into another Template as its own parameter.
local M_SLICES = {}
for part in string.gmatch((args[1])..',', "([^,]*),") do
local slice = part:match "^%s*(.-)%s*$"
if #slice <= 3 and tonumber(slice) ~= nil then
slice = findColorName(slice)
end
table.insert(M_SLICES, slice)
end
local colorIdsOrdered={}
for _, colorNameInput in ipairs(M_SLICES) do
colorNameLower = colorNameInput:gsub('%W',''):lower()
colorId = colorIds[colorNameLower]
if colorId ~= nil then
colorId = tonumber(colorId)
end
-- colorId must be a number for the sorting later
-- internally in this module, an unknown id is represented by numbers > 256
if colorId == nil then
colorId = unknownId
unknownId = unknownId + 1
end
colorCode = colorCodes[colorNameLower]
if colorCode ~= nil and not p.isColorNameInTable(colorIdsOrdered, colorNameLower) then
table.insert(colorIdsOrdered, {colorId, colorCode, colorNameInput})
end
end
-- the sorting function must be stable, i.e. a==b => b==a
table.sort(colorIdsOrdered, function(a,b) return a[1] < b[1] end)
-- colorInfo[1]: color Id
-- colorInfo[2]: color code (hex)
-- colorInfo[3]: color name as entered in the template call
for _, colorInfo in ipairs(colorIdsOrdered) do
table.insert(colorBlocks,'<div class="color-square" style="height:'..size..'px; width:'..size..'px; background:'..colorInfo[2]..';" title="'..colorInfo[3]..' ('..(colorInfo[1] < 256 and colorInfo[1] or 'no id')..')">'..(colorInfo[1] < 256 and '<span>'..colorInfo[1]..'</span>' or '')..'</div>')
end
return '<div class="color-container">'..table.concat(colorBlocks)..'</div>'
end
function p.isColorNameInTable(tab, colorNameLower)
for _, colorInfo in ipairs(tab) do
if colorInfo[3] == colorNameLower then return true end
end
return false
end
return p