component.py 21 KB

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