@zag-js/color-utils 0.70.0 → 0.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/hsl-color.ts DELETED
@@ -1,153 +0,0 @@
1
- import { clampValue, mod, toFixedNumber } from "@zag-js/numeric-range"
2
- import { Color } from "./color"
3
- import { HSBColor } from "./hsb-color"
4
- import { RGBColor } from "./rgb-color"
5
- import type { ColorChannel, ColorChannelRange, ColorFormat, ColorStringFormat, ColorType } from "./types"
6
-
7
- export const HSL_REGEX =
8
- /hsl\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%)\)|hsla\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d(.\d+)?)\)/
9
-
10
- export class HSLColor extends Color {
11
- constructor(
12
- private hue: number,
13
- private saturation: number,
14
- private lightness: number,
15
- private alpha: number,
16
- ) {
17
- super()
18
- }
19
-
20
- static parse(value: string): HSLColor | void {
21
- let m: RegExpMatchArray | null
22
- if ((m = value.match(HSL_REGEX))) {
23
- const [h, s, l, a] = (m[1] ?? m[2]).split(",").map((n) => Number(n.trim().replace("%", "")))
24
- return new HSLColor(mod(h, 360), clampValue(s, 0, 100), clampValue(l, 0, 100), clampValue(a ?? 1, 0, 1))
25
- }
26
- }
27
-
28
- toString(format: ColorStringFormat) {
29
- switch (format) {
30
- case "hex":
31
- return this.toRGB().toString("hex")
32
- case "hexa":
33
- return this.toRGB().toString("hexa")
34
- case "hsl":
35
- return `hsl(${this.hue}, ${toFixedNumber(this.saturation, 2)}%, ${toFixedNumber(this.lightness, 2)}%)`
36
- case "css":
37
- case "hsla":
38
- return `hsla(${this.hue}, ${toFixedNumber(this.saturation, 2)}%, ${toFixedNumber(this.lightness, 2)}%, ${
39
- this.alpha
40
- })`
41
- case "hsb":
42
- return this.toHSB().toString("hsb")
43
- case "rgb":
44
- return this.toRGB().toString("rgb")
45
- default:
46
- return this.toFormat(format).toString(format)
47
- }
48
- }
49
-
50
- toFormat(format: ColorFormat): ColorType {
51
- switch (format) {
52
- case "hsla":
53
- return this
54
- case "hsba":
55
- return this.toHSB()
56
- case "rgba":
57
- return this.toRGB()
58
- default:
59
- throw new Error("Unsupported color conversion: hsl -> " + format)
60
- }
61
- }
62
-
63
- /**
64
- * Converts a HSL color to HSB.
65
- * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_HSV.
66
- * @returns An HSBColor object.
67
- */
68
- private toHSB(): ColorType {
69
- let saturation = this.saturation / 100
70
- let lightness = this.lightness / 100
71
- let brightness = lightness + saturation * Math.min(lightness, 1 - lightness)
72
- saturation = brightness === 0 ? 0 : 2 * (1 - lightness / brightness)
73
- return new HSBColor(
74
- toFixedNumber(this.hue, 2),
75
- toFixedNumber(saturation * 100, 2),
76
- toFixedNumber(brightness * 100, 2),
77
- toFixedNumber(this.alpha, 2),
78
- )
79
- }
80
-
81
- /**
82
- * Converts a HSL color to RGB.
83
- * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative.
84
- * @returns An RGBColor object.
85
- */
86
- private toRGB(): ColorType {
87
- let hue = this.hue
88
- let saturation = this.saturation / 100
89
- let lightness = this.lightness / 100
90
- let a = saturation * Math.min(lightness, 1 - lightness)
91
- let fn = (n: number, k = (n + hue / 30) % 12) => lightness - a * Math.max(Math.min(k - 3, 9 - k, 1), -1)
92
- return new RGBColor(
93
- Math.round(fn(0) * 255),
94
- Math.round(fn(8) * 255),
95
- Math.round(fn(4) * 255),
96
- toFixedNumber(this.alpha, 2),
97
- )
98
- }
99
-
100
- clone(): ColorType {
101
- return new HSLColor(this.hue, this.saturation, this.lightness, this.alpha)
102
- }
103
-
104
- getChannelFormatOptions(channel: ColorChannel): Intl.NumberFormatOptions {
105
- switch (channel) {
106
- case "hue":
107
- return { style: "unit", unit: "degree", unitDisplay: "narrow" }
108
- case "saturation":
109
- case "lightness":
110
- case "alpha":
111
- return { style: "percent" }
112
- default:
113
- throw new Error("Unknown color channel: " + channel)
114
- }
115
- }
116
-
117
- formatChannelValue(channel: ColorChannel, locale: string) {
118
- let options = this.getChannelFormatOptions(channel)
119
- let value = this.getChannelValue(channel)
120
- if (channel === "saturation" || channel === "lightness") {
121
- value /= 100
122
- }
123
- return new Intl.NumberFormat(locale, options).format(value)
124
- }
125
-
126
- getChannelRange(channel: ColorChannel): ColorChannelRange {
127
- switch (channel) {
128
- case "hue":
129
- return { minValue: 0, maxValue: 360, step: 1, pageSize: 15 }
130
- case "saturation":
131
- case "lightness":
132
- return { minValue: 0, maxValue: 100, step: 1, pageSize: 10 }
133
- case "alpha":
134
- return { minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1 }
135
- default:
136
- throw new Error("Unknown color channel: " + channel)
137
- }
138
- }
139
-
140
- toJSON(): Record<"h" | "s" | "l" | "a", number> {
141
- return { h: this.hue, s: this.saturation, l: this.lightness, a: this.alpha }
142
- }
143
-
144
- getFormat(): ColorFormat {
145
- return "hsla"
146
- }
147
-
148
- private static colorChannels: [ColorChannel, ColorChannel, ColorChannel] = ["hue", "saturation", "lightness"]
149
-
150
- getChannels(): [ColorChannel, ColorChannel, ColorChannel] {
151
- return HSLColor.colorChannels
152
- }
153
- }
package/src/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export { getColorAreaGradient } from "./area-gradient"
2
- export { Color } from "./color"
3
- export { normalizeColor, parseColor } from "./parse-color"
4
- export type { ColorAxes, ColorChannel, ColorChannelRange, ColorFormat, ColorType } from "./types"
@@ -1,14 +0,0 @@
1
- const nativeColors /* @__PURE__ */ =
2
- "aliceblue:f0f8ff,antiquewhite:faebd7,aqua:00ffff,aquamarine:7fffd4,azure:f0ffff,beige:f5f5dc,bisque:ffe4c4,black:000000,blanchedalmond:ffebcd,blue:0000ff,blueviolet:8a2be2,brown:a52a2a,burlywood:deb887,cadetblue:5f9ea0,chartreuse:7fff00,chocolate:d2691e,coral:ff7f50,cornflowerblue:6495ed,cornsilk:fff8dc,crimson:dc143c,cyan:00ffff,darkblue:00008b,darkcyan:008b8b,darkgoldenrod:b8860b,darkgray:a9a9a9,darkgreen:006400,darkkhaki:bdb76b,darkmagenta:8b008b,darkolivegreen:556b2f,darkorange:ff8c00,darkorchid:9932cc,darkred:8b0000,darksalmon:e9967a,darkseagreen:8fbc8f,darkslateblue:483d8b,darkslategray:2f4f4f,darkturquoise:00ced1,darkviolet:9400d3,deeppink:ff1493,deepskyblue:00bfff,dimgray:696969,dodgerblue:1e90ff,firebrick:b22222,floralwhite:fffaf0,forestgreen:228b22,fuchsia:ff00ff,gainsboro:dcdcdc,ghostwhite:f8f8ff,gold:ffd700,goldenrod:daa520,gray:808080,green:008000,greenyellow:adff2f,honeydew:f0fff0,hotpink:ff69b4,indianred:cd5c5c,indigo:4b0082,ivory:fffff0,khaki:f0e68c,lavender:e6e6fa,lavenderblush:fff0f5,lawngreen:7cfc00,lemonchiffon:fffacd,lightblue:add8e6,lightcoral:f08080,lightcyan:e0ffff,lightgoldenrodyellow:fafad2,lightgrey:d3d3d3,lightgreen:90ee90,lightpink:ffb6c1,lightsalmon:ffa07a,lightseagreen:20b2aa,lightskyblue:87cefa,lightslategray:778899,lightsteelblue:b0c4de,lightyellow:ffffe0,lime:00ff00,limegreen:32cd32,linen:faf0e6,magenta:ff00ff,maroon:800000,mediumaquamarine:66cdaa,mediumblue:0000cd,mediumorchid:ba55d3,mediumpurple:9370d8,mediumseagreen:3cb371,mediumslateblue:7b68ee,mediumspringgreen:00fa9a,mediumturquoise:48d1cc,mediumvioletred:c71585,midnightblue:191970,mintcream:f5fffa,mistyrose:ffe4e1,moccasin:ffe4b5,navajowhite:ffdead,navy:000080,oldlace:fdf5e6,olive:808000,olivedrab:6b8e23,orange:ffa500,orangered:ff4500,orchid:da70d6,palegoldenrod:eee8aa,palegreen:98fb98,paleturquoise:afeeee,palevioletred:d87093,papayawhip:ffefd5,peachpuff:ffdab9,peru:cd853f,pink:ffc0cb,plum:dda0dd,powderblue:b0e0e6,purple:800080,red:ff0000,rosybrown:bc8f8f,royalblue:4169e1,saddlebrown:8b4513,salmon:fa8072,sandybrown:f4a460,seagreen:2e8b57,seashell:fff5ee,sienna:a0522d,silver:c0c0c0,skyblue:87ceeb,slateblue:6a5acd,slategray:708090,snow:fffafa,springgreen:00ff7f,steelblue:4682b4,tan:d2b48c,teal:008080,thistle:d8bfd8,tomato:ff6347,turquoise:40e0d0,violet:ee82ee,wheat:f5deb3,white:ffffff,whitesmoke:f5f5f5,yellow:ffff00,yellowgreen:9acd32"
3
-
4
- const makeMap = (str: string) => {
5
- const map = new Map<string, string>()
6
- const list = str.split(",")
7
- for (let i = 0; i < list.length; i++) {
8
- const [key, val] = list[i].split(":")
9
- map.set(key, `#${val}`)
10
- }
11
- return map
12
- }
13
-
14
- export const nativeColorMap /* @__PURE__ */ = makeMap(nativeColors)
@@ -1,25 +0,0 @@
1
- import { HSBColor } from "./hsb-color"
2
- import { HSLColor } from "./hsl-color"
3
- import { nativeColorMap } from "./native-color"
4
- import { RGBColor } from "./rgb-color"
5
- import type { ColorType } from "./types"
6
-
7
- export const parseColor = (value: string): ColorType => {
8
- if (nativeColorMap.has(value)) {
9
- return parseColor(nativeColorMap.get(value)!)
10
- }
11
-
12
- const result = RGBColor.parse(value) || HSBColor.parse(value) || HSLColor.parse(value)
13
-
14
- if (!result) {
15
- const error = new Error("Invalid color value: " + value)
16
- Error.captureStackTrace?.(error, parseColor)
17
- throw error
18
- }
19
-
20
- return result
21
- }
22
-
23
- export const normalizeColor = (v: string | ColorType) => {
24
- return typeof v === "string" ? parseColor(v) : v
25
- }
package/src/rgb-color.ts DELETED
@@ -1,230 +0,0 @@
1
- import { clampValue, toFixedNumber } from "@zag-js/numeric-range"
2
- import { Color } from "./color"
3
- import { HSBColor } from "./hsb-color"
4
- import { HSLColor } from "./hsl-color"
5
- import type { ColorChannel, ColorChannelRange, ColorFormat, ColorStringFormat, ColorType } from "./types"
6
-
7
- export class RGBColor extends Color {
8
- constructor(
9
- private red: number,
10
- private green: number,
11
- private blue: number,
12
- private alpha: number,
13
- ) {
14
- super()
15
- }
16
-
17
- static parse(value: string) {
18
- let colors: (number | undefined)[] = []
19
-
20
- // matching #rgb, #rgba, #rrggbb, #rrggbbaa
21
- if (/^#[\da-f]+$/i.test(value) && [4, 5, 7, 9].includes(value.length)) {
22
- const values = (value.length < 6 ? value.replace(/[^#]/gi, "$&$&") : value).slice(1).split("")
23
- while (values.length > 0) {
24
- colors.push(parseInt(values.splice(0, 2).join(""), 16))
25
- }
26
- colors[3] = colors[3] !== undefined ? colors[3] / 255 : undefined
27
- }
28
-
29
- // matching rgb(rrr, ggg, bbb), rgba(rrr, ggg, bbb, 0.a)
30
- const match = value.match(/^rgba?\((.*)\)$/)
31
-
32
- if (match?.[1]) {
33
- colors = match[1]
34
- .split(",")
35
- .map((value) => Number(value.trim()))
36
- .map((num, i) => clampValue(num, 0, i < 3 ? 255 : 1))
37
- }
38
-
39
- //@ts-expect-error
40
- return colors.length < 3 ? undefined : new RGBColor(colors[0], colors[1], colors[2], colors[3] ?? 1)
41
- }
42
-
43
- toString(format: ColorStringFormat) {
44
- switch (format) {
45
- case "hex":
46
- return (
47
- "#" +
48
- (
49
- this.red.toString(16).padStart(2, "0") +
50
- this.green.toString(16).padStart(2, "0") +
51
- this.blue.toString(16).padStart(2, "0")
52
- ).toUpperCase()
53
- )
54
- case "hexa":
55
- return (
56
- "#" +
57
- (
58
- this.red.toString(16).padStart(2, "0") +
59
- this.green.toString(16).padStart(2, "0") +
60
- this.blue.toString(16).padStart(2, "0") +
61
- Math.round(this.alpha * 255)
62
- .toString(16)
63
- .padStart(2, "0")
64
- ).toUpperCase()
65
- )
66
- case "rgb":
67
- return `rgb(${this.red}, ${this.green}, ${this.blue})`
68
- case "css":
69
- case "rgba":
70
- return `rgba(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`
71
- case "hsl":
72
- return this.toHSL().toString("hsl")
73
- case "hsb":
74
- return this.toHSB().toString("hsb")
75
- default:
76
- return this.toFormat(format).toString(format)
77
- }
78
- }
79
-
80
- toFormat(format: ColorFormat): ColorType {
81
- switch (format) {
82
- case "rgba":
83
- return this
84
- case "hsba":
85
- return this.toHSB()
86
- case "hsla":
87
- return this.toHSL()
88
- default:
89
- throw new Error("Unsupported color conversion: rgb -> " + format)
90
- }
91
- }
92
-
93
- toHexInt(): number {
94
- return (this.red << 16) | (this.green << 8) | this.blue
95
- }
96
-
97
- /**
98
- * Converts an RGB color value to HSB.
99
- * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB.
100
- * @returns An HSBColor object.
101
- */
102
- private toHSB(): ColorType {
103
- const red = this.red / 255
104
- const green = this.green / 255
105
- const blue = this.blue / 255
106
- const min = Math.min(red, green, blue)
107
- const brightness = Math.max(red, green, blue)
108
- const chroma = brightness - min
109
- const saturation = brightness === 0 ? 0 : chroma / brightness
110
- let hue = 0 // achromatic
111
-
112
- if (chroma !== 0) {
113
- switch (brightness) {
114
- case red:
115
- hue = (green - blue) / chroma + (green < blue ? 6 : 0)
116
- break
117
- case green:
118
- hue = (blue - red) / chroma + 2
119
- break
120
- case blue:
121
- hue = (red - green) / chroma + 4
122
- break
123
- }
124
-
125
- hue /= 6
126
- }
127
-
128
- return new HSBColor(
129
- toFixedNumber(hue * 360, 2),
130
- toFixedNumber(saturation * 100, 2),
131
- toFixedNumber(brightness * 100, 2),
132
- toFixedNumber(this.alpha, 2),
133
- )
134
- }
135
-
136
- /**
137
- * Converts an RGB color value to HSL.
138
- * Conversion formula adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB.
139
- * @returns An HSLColor object.
140
- */
141
- private toHSL(): ColorType {
142
- const red = this.red / 255
143
- const green = this.green / 255
144
- const blue = this.blue / 255
145
- const min = Math.min(red, green, blue)
146
- const max = Math.max(red, green, blue)
147
- const lightness = (max + min) / 2
148
- const chroma = max - min
149
-
150
- let hue = -1
151
- let saturation = -1
152
-
153
- if (chroma === 0) {
154
- hue = saturation = 0 // achromatic
155
- } else {
156
- saturation = chroma / (lightness < 0.5 ? max + min : 2 - max - min)
157
-
158
- switch (max) {
159
- case red:
160
- hue = (green - blue) / chroma + (green < blue ? 6 : 0)
161
- break
162
- case green:
163
- hue = (blue - red) / chroma + 2
164
- break
165
- case blue:
166
- hue = (red - green) / chroma + 4
167
- break
168
- }
169
-
170
- hue /= 6
171
- }
172
-
173
- return new HSLColor(
174
- toFixedNumber(hue * 360, 2),
175
- toFixedNumber(saturation * 100, 2),
176
- toFixedNumber(lightness * 100, 2),
177
- toFixedNumber(this.alpha, 2),
178
- )
179
- }
180
-
181
- clone(): ColorType {
182
- return new RGBColor(this.red, this.green, this.blue, this.alpha)
183
- }
184
-
185
- getChannelFormatOptions(channel: ColorChannel): Intl.NumberFormatOptions {
186
- switch (channel) {
187
- case "red":
188
- case "green":
189
- case "blue":
190
- return { style: "decimal" }
191
- case "alpha":
192
- return { style: "percent" }
193
- default:
194
- throw new Error("Unknown color channel: " + channel)
195
- }
196
- }
197
-
198
- formatChannelValue(channel: ColorChannel, locale: string) {
199
- let options = this.getChannelFormatOptions(channel)
200
- let value = this.getChannelValue(channel)
201
- return new Intl.NumberFormat(locale, options).format(value)
202
- }
203
-
204
- getChannelRange(channel: ColorChannel): ColorChannelRange {
205
- switch (channel) {
206
- case "red":
207
- case "green":
208
- case "blue":
209
- return { minValue: 0x0, maxValue: 0xff, step: 0x1, pageSize: 0x11 }
210
- case "alpha":
211
- return { minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1 }
212
- default:
213
- throw new Error("Unknown color channel: " + channel)
214
- }
215
- }
216
-
217
- toJSON(): Record<"r" | "g" | "b" | "a", number> {
218
- return { r: this.red, g: this.green, b: this.blue, a: this.alpha }
219
- }
220
-
221
- getFormat(): ColorFormat {
222
- return "rgba"
223
- }
224
-
225
- private static colorChannels: [ColorChannel, ColorChannel, ColorChannel] = ["red", "green", "blue"]
226
-
227
- getChannels(): [ColorChannel, ColorChannel, ColorChannel] {
228
- return RGBColor.colorChannels
229
- }
230
- }
package/src/types.ts DELETED
@@ -1,94 +0,0 @@
1
- export type ColorHexFormat = "hex" | "hexa"
2
-
3
- export type ColorFormat = "rgba" | "hsla" | "hsba"
4
-
5
- export type ColorStringFormat = ColorHexFormat | ColorFormat | "rgb" | "hsl" | "hsb" | "css"
6
-
7
- export type ColorChannel = "hue" | "saturation" | "brightness" | "lightness" | "red" | "green" | "blue" | "alpha"
8
-
9
- export interface Color2DAxes {
10
- xChannel: ColorChannel
11
- yChannel: ColorChannel
12
- }
13
-
14
- export interface ColorAxes extends Color2DAxes {
15
- zChannel: ColorChannel
16
- }
17
-
18
- export interface ColorChannelRange {
19
- /** The minimum value of the color channel. */
20
- minValue: number
21
- /** The maximum value of the color channel. */
22
- maxValue: number
23
- /** The step value of the color channel, used when incrementing and decrementing. */
24
- step: number
25
- /** The page step value of the color channel, used when incrementing and decrementing. */
26
- pageSize: number
27
- }
28
-
29
- export interface ColorType {
30
- /** Converts the color to the given color format, and returns a new Color object. */
31
- toFormat(format: ColorFormat): ColorType
32
- /** Converts the color to a JSON object. */
33
- toJSON(): Record<string, number>
34
- /** Converts the color to a string in the given format. */
35
- toString(format: ColorStringFormat): string
36
- /** Converts the color to hex, and returns an integer representation. */
37
- toHexInt(): number
38
-
39
- /**
40
- * Returns the numeric value for a given channel.
41
- * Throws an error if the channel is unsupported in the current color format.
42
- */
43
- getChannelValue(channel: ColorChannel): number
44
- /**
45
- * Sets the numeric value for a given channel, and returns a new Color object.
46
- * Throws an error if the channel is unsupported in the current color format.
47
- */
48
- withChannelValue(channel: ColorChannel, value: number): ColorType
49
- /**
50
- * Returns the formatted value for a given channel.
51
- */
52
- formatChannelValue(channel: ColorChannel, locale: string): string
53
-
54
- /**
55
- * Returns the minimum, maximum, and step values for a given channel.
56
- */
57
- getChannelRange(channel: ColorChannel): ColorChannelRange
58
- /**
59
- * Returns the color space, 'rgb', 'hsb' or 'hsl', for the current color.
60
- */
61
- getFormat(): ColorFormat
62
- /**
63
- * Returns the color space axes, xChannel, yChannel, zChannel.
64
- */
65
- getColorAxes(xyChannels: Color2DAxes): ColorAxes
66
- /**
67
- * Returns an array of the color channels within the current color space space.
68
- */
69
- getChannels(): [ColorChannel, ColorChannel, ColorChannel]
70
- /**
71
- * Returns a new Color object with the same values as the current color.
72
- */
73
- clone(): ColorType
74
- /**
75
- * Whether the color is equal to another color.
76
- */
77
- isEqual(color: ColorType): boolean
78
- /**
79
- * Increments the color channel by the given step size, and returns a new Color object.
80
- */
81
- incrementChannel(channel: ColorChannel, stepSize: number): ColorType
82
- /**
83
- * Decrements the color channel by the given step size, and returns a new Color object.
84
- */
85
- decrementChannel(channel: ColorChannel, stepSize: number): ColorType
86
- /**
87
- * Returns the color channel value as a percentage of the channel range.
88
- */
89
- getChannelValuePercent(channel: ColorChannel, value?: number): number
90
- /**
91
- * Returns the color channel value for a given percentage of the channel range.
92
- */
93
- getChannelPercentValue(channel: ColorChannel, percent: number): number
94
- }