adde Text.styled

This commit is contained in:
Will McGugan 2020-07-22 17:11:06 +01:00
parent 5cd6e0dfb5
commit 57f6215596
3 changed files with 33 additions and 0 deletions

View File

@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added description parameter to Progress.update
- Added rich.prompt
- Added detecting 'dumb' terminals
- Added Text.styled alternative constructor
### Fixes

View File

@ -208,6 +208,31 @@ class Text(JupyterMixin):
rendered_text.overflow = overflow
return rendered_text
@classmethod
def styled(
cls,
text: str,
style: StyleType = "",
*,
justify: "JustifyMethod" = None,
overflow: "OverflowMethod" = None,
) -> "Text":
"""Construct a Text instance with a pre-applied styled. A style applied in this way won't be used
to pad the text when it is justified.
Args:
text (str): A string containing console markup.
style (Union[str, Style]): Style to apply to the text. Defaults to "".
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
Returns:
Text: A text instance with a style applied to the entire string.
"""
styled_text = cls(text, justify=justify, overflow=overflow)
styled_text.stylize_all(style)
return styled_text
@classmethod
def assemble(
cls,

View File

@ -484,6 +484,13 @@ def test_assemble():
assert text._spans == [Span(3, 6, "bold")]
def test_styled():
text = Text.styled("foo", "bold red")
assert text.style == ""
assert str(text) == "foo"
assert text._spans == [Span(0, 3, "bold red")]
def test_strip_control_codes():
text = Text("foo\rbar")
assert str(text) == "foobar"