Skip to content

xnano.styles

xnano.styles

xnano.styles

How things look: colors, styles and styled text, and the look of anything written on a screen.

A Style holds colors and text modifiers, and styled text is built from spans that each carry their own. A screen, a placement and a region each have the same four properties for their look, color, border, padding and margin, which are Colors, a BorderAppearance, a PaddingAppearance and a MarginAppearance. Colors are given as names, hex strings or (red, green, blue) tuples wherever a ColorValue is accepted.

Classes:

  • AppearanceArguments –

    How written content looks: the appearance keywords of write.

  • CanvasAppearanceArguments –

    How a canvas itself looks: its colors, text modifiers, border, padding and margin.

  • SpacingDictionary –

    Space around text, edge by edge.

  • BorderAppearance –

    The border of an owner.

  • BorderSide –

    One side of a border: top, right, bottom or left.

  • Colors –

    The two colors of an owner: fg is the text, bg is what is behind it.

  • ColorSlot –

    One color of an owner: the text color, the background or the border color.

  • Edges –

    The four edges of a padding or a margin, in cells.

  • MarginAppearance –

    The transparent space outside the border; see Edges.

  • PaddingAppearance –

    The space between the border and the content; see Edges.

  • RichContent –

    A rich renderable, drawn at the size of the area that it is written in.

Attributes:

  • Spacing (TypeAlias) –

    Space around text: one value for every edge or a SpacingDictionary.

  • Color –

    A terminal color: a named palette color, a palette index or a true color.

  • ColorName –

    The names of the palette colors, such as 'red', 'light_blue' or 'reset'.

  • ColorValue –

    Anything that stands for a color: a name, a hex string, a tuple or a

  • Style –

    A foreground color, a background color and text modifiers such as bold and underline.

  • StyledText –

    Text made of differently styled spans.

  • TextContent –

    Text in any of its forms: a string, a StyledText or a

  • TextLine –

    One wrapped line of a text layout, with the text it holds and where it starts and

  • TextSpan –

    A run of text with one style.

  • BorderKind (TypeAlias) –

    The line style of a border.

Spacing module-attribute

Space around text: one value for every edge or a SpacingDictionary.

A whole number is a count of cells. A float (0.1) or a percentage string ('10%') is a share of the text's width for the left and right edges and of its height for the top and bottom edges, read when the spacing is applied.

Color module-attribute

Color = _CoreColor

A terminal color: a named palette color, a palette index or a true color.

Reach for it to compare or convert a color; anywhere a color is accepted, a name such as 'red', a hex string or a (red, green, blue) tuple works too.

import xnano
from xnano.styles import Color

with xnano.new(width=12, height=1) as canvas:
    canvas.screen.write('warm', foreground=Color('#ff8800'))
    assert Color('#ff8800').to_rgb() == (255, 136, 0)
    assert 'warm' in canvas.screen.render()

ColorName module-attribute

ColorName = _CoreColorName

The names of the palette colors, such as 'red', 'light_blue' or 'reset'.

Use it to annotate a parameter that accepts only a palette name.

import xnano
from xnano.styles import ColorName

sky: ColorName = 'light_blue'
with xnano.new(width=12, height=1) as canvas:
    canvas.screen.write('sky', foreground=sky)
    assert 'sky' in canvas.screen.render()

ColorValue module-attribute

ColorValue = _CoreColorValue

Anything that stands for a color: a name, a hex string, a tuple or a Color.

Use it to annotate a parameter that takes a color in any of those forms: a ColorName such as 'red', a hex string such as '#ff8800' or a (red, green, blue) tuple.

import xnano
from xnano.styles import ColorValue

colors: list[ColorValue] = ['red', '#00ff88', (255, 136, 0)]
with xnano.new(width=12, height=3) as canvas:
    for row, color in enumerate(colors):
        canvas.screen.write('text', y=row, foreground=color)
    assert canvas.screen.render().count('text') == 3

Style module-attribute

Style = _CoreStyle

A foreground color, a background color and text modifiers such as bold and underline.

Reach for it when several pieces of text share one look, or to combine a look with a StyledText span.

import xnano
from xnano.styles import Style

alert = Style('red', bold=True)
with xnano.new(width=12, height=1) as canvas:
    canvas.screen.write('alert', style=alert)
    assert 'bold' in alert.modifiers
    assert 'alert' in canvas.screen.render()

StyledText module-attribute

StyledText = _CoreStyledText

Text made of differently styled spans.

Use it when one line of text needs more than one style.

import xnano
from xnano.buffers import Buffer
from xnano.styles import Style, StyledText, TextSpan

message = StyledText([TextSpan('error: ', style=Style('red', bold=True)), TextSpan('disk full')])
with xnano.new(width=20, height=1) as canvas:
    canvas.screen.write(Buffer(message))
    assert str(message) == 'error: disk full'
    assert canvas.screen.render() == 'error: disk full'

TextContent module-attribute

TextContent = _CoreTextContent

Text in any of its forms: a string, a StyledText or a list of those.

Use it to annotate a parameter that takes text.

import xnano
from xnano.buffers import Buffer
from xnano.styles import Style, StyledText, TextContent, TextSpan

lines: TextContent = ['plain', StyledText([TextSpan('styled', style=Style('green'))])]
with xnano.new(width=8, height=2) as canvas:
    canvas.screen.write(Buffer(lines))
    assert canvas.screen.render().splitlines() == ['plain', 'styled']

TextLine module-attribute

TextLine = _CoreTextLine

One wrapped line of a text layout, with the text it holds and where it starts and ends.

Read it from xnano_core.layout_text when you need to know how a text wraps at a given width.

from xnano_core import layout_text

from xnano.styles import TextLine

line = layout_text('hello world', width=6).lines[0]
assert isinstance(line, TextLine)
assert line.text == 'hello '
assert (line.start_offset, line.end_offset, line.width) == (0, 6, 6)

TextSpan module-attribute

TextSpan = _CoreTextSpan

A run of text with one style.

Use it to build a StyledText whose runs look different.

import xnano
from xnano.buffers import Buffer
from xnano.styles import Style, StyledText, TextSpan

warning = TextSpan('warning', style=Style('yellow', bold=True))
with xnano.new(width=20, height=1) as canvas:
    canvas.screen.write(Buffer(StyledText([warning, TextSpan(': low disk')])))
    assert warning.text == 'warning'
    assert canvas.screen.render() == 'warning: low disk'

AppearanceArguments

Bases: CanvasAppearanceArguments

How written content looks: the appearance keywords of write.

Attributes:

  • title (str | None) –

    A title on the border of the content.

style instance-attribute

style: Style | None

A ready-made style that the colors and modifiers are applied over.

foreground instance-attribute

foreground: ColorValue | None

The foreground color.

background instance-attribute

background: ColorValue | None

The background color.

bold instance-attribute

bold: bool

Whether the cells are bold.

dim instance-attribute

dim: bool

Whether the cells are dimmed.

italic instance-attribute

italic: bool

Whether the cells are italic.

underline instance-attribute

underline: bool

Whether the cells are underlined.

blink: bool

Whether the cells blink.

reverse instance-attribute

reverse: bool

Whether foreground and background are swapped.

hidden instance-attribute

hidden: bool

Whether the cells are hidden.

crossed_out instance-attribute

crossed_out: bool

Whether the cells are struck through.

border instance-attribute

border: BorderKind | bool | None

The kind of border; True is 'plain' and False is none.

border_style instance-attribute

border_style: Style | None

The style of the border.

padding instance-attribute

padding: Spacing | None

Space between the border and the content.

margin instance-attribute

margin: Spacing | None

Space outside the border.

title instance-attribute

title: str | None

A title on the border.

CanvasAppearanceArguments

Bases: TypedDict

How a canvas itself looks: its colors, text modifiers, border, padding and margin.

These style the canvas, not what is written into it, so new() and open() accept them only without content. title is not one of them: on new() and open() it is the window title.

Attributes:

style instance-attribute

style: Style | None

A ready-made style that the colors and modifiers are applied over.

foreground instance-attribute

foreground: ColorValue | None

The foreground color.

background instance-attribute

background: ColorValue | None

The background color.

bold instance-attribute

bold: bool

Whether the cells are bold.

dim instance-attribute

dim: bool

Whether the cells are dimmed.

italic instance-attribute

italic: bool

Whether the cells are italic.

underline instance-attribute

underline: bool

Whether the cells are underlined.

blink: bool

Whether the cells blink.

reverse instance-attribute

reverse: bool

Whether foreground and background are swapped.

hidden instance-attribute

hidden: bool

Whether the cells are hidden.

crossed_out instance-attribute

crossed_out: bool

Whether the cells are struck through.

border instance-attribute

border: BorderKind | bool | None

The kind of border; True is 'plain' and False is none.

border_style instance-attribute

border_style: Style | None

The style of the border.

padding instance-attribute

padding: Spacing | None

Space between the border and the content.

margin instance-attribute

margin: Spacing | None

Space outside the border.

SpacingDictionary

Bases: TypedDict

Space around text, edge by edge.

Attributes:

top instance-attribute

top: int | float | Percentage | str

The space above, in cells.

right instance-attribute

right: int | float | Percentage | str

The space to the right.

bottom instance-attribute

bottom: int | float | Percentage | str

The space below.

left instance-attribute

left: int | float | Percentage | str

The space to the left.

vertical instance-attribute

vertical: int | float | Percentage | str

The space above and below, unless top or bottom is given.

horizontal instance-attribute

horizontal: int | float | Percentage | str

The space left and right, unless left or right is given.

BorderAppearance

BorderAppearance(owner: _Looked)

The border of an owner.

Attributes:

Make the border of an owner. Get it from owner.border instead of calling this.

Parameters:

  • owner (_Looked) –

    The canvas, placement or region.

Methods:

  • random –

    Draw the border on every side with a random kind of line and return the kind.

Source code in xnano/styles/_appearance.py
def __init__(self, owner: _Looked) -> None:
    """
    Make the border of an owner. Get it from ``owner.border`` instead of calling this.

    Args:
        owner: The canvas, placement or region.
    """
    self._owner = owner

kind property writable

kind: BorderKind | None

The kind of border on every side that does not say otherwise.

top property writable

The top side.

right property writable

right: BorderSide

The right side.

bottom property writable

bottom: BorderSide

The bottom side.

left property writable

left: BorderSide

The left side.

color property writable

color: ColorSlot

The color of the border.

title property writable

title: str | None

The text written on the top edge, or None.

random

random() -> BorderKind

Draw the border on every side with a random kind of line and return the kind.

The kind is one of 'plain', 'rounded', 'double' and 'thick'. It replaces the kind of every side, like assigning to kind, and is drawn at once. random.seed(...) repeats the kinds.

Returns:

Examples:

import random

import xnano

with xnano.new(width=12, height=5) as canvas:
    card = canvas.screen.write('hi')
    random.seed(1)
    chosen = card.border.random()
    assert card.border.kind == chosen
Source code in xnano/styles/_appearance.py
def random(self) -> _core.BorderKind:
    """
    Draw the border on every side with a random kind of line and return the kind.

    The kind is one of ``'plain'``, ``'rounded'``, ``'double'`` and ``'thick'``. It
    replaces the kind of every side, like assigning to ``kind``, and is drawn at once.
    ``random.seed(...)`` repeats the kinds.

    Returns:
        The [`BorderKind`][xnano.styles.BorderKind] the border was set to.

    Examples:
        ```python
        import random

        import xnano

        with xnano.new(width=12, height=5) as canvas:
            card = canvas.screen.write('hi')
            random.seed(1)
            chosen = card.border.random()
            assert card.border.kind == chosen
        ```
    """
    kind = cast('_core.BorderKind', random.choice(_BORDER_KINDS))
    self._assign_all(kind)
    return kind

BorderSide

BorderSide(owner: _Looked, name: str)

One side of a border: top, right, bottom or left.

Attributes:

  • kind (BorderKind | None) –

    The kind of line on this side, or None when the side is not drawn.

  • color (Color | None) –

    The color of this side, or None when it uses the border's own color.

Make a side. Get one from owner.border.top and its siblings instead.

Parameters:

  • owner (_Looked) –

    The canvas, placement or region.

  • name (str) –

    'top', 'right', 'bottom' or 'left'.

Methods:

  • random –

    Draw this side with a random kind of line and return the kind.

Source code in xnano/styles/_appearance.py
def __init__(self, owner: _Looked, name: str) -> None:
    """
    Make a side. Get one from ``owner.border.top`` and its siblings instead.

    Args:
        owner: The canvas, placement or region.
        name: ``'top'``, ``'right'``, ``'bottom'`` or ``'left'``.
    """
    self._owner = owner
    self._name = name

kind property writable

kind: BorderKind | None

The kind of line on this side, or None when the side is not drawn.

color property writable

color: Color | None

The color of this side, or None when it uses the border's own color.

random

random() -> BorderKind

Draw this side with a random kind of line and return the kind.

The kind is one of 'plain', 'rounded', 'double' and 'thick'; the side is always drawn, and the border's other sides stay as they are. The change is drawn at once. random.seed(...) repeats the kinds.

Returns:

Examples:

import random

import xnano

with xnano.new(width=12, height=5) as canvas:
    card = canvas.screen.write('hi', border='plain')
    random.seed(2)
    chosen = card.border.top.random()
    assert card.border.top.kind == chosen
Source code in xnano/styles/_appearance.py
def random(self) -> _core.BorderKind:
    """
    Draw this side with a random kind of line and return the kind.

    The kind is one of ``'plain'``, ``'rounded'``, ``'double'`` and ``'thick'``; the side
    is always drawn, and the border's other sides stay as they are. The change is drawn
    at once. ``random.seed(...)`` repeats the kinds.

    Returns:
        The [`BorderKind`][xnano.styles.BorderKind] the side was set to.

    Examples:
        ```python
        import random

        import xnano

        with xnano.new(width=12, height=5) as canvas:
            card = canvas.screen.write('hi', border='plain')
            random.seed(2)
            chosen = card.border.top.random()
            assert card.border.top.kind == chosen
        ```
    """
    kind = cast('_core.BorderKind', random.choice(_BORDER_KINDS))
    self.kind = kind
    return kind

Colors

Colors(owner: _Looked)

The two colors of an owner: fg is the text, bg is what is behind it.

Assigning accepts a color name, a (red, green, blue) tuple, a Color or another ColorSlot; 'reset' clears the color. A value that is not a color raises at the assignment and leaves the colors unchanged.

Attributes:

Make the colors of an owner. Get them from owner.color instead of calling this.

Parameters:

  • owner (_Looked) –

    The canvas, placement or region.

Methods:

  • shade –

    Color the background of every cell from a function of its position, in one write.

Source code in xnano/styles/_appearance.py
def __init__(self, owner: _Looked) -> None:
    """
    Make the colors of an owner. Get them from ``owner.color`` instead of calling this.

    Args:
        owner: The canvas, placement or region.
    """
    self._owner = owner

fg property writable

The color of the text.

bg property writable

The color behind the text.

shade

shade(function: Callable[[int, int], ColorValue | None]) -> None

Color the background of every cell from a function of its position, in one write.

Parameters:

  • function (Callable[[int, int], ColorValue | None]) –

    Called with (x, y) in cells; return the color, or None to leave the cell alone. For half-block or braille resolution use owner.region.half_blocks.shade or owner.region.braille.shade.

Source code in xnano/styles/_appearance.py
def shade(self, function: Callable[[int, int], ColorValue | None]) -> None:
    """
    Color the background of every cell from a function of its position, in one write.

    Args:
        function: Called with ``(x, y)`` in cells; return the color, or ``None`` to leave
            the cell alone. For half-block or braille resolution use
            ``owner.region.half_blocks.shade`` or ``owner.region.braille.shade``.
    """
    self.bg.shade(function)

ColorSlot

ColorSlot(owner: _Looked, name: str)

One color of an owner: the text color, the background or the border color.

A slot is live: changing it changes the owner. slot.value is the plain Color, a copy that changes nothing.

Attributes:

  • value (Color | None) –

    The plain color of the slot, or None when it has none.

Examples:

import xnano

with xnano.new(width=8, height=1) as canvas:
    label = canvas.screen.write('hi', background='#336699')
    label.color.bg.darken(0.2)
    darker = label.color.bg.value
    assert darker != xnano.Color('#336699')
    assert darker.darken(0.5) != label.color.bg.value

Make the slot of an owner. Get one from owner.color instead of calling this.

Parameters:

  • owner (_Looked) –

    The canvas, placement or region.

  • name (str) –

    'foreground', 'background' or 'border'.

Methods:

  • darken –

    Make the color darker, in place.

  • lighten –

    Make the color lighter, in place.

  • random –

    Set the slot to a random color, or to a random shade of base, in place.

  • shade –

    Color every cell of the owner from a function of its position, in one write.

Source code in xnano/styles/_appearance.py
def __init__(self, owner: _Looked, name: str) -> None:
    """
    Make the slot of an owner. Get one from ``owner.color`` instead of calling this.

    Args:
        owner: The canvas, placement or region.
        name: ``'foreground'``, ``'background'`` or ``'border'``.
    """
    self._owner = owner
    self._name = name

value property

value: Color | None

The plain Color of the slot, or None when it has none.

darken

darken(amount: float) -> None

Make the color darker, in place.

This changes the owner and returns nothing. To get a darker copy, use slot.value.darken(amount). Assigning the result of this call to another slot raises a TypeError, but this call has already darkened the owner by then.

Parameters:

  • amount (float) –

    How much darker, from 0.0 (unchanged) to 1.0 (black).

Raises:

Source code in xnano/styles/_appearance.py
def darken(self, amount: float) -> None:
    """
    Make the color darker, in place.

    This changes the owner and returns nothing. To get a darker copy, use
    ``slot.value.darken(amount)``. Assigning the result of this call to another slot
    raises a ``TypeError``, but this call has already darkened the owner by then.

    Args:
        amount: How much darker, from ``0.0`` (unchanged) to ``1.0`` (black).

    Raises:
        TerminalError: The slot has no color.
    """
    self._write(self._require_value('darken').darken(amount))

lighten

lighten(amount: float) -> None

Make the color lighter, in place.

Parameters:

  • amount (float) –

    How much lighter, from 0.0 (unchanged) to 1.0 (white).

Raises:

Source code in xnano/styles/_appearance.py
def lighten(self, amount: float) -> None:
    """
    Make the color lighter, in place.

    Args:
        amount: How much lighter, from ``0.0`` (unchanged) to ``1.0`` (white).

    Raises:
        TerminalError: The slot has no color.
    """
    self._write(self._require_value('lighten').lighten(amount))

random

random(base: ColorName | ColorValue | None = None) -> Color

Set the slot to a random color, or to a random shade of base, in place.

This is slot = Color.random(base); see Color.random. random.seed(...) repeats the colors.

Parameters:

  • base (ColorName | ColorValue | None, default: None ) –

    The color to pick shades of, or None for any color.

Returns:

Raises:

  • ValueError –

    base is Color.reset, or not a color.

Examples:

import xnano

with xnano.new(width=8, height=1) as canvas:
    label = canvas.screen.write('hi')
    chosen = label.color.fg.random('green')
    assert label.color.fg.value == chosen
    label.color.bg.random()
    assert label.color.bg.value is not None
Source code in xnano/styles/_appearance.py
def random(self, base: ColorName | ColorValue | None = None) -> _core.Color:
    """
    Set the slot to a random color, or to a random shade of ``base``, in place.

    This is ``slot = Color.random(base)``; see
    [`Color.random`][xnano_core.Color.random]. ``random.seed(...)`` repeats the colors.

    Args:
        base: The color to pick shades of, or ``None`` for any color.

    Returns:
        The [`Color`][xnano_core.Color] the slot was set to.

    Raises:
        ValueError: ``base`` is ``Color.reset``, or not a color.

    Examples:
        ```python
        import xnano

        with xnano.new(width=8, height=1) as canvas:
            label = canvas.screen.write('hi')
            chosen = label.color.fg.random('green')
            assert label.color.fg.value == chosen
            label.color.bg.random()
            assert label.color.bg.value is not None
        ```
    """
    color = _core.Color.random(base)
    self._write(color)
    return color

shade

shade(function: Callable[[int, int], ColorValue | None]) -> None

Color every cell of the owner from a function of its position, in one write.

Parameters:

  • function (Callable[[int, int], ColorValue | None]) –

    Called with (x, y) in cells; return the color, or None to leave the cell alone. For half-block or braille resolution use owner.region.half_blocks.shade or owner.region.braille.shade.

Raises:

  • TerminalError –

    The slot is border.color, which is one color for the whole border and cannot be shaded.

Examples:

import xnano

with xnano.new(width=4, height=2) as canvas:
    canvas.screen.color.bg.shade(lambda x, y: (x * 40, y * 40, 0))
    assert canvas.screen.region[3, 1].background.to_rgb() == (120, 40, 0)
Source code in xnano/styles/_appearance.py
def shade(self, function: Callable[[int, int], ColorValue | None]) -> None:
    """
    Color every cell of the owner from a function of its position, in one write.

    Args:
        function: Called with ``(x, y)`` in cells; return the color, or ``None`` to leave
            the cell alone. For half-block or braille resolution use
            ``owner.region.half_blocks.shade`` or ``owner.region.braille.shade``.

    Raises:
        TerminalError: The slot is ``border.color``, which is one color for the whole
            border and cannot be shaded.

    Examples:
        ```python
        import xnano

        with xnano.new(width=4, height=2) as canvas:
            canvas.screen.color.bg.shade(lambda x, y: (x * 40, y * 40, 0))
            assert canvas.screen.region[3, 1].background.to_rgb() == (120, 40, 0)
        ```
    """
    if self._name == 'border':
        raise TerminalError(
            'The border has one color, so border.color cannot be shaded cell by cell. '
            'Assign a color to border.color, or shade the content with color.fg.shade '
            'or color.bg.shade.'
        )
    from xnano.layout._region import Region

    owner = self._owner
    region = owner if isinstance(owner, Region) else owner.region
    if self._name == 'foreground':
        region._shade_foreground(function)
    else:
        region.shade(function)

Edges

Edges(owner: _Looked)

The four edges of a padding or a margin, in cells.

Reading an edge gives the number of cells it is now. Assigning accepts a number of cells, a float or a percentage such as '10%', which is a share of the content's size when the look is drawn.

Attributes:

Make the edges of an owner. Get them from owner.padding or owner.margin.

Parameters:

  • owner (_Looked) –

    The canvas, placement or region.

Source code in xnano/styles/_appearance.py
def __init__(self, owner: _Looked) -> None:
    """
    Make the edges of an owner. Get them from ``owner.padding`` or ``owner.margin``.

    Args:
        owner: The canvas, placement or region.
    """
    self._owner = owner

top property writable

top: int

The space above.

right property writable

right: int

The space to the right.

bottom property writable

bottom: int

The space below.

left property writable

left: int

The space to the left.

MarginAppearance

MarginAppearance(owner: _Looked)

Bases: Edges

The transparent space outside the border; see Edges.

Attributes:

Make the edges of an owner. Get them from owner.padding or owner.margin.

Parameters:

  • owner (_Looked) –

    The canvas, placement or region.

Source code in xnano/styles/_appearance.py
def __init__(self, owner: _Looked) -> None:
    """
    Make the edges of an owner. Get them from ``owner.padding`` or ``owner.margin``.

    Args:
        owner: The canvas, placement or region.
    """
    self._owner = owner

top property writable

top: int

The space above.

right property writable

right: int

The space to the right.

bottom property writable

bottom: int

The space below.

left property writable

left: int

The space to the left.

PaddingAppearance

PaddingAppearance(owner: _Looked)

Bases: Edges

The space between the border and the content; see Edges.

Attributes:

Make the edges of an owner. Get them from owner.padding or owner.margin.

Parameters:

  • owner (_Looked) –

    The canvas, placement or region.

Source code in xnano/styles/_appearance.py
def __init__(self, owner: _Looked) -> None:
    """
    Make the edges of an owner. Get them from ``owner.padding`` or ``owner.margin``.

    Args:
        owner: The canvas, placement or region.
    """
    self._owner = owner

top property writable

top: int

The space above.

right property writable

right: int

The space to the right.

bottom property writable

bottom: int

The space below.

left property writable

left: int

The space to the left.

RichContent

RichContent(renderable: RenderableType)

A rich renderable, drawn at the size of the area that it is written in.

Make one with from_rich. Write it like any other content. It accepts each object that follows the protocols of rich: an object with __rich_console__ or __rich__. An optional __rich_measure__ gives the natural width.

Rich draws the renderable at the width of its placement. If the write gives no width, rich uses the natural width of the renderable, at most the width of the canvas. If the write gives a height, the renderable gets it as options.height. If the write gives no height, a renderable that fills the height, such as a rich.layout.Layout, gets the height of the canvas. xnano draws the renderable again when its placement changes size.

Rich reads the time from the canvas clock. Thus, a rich.spinner.Spinner moves with the canvas and stops when the clock is paused. A rich.progress.Progress reads the time with its own get_time. To make it follow the canvas clock, give it get_time=lambda: canvas.clock.elapsed_seconds.

xnano draws text as rich.print draws it, with markup, emoji codes and highlighting. To draw text without them, give a rich.text.Text instead of a string.

xnano keeps the colors of rich: the 16 named colors, the 256 palette colors and true colors. It also keeps bold, dim, italic, underlined, blinking, reverse, concealed and struck-through text. A double underline shows as an underline. A frame, a circle and an overline show as plain text. xnano cells have no links, so a link keeps its text and its style, but not its address. xnano does not draw rich control codes, such as cursor movements.

If a renderable changes in place, call refresh() on its placement to draw it again. For example, do this after you add a row to a table. If rich raises an error when it draws the renderable, xnano does not change the error. On Python 3.11 and later, the error has a note that names from_rich() and the type of the renderable.

Attributes:

  • renderable –

    What rich draws: rich markup text, or an object with __rich_console__ or __rich__.

Examples:

import xnano
from rich.table import Table

table = Table('service', 'status')
table.add_row('web', '[green]up[/green]')

with xnano.new(width=30, height=6) as canvas:
    canvas.screen.write(xnano.from_rich(table))
    assert 'web' in canvas.screen.render()

Wrap a rich renderable. Use from_rich, which checks it first.

Parameters:

  • renderable (RenderableType) –

    Rich markup text, or an object with __rich_console__ or __rich__.

Methods:

  • __xnano_write__ –

    Return the cells that rich draws for the renderable, at the size of its area.

Source code in xnano/styles/_rich.py
def __init__(self, renderable: RenderableType) -> None:
    """
    Wrap a rich renderable. Use [`from_rich`][xnano.from_rich], which checks it first.

    Args:
        renderable: Rich markup text, or an object with ``__rich_console__`` or
            ``__rich__``.
    """
    self.renderable = renderable

__xnano_write__

__xnano_write__(context: Context[object, object]) -> Buffer

Return the cells that rich draws for the renderable, at the size of its area.

Source code in xnano/styles/_rich.py
def __xnano_write__(self, context: Context[object, object]) -> _core.Buffer:
    """Return the cells that rich draws for the renderable, at the size of its area."""
    from rich.console import Console
    from rich.measure import Measurement

    columns, rows = surface_of(context.target).region._grid_size()
    # The hook of a component context is the driver of the component. The driver
    # knows which sizes the write gave. A size that the write did not give follows the
    # content, so rich measures the content again on each run.
    driver = context.hook
    if not getattr(driver, '_is_width_given', True):
        columns = 0
    if not getattr(driver, '_is_height_given', True):
        rows = 0
    canvas_width = max(1, context.screen.width)
    # A console with its own width and height does not read the size of the terminal.
    # The console reads the canvas clock only when rich asks for the time. Thus, only a
    # renderable that moves runs again on each frame.
    console = Console(
        width=columns or canvas_width,
        height=rows or max(1, context.screen.height),
        color_system='truecolor',
        force_terminal=True,
        legacy_windows=False,
        file=io.StringIO(),
        get_time=lambda: context.clock.elapsed_seconds,
    )
    try:
        if not columns:
            natural = Measurement.get(console, console.options, self.renderable)
            console.width = max(1, min(natural.maximum, canvas_width))
        options = console.options.update(height=rows or None)
        lines = console.render_lines(self.renderable, options, pad=False)
        spans: list[_core.TextSpan] = []
        for index, line in enumerate(lines):
            if index:
                spans.append(_core.TextSpan('\n'))
            spans.extend(
                _core.TextSpan(segment.text, style=_style(segment.style))
                for segment in line
                if segment.text and not segment.control
            )
    except Exception as error:
        if sys.version_info >= (3, 11):
            error.add_note(
                f'from_rich() could not draw the {type(self.renderable).__name__} '
                'renderable. The error above occurred when rich drew it. To find the '
                'cause, print the renderable with rich.print().'
            )
        raise
    return _core.Buffer.with_text(_core.StyledText(spans))

__getattr__

__getattr__(name: str) -> object

Import a name the first time it is read, then keep it.

Source code in xnano/styles/__init__.py
def __getattr__(name: str) -> object:
    """Import a name the first time it is read, then keep it."""
    module = _MODULES.get(name)
    if module is None:
        raise AttributeError(
            f'xnano.styles has no name {name!r}. Its names are {", ".join(__all__)}.'
        )
    value = getattr(importlib.import_module(module), name)
    globals()[name] = value
    return value

__dir__

__dir__() -> list[str]

The public names of the module, including the ones that are imported when first read.

Source code in xnano/styles/__init__.py
def __dir__() -> list[str]:
    """The public names of the module, including the ones that are imported when first read."""
    return sorted(__all__)