component.py 22 KB

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