|
1 | 1 | """Color types for tppt.""" |
2 | 2 |
|
3 | | -from pptx.dml.color import RGBColor |
| 3 | +from typing import overload |
4 | 4 |
|
5 | 5 | from tppt.exception import ColorInvalidFormatError |
6 | 6 |
|
7 | 7 |
|
8 | 8 | class Color: |
9 | | - """Represents a color in RGB or by name.""" |
| 9 | + """Represents a color in RGB or by hex code. |
10 | 10 |
|
11 | | - def __init__(self, value: str | tuple[int, int, int]): |
| 11 | + Examples: |
| 12 | + >>> Color("#00B") |
| 13 | + >>> Color("#00BB00") |
| 14 | + >>> Color(255, 0, 0) |
| 15 | + """ |
| 16 | + |
| 17 | + @overload |
| 18 | + def __init__(self, r: str): ... |
| 19 | + |
| 20 | + @overload |
| 21 | + def __init__(self, r: int, g: int, b: int): ... |
| 22 | + |
| 23 | + def __init__(self, r: str | int, g: int | None = None, b: int | None = None): |
12 | 24 | """Initialize a Color instance.""" |
13 | | - if isinstance(value, str): |
14 | | - if not value.startswith("#"): |
15 | | - raise ColorInvalidFormatError(value) |
| 25 | + if isinstance(r, str): |
| 26 | + if not r.startswith("#"): |
| 27 | + raise ColorInvalidFormatError(r) |
16 | 28 |
|
17 | | - match len(value): |
| 29 | + match len(r): |
18 | 30 | case 4: |
19 | | - r = int(value[1:2], 16) |
20 | | - g = int(value[2:3], 16) |
21 | | - b = int(value[3:4], 16) |
| 31 | + # #123 は #112233 と同じであることに注意 |
| 32 | + self.r = int(r[1:2] * 2, 16) |
| 33 | + self.g = int(r[2:3] * 2, 16) |
| 34 | + self.b = int(r[3:4] * 2, 16) |
22 | 35 |
|
23 | | - self.value = RGBColor(r, g, b) |
24 | 36 | case 7: |
25 | | - r = int(value[1:3], 16) |
26 | | - g = int(value[3:5], 16) |
27 | | - b = int(value[5:7], 16) |
| 37 | + self.r = int(r[1:3], 16) |
| 38 | + self.g = int(r[3:5], 16) |
| 39 | + self.b = int(r[5:7], 16) |
28 | 40 |
|
29 | | - self.value = RGBColor(r, g, b) |
30 | 41 | case _: |
31 | | - raise ColorInvalidFormatError(value) |
| 42 | + raise ColorInvalidFormatError(r) |
32 | 43 |
|
33 | 44 | else: |
34 | | - r, g, b = value |
35 | 45 | self.r = r |
36 | | - self.g = g |
37 | | - self.b = b |
| 46 | + self.g = g # type: ignore |
| 47 | + self.b = b # type: ignore |
38 | 48 |
|
39 | 49 | def __repr__(self) -> str: |
40 | 50 | """Return string representation.""" |
|
0 commit comments