Module:Math-colors

From The Satanic Wiki
Revision as of 02:23, 30 April 2021 by WikiGOD (talk | contribs) (1 revision imported)
Jump to navigation Jump to search

Documentation for this module may be created at Module:Math-colors/doc

-- <nowiki>
local p = {}
local getArgs = require("Dev:Arguments").getArgs
local userError = require("Dev:User error")

-- @TODO: replace this with a real color module some day
local function isValidRgbColor(str)
    local channels = mw.text.split(str, "%s*,%s*")

    if #channels ~= 3 then
        return false
    end

    for i = 1, #channels do
        local channel = tonumber(channels[i])

        if not channel or (channel % 1 ~= 0)
        or (channel < 0) or (channel > 255) then
            return false
        end
    end

    return true
end

--% Describe the following function here.
--@ args (table)
--@ args.expression (string)
--@ [args.textColor] (string) defaults to "0,0,0"
--: (str)
function p.render(args)
    local expression = args.expression
    local color = args.textColor or "0,0,0"
    local frame = mw.getCurrentFrame()

    if not expression then
        error("missing expression", 0)
    end

    if not isValidRgbColor(color) then
        error("invalid text color (must be in the format <code>[red],[green],[blue]</code>, where each is a whole number from 0 through 255)", 0)
    end

    local html = mw.html.create(nil)
        :tag("span")
            :addClass("hidden")
            :css("display", "inline")
            :wikitext(frame:preprocess(
                "<math>\\color[RGB]{" .. color .. "}" .. expression .. "</math>"
            ))
            :done()
        :tag("span")
            :css("display", "none")
            :wikitext(frame:preprocess("<math>" .. expression .. "</math>"))
            :done()

    return tostring(html)
end

--% Describe the following function here.
--@ frame (table) The
--- [[Lua reference manual/Scribunto libraries#Frame object|frame object]]
--: (str)
function p.main(frame)
    local args = getArgs(frame)
    local success, response = pcall(p.render, args)

    return success and response or userError(response)
end

return p
-- </nowiki>