Source code for framed_text.framed_header

from termcolor import colored as col

from framed_text.color import Color
from framed_text.utils import (
    _shorten_framed_title,
    _validate_attrs,
    _calculate_dividers,
    _ansi_pipe_clean,
    _format_col_text,
    _get_terminal_width
)


[docs] class FramedHeader:
[docs] def __init__(self, title: str = '', divider: str = '─', frame_color: str | tuple[int, int, int] | Color | None = None, title_color: str | tuple[int, int, int] | Color | None = None, title_attrs: list[str] | None = None): """ Creates a string with a customizable divider. Can include a title. Matches the style of `FramedText`. **Attributes:** All ``termcolor`` attributes are supported: ``"bold"``, ``"dark"``, ``"italic"``, ``"underline"``, ``"reverse"``, ``"concealed"``, ``"strike"`` :param title: Title to display in the header :param frame_color: Color of the frame. Valid colors based off of termcolor's color options: string color code or RGB tuple :param title_color: Color of the title. Valid colors based off of termcolor's color options: string color code or RGB tuple :param divider: Divider to use. Will be repeated to fill the terminal width :param title_attrs: Attributes to apply to the title. See list above for valid attributes """ self._divider: str = divider if divider else '─' self._frame_color: Color = Color(frame_color) if frame_color else Color() self._title_color: Color = Color(title_color) if title_color else Color() self._title_attrs: list[str] | None = _validate_attrs(attrs=title_attrs) self._term_width: int = _get_terminal_width() self._title = _shorten_framed_title(title=title, limit=self._term_width - 6) self.text: str = self._format_text()
def __str__(self): return self.text def _format_text(self) -> str: """ Format the header :return: Header text """ _text: str = '' _frame_color: str | tuple[int, int, int] = self._frame_color.tc_color if self._title: _title: str = _format_col_text(text=self._title, color=self._title_color.tc_color, attrs=self._title_attrs) # Calculate Divider line start_len, end_len = _calculate_dividers(offset=4, title_len=len(self._title), width=self._term_width) if _frame_color: _text = (f"{col(f"{self._divider * start_len}|", _frame_color)} " f"{_title} {col(f"|{self._divider * end_len}", _frame_color)}") else: _text = f"{self._divider * start_len}| {_title} |{self._divider * end_len}" elif _frame_color: _text = f"{col(self._divider * self._term_width, _frame_color)}" else: _text = f"{self._divider * self._term_width}" return _ansi_pipe_clean(text=_text)