Module:Math-colors

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

--% Checks whether a given string is a valid RGB color. --@ str (str) --: (boolean) local function isValidColor(str) local parts = mw.text.split(str, "%s*,%s*")

if #parts ~= 3 then return false end

for i = 1, #parts do       local part = tonumber(parts[i])

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

return true end

--% Describe the following function here. --@ args (table) --: (str) function p._main(args) local expression = args.expression local bgColor = args.bgColor or "255,255,255" local textColor = args.textColor or "0,0,0" local badColor = "invalid %s color (must be in the format " ..                    ", where each is a " ..                     "whole number from 0 through 255)"

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

if not isValidColor(bgColor) then error(badColor:format("background"), 0) end

if not isValidColor(textColor) then error(badColor:format("text"), 0) end

local function renderMath(expression) local frame = mw.getCurrentFrame

return frame:preprocess("$$" .. expression .. "$$") end

local colored = mw.html.create("span") :addClass("hidden") :css("background-color", "rgb(" .. bgColor .. ")")       :css("color", "rgb(" .. textColor .. ")")       :css("display", "inline") :wikitext(renderMath( "\\pagecolor[RGB]{" .. bgColor .. "}" ..           "{\\color[RGB]{" .. textColor .. "}" .. expression .. "}"       ))

local plain = mw.html.create("span") :css("display", "none") :wikitext(renderMath(expression))

return tostring(colored) .. tostring(plain) end

--% Describe the following function here. --@ frame (table) The --- frame object --: (str) function p.main(frame) local args = getArgs(frame) local success, response = pcall(p._main, {       expression = args.expression,        bgColor = args["bg-color"],        textColor = args["text-color"]    })

return success and response or userError(response) end

return p --