component.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. """Base component definitions."""
  2. from __future__ import annotations
  3. from abc import ABC
  4. from typing import Any, Callable, Dict, List, Optional, Set, Type, Union
  5. from pynecone import utils
  6. from pynecone.base import Base
  7. from pynecone.components.tags import Tag
  8. from pynecone.event import (
  9. EVENT_ARG,
  10. EVENT_TRIGGERS,
  11. EventChain,
  12. EventHandler,
  13. EventSpec,
  14. )
  15. from pynecone.style import Style
  16. from pynecone.var import Var
  17. ImportDict = Dict[str, Set[str]]
  18. class Component(Base, ABC):
  19. """The base class for all Pynecone components."""
  20. # The children nested within the component.
  21. children: List[Component] = []
  22. # The style of the component.
  23. style: Style = Style()
  24. # A mapping from event triggers to event chains.
  25. event_triggers: Dict[str, EventChain] = {}
  26. # The library that the component is based on.
  27. library: Optional[str] = None
  28. # The tag to use when rendering the component.
  29. tag: Optional[str] = None
  30. # A unique key for the component.
  31. key: Any = None
  32. @classmethod
  33. def __init_subclass__(cls, **kwargs):
  34. """Set default properties.
  35. Args:
  36. **kwargs: The kwargs to pass to the superclass.
  37. """
  38. super().__init_subclass__(**kwargs)
  39. # Get all the props for the component.
  40. props = cls.get_props()
  41. # Convert fields to props, setting default values.
  42. for field in cls.get_fields().values():
  43. # If the field is not a component prop, skip it.
  44. if field.name not in props:
  45. continue
  46. # Set default values for any props.
  47. if utils._issubclass(field.type_, Var):
  48. field.required = False
  49. field.default = Var.create(field.default)
  50. def __init__(self, *args, **kwargs):
  51. """Initialize the component.
  52. Args:
  53. *args: Args to initialize the component.
  54. **kwargs: Kwargs to initialize the component.
  55. """
  56. # Get the component fields, triggers, and props.
  57. fields = self.get_fields()
  58. triggers = self.get_triggers()
  59. props = self.get_props()
  60. # Add any events triggers.
  61. if "event_triggers" not in kwargs:
  62. kwargs["event_triggers"] = {}
  63. kwargs["event_triggers"] = kwargs["event_triggers"].copy()
  64. # Iterate through the kwargs and set the props.
  65. for key, value in kwargs.items():
  66. if key in triggers:
  67. # Event triggers are bound to event chains.
  68. field_type = EventChain
  69. else:
  70. # If the key is not in the fields, skip it.
  71. if key not in props:
  72. continue
  73. # Set the field type.
  74. field_type = fields[key].type_
  75. # Check whether the key is a component prop.
  76. if utils._issubclass(field_type, Var):
  77. # Convert any constants into vars and make sure the types match.
  78. kwargs[key] = Var.create(value)
  79. passed_type = kwargs[key].type_
  80. expected_type = fields[key].outer_type_.__args__[0]
  81. assert utils._issubclass(
  82. passed_type, expected_type
  83. ), f"Invalid var passed for {key}, expected {expected_type}, got {passed_type}."
  84. # Check if the key is an event trigger.
  85. if key in triggers:
  86. kwargs["event_triggers"][key] = self._create_event_chain(key, value)
  87. # Remove any keys that were added as events.
  88. for key in kwargs["event_triggers"]:
  89. del kwargs[key]
  90. # Add style props to the component.
  91. kwargs["style"] = Style(
  92. {
  93. **kwargs.get("style", {}),
  94. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  95. }
  96. )
  97. # Construct the component.
  98. super().__init__(*args, **kwargs)
  99. def _create_event_chain(
  100. self,
  101. event_trigger: str,
  102. value: Union[EventHandler, List[EventHandler], Callable],
  103. ) -> EventChain:
  104. """Create an event chain from a variety of input types.
  105. Args:
  106. event_trigger: The event trigger to bind the chain to.
  107. value: The value to create the event chain from.
  108. Returns:
  109. The event chain.
  110. Raises:
  111. ValueError: If the value is not a valid event chain.
  112. """
  113. arg = self.get_controlled_value()
  114. # If the input is a single event handler, wrap it in a list.
  115. if isinstance(value, EventHandler):
  116. value = [value]
  117. # If the input is a list of event handlers, create an event chain.
  118. if isinstance(value, List):
  119. events = [utils.call_event_handler(v, arg) for v in value]
  120. # If the input is a callable, create an event chain.
  121. elif isinstance(value, Callable):
  122. events = utils.call_event_fn(value, arg)
  123. # Otherwise, raise an error.
  124. else:
  125. raise ValueError(f"Invalid event chain: {value}")
  126. # Add args to the event specs if necessary.
  127. if event_trigger in self.get_controlled_triggers():
  128. events = [
  129. EventSpec(
  130. handler=e.handler,
  131. local_args=(EVENT_ARG.name,),
  132. args=utils.get_handler_args(e, arg),
  133. )
  134. for e in events
  135. ]
  136. # Return the event chain.
  137. return EventChain(events=events)
  138. @classmethod
  139. def get_triggers(cls) -> Set[str]:
  140. """Get the event triggers for the component.
  141. Returns:
  142. The event triggers.
  143. """
  144. return EVENT_TRIGGERS | cls.get_controlled_triggers()
  145. @classmethod
  146. def get_controlled_triggers(cls) -> Set[str]:
  147. """Get the event triggers that pass the component's value to the handler.
  148. Returns:
  149. The controlled event triggers.
  150. """
  151. return set()
  152. @classmethod
  153. def get_controlled_value(cls) -> Var:
  154. """Get the var that is passed to the event handler for controlled triggers.
  155. Returns:
  156. The controlled value.
  157. """
  158. return EVENT_ARG
  159. def __repr__(self) -> str:
  160. """Represent the component in React.
  161. Returns:
  162. The code to render the component.
  163. """
  164. return self.render()
  165. def __str__(self) -> str:
  166. """Represent the component in React.
  167. Returns:
  168. The code to render the component.
  169. """
  170. return self.render()
  171. def _render(self) -> Tag:
  172. """Define how to render the component in React.
  173. Returns:
  174. The tag to render.
  175. """
  176. # Create the base tag.
  177. tag = Tag(name=self.tag)
  178. # Add component props to the tag.
  179. props = {attr: getattr(self, attr) for attr in self.get_props()}
  180. # Special case for props named `type_`.
  181. if hasattr(self, "type_"):
  182. props["type"] = getattr(self, "type_")
  183. return tag.add_props(**props)
  184. @classmethod
  185. def get_props(cls) -> Set[str]:
  186. """Get the unique fields for the component.
  187. Returns:
  188. The unique fields.
  189. """
  190. return set(cls.get_fields()) - set(Component.get_fields())
  191. @classmethod
  192. def create(cls, *children, **props) -> Component:
  193. """Create the component.
  194. Args:
  195. *children: The children of the component.
  196. **props: The props of the component.
  197. Returns:
  198. The component.
  199. Raises:
  200. TypeError: If an invalid child is passed.
  201. """
  202. # Import here to avoid circular imports.
  203. from pynecone.components.base.bare import Bare
  204. # Validate all the children.
  205. for child in children:
  206. if not utils._isinstance(child, ComponentChild):
  207. raise TypeError(
  208. "Children of Pynecone components must be other components, "
  209. "state vars, or primitive Python types. "
  210. f"Got child of type {type(child)}.",
  211. )
  212. children = [
  213. Bare.create(contents=Var.create(child, is_string=True))
  214. if not isinstance(child, Component)
  215. else child
  216. for child in children
  217. ]
  218. return cls(children=children, **props)
  219. def _add_style(self, style):
  220. self.style.update(style)
  221. def add_style(self, style: ComponentStyle) -> Component:
  222. """Add additional style to the component and its children.
  223. Args:
  224. style: A dict from component to styling.
  225. Returns:
  226. The component with the additional style.
  227. """
  228. if type(self) in style:
  229. # Extract the style for this component.
  230. component_style = Style(style[type(self)])
  231. # Only add stylee props that are not overriden.
  232. component_style = {
  233. k: v for k, v in component_style.items() if k not in self.style
  234. }
  235. # Add the style to the component.
  236. self._add_style(component_style)
  237. # Recursively add style to the children.
  238. for child in self.children:
  239. child.add_style(style)
  240. return self
  241. def render(self) -> str:
  242. """Render the component.
  243. Returns:
  244. The code to render the component.
  245. """
  246. tag = self._render()
  247. return str(
  248. tag.add_props(**self.event_triggers, key=self.key, sx=self.style).set(
  249. contents=utils.join(
  250. [str(tag.contents)] + [child.render() for child in self.children]
  251. ),
  252. )
  253. )
  254. def _get_custom_code(self) -> Optional[str]:
  255. """Get custom code for the component.
  256. Returns:
  257. The custom code.
  258. """
  259. return None
  260. def get_custom_code(self) -> Set[str]:
  261. """Get custom code for the component and its children.
  262. Returns:
  263. The custom code.
  264. """
  265. # Store the code in a set to avoid duplicates.
  266. code = set()
  267. # Add the custom code for this component.
  268. custom_code = self._get_custom_code()
  269. if custom_code is not None:
  270. code.add(custom_code)
  271. # Add the custom code for the children.
  272. for child in self.children:
  273. code |= child.get_custom_code()
  274. # Return the code.
  275. return code
  276. def _get_imports(self) -> ImportDict:
  277. if self.library is not None and self.tag is not None:
  278. return {self.library: {self.tag}}
  279. return {}
  280. def get_imports(self) -> ImportDict:
  281. """Get all the libraries and fields that are used by the component.
  282. Returns:
  283. The import dict with the required imports.
  284. """
  285. return utils.merge_imports(
  286. self._get_imports(), *[child.get_imports() for child in self.children]
  287. )
  288. # Map from component to styling.
  289. ComponentStyle = Dict[Union[str, Type[Component]], Any]
  290. ComponentChild = Union[utils.PrimitiveType, Var, Component]