list.py 5.1 KB

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