Skip to content

[Feature request] Add function to convert between rgb and hex notation #614

@lawvs

Description

@lawvs

Summary

polished is a very powerful library to processing colors, but some enviroments only support the hex notation format.

Therefore, is it possible to add new functions to format the color format or add a new parameter to rgb functions to restrict color string type (but there are too many functions).

Basic Example

const Format {
  auto: 'auto', // Default
  hex: 'hex',
  rgb: 'rgb' // Need more precise wording
}

toColorString({ red: 255, green: 205, blue: 100, alpha: 0.72, format: Format.hex })
// '#ffcd64b8'

// Or new color function

toHexColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 })
// '#ffcd64b8'

// A simple workaround
export const toHexColorString = (color: Object) => {
  if (typeof color !== 'object') throw new PolishedError(8)
  const colorString = toColorString(color)
  const maybeRgbaColor = parseToRgb(colorString);
  if ("alpha" in maybeRgbaColor) {
    const { alpha, ...RgbColor } = maybeRgbaColor;
    return rgb(RgbColor) + Math.trunc(alpha * 255).toString(16)
  }
  const RgbColor = maybeRgbaColor;
  return rgb(RgbColor)
};

Reasoning

Some environments do not support all CSS features.

For example, vscode theme config

Color values can be defined in the RGB color model with an alpha channel for transparency. As format, the following hexadecimal notations are supported: #RGB, #RGBA, #RRGGBB and #RRGGBBAA.
--vscode theme color references

image

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions