Skip to content

Commit

Permalink
Merge pull request #108 from escottalexander/color-range
Browse files Browse the repository at this point in the history
Limit color values away from edges
  • Loading branch information
escottalexander authored Jul 31, 2024
2 parents c6e6de5 + 0640c15 commit 329a61c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import HighchartsReact from "highcharts-react-official";
import { DatePicker } from "~~/components/impact-vector/inputs/datePicker";
import { useDarkMode } from "~~/hooks/scaffold-eth/useDarkMode";
import { IMetric } from "~~/services/mongodb/models/metric";
import { stringToColor, stringToRGBA } from "~~/utils/onchainImpactDashboard/common";
import { hexStringToRGBA, stringToColor } from "~~/utils/onchainImpactDashboard/common";

interface IProps {
totalsRecord: any[];
Expand Down Expand Up @@ -184,8 +184,8 @@ export const ProjectTotalsGraph = ({
y2: 1,
},
stops: [
[0, stringToRGBA(metricToWork.label || "", 0.4)],
[1, stringToRGBA(metricToWork.label || "", 0)],
[0, hexStringToRGBA(stringToColor(metricToWork.label || ""), 0.4)],
[1, hexStringToRGBA(stringToColor(metricToWork.label || ""), 0)],
],
},
marker: {
Expand Down
30 changes: 23 additions & 7 deletions packages/nextjs/utils/onchainImpactDashboard/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const formatDate = (dateString: string) => {
const hashString = (str: string) => {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
hash = Math.abs(str.charCodeAt(i) + ((hash << 5) - hash));
}
return hash;
};
Expand All @@ -41,16 +41,32 @@ const intToRGB = (i: number) => {
return "00000".substring(0, 6 - c.length) + c;
};

export const stringToColor = (str: string) => {
export const stringToColor = (str: string): string => {
const hash = hashString(str);
const color = intToRGB(hash);
if (!isColorWithinRange(color)) {
return stringToColor(str + "a");
}
console.log(`#${color}`);
return `#${color}`;
};

export const stringToRGBA = (str: string, opacity: number) => {
const hash = hashString(str);
const r = (hash >> 16) & 0xff;
const g = (hash >> 8) & 0xff;
const b = hash & 0xff;
export const hexStringToRGBA = (hex: string, opacity: number): string => {
const r = parseInt(hex.substring(1, 3), 16);
const g = parseInt(hex.substring(3, 5), 16);
const b = parseInt(hex.substring(5, 7), 16);
return `rgba(${r}, ${g}, ${b}, ${opacity})`;
};

const isColorWithinRange = (hexColor: string) => {
const r = parseInt(hexColor.substring(0, 2), 16);
const g = parseInt(hexColor.substring(2, 4), 16);
const b = parseInt(hexColor.substring(4, 6), 16);

for (const color of [r, g, b]) {
if (color < 31 || color > 223) {
return false;
}
}
return true;
};

0 comments on commit 329a61c

Please sign in to comment.