Skip to content

Commit 30e789d

Browse files
committed
add hsl colors support
1 parent 30d5f65 commit 30e789d

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

docs/source/style.rst

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,19 @@ Colors can be specified using one of the following formats:
127127
Both uppercase and lowercase letters are allowed.
128128

129129
- **RGB functional notation**:
130-
You may also use the CSS-like syntax:
130+
You may also use the CSS-like syntax: ``rgb(r, g, b)``
131131

132132
- ``"rgb(255, 0, 0)"`` (red)
133133
- ``"rgb(0, 128, 255)"`` (blue-ish)
134134

135135
Values must be integers between 0 and 255.
136136

137+
- **HSL functional notation**:
138+
You may also use the CSS-like syntax: ``hsl(h, s%, l%)``
139+
140+
- ``"hsl(0, 100%, 50%)"`` (red)
141+
- ``"hsl(39, 100%, 50%)"`` (orange)
142+
143+
Values must be integers, ``h`` between 0 and 360, ``s`` and ``l`` between 0 and 100.
144+
137145
If a color string is invalid or unsupported, an error will be raised at runtime.

pptx_shapes/units.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import colorsys
12
import re
23

34

@@ -49,9 +50,17 @@ def parse_color(color: str) -> str:
4950
if re.fullmatch(r"[\da-f]{6}", color):
5051
return color
5152

52-
match = re.fullmatch(r"rgb\s*\(\s*(?P<r>\d{1,3})\s*,\s*(?P<g>\d{1,3})\s*,\s*(?P<b>\d{1,3})\s*\)", color)
53+
color = re.sub(r"\s+", "", color)
54+
55+
match = re.fullmatch(r"rgb\((?P<r>\d{1,3}),(?P<g>\d{1,3}),(?P<b>\d{1,3})\)", color)
5356
if match:
5457
r, g, b = min(int(match.group("r")), 255), min(int(match.group("g")), 255), min(int(match.group("b")), 255)
5558
return f"{r:02X}{g:02X}{b:02X}"
5659

60+
match = re.fullmatch(r"hsl\((?P<h>\d{1,3}),(?P<s>\d{1,3})%,(?P<l>\d{1,3})%\)", color)
61+
if match:
62+
hsl = min(int(match.group("h")), 360) / 360, min(int(match.group("s")), 100) / 100, min(int(match.group("l")), 100) / 100
63+
r, g, b = colorsys.hls_to_rgb(h=hsl[0], s=hsl[1], l=hsl[2])
64+
return f"{int(r * 255):02X}{int(g * 255):02X}{int(b * 255):02X}"
65+
5766
raise ValueError(f'Invalid color format "{color}"')

0 commit comments

Comments
 (0)