Skip to content

Commit

Permalink
fix(ColorConvert): fix circular dependencies issue. #137
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed Jan 13, 2024
1 parent 43da734 commit 12eaa94
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 45 deletions.
10 changes: 0 additions & 10 deletions packages/color-convert/src/getContrastingColor.ts

This file was deleted.

42 changes: 37 additions & 5 deletions packages/color-convert/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
import { validHex } from './utils';

export * from './utils';
export * from './getContrastingColor';

const RGB_MAX = 255;
const HUE_MAX = 360;
const SV_MAX = 100;
Expand Down Expand Up @@ -305,3 +300,40 @@ export const color = (str: string | HsvaColor): ColorResult => {
}
return { rgb, hsl, hsv, rgba, hsla, hsva, hex, hexa };
};

export const getContrastingColor = (str: string | HsvaColor) => {
if (!str) {
return '#ffffff';
}
const col = color(str);
const yiq = (col.rgb.r * 299 + col.rgb.g * 587 + col.rgb.b * 114) / 1000;
return yiq >= 128 ? '#000000' : '#ffffff';
};

export const equalColorObjects = (first: ObjectColor, second: ObjectColor): boolean => {
if (first === second) return true;

for (const prop in first) {
// The following allows for a type-safe calling of this function (first & second have to be HSL, HSV, or RGB)
// with type-unsafe iterating over object keys. TS does not allow this without an index (`[key: string]: number`)
// on an object to define how iteration is normally done. To ensure extra keys are not allowed on our types,
// we must cast our object to unknown (as RGB demands `r` be a key, while `Record<string, x>` does not care if
// there is or not), and then as a type TS can iterate over.
if ((first as unknown as Record<string, number>)[prop] !== (second as unknown as Record<string, number>)[prop]) return false;
}

return true;
};

export const equalColorString = (first: string, second: string): boolean => {
return first.replace(/\s/g, '') === second.replace(/\s/g, '');
};

export const equalHex = (first: string, second: string): boolean => {
if (first.toLowerCase() === second.toLowerCase()) return true;

// To compare colors like `#FFF` and `ffffff` we convert them into RGB objects
return equalColorObjects(hexToRgba(first), hexToRgba(second));
};

export const validHex = (hex: string): boolean => /^#?([A-Fa-f0-9]{3,4}){1,2}$/.test(hex);
30 changes: 0 additions & 30 deletions packages/color-convert/src/utils.ts

This file was deleted.

0 comments on commit 12eaa94

Please sign in to comment.