Skip to content

Conversation

@abkaskari
Copy link

🔗 Related Issues

💥 What does this PR do?

🔧 Implementation Notes

💡 Additional Considerations

🔄 Types of changes

  • Cleanup (formatting, renaming)
  • Bug fix (backwards compatible)
  • New feature (non-breaking change which adds functionality and tests!)
  • Breaking change (fix or feature that would cause existing functionality to change)

@CLAassistant
Copy link

CLAassistant commented Feb 9, 2026

CLA assistant check
All committers have signed the CLA.

@selenium-ci selenium-ci added the C-nodejs JavaScript Bindings label Feb 9, 2026
@qodo-code-review
Copy link
Contributor

PR Type

Enhancement, Tests


Description

  • Add Color utility class for parsing and converting color formats

  • Support HEX, RGB, and RGBA color string parsing

  • Provide conversion methods between HEX and RGB formats

  • Include comprehensive test coverage for color conversions

  • Export parseCssColor helper function in WebElement module


File Walkthrough

Relevant files
Enhancement
color.js
Color utility class with format conversion                             

javascript/selenium-webdriver/lib/color.js

  • New Color class that parses and converts between HEX, RGB, and RGBA
    formats
  • Implements getter methods for RGB, RGBA, and HEX representations
  • Includes static helper methods for hexToRgb and rgbToHex conversions
  • Validates color string format and throws errors for unsupported
    formats
+68/-0   
webelement.js
Integrate Color utility into WebElement module                     

javascript/selenium-webdriver/lib/webelement.js

  • Import Color utility class at module level
  • Add parseCssColor helper function to convert CSS color strings to
    Color objects
  • Export parseCssColor function in module.exports
+13/-0   
Tests
color_test.js
Color class unit tests                                                                     

javascript/selenium-webdriver/lib/test/color_test.js

  • Test suite for Color class covering HEX to RGB conversion
  • Test RGB to HEX conversion functionality
  • Test RGBA color parsing with alpha channel support
  • Validates all getter methods return correct format strings
+24/-0   

@qodo-code-review
Copy link
Contributor

qodo-code-review bot commented Feb 9, 2026

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🟡
🎫 #5678
🟡
🎫 #1234
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Null input crash: The Color constructor calls colorStr.trim() without validating colorStr, which will throw
a non-actionable TypeError for null/undefined before the explicit validation in parse().

Referred Code
constructor(colorStr) {
  this.original = colorStr.trim();
  this.parse(this.original);

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Insufficient validation: The color parsing accepts unvalidated HEX/RGB(A) components (e.g., missing hex-length
checks, no numeric range checks for RGB 0-255 or alpha 0-1), enabling malformed external
inputs to be processed into inconsistent internal state (e.g., rgbToHex() returning null).

Referred Code
parse(colorStr) {
  if (!colorStr) throw new Error('Color string is required');

  // HEX
  if (colorStr.startsWith('#')) {
    this.hex = colorStr.toLowerCase();
    this.rgb = Color.hexToRgb(this.hex);
    this.alpha = 1;
  }
  // RGB / RGBA
  else if (colorStr.startsWith('rgb')) {
    const match = colorStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([0-9.]+))?\)/);
    if (!match) throw new Error(`Invalid rgb(a) format: ${colorStr}`);
    const [_, r, g, b, a] = match;
    this.rgb = `rgb(${r}, ${g}, ${b})`;
    this.hex = Color.rgbToHex(this.rgb);
    this.alpha = a !== undefined ? parseFloat(a) : 1;
  }
  // Named colors (optional)
  else {
    throw new Error(`Unsupported color format: ${colorStr}`);


 ... (clipped 38 lines)

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link
Contributor

qodo-code-review bot commented Feb 9, 2026

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Use an external library for color parsing

Instead of introducing a new custom color parser, the PR should leverage a
well-tested external library. This would offer more robust functionality and
reduce future maintenance efforts.

Examples:

javascript/selenium-webdriver/lib/color.js [1-68]
class Color {
  constructor(colorStr) {
    this.original = colorStr.trim();
    this.parse(this.original);
  }

  parse(colorStr) {
    if (!colorStr) throw new Error('Color string is required');

    // HEX

 ... (clipped 58 lines)

Solution Walkthrough:

Before:

// file: javascript/selenium-webdriver/lib/color.js
class Color {
  constructor(colorStr) {
    this.parse(colorStr.trim());
  }

  parse(colorStr) {
    if (colorStr.startsWith('#')) {
      // ... custom hex parsing logic ...
    } else if (colorStr.startsWith('rgb')) {
      // ... custom rgb(a) parsing logic ...
    } else {
      throw new Error(`Unsupported color format: ${colorStr}`);
    }
  }
  // ... other helper methods ...
}

// file: javascript/selenium-webdriver/lib/webelement.js
const Color = require('./color');
function parseCssColor(cssValue) {
  return new Color(cssValue);
}

After:

// file: javascript/selenium-webdriver/lib/color.js
// This file would be removed entirely.

// file: javascript/selenium-webdriver/lib/webelement.js
// A dependency like 'color' or 'tinycolor2' would be added to package.json
const color = require('some-color-library');

/**
 * Converts a CSS color string to a Color object from the external library.
 * @param {string} cssValue The CSS color string.
 * @return {Object} The Color object from the library.
 */
function parseCssColor(cssValue) {
  // The library handles all parsing, including formats not supported
  // by the custom implementation (e.g., HSL, named colors).
  return color(cssValue);
}
Suggestion importance[1-10]: 8

__

Why: This is a strong architectural suggestion that correctly identifies that the PR is "reinventing the wheel" for a solved problem, proposing a more robust and maintainable solution.

Medium
Possible issue
Validate RGBA component value ranges

Validate that parsed RGB values are within the 0-255 range and the alpha value
is between 0 and 1. Throw an error if the values are out of range.

javascript/selenium-webdriver/lib/color.js [16-24]

 // RGB / RGBA
 else if (colorStr.startsWith('rgb')) {
   const match = colorStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([0-9.]+))?\)/);
   if (!match) throw new Error(`Invalid rgb(a) format: ${colorStr}`);
   const [_, r, g, b, a] = match;
-  this.rgb = `rgb(${r}, ${g}, ${b})`;
+  const red = parseInt(r, 10), green = parseInt(g, 10), blue = parseInt(b, 10);
+  const alpha = a !== undefined ? parseFloat(a) : 1;
+
+  if (red > 255 || green > 255 || blue > 255 || alpha < 0 || alpha > 1) {
+    throw new Error(`Invalid color value: ${colorStr}`);
+  }
+
+  this.rgb = `rgb(${red}, ${green}, ${blue})`;
   this.hex = Color.rgbToHex(this.rgb);
-  this.alpha = a !== undefined ? parseFloat(a) : 1;
+  this.alpha = alpha;
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that RGB and alpha values are not validated, which could lead to incorrect color representations. Adding checks to throw an error for out-of-range values makes the color parser more robust.

Medium
Support and validate 3-digit hex

Add support for 3-digit shorthand hex colors by expanding them (e.g., "#abc" to
"#aabbcc") and throw an error for hex strings with invalid lengths.

javascript/selenium-webdriver/lib/color.js [11-15]

 if (colorStr.startsWith('#')) {
-  this.hex = colorStr.toLowerCase();
+  let hex = colorStr.toLowerCase();
+  if (hex.length === 4) {
+    hex = '#' + [...hex.slice(1)].map(c => c + c).join('');
+  } else if (hex.length !== 7) {
+    throw new Error(`Invalid hex format: ${colorStr}`);
+  }
+  this.hex = hex;
   this.rgb = Color.hexToRgb(this.hex);
   this.alpha = 1;
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: This suggestion correctly adds support for shorthand hex colors, a common CSS feature, and also includes validation for invalid hex string lengths, improving the parser's robustness.

Medium
Error on invalid RGB input

Modify the rgbToHex method to throw an error on invalid rgb input instead of
returning null, preventing silent failures.

javascript/selenium-webdriver/lib/color.js [55-65]

 static rgbToHex(rgb) {
   const match = rgb.match(/\d+/g);
-  if (!match) return null;
+  if (!match || match.length < 3) {
+    throw new Error(`Invalid RGB input: ${rgb}`);
+  }
   return (
     '#' +
     match
       .slice(0, 3)
-      .map((x) => parseInt(x).toString(16).padStart(2, '0'))
+      .map((x) => {
+        const val = Math.min(255, Math.max(0, parseInt(x, 10)));
+        return val.toString(16).padStart(2, '0');
+      })
       .join('')
   ).toLowerCase();
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out that returning null on invalid input can lead to silent failures. Changing this to throw an error improves error handling and makes the rgbToHex method's behavior more explicit and robust.

Low
  • Update

@cgoldberg
Copy link
Member

There is a already a PR open for this: #16944

Please don't submit PR's without filling out the template.

@cgoldberg cgoldberg closed this Feb 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants