Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: isDark() utility can receive null value #3774

Merged
merged 4 commits into from
Apr 22, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions framework/core/js/src/common/utils/isDark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,24 @@
* to preserve design consistency.
*/
export default function isDark(hexcolor: string): boolean {
SychO9 marked this conversation as resolved.
Show resolved Hide resolved
// return if hexcolor is undefined or shorter than 4 characters, shortest hex form is #333;
// decided against regex hex color validation for performance considerations
if (!hexcolor || hexcolor.length <= 4) {
SychO9 marked this conversation as resolved.
Show resolved Hide resolved
return false;
}

let hexnumbers = hexcolor.replace('#', '');

if (hexnumbers.length == 3) {
hexnumbers += hexnumbers;
}

const r = parseInt(hexnumbers.substr(0, 2), 16);
const g = parseInt(hexnumbers.substr(2, 2), 16);
const b = parseInt(hexnumbers.substr(4, 2), 16);
const r = parseInt(hexnumbers.slice(0, 2), 16);
const g = parseInt(hexnumbers.slice(2, 4), 16);
const b = parseInt(hexnumbers.slice(4, 6), 16);
const yiq = (r * 299 + g * 587 + b * 114) / 1000;

const threshold = parseInt(window.getComputedStyle(document.body).getPropertyValue('--yiq-threshold'));
const threshold = parseInt(getComputedStyle(document.body).getPropertyValue('--yiq-threshold').trim()) || 128;

return yiq < threshold;
}