list.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. """List components."""
  2. from __future__ import annotations
  3. from collections.abc import Iterable
  4. from typing import Any, Literal
  5. from reflex.components.component import Component, ComponentNamespace
  6. from reflex.components.core.foreach import Foreach
  7. from reflex.components.el.elements.typography import Li, Ol, Ul
  8. from reflex.components.lucide.icon import Icon
  9. from reflex.components.markdown.markdown import MarkdownComponentMap
  10. from reflex.components.radix.themes.typography.text import Text
  11. from reflex.vars.base import Var
  12. LiteralListStyleTypeUnordered = Literal[
  13. "none",
  14. "disc",
  15. "circle",
  16. "square",
  17. ]
  18. LiteralListStyleTypeOrdered = Literal[
  19. "none",
  20. "decimal",
  21. "decimal-leading-zero",
  22. "lower-roman",
  23. "upper-roman",
  24. "lower-greek",
  25. "lower-latin",
  26. "upper-latin",
  27. "armenian",
  28. "georgian",
  29. "lower-alpha",
  30. "upper-alpha",
  31. "hiragana",
  32. "katakana",
  33. ]
  34. class BaseList(Component, MarkdownComponentMap):
  35. """Base class for ordered and unordered lists."""
  36. tag = "ul"
  37. # The style of the list. Default to "none".
  38. list_style_type: Var[
  39. LiteralListStyleTypeUnordered | LiteralListStyleTypeOrdered
  40. ] = Var.create("none")
  41. # A list of items to add to the list.
  42. items: Var[Iterable] = Var.create([])
  43. @classmethod
  44. def create(
  45. cls,
  46. *children,
  47. **props,
  48. ):
  49. """Create a list component.
  50. Args:
  51. *children: The children of the component.
  52. **props: The properties of the component.
  53. Returns:
  54. The list component.
  55. """
  56. items = props.pop("items", None)
  57. list_style_type = props.pop("list_style_type", "none")
  58. if not children and items is not None:
  59. if isinstance(items, Var):
  60. children = [Foreach.create(items, ListItem.create)]
  61. else:
  62. children = [ListItem.create(item) for item in items]
  63. props["direction"] = "column"
  64. style = props.setdefault("style", {})
  65. style["list_style_type"] = list_style_type
  66. if "gap" in props:
  67. style["gap"] = props["gap"]
  68. return super().create(*children, **props)
  69. def add_style(self) -> dict[str, Any] | None:
  70. """Add style to the component.
  71. Returns:
  72. The style of the component.
  73. """
  74. return {
  75. "direction": "column",
  76. }
  77. def _exclude_props(self) -> list[str]:
  78. return ["items", "list_style_type"]
  79. class UnorderedList(BaseList, Ul):
  80. """Display an unordered list."""
  81. tag = "ul"
  82. @classmethod
  83. def create(
  84. cls,
  85. *children,
  86. **props,
  87. ):
  88. """Create an unordered list component.
  89. Args:
  90. *children: The children of the component.
  91. **props: The properties of the component.
  92. Returns:
  93. The list component.
  94. """
  95. items = props.pop("items", None)
  96. list_style_type = props.pop("list_style_type", "disc")
  97. props["margin_left"] = props.get("margin_left", "1.5rem")
  98. return super().create(
  99. *children, items=items, list_style_type=list_style_type, **props
  100. )
  101. class OrderedList(BaseList, Ol):
  102. """Display an ordered list."""
  103. tag = "ol"
  104. @classmethod
  105. def create(
  106. cls,
  107. *children,
  108. **props,
  109. ):
  110. """Create an ordered list component.
  111. Args:
  112. *children: The children of the component.
  113. **props: The properties of the component.
  114. Returns:
  115. The list component.
  116. """
  117. items = props.pop("items", None)
  118. list_style_type = props.pop("list_style_type", "decimal")
  119. props["margin_left"] = props.get("margin_left", "1.5rem")
  120. return super().create(
  121. *children, items=items, list_style_type=list_style_type, **props
  122. )
  123. class ListItem(Li, MarkdownComponentMap):
  124. """Display an item of an ordered or unordered list."""
  125. @classmethod
  126. def create(cls, *children, **props):
  127. """Create a list item component.
  128. Args:
  129. *children: The children of the component.
  130. **props: The properties of the component.
  131. Returns:
  132. The list item component.
  133. """
  134. for child in children:
  135. if isinstance(child, Text):
  136. child.as_ = "span"
  137. elif isinstance(child, Icon) and "display" not in child.style:
  138. child.style["display"] = "inline"
  139. return super().create(*children, **props)
  140. class List(ComponentNamespace):
  141. """List components."""
  142. item = staticmethod(ListItem.create)
  143. ordered = staticmethod(OrderedList.create)
  144. unordered = staticmethod(UnorderedList.create)
  145. __call__ = staticmethod(BaseList.create)
  146. list_ns = List()
  147. list_item = list_ns.item
  148. ordered_list = list_ns.ordered
  149. unordered_list = list_ns.unordered
  150. def __getattr__(name: Any):
  151. # special case for when accessing list to avoid shadowing
  152. # python's built in list object.
  153. if name == "list":
  154. return list_ns
  155. try:
  156. return globals()[name]
  157. except KeyError:
  158. raise AttributeError(f"module '{__name__} has no attribute '{name}'") from None