component.py 12 KB

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