1
0

component.py 24 KB

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