component.py 19 KB

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