| 1 |
@use "sass:color"; |
| 2 |
@use "sass:map"; |
| 3 |
@use "sass:math"; |
| 4 |
|
| 5 |
// Get color combinations that meet a minimum contrast ratio as per WCAG 2 |
| 6 |
|
| 7 |
// @param {color} $bg - Background color of the element |
| 8 |
// @param {color} optional $target-color-contrast-dark $target-color-contrast-light - Target text colors, defaul to our |
| 9 |
// $foundation-black and $foundation-white colors |
| 10 |
// @return {color} $max-ratio-color - The color that has the highest contrast ratio |
| 11 |
@function a11y-combination( |
| 12 |
$bg, |
| 13 |
$target-color-contrast-dark: $foundation-black, |
| 14 |
$target-color-contrast-light: $foundation-white, |
| 15 |
$min-contrast-ratio: $min-contrast-ratio-4 |
| 16 |
) { |
| 17 |
// will test against the specified foreground colors |
| 18 |
$foregrounds: $target-color-contrast-light, $target-color-contrast-dark; |
| 19 |
$max-ratio: 0; |
| 20 |
$max-ratio-color: null; |
| 21 |
|
| 22 |
@each $fg in $foregrounds { |
| 23 |
$contrast-ratio: get-contrast-ratio($bg, $fg); |
| 24 |
|
| 25 |
@if $contrast-ratio >= $min-contrast-ratio { |
| 26 |
@return $fg; |
| 27 |
} @else if $contrast-ratio > $max-ratio { |
| 28 |
$max-ratio: $contrast-ratio; |
| 29 |
$max-ratio-color: $fg; |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
@warn "Found no color leading to #{$min-contrast-ratio}:1 contrast ratio against #{$bg}..."; |
| 34 |
@return $max-ratio-color; |
| 35 |
} |
| 36 |
|
| 37 |
@function get-contrast-ratio($bg, $foreground) { |
| 38 |
$l1: luminance($bg); |
| 39 |
$l2: luminance($foreground); |
| 40 |
|
| 41 |
// return the relative contrast ratio |
| 42 |
@if $l1 > $l2 { |
| 43 |
@return math.div(($l1 + 0.05), ($l2 + 0.05)); |
| 44 |
} @else { |
| 45 |
@return math.div(($l2 + 0.05), ($l1 + 0.05)); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
// Return WCAG2.1 relative luminance |
| 50 |
// See https://www.w3.org/TR/WCAG/#dfn-relative-luminance |
| 51 |
// See https://www.w3.org/TR/WCAG/#dfn-contrast-ratio |
| 52 |
@function luminance($target-color) { |
| 53 |
$rgb-col: ( |
| 54 |
"r": color.red($target-color), |
| 55 |
"g": color.green($target-color), |
| 56 |
"b": color.blue($target-color), |
| 57 |
); |
| 58 |
|
| 59 |
@each $channel, $value in $rgb-col { |
| 60 |
// here we get RsRGB, GsRGB, and BsRGB |
| 61 |
// stylelint-disable-next-line number-max-precision |
| 62 |
@if math.div($value, 255) <= 0.04045 { |
| 63 |
$rgb-col: map.merge( |
| 64 |
$rgb-col, |
| 65 |
( |
| 66 |
$channel: math.div(math.div($value, 255), 12.92), |
| 67 |
) |
| 68 |
); |
| 69 |
} @else { |
| 70 |
$rgb-col: map.merge( |
| 71 |
$rgb-col, |
| 72 |
( |
| 73 |
$channel: math.pow( |
| 74 |
math.div((math.div($value, 255) + 0.055), 1.055), |
| 75 |
2.4 |
| 76 |
), |
| 77 |
) |
| 78 |
); |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
$r: map.get($rgb-col, "r"); |
| 83 |
$g: map.get($rgb-col, "g"); |
| 84 |
$b: map.get($rgb-col, "b"); |
| 85 |
|
| 86 |
@return (0.2126 * $r + 0.7152 * $g + 0.0722 * $b); |
| 87 |
} |