ux: color hex default to removeAlphaIfOpaque

This commit is contained in:
Cole Lawrence 2022-06-24 07:30:26 -04:00
parent 6dc68d9ae9
commit 28bd52d9e9
2 changed files with 12 additions and 4 deletions

View file

@ -42,12 +42,20 @@ export function parseRgbaFromHex(rgba: string) {
} }
} }
export function rgba2hex(rgba: Rgba) { export function rgba2hex(
rgba: Rgba,
{
/** Alpha is usually an optional value for most hex inputs, so if it's opaque, we can omit its value. */
removeAlphaIfOpaque = false,
} = {},
) {
const alpha = ((rgba.a * 255) | (1 << 8)).toString(16).slice(1)
const hex = const hex =
((rgba.r * 255) | (1 << 8)).toString(16).slice(1) + ((rgba.r * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.g * 255) | (1 << 8)).toString(16).slice(1) + ((rgba.g * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.b * 255) | (1 << 8)).toString(16).slice(1) + ((rgba.b * 255) | (1 << 8)).toString(16).slice(1) +
((rgba.a * 255) | (1 << 8)).toString(16).slice(1) (removeAlphaIfOpaque && alpha === 'ff' ? '' : alpha)
return `#${hex}` return `#${hex}`
} }
@ -59,7 +67,7 @@ export function decorateRgba(rgba: Rgba) {
return { return {
...rgba, ...rgba,
toString() { toString() {
return rgba2hex(this) return rgba2hex(this, {removeAlphaIfOpaque: true})
}, },
} }
} }

View file

@ -111,7 +111,7 @@ function RgbaPropEditor({
}} }}
/> />
<HexInput <HexInput
value={rgba2hex(value)} value={rgba2hex(value, {removeAlphaIfOpaque: true})}
temporarilySetValue={noop} temporarilySetValue={noop}
discardTemporaryValue={noop} discardTemporaryValue={noop}
permanentlySetValue={onChange} permanentlySetValue={onChange}