Skip to content

Commit fccc3e2

Browse files
feat: contrast util with yiq calculator (#3652)
* add yiq calculator util * fix: convert 3 chars hex to 6 chars hex * fix: clarify util name * feat: add text color variables not depending on the dark/light mode * refactor: change getContrast to isDark with for a more direct approach * fix: adjust snippet description * chore: change `var` to `let` Co-authored-by: David Wheatley <david@davwheat.dev>
1 parent f0a867b commit fccc3e2

3 files changed

Lines changed: 30 additions & 0 deletions

File tree

framework/core/js/src/common/compat.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import formatNumber from './utils/formatNumber';
3333
import mapRoutes from './utils/mapRoutes';
3434
import withAttr from './utils/withAttr';
3535
import * as FocusTrap from './utils/focusTrap';
36+
import isDark from './utils/isDark';
3637
import Notification from './models/Notification';
3738
import User from './models/User';
3839
import Post from './models/Post';
@@ -120,6 +121,7 @@ export default {
120121
'utils/throttleDebounce': ThrottleDebounce,
121122
'utils/isObject': isObject,
122123
'utils/focusTrap': FocusTrap,
124+
'utils/isDark': isDark,
123125
'models/Notification': Notification,
124126
'models/User': User,
125127
'models/Post': Post,
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* The `isDark` utility converts a hex color to rgb, and then calcul a YIQ
3+
* value in order to get the appropriate brightness value (is it dark or is it
4+
* light?) See https://www.w3.org/TR/AERT/#color-contrast for references. A YIQ
5+
* value >= 128 is a light color.
6+
*/
7+
8+
export default function isDark(hexcolor: String) {
9+
let hexnumbers = hexcolor.replace("#", "");
10+
11+
if (hexnumbers.length == 3) {
12+
hexnumbers += hexnumbers;
13+
}
14+
15+
const r = parseInt(hexnumbers.substr(0,2),16);
16+
const g = parseInt(hexnumbers.substr(2,2),16);
17+
const b = parseInt(hexnumbers.substr(4,2),16);
18+
const yiq = ((r*299)+(g*587)+(b*114))/1000;
19+
20+
return (yiq >= 128) ? false : true;
21+
}

framework/core/less/common/variables.less

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,13 @@
6464
@code-color: #fff;
6565
}
6666

67+
// Beyond dark or light mode, we need stable colors depending on the luminosity
68+
// of the parents element's background. This allow not to change the color
69+
// variable depending on the dark/light mode to get the same final color, and
70+
// thus to simplify the logic.
71+
@text-on-dark: #ddd;
72+
@text-on-light: #111;
73+
6774
@hero-bg: @control-bg;
6875
@hero-color: @control-color;
6976
@hero-muted-color: @control-color;

0 commit comments

Comments
 (0)