From e54bfe60ff1c51694ea8e161fdb4aafebcd0261a Mon Sep 17 00:00:00 2001 From: John Benediktsson Date: Wed, 3 Aug 2022 12:29:36 -0700 Subject: [PATCH] colors.contrast: implement WCAG color contrast ratio --- extra/colors/contrast/contrast-tests.factor | 7 ++++++ extra/colors/contrast/contrast.factor | 25 +++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 extra/colors/contrast/contrast-tests.factor create mode 100644 extra/colors/contrast/contrast.factor diff --git a/extra/colors/contrast/contrast-tests.factor b/extra/colors/contrast/contrast-tests.factor new file mode 100644 index 0000000000..f6c59bf1df --- /dev/null +++ b/extra/colors/contrast/contrast-tests.factor @@ -0,0 +1,7 @@ +USING: colors colors.contrast kernel tools.test ; + +{ 0.0 } [ COLOR: black relative-luminance ] unit-test +{ 1.0 } [ COLOR: white relative-luminance ] unit-test + +{ 1.0 } [ COLOR: blue dup contrast-ratio ] unit-test +{ 21.0 } [ COLOR: black COLOR: white contrast-ratio ] unit-test diff --git a/extra/colors/contrast/contrast.factor b/extra/colors/contrast/contrast.factor new file mode 100644 index 0000000000..2045c12579 --- /dev/null +++ b/extra/colors/contrast/contrast.factor @@ -0,0 +1,25 @@ +! Copyright (C) 2022 John Benediktsson +! See http://factorcode.org/license.txt for BSD license +USING: colors kernel math math.functions ; +IN: colors.contrast + + + +: relative-luminance ( color -- n ) + >rgba-components drop [ adjust-color ] tri@ + [ 0.2126 * ] [ 0.7152 * ] [ 0.0722 * ] tri* + + ; + +: contrast-ratio ( color1 color2 -- n ) + [ relative-luminance ] bi@ + 2dup < [ swap ] when [ 0.05 + ] bi@ / ; + +: passes-AA? ( contrast large? -- ? ) + 3.0 4.5 ? >= ; + +: passes-AAA? ( contrast large? -- ? ) + 4.5 7.0 ? >= ; -- 2.34.1