styled-components / polished

A lightweight toolset for writing styles in JavaScript ✨
https://polished.js.org/
MIT License
7.6k stars 209 forks source link

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

Open lawvs opened 2 years ago

lawvs commented 2 years ago

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

anilanar commented 1 year ago

I wanted to use polished to produce a 7 character (#xxxxxx) hex color so that it can be used by HTML5 <input type="color"> but polished produces shortest possible hex, which doesn't work with the native color picker.