Skip to content

Commit

Permalink
Merge pull request #5133 from Textualize/tint
Browse files Browse the repository at this point in the history
  • Loading branch information
willmcgugan authored Oct 21, 2024
2 parents 3daf4d7 + 793dd5b commit e3b1948
Show file tree
Hide file tree
Showing 5 changed files with 131 additions and 69 deletions.
26 changes: 26 additions & 0 deletions src/textual/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,32 @@ def blend(
new_alpha,
)

@lru_cache(maxsize=1024)
def tint(self, color: Color) -> Color:
"""Apply a tint to a color.
Similar to blend, but combines color and alpha.
Args:
color: A color with alpha component.
Returns:
New color
"""

r1, g1, b1, a1, ansi1 = self
if ansi1 is not None:
return self
r2, g2, b2, a2, ansi2 = color
if ansi2 is not None:
return self
return Color(
int(r1 + (r2 - r1) * a2),
int(g1 + (g2 - g1) * a2),
int(b1 + (b2 - b1) * a2),
a1,
)

def __add__(self, other: object) -> Color:
if isinstance(other, Color):
return self.blend(other, other.a, 1.0)
Expand Down
12 changes: 6 additions & 6 deletions src/textual/dom.py
Original file line number Diff line number Diff line change
Expand Up @@ -1031,11 +1031,11 @@ def rich_style(self) -> Style:
has_rule = styles.has_rule
opacity *= styles.opacity
if has_rule("background"):
text_background = (
background + styles.background + styles.background_tint
text_background = background + styles.background.tint(
styles.background_tint
)
background += (
styles.background + styles.background_tint
styles.background.tint(styles.background_tint)
).multiply_alpha(opacity)
else:
text_background = background
Expand Down Expand Up @@ -1124,7 +1124,7 @@ def background_colors(self) -> tuple[Color, Color]:
for node in reversed(self.ancestors_with_self):
styles = node.styles
base_background = background
background += styles.background + styles.background_tint
background += styles.background.tint(styles.background_tint)
return (base_background, background)

@property
Expand All @@ -1140,7 +1140,7 @@ def _opacity_background_colors(self) -> tuple[Color, Color]:
styles = node.styles
base_background = background
opacity *= styles.opacity
background += (styles.background + styles.background_tint).multiply_alpha(
background += styles.background.tint(styles.background_tint).multiply_alpha(
opacity
)
return (base_background, background)
Expand All @@ -1157,7 +1157,7 @@ def colors(self) -> tuple[Color, Color, Color, Color]:
for node in reversed(self.ancestors_with_self):
styles = node.styles
base_background = background
background += styles.background + styles.background_tint
background += styles.background.tint(styles.background_tint)
if styles.has_rule("color"):
base_color = color
if styles.auto_color:
Expand Down
Loading

0 comments on commit e3b1948

Please sign in to comment.