component.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 BaseVar, 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. elif key in props:
  74. # Set the field type.
  75. field_type = fields[key].type_
  76. else:
  77. continue
  78. # Check whether the key is a component prop.
  79. if utils._issubclass(field_type, Var):
  80. try:
  81. # Try to create a var from the value.
  82. kwargs[key] = Var.create(value)
  83. # Check that the var type is not None.
  84. if kwargs[key] is None:
  85. raise TypeError
  86. # Get the passed type and the var type.
  87. passed_type = kwargs[key].type_
  88. expected_type = fields[key].outer_type_.__args__[0]
  89. except TypeError:
  90. # If it is not a valid var, check the base types.
  91. passed_type = type(value)
  92. expected_type = fields[key].outer_type_
  93. if not utils._issubclass(passed_type, expected_type):
  94. raise TypeError(
  95. f"Invalid var passed for prop {key}, expected type {expected_type}, got value {value} of type {passed_type}."
  96. )
  97. # Check if the key is an event trigger.
  98. if key in triggers:
  99. kwargs["event_triggers"][key] = self._create_event_chain(key, value)
  100. # Remove any keys that were added as events.
  101. for key in kwargs["event_triggers"]:
  102. del kwargs[key]
  103. # Add style props to the component.
  104. kwargs["style"] = Style(
  105. {
  106. **kwargs.get("style", {}),
  107. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  108. }
  109. )
  110. # Construct the component.
  111. super().__init__(*args, **kwargs)
  112. def _create_event_chain(
  113. self,
  114. event_trigger: str,
  115. value: Union[Var, EventHandler, List[EventHandler], Callable],
  116. ) -> Union[EventChain, Var]:
  117. """Create an event chain from a variety of input types.
  118. Args:
  119. event_trigger: The event trigger to bind the chain to.
  120. value: The value to create the event chain from.
  121. Returns:
  122. The event chain.
  123. Raises:
  124. ValueError: If the value is not a valid event chain.
  125. """
  126. # If it's already an event chain, return it.
  127. if isinstance(value, Var):
  128. return value
  129. arg = self.get_controlled_value()
  130. # If the input is a single event handler, wrap it in a list.
  131. if isinstance(value, EventHandler):
  132. value = [value]
  133. # If the input is a list of event handlers, create an event chain.
  134. if isinstance(value, List):
  135. events = [utils.call_event_handler(v, arg) for v in value]
  136. # If the input is a callable, create an event chain.
  137. elif isinstance(value, Callable):
  138. events = utils.call_event_fn(value, arg)
  139. # Otherwise, raise an error.
  140. else:
  141. raise ValueError(f"Invalid event chain: {value}")
  142. # Add args to the event specs if necessary.
  143. if event_trigger in self.get_controlled_triggers():
  144. events = [
  145. EventSpec(
  146. handler=e.handler,
  147. local_args=(EVENT_ARG.name,),
  148. args=utils.get_handler_args(e, arg),
  149. )
  150. for e in events
  151. ]
  152. # Return the event chain.
  153. return EventChain(events=events)
  154. @classmethod
  155. def get_triggers(cls) -> Set[str]:
  156. """Get the event triggers for the component.
  157. Returns:
  158. The event triggers.
  159. """
  160. return EVENT_TRIGGERS | cls.get_controlled_triggers()
  161. @classmethod
  162. def get_controlled_triggers(cls) -> Set[str]:
  163. """Get the event triggers that pass the component's value to the handler.
  164. Returns:
  165. The controlled event triggers.
  166. """
  167. return set()
  168. @classmethod
  169. def get_controlled_value(cls) -> Var:
  170. """Get the var that is passed to the event handler for controlled triggers.
  171. Returns:
  172. The controlled value.
  173. """
  174. return EVENT_ARG
  175. def __repr__(self) -> str:
  176. """Represent the component in React.
  177. Returns:
  178. The code to render the component.
  179. """
  180. return self.render()
  181. def __str__(self) -> str:
  182. """Represent the component in React.
  183. Returns:
  184. The code to render the component.
  185. """
  186. return self.render()
  187. def _render(self) -> Tag:
  188. """Define how to render the component in React.
  189. Returns:
  190. The tag to render.
  191. """
  192. # Create the base tag.
  193. tag = Tag(name=self.tag)
  194. # Add component props to the tag.
  195. props = {attr: getattr(self, attr) for attr in self.get_props()}
  196. # Special case for props named `type_`.
  197. if hasattr(self, "type_"):
  198. props["type"] = getattr(self, "type_")
  199. return tag.add_props(**props)
  200. @classmethod
  201. def get_props(cls) -> Set[str]:
  202. """Get the unique fields for the component.
  203. Returns:
  204. The unique fields.
  205. """
  206. return set(cls.get_fields()) - set(Component.get_fields())
  207. @classmethod
  208. def create(cls, *children, **props) -> Component:
  209. """Create the component.
  210. Args:
  211. *children: The children of the component.
  212. **props: The props of the component.
  213. Returns:
  214. The component.
  215. Raises:
  216. TypeError: If an invalid child is passed.
  217. """
  218. # Import here to avoid circular imports.
  219. from pynecone.components.base.bare import Bare
  220. # Validate all the children.
  221. for child in children:
  222. # Make sure the child is a valid type.
  223. if not utils._isinstance(child, ComponentChild):
  224. raise TypeError(
  225. "Children of Pynecone components must be other components, "
  226. "state vars, or primitive Python types. "
  227. f"Got child {child} of type {type(child)}.",
  228. )
  229. children = [
  230. child
  231. if isinstance(child, Component)
  232. else Bare.create(contents=Var.create(child, is_string=True))
  233. for child in children
  234. ]
  235. return cls(children=children, **props)
  236. def _add_style(self, style):
  237. self.style.update(style)
  238. def add_style(self, style: ComponentStyle) -> Component:
  239. """Add additional style to the component and its children.
  240. Args:
  241. style: A dict from component to styling.
  242. Returns:
  243. The component with the additional style.
  244. """
  245. if type(self) in style:
  246. # Extract the style for this component.
  247. component_style = Style(style[type(self)])
  248. # Only add stylee props that are not overridden.
  249. component_style = {
  250. k: v for k, v in component_style.items() if k not in self.style
  251. }
  252. # Add the style to the component.
  253. self._add_style(component_style)
  254. # Recursively add style to the children.
  255. for child in self.children:
  256. child.add_style(style)
  257. return self
  258. def render(self) -> str:
  259. """Render the component.
  260. Returns:
  261. The code to render the component.
  262. """
  263. tag = self._render()
  264. return str(
  265. tag.add_props(**self.event_triggers, key=self.key, sx=self.style).set(
  266. contents=utils.join(
  267. [str(tag.contents)] + [child.render() for child in self.children]
  268. ).strip(),
  269. )
  270. )
  271. def _get_custom_code(self) -> Optional[str]:
  272. """Get custom code for the component.
  273. Returns:
  274. The custom code.
  275. """
  276. return None
  277. def get_custom_code(self) -> Set[str]:
  278. """Get custom code for the component and its children.
  279. Returns:
  280. The custom code.
  281. """
  282. # Store the code in a set to avoid duplicates.
  283. code = set()
  284. # Add the custom code for this component.
  285. custom_code = self._get_custom_code()
  286. if custom_code is not None:
  287. code.add(custom_code)
  288. # Add the custom code for the children.
  289. for child in self.children:
  290. code |= child.get_custom_code()
  291. # Return the code.
  292. return code
  293. def _get_imports(self) -> ImportDict:
  294. if self.library is not None and self.tag is not None:
  295. return {self.library: {self.tag}}
  296. return {}
  297. def get_imports(self) -> ImportDict:
  298. """Get all the libraries and fields that are used by the component.
  299. Returns:
  300. The import dict with the required imports.
  301. """
  302. return utils.merge_imports(
  303. self._get_imports(), *[child.get_imports() for child in self.children]
  304. )
  305. def get_custom_components(
  306. self, seen: Optional[Set[str]] = None
  307. ) -> Set[CustomComponent]:
  308. """Get all the custom components used by the component.
  309. Args:
  310. seen: The tags of the components that have already been seen.
  311. Returns:
  312. The set of custom components.
  313. """
  314. custom_components = set()
  315. # Store the seen components in a set to avoid infinite recursion.
  316. if seen is None:
  317. seen = set()
  318. for child in self.children:
  319. custom_components |= child.get_custom_components(seen=seen)
  320. return custom_components
  321. # Map from component to styling.
  322. ComponentStyle = Dict[Union[str, Type[Component]], Any]
  323. ComponentChild = Union[utils.PrimitiveType, Var, Component]
  324. class CustomComponent(Component):
  325. """A custom user-defined component."""
  326. # Use the components library.
  327. library = f"/{constants.COMPONENTS_PATH}"
  328. # The function that creates the component.
  329. component_fn: Callable[..., Component]
  330. # The props of the component.
  331. props: Dict[str, Any] = {}
  332. def __init__(self, *args, **kwargs):
  333. """Initialize the custom component.
  334. Args:
  335. *args: The args to pass to the component.
  336. **kwargs: The kwargs to pass to the component.
  337. """
  338. super().__init__(*args, **kwargs)
  339. # Unset the style.
  340. self.style = Style()
  341. # Set the tag to the name of the function.
  342. self.tag = utils.to_title_case(self.component_fn.__name__)
  343. # Set the props.
  344. props = typing.get_type_hints(self.component_fn)
  345. for key, value in kwargs.items():
  346. if key not in props:
  347. continue
  348. type_ = props[key]
  349. if utils._issubclass(type_, EventChain):
  350. value = self._create_event_chain(key, value)
  351. self.props[utils.to_camel_case(key)] = value
  352. continue
  353. type_ = utils.get_args(type_)[0]
  354. if utils._issubclass(type_, Base):
  355. try:
  356. value = BaseVar(name=value.json(), type_=type_, is_local=True)
  357. except Exception:
  358. value = Var.create(value)
  359. else:
  360. value = Var.create(value, is_string=type(value) is str)
  361. self.props[utils.to_camel_case(key)] = value
  362. def __eq__(self, other: Any) -> bool:
  363. """Check if the component is equal to another.
  364. Args:
  365. other: The other component.
  366. Returns:
  367. Whether the component is equal to the other.
  368. """
  369. return isinstance(other, CustomComponent) and self.tag == other.tag
  370. def __hash__(self) -> int:
  371. """Get the hash of the component.
  372. Returns:
  373. The hash of the component.
  374. """
  375. return hash(self.tag)
  376. @classmethod
  377. def get_props(cls) -> Set[str]:
  378. """Get the props for the component.
  379. Returns:
  380. The set of component props.
  381. """
  382. return set()
  383. def get_custom_components(
  384. self, seen: Optional[Set[str]] = None
  385. ) -> Set[CustomComponent]:
  386. """Get all the custom components used by the component.
  387. Args:
  388. seen: The tags of the components that have already been seen.
  389. Returns:
  390. The set of custom components.
  391. """
  392. assert self.tag is not None, "The tag must be set."
  393. # Store the seen components in a set to avoid infinite recursion.
  394. if seen is None:
  395. seen = set()
  396. custom_components = {self} | super().get_custom_components(seen=seen)
  397. # Avoid adding the same component twice.
  398. if self.tag not in seen:
  399. seen.add(self.tag)
  400. custom_components |= self.get_component().get_custom_components(seen=seen)
  401. return custom_components
  402. def _render(self) -> Tag:
  403. """Define how to render the component in React.
  404. Returns:
  405. The tag to render.
  406. """
  407. return Tag(name=self.tag).add_props(**self.props)
  408. def get_prop_vars(self) -> List[BaseVar]:
  409. """Get the prop vars.
  410. Returns:
  411. The prop vars.
  412. """
  413. return [
  414. BaseVar(
  415. name=name,
  416. type_=prop.type_ if utils._isinstance(prop, Var) else type(prop),
  417. )
  418. for name, prop in self.props.items()
  419. ]
  420. def get_component(self) -> Component:
  421. """Render the component.
  422. Returns:
  423. The code to render the component.
  424. """
  425. return self.component_fn(*self.get_prop_vars())
  426. def custom_component(
  427. component_fn: Callable[..., Component]
  428. ) -> Callable[..., CustomComponent]:
  429. """Create a custom component from a function.
  430. Args:
  431. component_fn: The function that creates the component.
  432. Returns:
  433. The decorated function.
  434. """
  435. @wraps(component_fn)
  436. def wrapper(*children, **props) -> CustomComponent:
  437. return CustomComponent(component_fn=component_fn, children=children, **props)
  438. return wrapper