0.0.2 • Published 11 months ago

@terrazzo/use-color v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

@terrazzo/use-color

React hook for memoizing and transforming any web-compatible color. Only 12 kB (with full support for all web colorspaces!) thanks to Culori.

Setup

pnpm i @terrazzo/use-color
import useColor, { formatCSS } from "@terrazzo/use-color";

const [color, setColor] = useColor("color(srgb 0.0 0.3 1.0)");

// Reading

color.css; // color(srgb 0.0 0.3 1.0)
color.original; // { mode: "srgb", r: 0, g: 0.3, b: 1.0, alpha: 1 }
color.p3; // { mode: "p3", r: 0.1184, g: 0.2956, b: 0.9611 }
formatCSS(color.p3); // color(display-p3 0.1184 0.2956 0.9611)

// Setting color

setColor("color(display-p3 0.12 0.3 0.98)");
setColor({ mode: "p3", r: 0.12, g: 0.3, b: 0.98 });

// Adjusting color relatively (lighten by 10% via Oklab)

setColor({ ...color.original.oklab, l: color.oklab.l + 0.1 });

Reading color

The color is fully memoized, so it can be used in any useEffect() hooks. This uses Culori to convert colors, but only the CSS Color Module 4 colorspaces are loaded. Further, all the properties are getters that cache their output, so even if accessing a different format, work will never be redone. You have the following property available:

PropertyTypeDescription
cssstringCSS-compatible color using Color Module 4
originalobjectCulori color object using the original mode of the color (tip: use color.original.mode to see the format)
a98objectCulori A98 color object
hslobjectCulori HSL color object
hsvobjectCulori HSV color object
lrgbobjectCulori LinearRGB color object
labobjectCulori CIELab color object (not to be confused with Oklab)
lchobjectCulori CIELCh color object (not to be confused with Oklch)
luvobjectCulori LUV color object
okhslobjectCulori Okhsl color object
okhsvobjectCulori Okhsv color object
oklabobjectCulori Oklab color object
oklchobjectCulori Oklch color object
p3objectCulori P3 color object
prophotoRgbobjectCulori ProPhotoRGB color object
rec2020objectCulori Rec2020 color object
rgbobject(sRGB) Culori RGB color object
srgbobject(alias of rgb)
xyzobject(alias of xyz65)
xyz50objectCulori Xyz50 color object
xyz65objectCulori Xyz65 color object

Setting color

Setting color can be done by either passing in any valid CSS string:

const [color, setColor] = useColor();

setColor("color(display-p3 0.12 0.3 0.98)");

Or any Culori object:

const [color, setColor] = useColor();

setColor({ mode: "p3", r: 0.12, g: 0.3, b: 0.98 });

Or adjusting the color object relatively (tip: for most purposes, adjusting by oklab will yield the best results):

const [color, setColor] = useColor();

setColor({
  ...color.original.oklab,
  l: color.oklab.l + 0.1, // Lighten by 10% via Oklab
});

Note: if adjusting by a different colorspace, that will affect the color.original and color.css output, which pulls the most-recently-used colorspace.

0.0.2

11 months ago

0.0.1

12 months ago

0.0.0

12 months ago