# 解析

> 在 JavaScript 中把 hex、rgb()、hsl()、hwb() 和现代语法的 CSS 颜色字符串解析为 HSVA 值，React 颜色选择器也用它。

Source: https://chroma-panel.jscrate.dev/zh/react/utils/parsing
Last updated: 2026-09-21

`parse` 读取 CSS 颜色字符串并返回 HSVA，输入无效时返回 `null`。如果校验时只要一个布尔值，就用 `isValidColor`。选择器的文本输入框用的也是这个解析器。

```ts
import { parse, isValidColor } from "chroma-panel";

parse("#3366cc");
parse("rgb(51 102 204)");
parse("hsl(220 60% 50%)");
parse("hwb(220 20% 20%)");
parse("oklch(72% 0.18 250)");
parse("color(display-p3 1 0.2 0.1)");

isValidColor("not a color"); // false
```

支持的格式包括 hex（3、4、6 和 8 位）、`rgb()`、`rgba()`、`hsl()`、`hsla()`、`hwb()`、`oklch()`、`oklab()`、`lab()`、`lch()`、`color(srgb …)` 和 `color(display-p3 …)`。hex 前面的 `#` 可以省略，色相可以使用 `deg`、`grad`、`rad` 或 `turn` 单位，透明度可以是数字或百分比。`transparent` 关键字始终可用。

如果需要保留输入的色彩空间，而不是直接转成 HSVA，请使用 `chroma-panel/color` 中的 `parseColor`。详见 [CSS Color 4](https://chroma-panel.jscrate.dev/zh/react/utils/css-color-4)。

## API 参考

```ts
function parse(input: string): Hsva | null
```

Turns any CSS color string into an Hsva, or null if it cannot be read. Hex, rgb(), hsl(), hwb() and the modern space-separated forms are all accepted; color names need registerNamedColors first.

```ts
function isValidColor(input: string): boolean
```

Whether parse would succeed, without building the result.

## 合并而不是替换

`ingest` 是面板内部使用的函数。它把修改合并进完整的 HSVA 值，而不是直接替换掉，色相和饱和度在极端值下能够保留，靠的就是这一点，详见[在颜色模型之间转换](https://chroma-panel.jscrate.dev/zh/react/utils/converting)。

```ts
function ingest(next: Hsva, prev: Hsva): Hsva
```

Merges a change into an existing color rather than replacing it, keeping the hue and saturation that other models drop at the extremes. This is why dragging brightness to black and back returns the color you started with.

## 命名颜色

在你注册颜色名称之前，`parse("rebeccapurple")` 会返回 null。这些名称 gzip 后约 1.3 kB，所以需要手动启用，详见[命名颜色](https://chroma-panel.jscrate.dev/zh/react/utils/named-colors)。
