component.py 18 KB

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