Skip to content

Commit 6cdf265

Browse files
author
genrichez
committed
fix: handle 3-digit shorthand hex in hex_to_rgb
Expand 3-char hex codes (e.g. #FFF) to 6-char before parsing. Fixes both _plotly_utils and matplotlylib copies. Closes #5661
1 parent 9611be4 commit 6cdf265

3 files changed

Lines changed: 13 additions & 0 deletions

File tree

_plotly_utils/colors/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,8 @@ def hex_to_rgb(value):
757757
:rtype (tuple) (r_value, g_value, b_value): tuple of rgb values
758758
"""
759759
value = value.lstrip("#")
760+
if len(value) == 3:
761+
value = "".join(c * 2 for c in value)
760762
hex_total_length = len(value)
761763
rgb_section_length = hex_total_length // 3
762764
return tuple(

plotly/matplotlylib/mpltools.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ def hex_to_rgb(value):
117117
118118
"""
119119
value = value.lstrip("#")
120+
if len(value) == 3:
121+
value = "".join(c * 2 for c in value)
120122
lv = len(value)
121123
return tuple(int(value[i : i + lv // 3], 16) for i in range(0, lv, lv // 3))
122124

tests/test_plotly_utils/colors/test_color_conversions.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,15 @@ def test_hex_to_rgb_basic_values():
1212
assert hex_to_rgb("#aabbcc") == (170, 187, 204)
1313

1414

15+
def test_hex_to_rgb_shorthand_3_digit():
16+
assert hex_to_rgb("#fff") == (255, 255, 255)
17+
assert hex_to_rgb("#000") == (0, 0, 0)
18+
assert hex_to_rgb("#abc") == (170, 187, 204)
19+
assert hex_to_rgb("#f00") == (255, 0, 0)
20+
assert hex_to_rgb("#0f0") == (0, 255, 0)
21+
assert hex_to_rgb("#00f") == (0, 0, 255)
22+
23+
1524
def test_label_rgb_formats_tuple():
1625
assert label_rgb((255, 0, 0)) == "rgb(255, 0, 0)"
1726
assert label_rgb((1, 2, 3)) == "rgb(1, 2, 3)"

0 commit comments

Comments
 (0)