Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

font-color-contrast

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

font-color-contrast - npm Package Compare versions

Comparing version 10.1.0 to 11.0.0

lib/cssNamedColors.d.ts

23

lib/index.d.ts

@@ -0,4 +1,5 @@

import { CssColor } from './CssNamedColorsType';
/**
* Analyses the color (normally used in the background) and retrieves what color (black or white) has a better contrast.
* @param hex The hex color number that must be a valid hexadecimal color number, with 6 characters, to work correctly.
* @param hex The hex color number must be a valid hexadecimal color number (<= 0xffffff).
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.

@@ -10,6 +11,14 @@ * @example fontColorContrast(0XF3DC56) === fontColorContrast(15981654)

* Analyses the color (normally used in the background) and retrieves what color (black or white) has a better contrast.
* @param hex The hex color string that must be a valid hexadecima color number to work correctly. Works with or without '#', with 3 or 6 color chars.
* @param cssColor The CSS named color string. The list of colors is defined as a TypeScript type to help the usage.
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.
* @example fontColorContrast('00FFDD') === fontColorContrast('0FD') === fontColorContrast('#00FFDD') === fontColorContrast('#0FD')
* @example fontColorContrast('beige')
* @example fontColorContrast('darkcyan', 0.3)
*/
declare function fontColorContrast(cssColor: CssColor, threshold?: number): '#ffffff' | '#000000';
/**
* Analyses the color (normally used in the background) and retrieves what color (black or white) has a better contrast.
* @param hex The hex color string must be a valid hexadecimal color number to work correctly. Works with or without '#', with 3 or 6 color chars. Any other length or an invalid hex character will be ignored. A space is allowed between the hash symbol and the number.
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.
* @example fontColorContrast('00FFDD') === fontColorContrast('0FD') === fontColorContrast('#00FFDD') === fontColorContrast('#0FD') === fontColorContrast('# 00FFDD') === fontColorContrast('# 0FD')
*/
declare function fontColorContrast(hex: string, threshold?: number): '#ffffff' | '#000000';

@@ -21,3 +30,3 @@ /**

* @param blue The blue portion of the color. Must be a number between 0 and 255.
* @example fontColorContrast('00', 'F3', D8) === fontColorContrast(0, 243, 216) === fontColorContrast(0x0, 0xF3, 0xd8).
* @example fontColorContrast(0, 243, 216) === fontColorContrast(0x0, 0xF3, 0xd8).
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.

@@ -28,8 +37,8 @@ */

* Analyses the color (normally used in the background) and retrieves what color (black or white) has a better contrast.
* @param redGreenBlue Array with red, green and blue. Each value must be a number between 0 and 255.
* @param rgbArray Array with red, green and blue. Each value must be a number between 0 and 255.
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.
* @example fontColorContrast(['00', 'F3', 'D8']) === fontColorContrast([0, 243, 216]) === fontColorContrast([0x0, 0xF3, 0xd8])
* @example fontColorContrast(fontColorContrast([0, 243, 216]) === fontColorContrast([0x0, 0xF3, 0xd8])
*/
declare function fontColorContrast(redGreenBlue: number[], threshold?: number): '#ffffff' | '#000000';
declare function fontColorContrast(rgbArray: number[], threshold?: number): '#ffffff' | '#000000';
export default fontColorContrast;
//# sourceMappingURL=index.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const hashRegEx = /#/;
const hexRegEx = /0x/i;
let isRGB;
let isArray;
let isHexString;
let isHexNumber;
const FontColorContrast_1 = require("./FontColorContrast");
function fontColorContrast(hexColorOrRedOrArray, greenOrThreshold, blue, threshold) {
let red = 0;
let green = 0;
isRGB = !!(blue !== undefined);
isArray = Array.isArray(hexColorOrRedOrArray);
isHexString = typeof hexColorOrRedOrArray === 'string' && !isRGB;
isHexNumber = typeof hexColorOrRedOrArray === 'number' && !isRGB;
if (isHexString || isHexNumber) {
[red, green, blue] = hexColorToRGB(hexColorOrRedOrArray);
threshold = greenOrThreshold;
}
else if (isRGB || isArray) {
[red, green, blue, threshold] = arrayOrRgbToRGB(hexColorOrRedOrArray, greenOrThreshold, blue, threshold);
}
else {
// Not a color, respond with white color
return '#ffffff';
}
return contrastFromHSP(red, green, blue, threshold);
const fcc = new FontColorContrast_1.FontColorContrast(hexColorOrRedOrArray, greenOrThreshold, blue, threshold);
return fcc.getColor();
}
exports.default = fontColorContrast;
/**
* Converts a hexadecimal string to it's correspondent integer
* @param hexString The hexadecimal string
* @returns The integer value
*/
function hexToDec(hexString) {
const decString = (hexString).replace(/[^a-f0-9]/gi, '');
return parseInt(decString, 16);
}
/**
* Converts a ColorIntensity string or number, with all possibilities (e.g. '#009', '009', '#000099', '000099', 153, 0x00099) to the respective RGB values
* @param hexColor The color string or number
* @returns The array with the RGB values
* @example All these examples produces the same value
* hexColorToRGB('#0C9')
* hexColorToRGB('0C9')
* hexColorToRGB('#00CC99')
* hexColorToRGB('00cc99')
* hexColorToRGB(52377)
* hexColorToRGB(0x00Cc99)
*/
function hexColorToRGB(hexColor) {
let red, green, blue;
const hasHash = hashRegEx.test(hexColor);
const hasHex = hexRegEx.test(hexColor);
const color = isHexNumber
? hexColor.toString(16)
: hasHash
? hexColor.replace(hashRegEx, '')
: hasHex
? hexColor.replace(hexRegEx, '')
: hexColor;
// Color has only a single char in the last digit, so the last digit must be repeated, and red and green are 0
if (color.length === 1) {
red = 0;
green = 0;
blue = hexToDec(color.repeat(2));
// Color has two chars in the last digit, so red and green are 0
}
else if (color.length === 2) {
red = 0;
green = 0;
blue = hexToDec(color);
// Color has one chars for each color, so they must be repeated
}
else if (color.length === 3) {
red = hexToDec(color[0].repeat(2));
green = hexToDec(color[1].repeat(2));
blue = hexToDec(color[2].repeat(2));
// Color has only for chars, so red is 0
}
else if (color.length === 4) {
red = 0;
green = hexToDec(color.substr(0, 2));
blue = hexToDec(color.substr(2, 2));
// All chars are filled, so no transformation is needed
}
else {
red = hexToDec(color.substr(0, 2));
green = hexToDec(color.substr(2, 2));
blue = hexToDec(color.substr(4, 2));
}
return [red, green, blue];
}
/**
* Converts a color array or separated in RGB to the respective RGB values
* @param redOrArray The RGB array or the color red
* @param greenOrThreshold The color green
* @param blue The color blue
* @returns The array with the RGB values
* @example All these examples produces the same value
* arrayOrRgbToRGB(0, 0xcc, 153)
* arrayOrRgbToRGB(0x0, 0xcc, 153)
* arrayOrRgbToRGB(0, 204, 0x99)
* arrayOrRgbToRGB([0, 0xcc, 153])
* arrayOrRgbToRGB([0x0, 0xcc, 153])
* arrayOrRgbToRGB([0, 204, 0x99])
*/
function arrayOrRgbToRGB(redOrArray, greenOrThreshold, blue, threshold) {
let r = 0;
let g = 0;
let b = 0;
let t = 0;
if (isArray) {
r = redOrArray[0];
g = redOrArray[1];
b = redOrArray[2];
t = greenOrThreshold;
}
else if (isRGB) {
r = redOrArray;
g = greenOrThreshold;
b = blue;
t = threshold;
}
return [r, g, b, t];
}
/**
* Calculates the best color (black or white) to contrast with the passed RGB color using the algorithm from https://alienryderflex.com/hsp.html
* @param red The color red value
* @param green The color green value
* @param blue The color blue value
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.
* @returns Black or White depending on the best possible contrast
*/
function contrastFromHSP(red, green, blue, threshold = 0.5) {
const pRed = 0.299;
const pGreen = 0.587;
const pBlue = 0.114;
const contrast = Math.sqrt(pRed * Math.pow((red / 255), 2) +
pGreen * Math.pow((green / 255), 2) +
pBlue * Math.pow((blue / 255), 2));
return contrast > threshold
? '#000000'
: '#ffffff';
}
//# sourceMappingURL=index.js.map
{
"name": "font-color-contrast",
"version": "10.1.0",
"version": "11.0.0",
"description": "JavaScript module to use black or white font according to the given background color",

@@ -5,0 +5,0 @@ "scripts": {

@@ -6,3 +6,3 @@ # font-color-contrast

[![Build Status](https://scrutinizer-ci.com/g/russoedu/font-color-contrast/badges/build.png?b=master)](https://scrutinizer-ci.com/g/russoedu/font-color-contrast/build-status/master)
[![Coverage Status](https://coveralls.io/repos/github/russoedu/font-color-contrast/badge.svg?branch=ts)](https://coveralls.io/github/russoedu/font-color-contrast?branch=ts)
[![Coverage Status](https://coveralls.io/repos/github/russoedu/font-color-contrast/badge.svg?branch=master)](https://coveralls.io/github/russoedu/font-color-contrast?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/russoedu/font-color-contrast/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/russoedu/font-color-contrast/?branch=master)

@@ -12,6 +12,21 @@ [![Code Climate](https://codeclimate.com/github/dwyl/esta/badges/gpa.svg)](https://codeclimate.com/github/russoedu/font-color-contrast)

JavaScript module to select black or white to a font according to the background for the best possible contrast.
font-color-contrast is a JavaScript module to help you select black or white for a font according to the brightness of the background color to give you the best possible contrast.
Calculates the best color (black or white) to contrast with the passed color using the algorithm from https://alienryderflex.com/hsp.html
### How does it work
font-color-contrast uses the algorithm described in the article [HSP Color Model — Alternative to HSV (HSB) and HSL](https://alienryderflex.com/hsp.html) where brightness is described as
<p>
<img src="https://render.githubusercontent.com/render/math?math=brightness=\sqrt{0.299 * red^2 %2B 0.587 * green^2 %2B 0.114 * blue^2}">
</p>
Any brightness smaller than 50% means the background is dark.
Any brightness bigger than 50% means the background is light.
This way, font-color-contrast will (with the default threshold of 0.5) return white (`'#ffffff'`) for dark brightness and black (`'#000000'`) for light brightness.
You can change this behaviour by passing the optional `threshold` parameter, so the comparison will be with the value you passed, not with 50%.
## Installation

@@ -28,2 +43,5 @@

- fontColor('f7d4fc', 0.2)
- with a CSS color
- fontColor('olivedrab')
- fontColor('olivedrab', 0.2)
- with a color number

@@ -42,18 +60,21 @@ - fontColor(0xf7d56a)

Example:
### Examples
```Typescript
import fontColorContrast from 'font-color-contrast'
const myStringBg = '#00CC99'
const myStringBg = '#d2691e'
const fontColor = fontColorContrast(myStringBg) // '#000000'
const myNumberBg = 0x00cc99
const myCssColorBg = 'chocolate'
const fontColor = fontColorContrast(myCssColorBg) // '#000000'
const myNumberBg = 0xd2691e
const fontColor = fontColorContrast(myNumberBg) // '#000000'
const red = 0
const green = 204
const blue = 153
const red = 210
const green = 105
const blue = 30
const fontColor = fontColorContrast(red, green, blue) // '#000000'
const myArrayBg = [0, green: 204, blue: 153]
const myArrayBg = [red, green, blue]
const fontColor = fontColorContrast(myArrayBg) // '#000000'

@@ -73,8 +94,10 @@

## Overflows
The 4 possible overflows are described next:
### Number
```Typescript
/**
* Analyses the color (normally used in the background) and retrieves what color (black or white) has a better contrast.
* @param hex The hex color number that must be a valid hexadecimal color number, with 6 characters, to work correctly.
* @param hex The hex color number must be a valid hexadecimal color number (<= 0xffffff).
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.

@@ -86,19 +109,30 @@ * @example fontColorContrast(0XF3DC56) === fontColorContrast(15981654)

### CSS named color
```Typescript
/**
* Analyses the color (normally used in the background) and retrieves what color (black or white) has a better contrast.
* @param hex The hex color string that must be a valid hexadecima color number to work correctly. Works with or without '#', with 3 or 6 color chars.
* @param cssColor The CSS named color string. The list of colors is defined as a TypeScript type to help the usage.
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.
* @example fontColorContrast('00FFDD') === fontColorContrast('0FD') === fontColorContrast('#00FFDD') === fontColorContrast('#0FD')
* @example fontColorContrast('beige')
* @example fontColorContrast('darkcyan', 0.3)
*/
function fontColorContrast (cssColor: CssColor, threshold?: number): '#ffffff' | '#000000'
```
### Hex string
```Typescript
/**
* @param hex The hex color string must be a valid hexadecimal color number to work correctly. Works with or without '#', with 3 or 6 color chars. Any other length or an invalid hex character will be ignored. A space is allowed between the hash symbol and the number.
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.
* @example fontColorContrast('00FFDD') === fontColorContrast('0FD') === fontColorContrast('#00FFDD') === fontColorContrast('#0FD') === fontColorContrast('# 00FFDD') === fontColorContrast('# 0FD')
*/
function fontColorContrast (hex: string, threshold?: number): '#ffffff' | '#000000'
```
### RGB numbers
```Typescript
/**
* Analyses the color (normally used in the background) and retrieves what color (black or white) has a better contrast.
* @param red The red portion of the color. Must be a number between 0 and 255.
* @param green The green portion of the color. Must be a number between 0 and 255.
* @param blue The blue portion of the color. Must be a number between 0 and 255.
* @example fontColorContrast('00', 'F3', D8) === fontColorContrast(0, 243, 216) === fontColorContrast(0x0, 0xF3, 0xd8).
* @example fontColorContrast(0, 243, 216) === fontColorContrast(0x0, 0xF3, 0xd8).
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.

@@ -109,8 +143,8 @@ */

### RGB numbers array
```Typescript
/**
* Analyses the color (normally used in the background) and retrieves what color (black or white) has a better contrast.
* @param redGreenBlue Array with red, green and blue. Each value must be a number between 0 and 255.
* @param rgbArray Array with red, green and blue. Each value must be a number between 0 and 255.
* @param threshold Contrast threshold to control the resulting font color, float values from 0 to 1. Default is 0.5.
* @example fontColorContrast(['00', 'F3', 'D8']) === fontColorContrast([0, 243, 216]) === fontColorContrast([0x0, 0xF3, 0xd8])
* @example fontColorContrast(fontColorContrast([0, 243, 216]) === fontColorContrast([0x0, 0xF3, 0xd8])
*/

@@ -120,17 +154,6 @@ function fontColorContrast(redGreenBlue: number[], threshold?: number): '#ffffff' | '#000000'

## Tests
## Tests and coverage
Tests made using [Jest](https://jestjs.io/) to check color format possibilities and contrast, including all CSS colors and WebSafe (90's stuff) colors as shown in the image below
Tests made using [Jest](https://jestjs.io/) with [![Coverage Status](https://coveralls.io/repos/github/russoedu/font-color-contrast/badge.svg?branch=ts)](https://coveralls.io/github/russoedu/font-color-contrast?branch=ts)
## Examples
These examples are using the default 0.5 threshold.
### WebSafe colors
![Sample with WebSafe colors](https://github.com/russoedu/font-color-contrast/blob/master/websafe-colors.jpeg?raw=true)
### CSS colors
![Sample with CSS colors](https://github.com/russoedu/font-color-contrast/blob/master/css-colors.jpeg?raw=true)
## Version history

@@ -144,6 +167,6 @@

Only numbers are now accepted as params when using array or RGB, because it was impossible to know if the string was decimal or hexadecimal. Accepting only numbers we can be sure the correct values are being used to calculate the contrast.
Only numbers are now accepted as params when using array or RGB because it was impossible to know if the string was decimal or hexadecimal. Accepting only numbers we can be sure the correct values are being used to calculate the contrast.
### 9.1.0
Updated algorithm from https://alienryderflex.com/hsp.html with new thresholds for better contrast.
Updated the algorithm from https://alienryderflex.com/hsp.html with new thresholds for better contrast.

@@ -155,1 +178,9 @@ ### 10.0.0

Changed target to ES2015
### 10.1.0
Fixed package installation from the new TS version
### 11.0.0
Many improved checks to make sure the color is a valid set color and recreated all tests. The function now encapsulates a function in a class.
[CSS named colors](https://www.w3.org/wiki/CSS/Properties/color/keywords) can now be passed as a param.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc