constrain.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from typing import Optional, TYPE_CHECKING
  2. from .jupyter import JupyterMixin
  3. from .measure import Measurement
  4. if TYPE_CHECKING:
  5. from .console import Console, ConsoleOptions, RenderableType, RenderResult
  6. class Constrain(JupyterMixin):
  7. """Constrain the width of a renderable to a given number of characters.
  8. Args:
  9. renderable (RenderableType): A renderable object.
  10. width (int, optional): The maximum width (in characters) to render. Defaults to 80.
  11. """
  12. def __init__(self, renderable: "RenderableType", width: Optional[int] = 80) -> None:
  13. self.renderable = renderable
  14. self.width = width
  15. def __rich_console__(
  16. self, console: "Console", options: "ConsoleOptions"
  17. ) -> "RenderResult":
  18. if self.width is None:
  19. yield self.renderable
  20. else:
  21. child_options = options.update_width(min(self.width, options.max_width))
  22. yield from console.render(self.renderable, child_options)
  23. def __rich_measure__(
  24. self, console: "Console", options: "ConsoleOptions"
  25. ) -> "Measurement":
  26. if self.width is not None:
  27. options = options.update_width(self.width)
  28. measurement = Measurement.get(console, options, self.renderable)
  29. return measurement