Skip to content

Conversation

@abcd0f
Copy link
Contributor

@abcd0f abcd0f commented Jan 23, 2026

PR Description

📝 Summary

Add cssVarToRgba utility function to convert CSS variables to RGBA color strings for dynamic theme support in charts.

🎯 Purpose

When using charting libraries like ECharts, we need to convert project CSS variables (typically in HSL format) to RGBA format to:

  • Dynamically apply theme colors to charts
  • Support color transparency adjustment
  • Enable automatic chart color updates during theme switching

✨ Changes

New Features

  • Add cssVarToRgba(cssVar: string, alpha?: number): string function
  • Support reading HSL color values from CSS custom properties
  • Support custom alpha/transparency parameter (0-1)
  • Return standard RGBA format color string

Implementation Details

  1. Read CSS variable value from document.documentElement
  2. Convert HSL value to complete HSL color string
  3. Convert to RGB format via convertToRgb
  4. Use TinyColor library to set alpha and output RGBA string

💻 Code

/**
 * Convert CSS variable to RGBA color string, useful for dynamically changing theme colors in ECharts
 * 
 * @param cssVar - CSS custom property variable name (e.g., '--primary-color')
 * @param alpha - Alpha/transparency value, defaults to 1 (opaque)
 * @returns RGBA format color string
 */
function cssVarToRgba(cssVar: string, alpha = 1) {
  const el = document.documentElement;
  const hslVal = getComputedStyle(el).getPropertyValue(cssVar).trim();
  const color = convertToRgb(`hsl(${hslVal})`);
  const rgba = new TinyColor(color).setAlpha(alpha).toRgbString();
  return rgba;
}

🔧 Usage Example

// CSS variable definition
// :root {
//   --primary-color: 221 83% 53%;
// }

// Basic usage
const color = cssVarToRgba('--primary-color');
// Returns: 'rgba(59, 130, 246, 1)'

// With transparency
const transparent = cssVarToRgba('--primary-color', 0.3);
// Returns: 'rgba(59, 130, 246, 0.3)'

// ECharts usage scenario
const option = {
  color: [
    cssVarToRgba('--primary-color'),
    cssVarToRgba('--success-color'),
    cssVarToRgba('--warning-color')
  ],
  series: [{
    type: 'line',
    lineStyle: {
      color: cssVarToRgba('--primary-color')
    },
    areaStyle: {
      color: cssVarToRgba('--primary-color', 0.2)
    }
  }]
};

// Theme switching
function updateChartTheme(chart) {
  chart.setOption({
    color: [
      cssVarToRgba('--primary-color'),
      cssVarToRgba('--secondary-color')
    ]
  });
}

📦 Dependencies

  • TinyColor: Color manipulation library
  • convertToRgb: Internal HSL to RGB conversion function

✅ Testing Checklist

  • Function correctly reads CSS variables
  • HSL to RGBA conversion works correctly
  • Alpha parameter takes effect properly
  • Default alpha value is 1 (opaque)
  • Tested in real ECharts scenarios
  • Works with theme switching

📋 Type of Change

  • ✨ New feature (non-breaking change which adds functionality)
  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📚 Documentation update
  • 🎨 Style update (formatting, renaming)
  • ♻️ Code refactoring (no functional changes)
  • ⚡ Performance improvement
  • ✅ Test update

🔗 Related Issues

Closes #[issue_number] (if applicable)

📌 Notes

  • This function assumes CSS variables store HSL values without the hsl() wrapper, in the format 221 83% 53%
  • The CSS variable name must include the -- prefix (e.g., '--primary-color')
  • Alpha va

Summary by CodeRabbit

  • New Features
    • Added a color conversion utility that converts CSS color variables to RGBA format with customizable opacity levels.

✏️ Tip: You can customize this high-level summary in your review settings.

新增cssVarToRgba函数,用于将CSS自定义属性变量转换为RGBA颜色字符串,
支持设置透明度,默认为1(不透明),可用于echarts动态更改主题颜色。
@changeset-bot
Copy link

changeset-bot bot commented Jan 23, 2026

⚠️ No Changeset found

Latest commit: fa18f92

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 23, 2026

📝 Walkthrough

Walkthrough

A new utility function cssVarToRgba is added to the color conversion module. This function reads CSS variables from the root element, converts HSL values to RGB format, applies an optional alpha channel using TinyColor, and returns the resulting RGBA string.

Changes

Cohort / File(s) Change Summary
Color Conversion Utility
packages/@core/base/shared/src/color/convert.ts
Added new public function cssVarToRgba(cssVar: string, alpha = 1) that converts CSS variables to RGBA strings by reading root element values, converting HSL to RGB, and applying alpha transparency.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 A whisker-twitch of color bright,
CSS vars now RGBA-light,
From HSL to RGB we go,
With alpha blends our hues will glow!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive The description is comprehensive and covers purpose, implementation details, usage examples, and dependencies. However, the testing checklist items are unchecked and the PR is incomplete at the end ('Alpha va...'). Complete the truncated notes section, verify and check the testing checklist items to confirm all requirements have been met before merging.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change—adding a CSS variable to RGBA color conversion utility for the @core/base package.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

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
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: 1

🤖 Fix all issues with AI agents
In `@packages/`@core/base/shared/src/color/convert.ts:
- Around line 63-69: The cssVarToRgba function accesses document.documentElement
and getComputedStyle directly and doesn't validate the returned CSS variable
value; update cssVarToRgba to be safe in SSR by early-returning or throwing when
window/document are undefined (guarding access to document.documentElement and
getComputedStyle), and validate the result of getPropertyValue(cssVar) (ensure
non-empty and matches expected HSL parts) before calling convertToRgb and
TinyColor; if invalid, return a sensible fallback (e.g., null or a default rgba
string) or throw a clear error so server environments and missing CSS variables
are handled predictably.
🧹 Nitpick comments (1)
packages/@core/base/shared/src/color/convert.ts (1)

63-63: Add explicit return type annotation.

For consistency with the other functions in this file and for better type safety, consider adding an explicit return type.

✏️ Suggested fix
-function cssVarToRgba(cssVar: string, alpha = 1) {
+function cssVarToRgba(cssVar: string, alpha = 1): string {

Comment on lines +63 to +69
function cssVarToRgba(cssVar: string, alpha = 1) {
const el = document.documentElement;
const hslVal = getComputedStyle(el).getPropertyValue(cssVar).trim();
const color = convertToRgb(`hsl(${hslVal})`);
const rgba = new TinyColor(color).setAlpha(alpha).toRgbString();
return rgba;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

SSR/Node.js compatibility issue: document is undefined in server environments.

Directly accessing document.documentElement will throw a ReferenceError in SSR or Node.js contexts. Consider adding a guard or documenting that this function is browser-only.

Additionally, if the CSS variable doesn't exist, getPropertyValue returns an empty string, resulting in hsl() which silently converts to black (rgb(0, 0, 0)). Consider validating and handling this case explicitly.

🛠️ Suggested fix with SSR guard and validation
 function cssVarToRgba(cssVar: string, alpha = 1): string {
+  if (typeof document === 'undefined') {
+    console.warn('cssVarToRgba: document is not available in this environment');
+    return `rgba(0, 0, 0, ${alpha})`;
+  }
   const el = document.documentElement;
   const hslVal = getComputedStyle(el).getPropertyValue(cssVar).trim();
+  if (!hslVal) {
+    console.warn(`cssVarToRgba: CSS variable "${cssVar}" not found or empty`);
+    return `rgba(0, 0, 0, ${alpha})`;
+  }
   const color = convertToRgb(`hsl(${hslVal})`);
   const rgba = new TinyColor(color).setAlpha(alpha).toRgbString();
   return rgba;
 }
📝 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
function cssVarToRgba(cssVar: string, alpha = 1) {
const el = document.documentElement;
const hslVal = getComputedStyle(el).getPropertyValue(cssVar).trim();
const color = convertToRgb(`hsl(${hslVal})`);
const rgba = new TinyColor(color).setAlpha(alpha).toRgbString();
return rgba;
}
function cssVarToRgba(cssVar: string, alpha = 1): string {
if (typeof document === 'undefined') {
console.warn('cssVarToRgba: document is not available in this environment');
return `rgba(0, 0, 0, ${alpha})`;
}
const el = document.documentElement;
const hslVal = getComputedStyle(el).getPropertyValue(cssVar).trim();
if (!hslVal) {
console.warn(`cssVarToRgba: CSS variable "${cssVar}" not found or empty`);
return `rgba(0, 0, 0, ${alpha})`;
}
const color = convertToRgb(`hsl(${hslVal})`);
const rgba = new TinyColor(color).setAlpha(alpha).toRgbString();
return rgba;
}
🤖 Prompt for AI Agents
In `@packages/`@core/base/shared/src/color/convert.ts around lines 63 - 69, The
cssVarToRgba function accesses document.documentElement and getComputedStyle
directly and doesn't validate the returned CSS variable value; update
cssVarToRgba to be safe in SSR by early-returning or throwing when
window/document are undefined (guarding access to document.documentElement and
getComputedStyle), and validate the result of getPropertyValue(cssVar) (ensure
non-empty and matches expected HSL parts) before calling convertToRgb and
TinyColor; if invalid, return a sensible fallback (e.g., null or a default rgba
string) or throw a clear error so server environments and missing CSS variables
are handled predictably.

@abcd0f abcd0f closed this Jan 28, 2026
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