Bluesky's "Application Layout Framework"
1export function alpha(color: string, opacity: number) {
2 if (color.startsWith('hsl(')) {
3 return 'hsla(' + color.slice('hsl('.length, -1) + `, ${opacity})`
4 } else if (color.startsWith('rgb(')) {
5 return 'rgba(' + color.slice('rgb('.length, -1) + `, ${opacity})`
6 } else if (color.startsWith('#')) {
7 if (color.length === 7) {
8 const alphaHex = Math.round(opacity * 255).toString(16)
9 // Per MDN: If there is only one number, it is duplicated: e means ee
10 // https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color
11 return color.slice(0, 7) + alphaHex.padStart(2, alphaHex)
12 } else if (color.length === 4) {
13 // convert to 6-digit hex before adding opacity
14 const [r, g, b] = color.slice(1).split('')
15 const alphaHex = Math.round(opacity * 255).toString(16)
16 return `#${r.repeat(2)}${g.repeat(2)}${b.repeat(2)}${alphaHex.padStart(
17 2,
18 alphaHex,
19 )}`
20 }
21 }
22 return color
23}