component.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. """Base component definitions."""
  2. from __future__ import annotations
  3. import typing
  4. from abc import ABC
  5. from functools import wraps
  6. from typing import Any, Callable, Dict, List, Optional, Set, Type, Union
  7. from pynecone import constants, utils
  8. from pynecone.base import Base
  9. from pynecone.components.tags import Tag
  10. from pynecone.event import (
  11. EVENT_ARG,
  12. EVENT_TRIGGERS,
  13. EventChain,
  14. EventHandler,
  15. EventSpec,
  16. )
  17. from pynecone.style import Style
  18. from pynecone.var import Var
  19. ImportDict = Dict[str, Set[str]]
  20. class Component(Base, ABC):
  21. """The base class for all Pynecone components."""
  22. # The children nested within the component.
  23. children: List[Component] = []
  24. # The style of the component.
  25. style: Style = Style()
  26. # A mapping from event triggers to event chains.
  27. event_triggers: Dict[str, Union[EventChain, Var]] = {}
  28. # The library that the component is based on.
  29. library: Optional[str] = None
  30. # The tag to use when rendering the component.
  31. tag: Optional[str] = None
  32. # A unique key for the component.
  33. key: Any = None
  34. @classmethod
  35. def __init_subclass__(cls, **kwargs):
  36. """Set default properties.
  37. Args:
  38. **kwargs: The kwargs to pass to the superclass.
  39. """
  40. super().__init_subclass__(**kwargs)
  41. # Get all the props for the component.
  42. props = cls.get_props()
  43. # Convert fields to props, setting default values.
  44. for field in cls.get_fields().values():
  45. # If the field is not a component prop, skip it.
  46. if field.name not in props:
  47. continue
  48. # Set default values for any props.
  49. if utils._issubclass(field.type_, Var):
  50. field.required = False
  51. field.default = Var.create(field.default)
  52. def __init__(self, *args, **kwargs):
  53. """Initialize the component.
  54. Args:
  55. *args: Args to initialize the component.
  56. **kwargs: Kwargs to initialize the component.
  57. Raises:
  58. TypeError: If an invalid prop is passed.
  59. """
  60. # Get the component fields, triggers, and props.
  61. fields = self.get_fields()
  62. triggers = self.get_triggers()
  63. props = self.get_props()
  64. # Add any events triggers.
  65. if "event_triggers" not in kwargs:
  66. kwargs["event_triggers"] = {}
  67. kwargs["event_triggers"] = kwargs["event_triggers"].copy()
  68. # Iterate through the kwargs and set the props.
  69. for key, value in kwargs.items():
  70. if key in triggers:
  71. # Event triggers are bound to event chains.
  72. field_type = EventChain
  73. else:
  74. # If the key is not in the fields, skip it.
  75. if key not in props:
  76. continue
  77. # Set the field type.
  78. field_type = fields[key].type_
  79. # Check whether the key is a component prop.
  80. if utils._issubclass(field_type, Var):
  81. try:
  82. # Try to create a var from the value.
  83. kwargs[key] = Var.create(value)
  84. # Check that the var type is not None.
  85. if kwargs[key] is None:
  86. raise TypeError
  87. # Get the passed type and the var type.
  88. passed_type = kwargs[key].type_
  89. expected_type = fields[key].outer_type_.__args__[0]
  90. except TypeError:
  91. # If it is not a valid var, check the base types.
  92. passed_type = type(value)
  93. expected_type = fields[key].outer_type_
  94. if not utils._issubclass(passed_type, expected_type):
  95. raise TypeError(
  96. f"Invalid var passed for prop {key}, expected type {expected_type}, got value {value} of type {passed_type}."
  97. )
  98. # Check if the key is an event trigger.
  99. if key in triggers:
  100. kwargs["event_triggers"][key] = self._create_event_chain(key, value)
  101. # Remove any keys that were added as events.
  102. for key in kwargs["event_triggers"]:
  103. del kwargs[key]
  104. # Add style props to the component.
  105. kwargs["style"] = Style(
  106. {
  107. **kwargs.get("style", {}),
  108. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  109. }
  110. )
  111. # Construct the component.
  112. super().__init__(*args, **kwargs)
  113. def _create_event_chain(
  114. self,
  115. event_trigger: str,
  116. value: Union[Var, EventHandler, List[EventHandler], Callable],
  117. ) -> Union[EventChain, Var]:
  118. """Create an event chain from a variety of input types.
  119. Args:
  120. event_trigger: The event trigger to bind the chain to.
  121. value: The value to create the event chain from.
  122. Returns:
  123. The event chain.
  124. Raises:
  125. ValueError: If the value is not a valid event chain.
  126. """
  127. # If it's already an event chain, return it.
  128. if isinstance(value, Var):
  129. return value
  130. arg = self.get_controlled_value()
  131. # If the input is a single event handler, wrap it in a list.
  132. if isinstance(value, EventHandler):
  133. value = [value]
  134. # If the input is a list of event handlers, create an event chain.
  135. if isinstance(value, List):
  136. events = [utils.call_event_handler(v, arg) for v in value]
  137. # If the input is a callable, create an event chain.
  138. elif isinstance(value, Callable):
  139. events = utils.call_event_fn(value, arg)
  140. # Otherwise, raise an error.
  141. else:
  142. raise ValueError(f"Invalid event chain: {value}")
  143. # Add args to the event specs if necessary.
  144. if event_trigger in self.get_controlled_triggers():
  145. events = [
  146. EventSpec(
  147. handler=e.handler,
  148. local_args=(EVENT_ARG.name,),
  149. args=utils.get_handler_args(e, arg),
  150. )
  151. for e in events
  152. ]
  153. # Return the event chain.
  154. return EventChain(events=events)
  155. @classmethod
  156. def get_triggers(cls) -> Set[str]:
  157. """Get the event triggers for the component.
  158. Returns:
  159. The event triggers.
  160. """
  161. return EVENT_TRIGGERS | cls.get_controlled_triggers()
  162. @classmethod
  163. def get_controlled_triggers(cls) -> Set[str]:
  164. """Get the event triggers that pass the component's value to the handler.
  165. Returns:
  166. The controlled event triggers.
  167. """
  168. return set()
  169. @classmethod
  170. def get_controlled_value(cls) -> Var:
  171. """Get the var that is passed to the event handler for controlled triggers.
  172. Returns:
  173. The controlled value.
  174. """
  175. return EVENT_ARG
  176. def __repr__(self) -> str:
  177. """Represent the component in React.
  178. Returns:
  179. The code to render the component.
  180. """
  181. return self.render()
  182. def __str__(self) -> str:
  183. """Represent the component in React.
  184. Returns:
  185. The code to render the component.
  186. """
  187. return self.render()
  188. def _render(self) -> Tag:
  189. """Define how to render the component in React.
  190. Returns:
  191. The tag to render.
  192. """
  193. # Create the base tag.
  194. tag = Tag(name=self.tag)
  195. # Add component props to the tag.
  196. props = {attr: getattr(self, attr) for attr in self.get_props()}
  197. # Special case for props named `type_`.
  198. if hasattr(self, "type_"):
  199. props["type"] = getattr(self, "type_")
  200. return tag.add_props(**props)
  201. @classmethod
  202. def get_props(cls) -> Set[str]:
  203. """Get the unique fields for the component.
  204. Returns:
  205. The unique fields.
  206. """
  207. return set(cls.get_fields()) - set(Component.get_fields())
  208. @classmethod
  209. def create(cls, *children, **props) -> Component:
  210. """Create the component.
  211. Args:
  212. *children: The children of the component.
  213. **props: The props of the component.
  214. Returns:
  215. The component.
  216. Raises:
  217. TypeError: If an invalid child is passed.
  218. """
  219. # Import here to avoid circular imports.
  220. from pynecone.components.base.bare import Bare
  221. # Validate all the children.
  222. for child in children:
  223. # Make sure the child is a valid type.
  224. if not utils._isinstance(child, ComponentChild):
  225. raise TypeError(
  226. "Children of Pynecone components must be other components, "
  227. "state vars, or primitive Python types. "
  228. f"Got child {child} of type {type(child)}.",
  229. )
  230. children = [
  231. Bare.create(contents=Var.create(child, is_string=True))
  232. if not isinstance(child, Component)
  233. else child
  234. for child in children
  235. ]
  236. return cls(children=children, **props)
  237. def _add_style(self, style):
  238. self.style.update(style)
  239. def add_style(self, style: ComponentStyle) -> Component:
  240. """Add additional style to the component and its children.
  241. Args:
  242. style: A dict from component to styling.
  243. Returns:
  244. The component with the additional style.
  245. """
  246. if type(self) in style:
  247. # Extract the style for this component.
  248. component_style = Style(style[type(self)])
  249. # Only add stylee props that are not overriden.
  250. component_style = {
  251. k: v for k, v in component_style.items() if k not in self.style
  252. }
  253. # Add the style to the component.
  254. self._add_style(component_style)
  255. # Recursively add style to the children.
  256. for child in self.children:
  257. child.add_style(style)
  258. return self
  259. def render(self) -> str:
  260. """Render the component.
  261. Returns:
  262. The code to render the component.
  263. """
  264. tag = self._render()
  265. return str(
  266. tag.add_props(**self.event_triggers, key=self.key, sx=self.style).set(
  267. contents=utils.join(
  268. [str(tag.contents)] + [child.render() for child in self.children]
  269. ),
  270. )
  271. )
  272. def _get_custom_code(self) -> Optional[str]:
  273. """Get custom code for the component.
  274. Returns:
  275. The custom code.
  276. """
  277. return None
  278. def get_custom_code(self) -> Set[str]:
  279. """Get custom code for the component and its children.
  280. Returns:
  281. The custom code.
  282. """
  283. # Store the code in a set to avoid duplicates.
  284. code = set()
  285. # Add the custom code for this component.
  286. custom_code = self._get_custom_code()
  287. if custom_code is not None:
  288. code.add(custom_code)
  289. # Add the custom code for the children.
  290. for child in self.children:
  291. code |= child.get_custom_code()
  292. # Return the code.
  293. return code
  294. def _get_imports(self) -> ImportDict:
  295. if self.library is not None and self.tag is not None:
  296. return {self.library: {self.tag}}
  297. return {}
  298. def get_imports(self) -> ImportDict:
  299. """Get all the libraries and fields that are used by the component.
  300. Returns:
  301. The import dict with the required imports.
  302. """
  303. return utils.merge_imports(
  304. self._get_imports(), *[child.get_imports() for child in self.children]
  305. )
  306. def get_custom_components(self) -> Set[CustomComponent]:
  307. """Get all the custom components used by the component.
  308. Returns:
  309. The set of custom components.
  310. """
  311. custom_components = set()
  312. for child in self.children:
  313. custom_components |= child.get_custom_components()
  314. return custom_components
  315. # Map from component to styling.
  316. ComponentStyle = Dict[Union[str, Type[Component]], Any]
  317. ComponentChild = Union[utils.PrimitiveType, Var, Component]
  318. class CustomComponent(Component):
  319. """A custom user-defined component."""
  320. # Use the components library.
  321. library = f"/{constants.COMPONENTS_PATH}"
  322. # The function that creates the component.
  323. component_fn: Callable[..., Component]
  324. # The props of the component.
  325. props: Dict[str, Any] = {}
  326. def __init__(self, *args, **kwargs):
  327. """Initialize the custom component.
  328. Args:
  329. *args: The args to pass to the component.
  330. **kwargs: The kwargs to pass to the component.
  331. """
  332. super().__init__(*args, **kwargs)
  333. # Unset the style.
  334. self.style = Style()
  335. # Set the tag to the name of the function.
  336. self.tag = utils.to_title_case(self.component_fn.__name__)
  337. # Set the props.
  338. props = typing.get_type_hints(self.component_fn)
  339. for key, value in kwargs.items():
  340. if key not in props:
  341. continue
  342. type_ = props[key]
  343. if utils._issubclass(type_, EventChain):
  344. value = self._create_event_chain(key, value)
  345. else:
  346. value = Var.create(value)
  347. self.props[utils.to_camel_case(key)] = value
  348. def __eq__(self, other) -> bool:
  349. """Check if the component is equal to another.
  350. Args:
  351. other: The other component.
  352. Returns:
  353. Whether the component is equal to the other.
  354. """
  355. return isinstance(other, CustomComponent) and self.tag == other.tag
  356. def __hash__(self) -> int:
  357. """Get the hash of the component.
  358. Returns:
  359. The hash of the component.
  360. """
  361. return hash(self.tag)
  362. @classmethod
  363. def get_props(cls) -> Set[str]:
  364. """Get the props for the component.
  365. Returns:
  366. The set of component props.
  367. """
  368. return set()
  369. def get_custom_components(self) -> Set[CustomComponent]:
  370. """Get all the custom components used by the component.
  371. Returns:
  372. The set of custom components.
  373. """
  374. return {self} | super().get_custom_components()
  375. def _render(self) -> Tag:
  376. """Define how to render the component in React.
  377. Returns:
  378. The tag to render.
  379. """
  380. return Tag(name=self.tag).add_props(**self.props)
  381. def custom_component(
  382. component_fn: Callable[..., Component]
  383. ) -> Callable[..., CustomComponent]:
  384. """Create a custom component from a function.
  385. Args:
  386. component_fn: The function that creates the component.
  387. Returns:
  388. The decorated function.
  389. """
  390. @wraps(component_fn)
  391. def wrapper(*children, **props) -> CustomComponent:
  392. return CustomComponent(component_fn=component_fn, children=children, **props)
  393. return wrapper