יחידה:WCAG
היחידה נועדה לאפשר הצגת טקסט תוך שמירה על ניגודיות מומלצת בהתאם לתקן .
היחידה מייצאת שלוש פונקציות.
- _getContrastTextColor - מקבלת צבע רקע ומחזירה את הצבע הרצוי לטקסט
- _getContrastRatio - קבלת שני צבעים ובדיקה האם הניגודיות ביניהם תואמת לתקן
- getContrastTextColor - להכללה
{{#invoke:getContrastTextColor|<צבע רקע>}}
local WCAG = {}
-- Function to determine the optimal text color (black or white) based on background color
-- according to WCAG (Web Content Accessibility Guidelines) standards
-- Input: Background color in hex format (e.g., "#FF5733" or "FF5733") or RGB values (0-255)
-- Output: Suitable text color ("#000000" for black or "#FFFFFF" for white)
function WCAG._getContrastTextColor(backgroundColor)
mw.logObject("backgroundColor: "..backgroundColor)
local r, g, b
-- Handle different input formats
if type(backgroundColor) == "string" then
-- Remove # if present
backgroundColor = backgroundColor:gsub("#", "")
-- Convert hex to RGB
r = tonumber(backgroundColor:sub(1, 2), 16) or 0
g = tonumber(backgroundColor:sub(3, 4), 16) or 0
b = tonumber(backgroundColor:sub(5, 6), 16) or 0
elseif type(backgroundColor) == "table" then
r = backgroundColor.r or backgroundColor[1] or 0
g = backgroundColor.g or backgroundColor[2] or 0
b = backgroundColor.b or backgroundColor[3] or 0
else
return "#000000" -- default to black on error
end
-- Normalize RGB values to range 0-1
r = r / 255
g = g / 255
b = b / 255
-- Calculate luminance according to WCAG formula
-- Convert RGB to sRGB
r = r <= 0.03928 and r/12.92 or ((r+0.055)/1.055)^2.4
g = g <= 0.03928 and g/12.92 or ((g+0.055)/1.055)^2.4
b = b <= 0.03928 and b/12.92 or ((b+0.055)/1.055)^2.4
-- Calculate relative luminance
local luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
-- WCAG recommends black text on light backgrounds and white text on dark backgrounds
-- The threshold is typically at luminance of 0.5 but WCAG suggests 0.179 for better compliance
if luminance > 0.179 then
return "#000000" -- black text for light backgrounds
else
return "#FFFFFF" -- white text for dark backgrounds
end
end
-- Calculate contrast ratio between two colors (for advanced usage)
function WCAG._getContrastRatio(color1, color2)
-- Implementation would convert colors to luminance values
-- and calculate (L1 + 0.05) / (L2 + 0.05) where L1 is the lighter color
-- This is a stub - expand as needed
local l1 = 0.9 -- luminance of color1
local l2 = 0.1 -- luminance of color2
-- Ensure l1 is the lighter color (higher luminance)
if l2 > l1 then
l1, l2 = l2, l1
end
-- Calculate contrast ratio
return (l1 + 0.05) / (l2 + 0.05)
end
function WCAG.getContrastTextColor(frame)
local backgroundColor = frame.args[1]
return WCAG._getContrastTextColor(backgroundColor)
end
-- Example usage:
-- local textColor = getContrastTextColor("#3366FF")
-- local textColor = getContrastTextColor({51, 102, 255})
-- local contrastRatio = getContrastRatio("#FFFFFF", "#000000") -- Would return approximately 21:1
return WCAG