Skip to content

Commit

Permalink
feat(color): update color() to accept CSS color strings
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Mar 1, 2023
1 parent 137d322 commit 0d5b3e9
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion packages/color/src/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
ParsedColor,
TypedColor,
} from "./api.js";
import { parseCss } from "./css/parse-css.js";
import { hcy } from "./hcy/hcy.js";
import { hsi } from "./hsi/hsi.js";
import { hsl } from "./hsl/hsl.js";
Expand All @@ -15,6 +16,7 @@ import { labD50 } from "./lab/lab50.js";
import { labD65 } from "./lab/lab65.js";
import { lch } from "./lch/lch.js";
import { oklab } from "./oklab/oklab.js";
import { oklch } from "./oklch/oklch.js";
import { rgb } from "./rgb/rgb.js";
import { srgb } from "./srgb/srgb.js";
import { xyy } from "./xyy/xyy.js";
Expand All @@ -33,6 +35,7 @@ const FACTORIES: Record<ColorMode, ColorFactory<any>> = {
lab65: labD65,
lch,
oklab,
oklch,
rgb,
srgb,
xyy,
Expand All @@ -41,6 +44,29 @@ const FACTORIES: Record<ColorMode, ColorFactory<any>> = {
ycc,
};

/**
* Takes an CSS color string or the result of {@link parseCss} or a
* {@link ColorMode} and raw buffer and returns a suitable typed color wrapper
* for it (potentially by first parsing the color).
*
* @example
* ```ts
* color("springgreen");
* // $Color [srgb] { offset: 0, stride: 1, buf: [ 0, 1, 0.498, 1 ] }
*
* color("#ff0")
* // $Color [srgb] { offset: 0, stride: 1, buf: [ 1, 1, 0, 1 ] }
*
* color("oklch(60% 0.15 50)");
* // $Color [oklch] { offset: 0, stride: 1, buf: [ 0.6, 0.0015, 0.139, 1 ] }
*
* color("hsv", [0.5, 1, 1, 1])
* // $Color [hsv] { offset: 0, stride: 1, buf: [ 0.5, 1, 1, 1 ] }
* ```
*
* @param src
*/
export function color(src: string): TypedColor<any>;
export function color(
src: ParsedColor,
buf?: Color,
Expand All @@ -59,7 +85,10 @@ export function color(
idx?: number,
stride?: number
): TypedColor<any> {
if (isString(src)) return FACTORIES[<ColorMode>src](buf, idx, stride);
if (isString(src))
return buf
? FACTORIES[<ColorMode>src](buf, idx, stride)
: color(<ParsedColor>parseCss(src));
if (buf) {
const res = FACTORIES[(<ParsedColor>src).mode](buf, idx, stride);
res.set(src.deref());
Expand Down

0 comments on commit 0d5b3e9

Please sign in to comment.