Skip to content

Commit

Permalink
fix(utils): handle hex colors with alpha component (#27497)
Browse files Browse the repository at this point in the history
  • Loading branch information
thmsobrmlr authored Jan 15, 2025
1 parent c0479ae commit dba8839
Showing 1 changed file with 17 additions and 17 deletions.
34 changes: 17 additions & 17 deletions frontend/src/lib/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1452,30 +1452,30 @@ export function resolveWebhookService(webhookUrl: string): string {
return 'your webhook service'
}

export function hexToRGB(hex: string): { r: number; g: number; b: number } {
const originalString = hex.trim()
const hasPoundSign = originalString[0] === '#'
let originalColor = hasPoundSign ? originalString.slice(1) : originalString

// convert 3-digit hex colors to 6-digit
if (originalColor.length === 3) {
originalColor = originalColor
export function hexToRGB(hex: string): { r: number; g: number; b: number; a: number } {
// Remove the "#" if it exists
hex = hex.replace(/^#/, '')

// Handle shorthand notation (e.g., "#123" => "#112233")
if (hex.length === 3 || hex.length === 4) {
hex = hex
.split('')
.map((c) => c + c)
.map((char) => char + char)
.join('')
}

// make sure we have a 6-digit color
if (originalColor.length !== 6) {
if (hex.length !== 6 && hex.length !== 8) {
console.warn(`Incorrectly formatted color string: ${hex}.`)
return { r: 0, g: 0, b: 0 }
return { r: 0, g: 0, b: 0, a: 0 }
}

const originalBase16 = parseInt(originalColor, 16)
const r = originalBase16 >> 16
const g = (originalBase16 >> 8) & 0x00ff
const b = originalBase16 & 0x0000ff
return { r, g, b }
// Extract the rgb values
const r = parseInt(hex.slice(0, 2), 16)
const g = parseInt(hex.slice(2, 4), 16)
const b = parseInt(hex.slice(4, 6), 16)
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1

return { r, g, b, a }
}

export function hexToRGBA(hex: string, alpha = 1): string {
Expand Down

0 comments on commit dba8839

Please sign in to comment.