Module:ColorSel

From Elwiki

Documentation for this module may be created at Module:ColorSel/doc

-- This is core Color Selector function for `Template:ColorSel`.
-- Do not use #invoke to invoke this module directly.

local getArgs = require('Module:Arguments').getArgs
local data = mw.loadData('Module:ColorSel/data')
local p = {}

local function getRawMap(category)
    return (data.raw[category] and data.raw)
end

local function getGroupMap(category)
    return data.group[category]
end

local function getMap(category)
    local match_map

    -- Try to match raw map
    match_map = getRawMap(category)
    if match_map then
        return { ["type"] = "raw", ["map"] = match_map }
    end

    -- Try to match grouped map
    match_map = getGroupMap(category)
    if match_map then
        return { ["type"] = "group", ["map"] = match_map }
    end

    return {}
end

local function recursiveFindKey(map, key)
    map = map or {}
    key = key or ''

    local value = map[key] or ''
    if value:sub(1, 1) == '@' then
        key = value:sub(2)
        value = recursiveFindKey(map, key)
    end

    return value
end

local function getKey(category, input)
    local match_map = getMap(category)

    if match_map.type == "raw" then
        return ("#" .. (match_map.map[category] or match_map.map.default))
    elseif match_map.type == "group" then
        return ("#" .. recursiveFindKey(match_map.map, input))
    end
end

-- Main process
function p.main(frame)
    local args = getArgs(frame)

    local category = args[1] or ''
    local input = args[2] or ''

    return getKey(category, input)
end

return p