Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lawvs opened this issue Apr 26, 2022 · 1 comment
Open

Comments

@lawvs
Copy link

lawvs commented Apr 26, 2022

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants