component.py 21 KB

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