styled.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from typing import TYPE_CHECKING
  2. from .measure import Measurement
  3. from .segment import Segment
  4. from .style import StyleType
  5. if TYPE_CHECKING:
  6. from .console import Console, ConsoleOptions, RenderResult, RenderableType
  7. class Styled:
  8. """Apply a style to a renderable.
  9. Args:
  10. renderable (RenderableType): Any renderable.
  11. style (StyleType): A style to apply across the entire renderable.
  12. """
  13. def __init__(self, renderable: "RenderableType", style: "StyleType") -> None:
  14. self.renderable = renderable
  15. self.style = style
  16. def __rich_console__(
  17. self, console: "Console", options: "ConsoleOptions"
  18. ) -> "RenderResult":
  19. style = console.get_style(self.style)
  20. rendered_segments = console.render(self.renderable, options)
  21. segments = Segment.apply_style(rendered_segments, style)
  22. return segments
  23. def __rich_measure__(
  24. self, console: "Console", options: "ConsoleOptions"
  25. ) -> Measurement:
  26. return Measurement.get(console, options, self.renderable)
  27. if __name__ == "__main__": # pragma: no cover
  28. from pip._vendor.rich import print
  29. from pip._vendor.rich.panel import Panel
  30. panel = Styled(Panel("hello"), "on blue")
  31. print(panel)