Caching color blending in Opacity, ignoring ANSI colors

This commit is contained in:
Darren Burns
2022-02-09 10:14:41 +00:00
parent 2648cc0305
commit 3b0cab6f79
2 changed files with 22 additions and 10 deletions

View File

@@ -1,5 +1,7 @@
import functools
from time import sleep from time import sleep
from rich.color import Color
from rich.console import ConsoleOptions, Console, RenderResult, RenderableType from rich.console import ConsoleOptions, Console, RenderResult, RenderableType
from rich.live import Live from rich.live import Live
from rich.panel import Panel from rich.panel import Panel
@@ -34,17 +36,12 @@ class Opacity:
yield segment yield segment
continue continue
fg, bg = style.color, style.bgcolor fg, bg = style.color, style.bgcolor
# TODO: Ignore ansi colours since there will be no rgb triplet if fg and fg.triplet and bg and bg.triplet:
# stored on the Color for them. We could check if there's a
# color.triplet to detect ansi, or maybe there's another way
if fg and bg:
style = Style.from_color(
color=blend_colors(bg, fg, ratio=opacity),
bgcolor=bg,
)
yield Segment( yield Segment(
text=segment.text, text=segment.text,
style=style, style=_get_blended_style_cached(
fg_color=fg, bg_color=bg, opacity=opacity
),
control=segment.control, control=segment.control,
) )
else: else:
@@ -52,6 +49,16 @@ class Opacity:
yield "" yield ""
@functools.lru_cache(maxsize=1024)
def _get_blended_style_cached(
fg_color: Color, bg_color: Color, opacity: float
) -> Style:
return Style.from_color(
color=blend_colors(bg_color, fg_color, ratio=opacity),
bgcolor=bg_color,
)
if __name__ == "__main__": if __name__ == "__main__":
console = Console() console = Console()

View File

@@ -1,9 +1,14 @@
import pytest import pytest
from rich.text import Text
from tests.utilities.render import render
from textual.renderables.opacity import Opacity
@pytest.mark.skip @pytest.mark.skip
def test_simple_opacity(): def test_simple_opacity():
pass text = Text("Hello, world!", style="#ff0000 on #00ff00")
assert render(Opacity(text, value=.5)) == ""
@pytest.mark.skip @pytest.mark.skip