Skip to content

Commit a8c9b01

Browse files
committed
Contrast for rgb color
1 parent 1cca554 commit a8c9b01

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

packages/uui-color-swatch/lib/uui-color-swatch.element.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,10 @@ export class UUIColorSwatchElement extends LabelMixin(
9898
const color = this.color ?? this.value;
9999
if (color.startsWith('#')) {
100100
this._contrast = this.#contrast(color) === 'light' ? 'light' : 'dark';
101+
} else if (color.startsWith('rgb')) {
102+
const [r, g, b] = color.match(/\d+/g)?.map(Number) ?? [0, 0, 0];
103+
this._contrast =
104+
this.#contrast(this.#rgbToHex(r, g, b)) === 'light' ? 'light' : 'dark';
101105
}
102106
}
103107

@@ -148,6 +152,9 @@ export class UUIColorSwatchElement extends LabelMixin(
148152
return [r, g, b];
149153
}
150154

155+
#rgbToHex = (r: number, g: number, b: number, hash: '#' | '' = ''): string =>
156+
hash + ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
157+
151158
render() {
152159
return html`
153160
<button

0 commit comments

Comments
 (0)