@solid-primitives/utils 6.4.1 → 7.0.0-next.1

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/LICENSE CHANGED
@@ -19,3 +19,74 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
+
23
+ ---
24
+
25
+ Portions of the color utilities (src/colors/) are derived from third-party
26
+ sources under the following licenses:
27
+
28
+ ---
29
+
30
+ Kobalte — MIT License
31
+ Copyright (c) Fabien Marie-Louise
32
+ https://github.com/kobaltedev/kobalte
33
+
34
+ Permission is hereby granted, free of charge, to any person obtaining a copy
35
+ of this software and associated documentation files (the "Software"), to deal
36
+ in the Software without restriction, including without limitation the rights
37
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
38
+ copies of the Software, and to permit persons to whom the Software is
39
+ furnished to do so, subject to the following conditions:
40
+
41
+ The above copyright notice and this permission notice shall be included in all
42
+ copies or substantial portions of the Software.
43
+
44
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
45
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
46
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
47
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
48
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
49
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
50
+ SOFTWARE.
51
+
52
+ ---
53
+
54
+ React Spectrum — Apache License 2.0
55
+ Copyright (c) 2020 Adobe
56
+ https://github.com/adobe/react-spectrum
57
+
58
+ Licensed under the Apache License, Version 2.0 (the "License");
59
+ you may not use this file except in compliance with the License.
60
+ You may obtain a copy of the License at
61
+
62
+ https://www.apache.org/licenses/LICENSE-2.0
63
+
64
+ Unless required by applicable law or agreed to in writing, software
65
+ distributed under the License is distributed on an "AS IS" BASIS,
66
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
67
+ See the License for the specific language governing permissions and
68
+ limitations under the License.
69
+
70
+ ---
71
+
72
+ OKLab color space — MIT License
73
+ Copyright (c) Björn Ottosson
74
+ https://bottosson.github.io/posts/oklab/
75
+
76
+ Permission is hereby granted, free of charge, to any person obtaining a copy
77
+ of this software and associated documentation files (the "Software"), to deal
78
+ in the Software without restriction, including without limitation the rights
79
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
80
+ copies of the Software, and to permit persons to whom the Software is
81
+ furnished to do so, subject to the following conditions:
82
+
83
+ The above copyright notice and this permission notice shall be included in all
84
+ copies or substantial portions of the Software.
85
+
86
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
87
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
88
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
89
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
90
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
91
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
92
+ SOFTWARE.
package/README.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  # @solid-primitives/utils
6
6
 
7
+ [![tested with vitest](https://img.shields.io/badge/tested_with-vitest-6E9F18?style=for-the-badge&logo=vitest)](https://vitest.dev)
8
+
7
9
  Solid Primitives Utilities is a support and helper package for a number of primitives in our library. Please free to augment or centralize useful utilities and methods in this package for sharing.
8
10
 
9
11
  ## Installation
@@ -115,6 +117,280 @@ const { data } = createSSE<Event>(url, { transform: safe(json) });
115
117
  - **`safe(transform, fallback?)`** - Wrap any transform in a `try/catch`; returns `fallback` instead of throwing
116
118
  - **`pipe(a, b)`** - Compose two transforms into one
117
119
 
120
+ ## wrapSetter
121
+
122
+ It is a typical use case to react on setting a new value; this is especially cumbersome for stores, where you otherwise need the `deep` package to make effects subscribe to all changes. A more performant and simple approach is to wrap the setter of your signal or store. To simplify this approach, we provide a `wrapSetter` function:
123
+
124
+ ```ts
125
+ import { createStore } from "solid-js";
126
+ import { wrapSetter } from "@solid-primitives/utils";
127
+
128
+ const [state, setState] = wrapSetter(
129
+ createStore(
130
+ localStorage.getItem("persistedState")
131
+ ? JSON.parse(localStorage.getItem("persistedState"))
132
+ : initialState,
133
+ ),
134
+ setter => next => {
135
+ const output = setState(next);
136
+ localStorage.setItem(
137
+ "persistedState",
138
+ latest(() => JSON.stringify(state)),
139
+ );
140
+ return output;
141
+ },
142
+ );
143
+ ```
144
+
145
+ If the signal or store is destructured into a tuple and augmented with additional values, those are left intact in the output. For the TS types to work, you need to `as const` the new tuple:
146
+
147
+ ```ts
148
+ import { createSignal } from "solid-js";
149
+ import { wrapSetter } from "@solid-primitives/utils";
150
+
151
+ const augmentedSignal = [...createSignal(0), { extra: "data" }] as const;
152
+ const [count, setCount, data] = wrapSetter(
153
+ augmented,
154
+ setter => next => (console.log(next), setter(next)),
155
+ );
156
+ ```
157
+
158
+ ## Color utilities
159
+
160
+ Multi-format color parsing, conversion, and accessibility naming — available as a separate subpath so you only pay for what you use.
161
+
162
+ > **Credits** — The core color types, parsing, and color-space conversion logic (`types.ts`, `helpers.ts`, `intl.ts`) are adapted from [Kobalte](https://github.com/kobaltedev/kobalte) (MIT, Copyright Fabien Marie-Louise), which itself credits the [React Spectrum](https://github.com/adobe/react-spectrum) team (Apache 2.0, Copyright 2020 Adobe). The OKLCH inverse pipeline in `manipulation.ts` uses coefficients from [Björn Ottosson's OKLab](https://bottosson.github.io/posts/oklab/) work.
163
+
164
+ ```ts
165
+ import {
166
+ parseColor,
167
+ normalizeColor,
168
+ getColorChannels,
169
+ normalizeHue,
170
+ } from "@solid-primitives/utils/colors";
171
+ import { COLOR_INTL_TRANSLATIONS } from "@solid-primitives/utils/colors";
172
+ ```
173
+
174
+ ### Parsing & conversion
175
+
176
+ ```ts
177
+ const color = parseColor("#3264C8");
178
+
179
+ color.toString(); // "rgb(50, 100, 200)" (css default)
180
+ color.toString("hsl"); // "hsl(220 60% 49.02%)"
181
+ color.toString("hsb"); // "hsb(220 75% 78.43%)"
182
+ color.toString("hex"); // "#3264C8"
183
+ color.toString("hexa"); // "#3264C8FF"
184
+
185
+ // Convert to another space and inspect channels
186
+ const hsl = color.toFormat("hsl");
187
+ hsl.getChannelValue("hue"); // 220
188
+ hsl.getChannelValue("saturation"); // 60
189
+ hsl.getChannelValue("lightness"); // 49.02
190
+
191
+ // Derive a new color by changing one channel
192
+ const lighter = hsl.withChannelValue("lightness", 70);
193
+ lighter.toString("hex"); // "#6699E8"
194
+ ```
195
+
196
+ Accepted input formats:
197
+
198
+ | Format | Examples |
199
+ | ------ | ------------------------------------------------------------------------------------------ |
200
+ | Hex | `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa` |
201
+ | RGB | `rgb(50 100 200)`, `rgb(50, 100, 200)`, `rgb(50 100 200 / 0.5)`, `rgba(50, 100, 200, 0.5)` |
202
+ | HSL | `hsl(220, 60%, 49%)`, `hsla(220, 60%, 49%, 0.5)` |
203
+ | HSB | `hsb(220, 75%, 78%)`, `hsba(220, 75%, 78%, 0.5)` |
204
+
205
+ `parseColor` throws for unrecognised strings. Use `normalizeColor` when your input may already be a `Color` object:
206
+
207
+ ```ts
208
+ function accept(value: string | Color) {
209
+ const color = normalizeColor(value); // no-op if already a Color
210
+ }
211
+ ```
212
+
213
+ ### Channel metadata
214
+
215
+ ```ts
216
+ // Ordered channel names for a space
217
+ getColorChannels("rgb"); // ["red", "green", "blue"]
218
+ getColorChannels("hsl"); // ["hue", "saturation", "lightness"]
219
+ getColorChannels("hsb"); // ["hue", "saturation", "brightness"]
220
+
221
+ // Range info for driving sliders
222
+ color.getChannelRange("red"); // { minValue: 0, maxValue: 255, step: 1, pageSize: 17 }
223
+ color.getChannelRange("alpha"); // { minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1 }
224
+
225
+ // Intl format options for display
226
+ color.getChannelFormatOptions("hue"); // { style: "unit", unit: "degree", unitDisplay: "narrow" }
227
+
228
+ // Locale-aware formatted value
229
+ color.toFormat("hsl").formatChannelValue("saturation"); // "60%"
230
+
231
+ // Axis layout for a 2D color area picker
232
+ color.getColorSpaceAxes({ xChannel: "saturation", yChannel: "brightness" });
233
+ // { xChannel: "saturation", yChannel: "brightness", zChannel: "hue" }
234
+ ```
235
+
236
+ ### Hue normalization
237
+
238
+ ```ts
239
+ normalizeHue(370); // 10
240
+ normalizeHue(-10); // 350
241
+ normalizeHue(360); // 360 — kept distinct from 0 for full-circle sliders
242
+ ```
243
+
244
+ ### Accessible color naming
245
+
246
+ `getColorName` converts to [OKLCH](https://www.w3.org/TR/css-color-4/#the-oklch-notation) — a perceptually uniform space — and produces a human-readable description suitable for `aria-label` and similar attributes. Pass `COLOR_INTL_TRANSLATIONS` for English or supply your own translations object.
247
+
248
+ ```ts
249
+ import { parseColor, COLOR_INTL_TRANSLATIONS } from "@solid-primitives/utils/colors";
250
+
251
+ const t = COLOR_INTL_TRANSLATIONS;
252
+
253
+ parseColor("#3264C8").getColorName(t); // "dark vibrant blue"
254
+ parseColor("hsl(48 80% 55%)").getColorName(t); // "orange"
255
+ parseColor("rgb(50 100 200 / 0.2)").getColorName(t); // "dark vibrant blue, 80% transparent"
256
+
257
+ parseColor("#3264C8").getHueName(t); // "blue"
258
+ parseColor("#c86432").getHueName(t); // "brown"
259
+
260
+ // Channel label for a slider aria-label
261
+ parseColor("#fff").getChannelName("saturation", t); // "Saturation"
262
+ ```
263
+
264
+ Providing translations for other locales:
265
+
266
+ ```ts
267
+ import type { ColorIntlTranslations } from "@solid-primitives/utils/colors";
268
+
269
+ const frTranslations: ColorIntlTranslations = {
270
+ ...COLOR_INTL_TRANSLATIONS,
271
+ hue: "Teinte",
272
+ saturation: "Saturation",
273
+ lightness: "Luminosité",
274
+ blue: "bleu",
275
+ // ...
276
+ };
277
+ ```
278
+
279
+ ### Safe parsing
280
+
281
+ ```ts
282
+ tryParseColor("#3264C8"); // Color
283
+ tryParseColor("nope"); // undefined — never throws
284
+
285
+ isValidColor("#3264C8"); // true
286
+ isValidColor("nope"); // false
287
+
288
+ detectColorFormat("rgb(50, 100, 200)"); // "rgb"
289
+ detectColorFormat("#3264C8FF"); // "hexa"
290
+ detectColorFormat("hsla(220, 60%, 49%, 0.5)"); // "hsla"
291
+ detectColorFormat("nope"); // undefined
292
+ ```
293
+
294
+ ### Manipulation
295
+
296
+ All manipulation functions return a new `Color`; the input is never mutated. `amount` is a 0–1 ratio representing percentage points on the relevant HSL channel (e.g. `0.1` = 10 pp).
297
+
298
+ ```ts
299
+ import {
300
+ lighten,
301
+ darken,
302
+ saturate,
303
+ desaturate,
304
+ complement,
305
+ mix,
306
+ } from "@solid-primitives/utils/colors";
307
+
308
+ lighten(color, 0.1); // +10 lightness (HSL)
309
+ darken(color, 0.1); // −10 lightness (HSL)
310
+ saturate(color, 0.2); // +20 saturation (HSL)
311
+ desaturate(color, 0.2); // −20 saturation (HSL)
312
+ complement(color); // hue + 180° (HSL)
313
+
314
+ mix(black, white); // 50/50 blend in RGB
315
+ mix(black, white, 0.25); // 25% toward white
316
+ ```
317
+
318
+ ### Accessibility (WCAG 2.1)
319
+
320
+ ```ts
321
+ import { contrastRatio, isReadable } from "@solid-primitives/utils/colors";
322
+
323
+ contrastRatio(parseColor("#000"), parseColor("#fff")); // 21
324
+ contrastRatio(parseColor("#3264C8"), parseColor("#fff")); // ~3.9
325
+
326
+ // AA / AAA, normal / large text
327
+ isReadable(fg, bg); // AA normal (≥ 4.5 : 1)
328
+ isReadable(fg, bg, "AA", "large"); // AA large (≥ 3.0 : 1)
329
+ isReadable(fg, bg, "AAA"); // AAA normal (≥ 7.0 : 1)
330
+ isReadable(fg, bg, "AAA", "large"); // AAA large (≥ 4.5 : 1)
331
+ ```
332
+
333
+ ### Color scales
334
+
335
+ ```ts
336
+ import { colorScale, perceptualColorScale } from "@solid-primitives/utils/colors";
337
+
338
+ // 5-step RGB gradient from black to white
339
+ colorScale(parseColor("#000"), parseColor("#fff"), 5);
340
+ // [#000000, #404040, #808080, #BFBFBF, #FFFFFF]
341
+
342
+ // 5-step perceptual gradient (OKLCH space, shortest hue arc)
343
+ // Red → Blue goes through purple, not green
344
+ perceptualColorScale(parseColor("hsl(0, 80%, 50%)"), parseColor("hsl(240, 80%, 50%)"), 5);
345
+ ```
346
+
347
+ ### List of exports
348
+
349
+ **Parsing**
350
+
351
+ - **`parseColor(value)`** - Parse a color string; throws on invalid input
352
+ - **`normalizeColor(value)`** - Accept a string or `Color`, always return a `Color`
353
+ - **`tryParseColor(value)`** - Like `parseColor` but returns `undefined` instead of throwing
354
+ - **`isValidColor(value)`** - Boolean check without parsing overhead
355
+ - **`detectColorFormat(value)`** - Detect the syntax format of a color string
356
+
357
+ **Color space / channels**
358
+
359
+ - **`getColorChannels(space)`** - Ordered channel triple for a color space
360
+ - **`normalizeHue(hue)`** - Wrap a hue angle to `[0, 360]`
361
+ - **`colorToOKLCH(color)`** - Convert any `Color` to `[L, C, H]` in OKLCH space
362
+
363
+ **Manipulation**
364
+
365
+ - **`lighten(color, amount)`** / **`darken(color, amount)`** - Adjust HSL lightness
366
+ - **`saturate(color, amount)`** / **`desaturate(color, amount)`** - Adjust HSL saturation
367
+ - **`complement(color)`** - Hue + 180°
368
+ - **`mix(a, b, ratio?)`** - Blend two colors in RGB space
369
+
370
+ **Accessibility**
371
+
372
+ - **`contrastRatio(a, b)`** - WCAG 2.1 contrast ratio (1–21)
373
+ - **`isReadable(fg, bg, level?, size?)`** - WCAG 2.1 AA / AAA compliance check
374
+
375
+ **Color scales**
376
+
377
+ - **`colorScale(from, to, steps)`** - Linear RGB gradient
378
+ - **`perceptualColorScale(from, to, steps)`** - Perceptually uniform OKLCH gradient
379
+
380
+ **i18n / naming**
381
+
382
+ - **`COLOR_INTL_TRANSLATIONS`** - Default English translations
383
+ - **`ColorIntlTranslations`** _(type)_ - Shape of a translations object
384
+
385
+ **Types**
386
+
387
+ - **`Color`** _(interface)_ - The immutable color value type
388
+ - **`ColorFormat`** _(type)_ - `"hex" | "hexa" | "rgb" | "rgba" | "hsl" | "hsla" | "hsb" | "hsba"`
389
+ - **`ColorSpace`** _(type)_ - `"rgb" | "hsl" | "hsb"`
390
+ - **`ColorChannel`** _(type)_ - `"hue" | "saturation" | "brightness" | "lightness" | "red" | "green" | "blue" | "alpha"`
391
+ - **`ColorAxes`** _(type)_ - `{ xChannel, yChannel, zChannel: ColorChannel }`
392
+ - **`ColorChannelRange`** _(type)_ - `{ minValue, maxValue, step, pageSize }`
393
+
118
394
  ## Changelog
119
395
 
120
396
  See [CHANGELOG.md](./CHANGELOG.md)
@@ -0,0 +1,46 @@
1
+ import type { ColorChannel, ColorSpace, Color as IColor } from "./types.js";
2
+ /**
3
+ * Parses a color string into a {@link Color} object.
4
+ *
5
+ * Supported formats:
6
+ * - **Hex**: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`
7
+ * - **RGB**: `rgb(r g b)`, `rgb(r, g, b)`, `rgb(r g b / a)`, `rgba(r, g, b, a)`
8
+ * - **HSL**: `hsl(h, s%, l%)`, `hsla(h, s%, l%, a)`
9
+ * - **HSB**: `hsb(h, s%, b%)`, `hsba(h, s%, b%, a)`
10
+ *
11
+ * @throws if the string does not match any supported format.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const color = parseColor("#3264C8");
16
+ * color.toString("hsl"); // "hsl(220 60% 49.02%)"
17
+ * ```
18
+ */
19
+ export declare function parseColor(value: string): IColor;
20
+ /**
21
+ * Accepts either a color string or an existing {@link Color} and always returns a `Color`.
22
+ * Useful for normalizing props that accept both forms.
23
+ */
24
+ export declare function normalizeColor(v: string | IColor): IColor;
25
+ /**
26
+ * Returns the ordered channel triple for a given color space.
27
+ *
28
+ * - `"rgb"` → `["red", "green", "blue"]`
29
+ * - `"hsl"` → `["hue", "saturation", "lightness"]`
30
+ * - `"hsb"` → `["hue", "saturation", "brightness"]`
31
+ */
32
+ export declare function getColorChannels(colorSpace: ColorSpace): [ColorChannel, ColorChannel, ColorChannel];
33
+ /**
34
+ * Normalizes a hue angle to the range `[0, 360]`.
35
+ * Exactly `360` is kept as-is so that a full-circle endpoint stays distinct from `0`.
36
+ */
37
+ export declare function normalizeHue(hue: number): number;
38
+ /**
39
+ * Converts any {@link Color} to OKLCH `[L, C, H]` — a perceptually uniform space
40
+ * where L is perceived lightness (0–1), C is chroma (≥ 0), and H is a hue angle (0–360).
41
+ *
42
+ * Full pipeline: sRGB bytes → linear sRGB (gamma-expand) → CIE XYZ D65 → OKLab → OKLCH.
43
+ *
44
+ * @see https://www.w3.org/TR/css-color-4/#color-conversion-code
45
+ */
46
+ export declare function colorToOKLCH(color: IColor): [l: number, c: number, h: number];