display_table.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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("Schema", no_wrap=True)
  77. table.add_column("Library", no_wrap=True)
  78. settings = self.settings
  79. for template in templates:
  80. name = template.metadata.name or settings.TEXT_UNNAMED_TEMPLATE
  81. tags_list = template.metadata.tags or []
  82. tags = ", ".join(tags_list) if tags_list else "-"
  83. version = str(template.metadata.version) if template.metadata.version else ""
  84. schema = template.schema_version if hasattr(template, "schema_version") else "1.0"
  85. # Format library with icon and color
  86. library_name = template.metadata.library or ""
  87. library_type = template.metadata.library_type or "git"
  88. icon = IconManager.UI_LIBRARY_STATIC if library_type == "static" else IconManager.UI_LIBRARY_GIT
  89. color = "yellow" if library_type == "static" else "blue"
  90. library_display = f"[{color}]{icon} {library_name}[/{color}]"
  91. table.add_row(template.id, name, tags, version, schema, library_display)
  92. self.base._print_table(table)
  93. def render_status_table(
  94. self,
  95. _title: str,
  96. rows: list[tuple[str, str, bool]],
  97. columns: tuple[str, str] = ("Item", "Status"),
  98. ) -> None:
  99. """Display a status table with success/error indicators.
  100. Args:
  101. _title: Table title (unused, kept for API compatibility)
  102. rows: List of tuples (name, message, success_bool)
  103. columns: Column headers (name_header, status_header)
  104. """
  105. table = Table(show_header=True)
  106. table.add_column(columns[0], style="cyan", no_wrap=True)
  107. table.add_column(columns[1])
  108. for name, message, success in rows:
  109. status_style = "green" if success else "red"
  110. status_icon = IconManager.get_status_icon("success" if success else "error")
  111. table.add_row(name, f"[{status_style}]{status_icon} {message}[/{status_style}]")
  112. self.base._print_table(table)
  113. def render_summary_table(self, title: str, items: dict[str, str]) -> None:
  114. """Display a simple two-column summary table.
  115. Args:
  116. title: Table title
  117. items: Dictionary of key-value pairs to display
  118. """
  119. settings = self.settings
  120. table = Table(
  121. title=title,
  122. show_header=False,
  123. box=None,
  124. padding=settings.PADDING_TABLE_NORMAL,
  125. )
  126. table.add_column(style="bold")
  127. table.add_column()
  128. for key, value in items.items():
  129. table.add_row(key, value)
  130. self.base._print_table(table)
  131. def render_file_operation_table(self, files: list[tuple[str, int, str]]) -> None:
  132. """Display a table of file operations with sizes and statuses.
  133. Args:
  134. files: List of tuples (file_path, size_bytes, status)
  135. """
  136. settings = self.settings
  137. table = Table(
  138. show_header=True,
  139. header_style=settings.STYLE_TABLE_HEADER,
  140. box=None,
  141. padding=settings.PADDING_TABLE_COMPACT,
  142. )
  143. table.add_column("File", style="white", no_wrap=False)
  144. table.add_column("Size", justify="right", style=settings.COLOR_MUTED)
  145. table.add_column("Status", style=settings.COLOR_WARNING)
  146. for file_path, size_bytes, status in files:
  147. size_str = self.base.format_file_size(size_bytes)
  148. table.add_row(str(file_path), size_str, status)
  149. self.base._print_table(table)
  150. def _build_section_label(
  151. self,
  152. section_name: str,
  153. section_data: dict,
  154. show_all: bool,
  155. ) -> str:
  156. """Build section label with metadata."""
  157. section_desc = section_data.get("description", "")
  158. section_toggle = section_data.get("toggle")
  159. section_needs = section_data.get("needs")
  160. label = f"[cyan]{section_name}[/cyan]"
  161. if section_toggle:
  162. label += f" [dim](toggle: {section_toggle})[/dim]"
  163. if section_needs:
  164. needs_str = ", ".join(section_needs) if isinstance(section_needs, list) else section_needs
  165. label += f" [dim](needs: {needs_str})[/dim]"
  166. if show_all and section_desc:
  167. label += f"\n [dim]{section_desc}[/dim]"
  168. return label
  169. def _build_variable_label(
  170. self,
  171. var_name: str,
  172. var_data: dict,
  173. show_all: bool,
  174. ) -> str:
  175. """Build variable label with type and default value."""
  176. var_type = var_data.get("type", "string")
  177. var_default = var_data.get("default", "")
  178. var_desc = var_data.get("description", "")
  179. var_sensitive = var_data.get("sensitive", False)
  180. label = f"[green]{var_name}[/green] [dim]({var_type})[/dim]"
  181. if var_default is not None and var_default != "":
  182. settings = self.settings
  183. display_val = settings.SENSITIVE_MASK if var_sensitive else str(var_default)
  184. if not var_sensitive:
  185. display_val = self.base.truncate(display_val, settings.VALUE_MAX_LENGTH_DEFAULT)
  186. label += f" = [{settings.COLOR_WARNING}]{display_val}[/{settings.COLOR_WARNING}]"
  187. if show_all and var_desc:
  188. label += f"\n [dim]{var_desc}[/dim]"
  189. return label
  190. def _add_section_variables(self, section_node, section_vars: dict, show_all: bool) -> None:
  191. """Add variables to a section node."""
  192. for var_name, var_data in section_vars.items():
  193. if isinstance(var_data, dict):
  194. var_label = self._build_variable_label(var_name, var_data, show_all)
  195. section_node.add(var_label)
  196. else:
  197. # Simple key-value pair
  198. section_node.add(f"[green]{var_name}[/green] = [yellow]{var_data}[/yellow]")
  199. def render_config_tree(self, spec: dict, module_name: str, show_all: bool = False) -> None:
  200. """Display configuration spec as a tree view.
  201. Args:
  202. spec: The configuration spec dictionary
  203. module_name: Name of the module
  204. show_all: If True, show all details including descriptions
  205. """
  206. if not spec:
  207. self.base.text(f"No configuration found for module '{module_name}'", style="yellow")
  208. return
  209. # Create root tree node
  210. icon = IconManager.config()
  211. tree = Tree(f"[bold blue]{icon} {str.capitalize(module_name)} Configuration[/bold blue]")
  212. for section_name, section_data in spec.items():
  213. if not isinstance(section_data, dict):
  214. continue
  215. # Build and add section
  216. section_label = self._build_section_label(section_name, section_data, show_all)
  217. section_node = tree.add(section_label)
  218. # Add variables to section
  219. section_vars = section_data.get("vars") or {}
  220. if section_vars:
  221. self._add_section_variables(section_node, section_vars, show_all)
  222. self.base._print_tree(tree)