Skip to content

feat(color-picker): migrate to culori and add add OKLCH support#816

Open
paanSinghCoder wants to merge 2 commits into
mainfrom
feat/color-picker-culori-oklch
Open

feat(color-picker): migrate to culori and add add OKLCH support#816
paanSinghCoder wants to merge 2 commits into
mainfrom
feat/color-picker-culori-oklch

Conversation

@paanSinghCoder
Copy link
Copy Markdown
Contributor

@paanSinghCoder paanSinghCoder commented May 20, 2026

Summary

  • Swaps color for culori in the ColorPicker component so it can accept and emit oklch() alongside hex/rgb/hsl
  • Adds oklch to SUPPORTED_MODES and a formatOklch() helper (4-decimal L/C, 2-decimal H, hue pinned to 0 for grays)
  • Updates docs (props, demo, mdx) and adds an example page at /examples/color-picker

Why culori (not color-convert)

The picker's value prop accepts any CSS color string from consumers — hex, rgb/rgba, hsl/hsla, oklch, named colors. color-convert is route-based; it has no CSS parser and no stringifiers (except a hex helper), so we'd hand-roll ~170 lines of parsers and formatters. culori ships exactly the surface this component needs.

culori util used here What it does color-convert equivalent?
parse Any CSS string → typed color object No — color-convert takes numeric tuples only
converter('hsl') Any color object → HSL No — explicit routes only (c.rgb.hsl, c.hex.rgb, …)
formatHex Color → #rrggbb Partial — c.rgb.hex returns 'FF0000' (no #, no alpha)
formatHex8 Color → #rrggbbaa No — manual alpha-to-hex concat
formatHsl Color → hsl(...) / hsla(...) No — manual template
formatRgb Color → rgb(...) / rgba(...) No — manual template

Caveat

Sliders still operate in HSL. oklch is an I/O format, not a perceptual editing mode — an oklch() value passed in will not be bit-identical when read back, because the round-trip goes through HSL → sRGB → OKLCH.

Follow-up

The VS Code plugin (#759) currently uses color-convert because its input is a closed set of oklch() tokens. We could move it to culori later to consolidate on one color library across the monorepo — the trade-off is ~9 KB gzipped in the plugin bundle vs. removing the parser/scaling/type-shim glue we hand-rolled there.

Test plan

  • pnpm test components/color-picker — 24/24 passing (3 new tests for oklch input, oklch mode output, and oklch alpha tail)
  • pnpm tsc --noEmit clean on touched files
  • pnpm biome check clean on touched files
  • Visit /examples/color-picker in the docs site and verify each card

🤖 Generated with Claude Code

Replaces the `color` dependency with `culori` so the picker can accept
and emit `oklch()` values alongside hex/rgb/hsl.

The picker's HSL state shape is unchanged, so sliders and the context
contract are untouched. OKLCH input is parsed via culori; OKLCH output
is formatted with 4-decimal L/C, 2-decimal H, hue pinned to 0 for
achromatic colors. Hex output remains uppercase with alpha-aware width
to match the previous behavior.

Note: sliders still operate in HSL — OKLCH is an I/O format, not a
perceptual editing mode, so OKLCH round-trips are not bit-identical.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown

vercel Bot commented May 20, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
apsara Ready Ready Preview, Comment May 20, 2026 5:52am

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 20, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 26a57307-1b9a-401a-b95c-7c27ed4bddc7

📥 Commits

Reviewing files that changed from the base of the PR and between af695d2 and 5a23cd6.

📒 Files selected for processing (2)
  • packages/raystack/components/color-picker/color-picker-mode.tsx
  • packages/raystack/components/color-picker/utils.ts

📝 Walkthrough

Walkthrough

This PR adds OKLCH color mode support to the ColorPicker component. The core change replaces the color package with culori and introduces parseColor and getColorString utilities to handle color conversion and formatting across multiple modes. All ColorPicker components (root, input, area) are updated to use these new utilities, and type signatures are expanded to include 'oklch' as a supported mode. Documentation and a comprehensive example page are provided, along with test coverage for oklch parsing, output formatting, and alpha handling.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ColorPickerRoot
  participant Utils as utils.ts
  participant Culori as culori

  Client->>ColorPickerRoot: mount with defaultValue / value / mode
  ColorPickerRoot->>Utils: parseColor(value/defaultValue)
  Utils->>Culori: parse & convert to internal ColorObject
  Culori-->>Utils: ColorObject {h,s,l,alpha}
  ColorPickerRoot->>Utils: getColorString(ColorObject, mode)
  Utils->>Culori: format to hex/hsl/rgb/oklch
  Culori-->>Utils: formatted string
  ColorPickerRoot-->>Client: emit onValueChange(formatted string)
Loading

Possibly related issues

Suggested reviewers

  • rsbh
  • rohilsurana
  • rohanchkrabrty
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: migrating the ColorPicker component from the 'color' library to 'culori' and adding OKLCH color mode support.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, covering the library migration, OKLCH support, documentation updates, design rationale, caveats, and test results.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/raystack/components/color-picker/utils.ts`:
- Around line 10-12: SUPPORTED_MODES is currently typed as string[] so ModeType
widens to string; change SUPPORTED_MODES to a readonly tuple by appending "as
const" to preserve literal types and make ModeType a union of
'hex'|'hsl'|'rgb'|'oklch'. Update the declaration of SUPPORTED_MODES (and any
related imports if necessary) so ModeType (derived from (typeof
SUPPORTED_MODES)[number]) correctly narrows, which will ensure getColorString
and its switch/default behavior can be type-checked against only valid modes.
- Around line 30-53: formatOklch currently uses round (which returns a Number
via Number.parseFloat(n.toFixed(p))) causing trailing zeros to be dropped and
violating the "4-decimal L/C, 2-decimal H" contract; change the implementation
so the values are formatted as fixed-width decimal strings (use toFixed(p)
directly) and ensure formatOklch concatenates those string results (update the
round helper to return a string or replace calls to round(L/C/H/alpha) in
formatOklch with num.toFixed(p)) so L and C are 4-decimal, H is 2-decimal, and
alpha is 4-decimal when included (refer to formatOklch and the round helper).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c786a0e2-b310-412e-81da-d1764df00178

📥 Commits

Reviewing files that changed from the base of the PR and between b99d0f5 and af695d2.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (10)
  • apps/www/src/app/examples/color-picker/page.tsx
  • apps/www/src/content/docs/components/color-picker/demo.ts
  • apps/www/src/content/docs/components/color-picker/index.mdx
  • apps/www/src/content/docs/components/color-picker/props.ts
  • packages/raystack/components/color-picker/__tests__/color-picker.test.tsx
  • packages/raystack/components/color-picker/color-picker-area.tsx
  • packages/raystack/components/color-picker/color-picker-input.tsx
  • packages/raystack/components/color-picker/color-picker-root.tsx
  • packages/raystack/components/color-picker/utils.ts
  • packages/raystack/package.json

Comment thread packages/raystack/components/color-picker/utils.ts Outdated
Comment on lines +30 to +53
const round = (n: number, p: number) => Number.parseFloat(n.toFixed(p));

/**
* Serializes a culori-shaped HSL color as oklch(L C H[ / A]).
* Matches the design system's token format: 4-decimal L/C, 2-decimal H,
* H pinned to 0 for achromatic colors (culori would emit `none` per CSS
* Color 4, which is correct but inconsistent with how tokens are written).
*/
const formatOklch = (hsl: {
mode: 'hsl';
h: number;
s: number;
l: number;
alpha: number;
}): string => {
const oklch = toOklch(hsl);
if (!oklch) return '';
const L = round(oklch.l ?? 0, 4);
const C = round(oklch.c ?? 0, 4);
const H = C === 0 || !Number.isFinite(oklch.h) ? 0 : round(oklch.h ?? 0, 2);
const body = `${L} ${C} ${H}`;
return hsl.alpha === 1
? `oklch(${body})`
: `oklch(${body} / ${round(hsl.alpha, 4)})`;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

In JavaScript, does Number.parseFloat((0.5).toFixed(4)) preserve trailing zeros in the resulting string representation?

💡 Result:

No, Number.parseFloat((0.5).toFixed(4)) does not preserve trailing zeros in the resulting value because it returns a number type, which does not store formatting information like trailing zeros [1][2]. Here is the breakdown of the process: 1. The.toFixed(4) method is called on the number 0.5. This method returns a string representation of the number, padded with zeros to the specified number of decimal places [3]. In this case, it returns the string "0.5000" [3]. 2. The Number.parseFloat function then takes that string ("0.5000") and parses it into a floating-point number [1][2]. 3. Because the result is a JavaScript Number (a 64-bit binary floating-point value), it cannot maintain trailing zeros [1][4]. When the number 0.5 is represented as a numeric type, it is simply 0.5, and any trailing zeros from the string representation are discarded [1]. If you need to preserve trailing zeros, you must keep the value as a string [3][4].

Citations:


🏁 Script executed:

# First, locate and examine the actual file
fd -t f "utils.ts" -path "*color-picker*"

Repository: raystack/apsara

Length of output: 228


🏁 Script executed:

# Read the specific file to see the code at lines 30-53
cat -n packages/raystack/components/color-picker/utils.ts | sed -n '25,60p'

Repository: raystack/apsara

Length of output: 1501


🏁 Script executed:

# Search for tests related to formatOklch
fd -t f "*.test\|*.spec" -path "*color-picker*" | head -20

Repository: raystack/apsara

Length of output: 228


🏁 Script executed:

# Check if there are any tests that validate the format
rg "formatOklch" --type typescript -A 5 -B 5

Repository: raystack/apsara

Length of output: 94


🏁 Script executed:

# Find test files in color-picker directory
find packages/raystack/components/color-picker -type f \( -name "*.test.*" -o -name "*.spec.*" \)

Repository: raystack/apsara

Length of output: 133


🏁 Script executed:

# Search for formatOklch usage in tests or elsewhere
rg "formatOklch" -B 3 -A 3

Repository: raystack/apsara

Length of output: 1127


🏁 Script executed:

# Look for any validation of oklch format
rg "oklch\(" -B 2 -A 2 | head -100

Repository: raystack/apsara

Length of output: 8924


🏁 Script executed:

# Check the test file for formatOklch tests
cat -n packages/raystack/components/color-picker/__tests__/color-picker.test.tsx | head -150

Repository: raystack/apsara

Length of output: 5362


🏁 Script executed:

# Search for any format validation or assertions on oklch output
rg "oklch\(" packages/raystack/components/color-picker/__tests__/ -B 2 -A 2

Repository: raystack/apsara

Length of output: 626


🏁 Script executed:

# Search for more tests related to format, especially comparing output
rg "formatOklch\|oklch\(" packages/raystack/components/color-picker/ -B 3 -A 5

Repository: raystack/apsara

Length of output: 41


🏁 Script executed:

# Look for utils.test or any unit tests specifically for utils.ts
find packages/raystack/components/color-picker -name "*utils*" -type f

Repository: raystack/apsara

Length of output: 110


🏁 Script executed:

# Check if there's any validation of the output format or round function
rg "round\|toFixed" packages/raystack/components/color-picker/ -B 2 -A 2

Repository: raystack/apsara

Length of output: 41


🏁 Script executed:

# Create a test to demonstrate the actual behavior of formatOklch
cat > /tmp/test_format.js << 'EOF'
// Simulate the current implementation
const round = (n, p) => Number.parseFloat(n.toFixed(p));

// Test with values that would lose trailing zeros
const testValues = [
  { name: "0.5 with 4 decimals", value: 0.5, decimals: 4 },
  { name: "0.1 with 4 decimals", value: 0.1, decimals: 4 },
  { name: "1.0 with 4 decimals", value: 1.0, decimals: 4 },
  { name: "50.12 with 2 decimals", value: 50.12, decimals: 2 },
];

console.log("Current implementation (parseFloat(toFixed())):");
testValues.forEach(({name, value, decimals}) => {
  const rounded = round(value, decimals);
  const inTemplate = `Value: ${rounded}`;
  console.log(`  ${name}: ${value.toFixed(decimals)} -> ${rounded} -> "${inTemplate}"`);
});

console.log("\nProposed implementation (toFixed() directly):");
testValues.forEach(({name, value, decimals}) => {
  const fixed = value.toFixed(decimals);
  const inTemplate = `Value: ${fixed}`;
  console.log(`  ${name}: ${value.toFixed(decimals)} -> "${inTemplate}"`);
});

// Test a realistic oklch output
console.log("\nRealistic oklch output example:");
const hsl = { mode: 'hsl', h: 45, s: 100, l: 50, alpha: 1 };
const fakeOklch = { l: 0.5, c: 0.15, h: 45.67 }; // Simplified example

// Current implementation
const L_current = round(0.5, 4);
const C_current = round(0.15, 4);
const H_current = round(45.67, 2);
const oklch_current = `oklch(${L_current} ${C_current} ${H_current})`;
console.log(`  Current: ${oklch_current}`);

// Proper implementation
const L_proper = (0.5).toFixed(4);
const C_proper = (0.15).toFixed(4);
const H_proper = (45.67).toFixed(2);
const oklch_proper = `oklch(${L_proper} ${C_proper} ${H_proper})`;
console.log(`  Proper:  ${oklch_proper}`);
EOF
node /tmp/test_format.js

Repository: raystack/apsara

Length of output: 667


formatOklch rounds values but does not preserve the stated decimal format.

The current implementation using Number.parseFloat(n.toFixed(p)) converts to a number, which loses trailing zeros when interpolated into the template literal. This violates the documented contract: "4-decimal L/C, 2-decimal H." For example, with L=0.5 and C=0.15, the output is oklch(0.5 0.15 ...) instead of the intended oklch(0.5000 0.1500 ...).

To preserve the fixed decimal width, use toFixed(p) directly, which returns a properly formatted string:

Proposed fix
-const round = (n: number, p: number) => Number.parseFloat(n.toFixed(p));
+const fixed = (n: number, p: number) => (Number.isFinite(n) ? n : 0).toFixed(p);
@@
-  const L = round(oklch.l ?? 0, 4);
-  const C = round(oklch.c ?? 0, 4);
-  const H = C === 0 || !Number.isFinite(oklch.h) ? 0 : round(oklch.h ?? 0, 2);
+  const cRaw = oklch.c ?? 0;
+  const L = fixed(oklch.l ?? 0, 4);
+  const C = fixed(cRaw, 4);
+  const H = cRaw === 0 || !Number.isFinite(oklch.h) ? '0.00' : fixed(oklch.h ?? 0, 2);
@@
-    : `oklch(${body} / ${round(hsl.alpha, 4)})`;
+    : `oklch(${body} / ${fixed(hsl.alpha, 4)})`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const round = (n: number, p: number) => Number.parseFloat(n.toFixed(p));
/**
* Serializes a culori-shaped HSL color as oklch(L C H[ / A]).
* Matches the design system's token format: 4-decimal L/C, 2-decimal H,
* H pinned to 0 for achromatic colors (culori would emit `none` per CSS
* Color 4, which is correct but inconsistent with how tokens are written).
*/
const formatOklch = (hsl: {
mode: 'hsl';
h: number;
s: number;
l: number;
alpha: number;
}): string => {
const oklch = toOklch(hsl);
if (!oklch) return '';
const L = round(oklch.l ?? 0, 4);
const C = round(oklch.c ?? 0, 4);
const H = C === 0 || !Number.isFinite(oklch.h) ? 0 : round(oklch.h ?? 0, 2);
const body = `${L} ${C} ${H}`;
return hsl.alpha === 1
? `oklch(${body})`
: `oklch(${body} / ${round(hsl.alpha, 4)})`;
const fixed = (n: number, p: number) => (Number.isFinite(n) ? n : 0).toFixed(p);
/**
* Serializes a culori-shaped HSL color as oklch(L C H[ / A]).
* Matches the design system's token format: 4-decimal L/C, 2-decimal H,
* H pinned to 0 for achromatic colors (culori would emit `none` per CSS
* Color 4, which is correct but inconsistent with how tokens are written).
*/
const formatOklch = (hsl: {
mode: 'hsl';
h: number;
s: number;
l: number;
alpha: number;
}): string => {
const oklch = toOklch(hsl);
if (!oklch) return '';
const cRaw = oklch.c ?? 0;
const L = fixed(oklch.l ?? 0, 4);
const C = fixed(cRaw, 4);
const H = cRaw === 0 || !Number.isFinite(oklch.h) ? '0.00' : fixed(oklch.h ?? 0, 2);
const body = `${L} ${C} ${H}`;
return hsl.alpha === 1
? `oklch(${body})`
: `oklch(${body} / ${fixed(hsl.alpha, 4)})`;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/raystack/components/color-picker/utils.ts` around lines 30 - 53,
formatOklch currently uses round (which returns a Number via
Number.parseFloat(n.toFixed(p))) causing trailing zeros to be dropped and
violating the "4-decimal L/C, 2-decimal H" contract; change the implementation
so the values are formatted as fixed-width decimal strings (use toFixed(p)
directly) and ensure formatOklch concatenates those string results (update the
round helper to return a string or replace calls to round(L/C/H/alpha) in
formatOklch with num.toFixed(p)) so L and C are 4-decimal, H is 2-decimal, and
alpha is 4-decimal when included (refer to formatOklch and the round helper).

@paanSinghCoder paanSinghCoder changed the title feat(color-picker): migrate to culori and add OKLCH mode feat(color-picker): migrate to culori and add add OKLCH support May 20, 2026
Comment thread packages/raystack/components/color-picker/utils.ts
Without `as const`, `SUPPORTED_MODES` is `string[]` so `ModeType` widens
to `string` — invalid modes pass type-checking and silently fall back
to RGB in `getColorString`. `options` on `ColorPickerMode` is widened
to `readonly ModeType[]` to accept the const tuple as its default.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants