tree.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. from typing import Iterator, List, Optional, Tuple
  2. from ._loop import loop_first, loop_last
  3. from .console import Console, ConsoleOptions, RenderableType, RenderResult
  4. from .jupyter import JupyterMixin
  5. from .measure import Measurement
  6. from .segment import Segment
  7. from .style import Style, StyleStack, StyleType
  8. from .styled import Styled
  9. GuideType = Tuple[str, str, str, str]
  10. class Tree(JupyterMixin):
  11. """A renderable for a tree structure.
  12. Attributes:
  13. ASCII_GUIDES (GuideType): Guide lines used when Console.ascii_only is True.
  14. TREE_GUIDES (List[GuideType, GuideType, GuideType]): Default guide lines.
  15. Args:
  16. label (RenderableType): The renderable or str for the tree label.
  17. style (StyleType, optional): Style of this tree. Defaults to "tree".
  18. guide_style (StyleType, optional): Style of the guide lines. Defaults to "tree.line".
  19. expanded (bool, optional): Also display children. Defaults to True.
  20. highlight (bool, optional): Highlight renderable (if str). Defaults to False.
  21. hide_root (bool, optional): Hide the root node. Defaults to False.
  22. """
  23. ASCII_GUIDES = (" ", "| ", "+-- ", "`-- ")
  24. TREE_GUIDES = [
  25. (" ", "│ ", "├── ", "└── "),
  26. (" ", "┃ ", "┣━━ ", "┗━━ "),
  27. (" ", "║ ", "╠══ ", "╚══ "),
  28. ]
  29. def __init__(
  30. self,
  31. label: RenderableType,
  32. *,
  33. style: StyleType = "tree",
  34. guide_style: StyleType = "tree.line",
  35. expanded: bool = True,
  36. highlight: bool = False,
  37. hide_root: bool = False,
  38. ) -> None:
  39. self.label = label
  40. self.style = style
  41. self.guide_style = guide_style
  42. self.children: List[Tree] = []
  43. self.expanded = expanded
  44. self.highlight = highlight
  45. self.hide_root = hide_root
  46. def add(
  47. self,
  48. label: RenderableType,
  49. *,
  50. style: Optional[StyleType] = None,
  51. guide_style: Optional[StyleType] = None,
  52. expanded: bool = True,
  53. highlight: Optional[bool] = False,
  54. ) -> "Tree":
  55. """Add a child tree.
  56. Args:
  57. label (RenderableType): The renderable or str for the tree label.
  58. style (StyleType, optional): Style of this tree. Defaults to "tree".
  59. guide_style (StyleType, optional): Style of the guide lines. Defaults to "tree.line".
  60. expanded (bool, optional): Also display children. Defaults to True.
  61. highlight (Optional[bool], optional): Highlight renderable (if str). Defaults to False.
  62. Returns:
  63. Tree: A new child Tree, which may be further modified.
  64. """
  65. node = Tree(
  66. label,
  67. style=self.style if style is None else style,
  68. guide_style=self.guide_style if guide_style is None else guide_style,
  69. expanded=expanded,
  70. highlight=self.highlight if highlight is None else highlight,
  71. )
  72. self.children.append(node)
  73. return node
  74. def __rich_console__(
  75. self, console: "Console", options: "ConsoleOptions"
  76. ) -> "RenderResult":
  77. stack: List[Iterator[Tuple[bool, Tree]]] = []
  78. pop = stack.pop
  79. push = stack.append
  80. new_line = Segment.line()
  81. get_style = console.get_style
  82. null_style = Style.null()
  83. guide_style = get_style(self.guide_style, default="") or null_style
  84. SPACE, CONTINUE, FORK, END = range(4)
  85. _Segment = Segment
  86. def make_guide(index: int, style: Style) -> Segment:
  87. """Make a Segment for a level of the guide lines."""
  88. if options.ascii_only:
  89. line = self.ASCII_GUIDES[index]
  90. else:
  91. guide = 1 if style.bold else (2 if style.underline2 else 0)
  92. line = self.TREE_GUIDES[0 if options.legacy_windows else guide][index]
  93. return _Segment(line, style)
  94. levels: List[Segment] = [make_guide(CONTINUE, guide_style)]
  95. push(iter(loop_last([self])))
  96. guide_style_stack = StyleStack(get_style(self.guide_style))
  97. style_stack = StyleStack(get_style(self.style))
  98. remove_guide_styles = Style(bold=False, underline2=False)
  99. depth = 0
  100. while stack:
  101. stack_node = pop()
  102. try:
  103. last, node = next(stack_node)
  104. except StopIteration:
  105. levels.pop()
  106. if levels:
  107. guide_style = levels[-1].style or null_style
  108. levels[-1] = make_guide(FORK, guide_style)
  109. guide_style_stack.pop()
  110. style_stack.pop()
  111. continue
  112. push(stack_node)
  113. if last:
  114. levels[-1] = make_guide(END, levels[-1].style or null_style)
  115. guide_style = guide_style_stack.current + get_style(node.guide_style)
  116. style = style_stack.current + get_style(node.style)
  117. prefix = levels[(2 if self.hide_root else 1) :]
  118. renderable_lines = console.render_lines(
  119. Styled(node.label, style),
  120. options.update(
  121. width=options.max_width
  122. - sum(level.cell_length for level in prefix),
  123. highlight=self.highlight,
  124. height=None,
  125. ),
  126. pad=options.justify is not None,
  127. )
  128. if not (depth == 0 and self.hide_root):
  129. for first, line in loop_first(renderable_lines):
  130. if prefix:
  131. yield from _Segment.apply_style(
  132. prefix,
  133. style.background_style,
  134. post_style=remove_guide_styles,
  135. )
  136. yield from line
  137. yield new_line
  138. if first and prefix:
  139. prefix[-1] = make_guide(
  140. SPACE if last else CONTINUE, prefix[-1].style or null_style
  141. )
  142. if node.expanded and node.children:
  143. levels[-1] = make_guide(
  144. SPACE if last else CONTINUE, levels[-1].style or null_style
  145. )
  146. levels.append(
  147. make_guide(END if len(node.children) == 1 else FORK, guide_style)
  148. )
  149. style_stack.push(get_style(node.style))
  150. guide_style_stack.push(get_style(node.guide_style))
  151. push(iter(loop_last(node.children)))
  152. depth += 1
  153. def __rich_measure__(
  154. self, console: "Console", options: "ConsoleOptions"
  155. ) -> "Measurement":
  156. stack: List[Iterator[Tree]] = [iter([self])]
  157. pop = stack.pop
  158. push = stack.append
  159. minimum = 0
  160. maximum = 0
  161. measure = Measurement.get
  162. level = 0
  163. while stack:
  164. iter_tree = pop()
  165. try:
  166. tree = next(iter_tree)
  167. except StopIteration:
  168. level -= 1
  169. continue
  170. push(iter_tree)
  171. min_measure, max_measure = measure(console, options, tree.label)
  172. indent = level * 4
  173. minimum = max(min_measure + indent, minimum)
  174. maximum = max(max_measure + indent, maximum)
  175. if tree.expanded and tree.children:
  176. push(iter(tree.children))
  177. level += 1
  178. return Measurement(minimum, maximum)
  179. if __name__ == "__main__": # pragma: no cover
  180. from rich.console import Group
  181. from rich.markdown import Markdown
  182. from rich.panel import Panel
  183. from rich.syntax import Syntax
  184. from rich.table import Table
  185. table = Table(row_styles=["", "dim"])
  186. table.add_column("Released", style="cyan", no_wrap=True)
  187. table.add_column("Title", style="magenta")
  188. table.add_column("Box Office", justify="right", style="green")
  189. table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690")
  190. table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
  191. table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889")
  192. table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889")
  193. code = """\
  194. class Segment(NamedTuple):
  195. text: str = ""
  196. style: Optional[Style] = None
  197. is_control: bool = False
  198. """
  199. syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
  200. markdown = Markdown(
  201. """\
  202. ### example.md
  203. > Hello, World!
  204. >
  205. > Markdown _all_ the things
  206. """
  207. )
  208. root = Tree("🌲 [b green]Rich Tree", highlight=True, hide_root=True)
  209. node = root.add(":file_folder: Renderables", guide_style="red")
  210. simple_node = node.add(":file_folder: [bold yellow]Atomic", guide_style="uu green")
  211. simple_node.add(Group("📄 Syntax", syntax))
  212. simple_node.add(Group("📄 Markdown", Panel(markdown, border_style="green")))
  213. containers_node = node.add(
  214. ":file_folder: [bold magenta]Containers", guide_style="bold magenta"
  215. )
  216. containers_node.expanded = True
  217. panel = Panel.fit("Just a panel", border_style="red")
  218. containers_node.add(Group("📄 Panels", panel))
  219. containers_node.add(Group("📄 [b magenta]Table", table))
  220. console = Console()
  221. console.print(root)