Source code for framed_text.framed_header
from termcolor import colored as col
from framed_text.utils import (
_validate_color,
_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 = '', frame_color: str | tuple[int, int, int] = '',
title_color: str | tuple[int, int, int] = '', divider: str = '─',
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 attrs: Attributes to apply to the title. See list above for valid attributes
"""
self.title: str = title
self.frame_color: str | tuple[int, int, int] = frame_color
self.title_color: str | tuple[int, int, int] = title_color
self.attrs: list[str] = attrs if attrs else []
self.divider: str = divider if divider else '─'
self._term_width: int = _get_terminal_width()
self.text: str = ''
# Error handling
if self.frame_color:
_validate_color(color=self.frame_color)
if self.title_color:
_validate_color(color=self.title_color)
if self.attrs:
_validate_attrs(attrs=self.attrs)
# Setup title
self.title = _shorten_framed_title(title=self.title, limit=self._term_width - 6)
# Setup text
if self.title:
# Color and Attributes
title: str = _format_col_text(text=self.title, color=self.title_color, attrs=self.attrs)
# Calculate Divider line
start_len, end_len = _calculate_dividers(offset=4, title_len=len(self.title), width=self._term_width)
if self.frame_color:
self.text = f"{col(f"{self.divider * start_len}|", self.frame_color)} {title} {col(f"|{self.divider * end_len}", self.frame_color)}"
else:
self.text = f"{self.divider * start_len}| {title} |{self.divider * end_len}"
else:
if self.frame_color:
self.text = f"{col(self.divider * self._term_width, self.frame_color)}"
else:
self.text = f"{self.divider * self._term_width}"
self.text = _ansi_pipe_clean(text=self.text)
def __str__(self):
return self.text