Skip to content

Commit 0e4f4be

Browse files
committed
refactor: optimize withAlpha function
1 parent 73ac7f5 commit 0e4f4be

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

app/utils/colors.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,18 @@
66
* opacity utilities — colors must be fully resolved values.
77
*/
88
export function withAlpha(color: string, alpha: number): string {
9-
if (color.startsWith('oklch(')) return color.replace(')', ` / ${alpha})`)
10-
if (color.startsWith('#'))
11-
return (
12-
color +
13-
Math.round(alpha * 255)
14-
.toString(16)
15-
.padStart(2, '0')
16-
)
9+
const clamped = Math.min(Math.max(alpha, 0), 1)
10+
if (color.startsWith('oklch(')) {
11+
const withoutAlpha = color.replace(/\s*\/[^)]*(?=\))/, '')
12+
return withoutAlpha.replace(')', ` / ${clamped})`)
13+
}
14+
if (/^#([a-f\d]{6}|[a-f\d]{8})$/i.test(color)) {
15+
const base = color.slice(0, 7)
16+
const a = Math.round(clamped * 255)
17+
.toString(16)
18+
.padStart(2, '0')
19+
return `${base}${a}`
20+
}
1721
return color
1822
}
1923

0 commit comments

Comments
 (0)