display_table.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. from __future__ import annotations
  2. import logging
  3. from typing import TYPE_CHECKING
  4. from rich.table import Table
  5. from rich.tree import Tree
  6. from .display_icons import IconManager
  7. from .display_settings import DisplaySettings
  8. if TYPE_CHECKING:
  9. from .display_base import BaseDisplay
  10. logger = logging.getLogger(__name__)
  11. class TableDisplay:
  12. """Table rendering.
  13. Provides methods for displaying data tables with flexible formatting.
  14. """
  15. def __init__(self, settings: DisplaySettings, base: BaseDisplay):
  16. """Initialize TableDisplay.
  17. Args:
  18. settings: Display settings for formatting
  19. base: BaseDisplay instance for utility methods
  20. """
  21. self.settings = settings
  22. self.base = base
  23. def data_table(
  24. self,
  25. columns: list[dict],
  26. rows: list,
  27. title: str | None = None,
  28. row_formatter: callable | None = None,
  29. ) -> None:
  30. """Display a data table with configurable columns and formatting.
  31. Args:
  32. columns: List of column definitions, each dict with:
  33. - name: Column header text
  34. - style: Optional Rich style (e.g., "bold", "cyan")
  35. - no_wrap: Optional bool to prevent text wrapping
  36. - justify: Optional justify ("left", "right", "center")
  37. rows: List of data rows (dicts, tuples, or objects)
  38. title: Optional table title
  39. row_formatter: Optional function(row) -> tuple to transform row data
  40. """
  41. table = Table(title=title, show_header=True)
  42. # Add columns
  43. for col in columns:
  44. table.add_column(
  45. col["name"],
  46. style=col.get("style"),
  47. no_wrap=col.get("no_wrap", False),
  48. justify=col.get("justify", "left"),
  49. )
  50. # Add rows
  51. for row in rows:
  52. if row_formatter:
  53. formatted_row = row_formatter(row)
  54. elif isinstance(row, dict):
  55. formatted_row = tuple(str(row.get(col["name"], "")) for col in columns)
  56. else:
  57. formatted_row = tuple(str(cell) for cell in row)
  58. table.add_row(*formatted_row)
  59. self.base._print_table(table)
  60. def render_templates_table(self, templates: list, module_name: str, _title: str) -> None:
  61. """Display a table of templates with library type indicators.
  62. Args:
  63. templates: List of Template objects
  64. module_name: Name of the module
  65. _title: Title for the table (unused, kept for API compatibility)
  66. """
  67. if not templates:
  68. logger.info(f"No templates found for module '{module_name}'")
  69. return
  70. logger.info(f"Listing {len(templates)} templates for module '{module_name}'")
  71. table = Table()
  72. table.add_column("ID", style="bold", no_wrap=True)
  73. table.add_column("Name")
  74. table.add_column("Tags")
  75. table.add_column("Version", no_wrap=True)
  76. table.add_column("Library", no_wrap=True)
  77. settings = self.settings
  78. for template in templates:
  79. name = template.metadata.name or settings.TEXT_UNNAMED_TEMPLATE
  80. tags_list = template.metadata.tags or []
  81. tags = ", ".join(tags_list) if tags_list else "-"
  82. version = str(template.metadata.version) if template.metadata.version else ""
  83. # Format library with icon and color
  84. library_name = template.metadata.library or ""
  85. library_type = template.metadata.library_type or "git"
  86. icon = IconManager.UI_LIBRARY_STATIC if library_type == "static" else IconManager.UI_LIBRARY_GIT
  87. color = "yellow" if library_type == "static" else "blue"
  88. library_display = f"[{color}]{icon} {library_name}[/{color}]"
  89. table.add_row(template.id, name, tags, version, library_display)
  90. self.base._print_table(table)
  91. def render_status_table(
  92. self,
  93. _title: str,
  94. rows: list[tuple[str, str, bool]],
  95. columns: tuple[str, str] = ("Item", "Status"),
  96. ) -> None:
  97. """Display a status table with success/error indicators.
  98. Args:
  99. _title: Table title (unused, kept for API compatibility)
  100. rows: List of tuples (name, message, success_bool)
  101. columns: Column headers (name_header, status_header)
  102. """
  103. table = Table(show_header=True)
  104. table.add_column(columns[0], style="cyan", no_wrap=True)
  105. table.add_column(columns[1])
  106. for name, message, success in rows:
  107. status_style = "green" if success else "red"
  108. status_icon = IconManager.get_status_icon("success" if success else "error")
  109. table.add_row(name, f"[{status_style}]{status_icon} {message}[/{status_style}]")
  110. self.base._print_table(table)
  111. def render_summary_table(self, title: str, items: dict[str, str]) -> None:
  112. """Display a simple two-column summary table.
  113. Args:
  114. title: Table title
  115. items: Dictionary of key-value pairs to display
  116. """
  117. settings = self.settings
  118. table = Table(
  119. title=title,
  120. show_header=False,
  121. box=None,
  122. padding=settings.PADDING_TABLE_NORMAL,
  123. )
  124. table.add_column(style="bold")
  125. table.add_column()
  126. for key, value in items.items():
  127. table.add_row(key, value)
  128. self.base._print_table(table)
  129. def render_file_operation_table(self, files: list[tuple[str, int, str]]) -> None:
  130. """Display a table of file operations with sizes and statuses.
  131. Args:
  132. files: List of tuples (file_path, size_bytes, status)
  133. """
  134. settings = self.settings
  135. table = Table(
  136. show_header=True,
  137. header_style=settings.STYLE_TABLE_HEADER,
  138. box=None,
  139. padding=settings.PADDING_TABLE_COMPACT,
  140. )
  141. table.add_column("File", style="white", no_wrap=False)
  142. table.add_column("Size", justify="right", style=settings.COLOR_MUTED)
  143. table.add_column("Status", style=settings.COLOR_WARNING)
  144. for file_path, size_bytes, status in files:
  145. size_str = self.base.format_file_size(size_bytes)
  146. table.add_row(str(file_path), size_str, status)
  147. self.base._print_table(table)
  148. def _build_section_label(
  149. self,
  150. section_name: str,
  151. section_data: dict,
  152. show_all: bool,
  153. ) -> str:
  154. """Build section label with metadata."""
  155. section_desc = section_data.get("description", "")
  156. section_toggle = section_data.get("toggle")
  157. section_needs = section_data.get("needs")
  158. label = f"[cyan]{section_name}[/cyan]"
  159. if section_toggle:
  160. label += f" [dim](toggle: {section_toggle})[/dim]"
  161. if section_needs:
  162. needs_str = ", ".join(section_needs) if isinstance(section_needs, list) else section_needs
  163. label += f" [dim](needs: {needs_str})[/dim]"
  164. if show_all and section_desc:
  165. label += f"\n [dim]{section_desc}[/dim]"
  166. return label
  167. def _build_variable_label(
  168. self,
  169. var_name: str,
  170. var_data: dict,
  171. show_all: bool,
  172. ) -> str:
  173. """Build variable label with type and default value."""
  174. var_type = var_data.get("type", "string")
  175. var_default = var_data.get("default", "")
  176. var_desc = var_data.get("description", "")
  177. var_sensitive = var_data.get("sensitive", False)
  178. label = f"[green]{var_name}[/green] [dim]({var_type})[/dim]"
  179. if var_default is not None and var_default != "":
  180. settings = self.settings
  181. display_val = settings.SENSITIVE_MASK if var_sensitive else str(var_default)
  182. if not var_sensitive:
  183. display_val = self.base.truncate(display_val, settings.VALUE_MAX_LENGTH_DEFAULT)
  184. label += f" = [{settings.COLOR_WARNING}]{display_val}[/{settings.COLOR_WARNING}]"
  185. if show_all and var_desc:
  186. label += f"\n [dim]{var_desc}[/dim]"
  187. return label
  188. def _add_section_variables(self, section_node, section_vars: dict, show_all: bool) -> None:
  189. """Add variables to a section node."""
  190. for var_name, var_data in section_vars.items():
  191. if isinstance(var_data, dict):
  192. var_label = self._build_variable_label(var_name, var_data, show_all)
  193. section_node.add(var_label)
  194. else:
  195. # Simple key-value pair
  196. section_node.add(f"[green]{var_name}[/green] = [yellow]{var_data}[/yellow]")
  197. def render_config_tree(self, spec: dict, module_name: str, show_all: bool = False) -> None:
  198. """Display configuration spec as a tree view.
  199. Args:
  200. spec: The configuration spec dictionary
  201. module_name: Name of the module
  202. show_all: If True, show all details including descriptions
  203. """
  204. if not spec:
  205. self.base.text(f"No configuration found for module '{module_name}'", style="yellow")
  206. return
  207. # Create root tree node
  208. icon = IconManager.config()
  209. tree = Tree(f"[bold blue]{icon} {str.capitalize(module_name)} Configuration[/bold blue]")
  210. for section_name, section_data in spec.items():
  211. if not isinstance(section_data, dict):
  212. continue
  213. # Build and add section
  214. section_label = self._build_section_label(section_name, section_data, show_all)
  215. section_node = tree.add(section_label)
  216. # Add variables to section
  217. section_vars = section_data.get("vars") or {}
  218. if section_vars:
  219. self._add_section_variables(section_node, section_vars, show_all)
  220. self.base._print_tree(tree)