Skip to content

Commit

Permalink
feat: add dynamic text color based on bg color
Browse files Browse the repository at this point in the history
  • Loading branch information
moonbamijam committed May 29, 2024
1 parent 909d76e commit 032710a
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/components/ui/colorcard/ColorCard.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState } from "react";
import colorCardStyles from "./color-card.module.scss";
import useDynamicTextColor from "../../../hooks/useDynamicTextColor";

type ColorCardProps = {
backgroundColor: string;
Expand All @@ -10,6 +11,7 @@ const ClickToCopy = (text: string) => {
};

const ColorCard = ({ backgroundColor }: ColorCardProps) => {
const { getTextColor } = useDynamicTextColor();
const [isCopied, setIsCopied] = useState(false);
const copied = () => setIsCopied(false);

Expand All @@ -26,7 +28,10 @@ const ColorCard = ({ backgroundColor }: ColorCardProps) => {
releaseDisplayedIsCopied();
}}
>
<p className={`${colorCardStyles.color_hex}`}>
<p
style={{ color: getTextColor(backgroundColor) }}
className={`${colorCardStyles.color_hex}`}
>
{isCopied ? "copied to clipboard" : backgroundColor}
</p>
</div>
Expand Down
3 changes: 1 addition & 2 deletions src/components/ui/colorcard/color-card.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
text-align: center;
cursor: pointer;
.color_hex {
color: white;
text-transform: uppercase;
opacity: 70%;
opacity: 80%;
}
}
40 changes: 40 additions & 0 deletions src/hooks/useDynamicTextColor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// by Sinan Aksay. March 23, 2020. https://wunnle.com/dynamic-text-color-based-on-background

const useDynamicTextColor = () => {
const getRGB = (c: any) => {
return parseInt(c, 16) || c;
};

const getsRGB = (c: any) => {
return getRGB(c) / 255 <= 0.03928
? getRGB(c) / 255 / 12.92
: Math.pow((getRGB(c) / 255 + 0.055) / 1.055, 2.4);
};

const getLuminance = (hexColor: string) => {
return (
0.2126 * getsRGB(hexColor.substr(1, 2)) +
0.7152 * getsRGB(hexColor.substr(3, 2)) +
0.0722 * getsRGB(hexColor.substr(-2))
);
};

const getContrast = (f: any, b: any) => {
const L1 = getLuminance(f);
const L2 = getLuminance(b);
return (Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05);
};

const getTextColor = (bgColor: string) => {
const whiteContrast = getContrast(bgColor, "#FFFFFF");
const blackContrast = getContrast(bgColor, "#000000");

return whiteContrast > blackContrast ? "#FFFFFF" : "#000000";
};

return {
getTextColor,
};
};

export default useDynamicTextColor;

0 comments on commit 032710a

Please sign in to comment.