component.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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.constants import EventTriggers
  11. from reflex.event import (
  12. EventChain,
  13. EventHandler,
  14. EventSpec,
  15. call_event_fn,
  16. call_event_handler,
  17. get_handler_args,
  18. )
  19. from reflex.style import Style
  20. from reflex.utils import console, format, imports, types
  21. from reflex.vars import BaseVar, ImportVar, Var
  22. class Component(Base, ABC):
  23. """The base class for all Reflex components."""
  24. # The children nested within the component.
  25. children: List[Component] = []
  26. # The style of the component.
  27. style: Style = Style()
  28. # A mapping from event triggers to event chains.
  29. event_triggers: Dict[str, Union[EventChain, Var]] = {}
  30. # The library that the component is based on.
  31. library: Optional[str] = None
  32. # List here the non-react dependency needed by `library`
  33. lib_dependencies: List[str] = []
  34. # The tag to use when rendering the component.
  35. tag: Optional[str] = None
  36. # The alias for the tag.
  37. alias: Optional[str] = None
  38. # Whether the import is default or named.
  39. is_default: Optional[bool] = False
  40. # A unique key for the component.
  41. key: Any = None
  42. # The id for the component.
  43. id: Any = None
  44. # The class name for the component.
  45. class_name: Any = None
  46. # Special component props.
  47. special_props: Set[Var] = set()
  48. # Whether the component should take the focus once the page is loaded
  49. autofocus: bool = False
  50. # components that cannot be children
  51. invalid_children: List[str] = []
  52. # components that are only allowed as children
  53. valid_children: List[str] = []
  54. # custom attribute
  55. custom_attrs: Dict[str, str] = {}
  56. @classmethod
  57. def __init_subclass__(cls, **kwargs):
  58. """Set default properties.
  59. Args:
  60. **kwargs: The kwargs to pass to the superclass.
  61. """
  62. super().__init_subclass__(**kwargs)
  63. # Get all the props for the component.
  64. props = cls.get_props()
  65. # Convert fields to props, setting default values.
  66. for field in cls.get_fields().values():
  67. # If the field is not a component prop, skip it.
  68. if field.name not in props:
  69. continue
  70. # Set default values for any props.
  71. if types._issubclass(field.type_, Var):
  72. field.required = False
  73. field.default = Var.create(field.default)
  74. def __init__(self, *args, **kwargs):
  75. """Initialize the component.
  76. Args:
  77. *args: Args to initialize the component.
  78. **kwargs: Kwargs to initialize the component.
  79. Raises:
  80. TypeError: If an invalid prop is passed.
  81. """
  82. # Set the id and children initially.
  83. children = kwargs.get("children", [])
  84. initial_kwargs = {
  85. "id": kwargs.get("id"),
  86. "children": children,
  87. **{
  88. prop: Var.create(kwargs[prop])
  89. for prop in self.get_initial_props()
  90. if prop in kwargs
  91. },
  92. }
  93. super().__init__(**initial_kwargs)
  94. self._validate_component_children(children)
  95. # Get the component fields, triggers, and props.
  96. fields = self.get_fields()
  97. triggers = self.get_event_triggers().keys()
  98. props = self.get_props()
  99. # Add any events triggers.
  100. if "event_triggers" not in kwargs:
  101. kwargs["event_triggers"] = {}
  102. kwargs["event_triggers"] = kwargs["event_triggers"].copy()
  103. # Iterate through the kwargs and set the props.
  104. for key, value in kwargs.items():
  105. if key in triggers:
  106. # Event triggers are bound to event chains.
  107. field_type = EventChain
  108. elif key in props:
  109. # Set the field type.
  110. field_type = fields[key].type_
  111. else:
  112. continue
  113. # Check whether the key is a component prop.
  114. if types._issubclass(field_type, Var):
  115. try:
  116. # Try to create a var from the value.
  117. kwargs[key] = Var.create(value)
  118. # Check that the var type is not None.
  119. if kwargs[key] is None:
  120. raise TypeError
  121. # Get the passed type and the var type.
  122. passed_type = kwargs[key].type_
  123. expected_type = fields[key].outer_type_.__args__[0]
  124. except TypeError:
  125. # If it is not a valid var, check the base types.
  126. passed_type = type(value)
  127. expected_type = fields[key].outer_type_
  128. if not types._issubclass(passed_type, expected_type):
  129. raise TypeError(
  130. f"Invalid var passed for prop {key}, expected type {expected_type}, got value {value} of type {passed_type}."
  131. )
  132. # Check if the key is an event trigger.
  133. if key in triggers:
  134. # Temporarily disable full control for event triggers.
  135. kwargs["event_triggers"][key] = self._create_event_chain(key, value)
  136. # Remove any keys that were added as events.
  137. for key in kwargs["event_triggers"]:
  138. del kwargs[key]
  139. # Add style props to the component.
  140. style = kwargs.get("style", {})
  141. if isinstance(style, List):
  142. # Merge styles, the later ones overriding keys in the earlier ones.
  143. style = {k: v for style_dict in style for k, v in style_dict.items()}
  144. kwargs["style"] = Style(
  145. {
  146. **style,
  147. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  148. }
  149. )
  150. if "custom_attrs" not in kwargs:
  151. kwargs["custom_attrs"] = {}
  152. # Convert class_name to str if it's list
  153. class_name = kwargs.get("class_name", "")
  154. if isinstance(class_name, (List, tuple)):
  155. kwargs["class_name"] = " ".join(class_name)
  156. # Construct the component.
  157. super().__init__(*args, **kwargs)
  158. def _create_event_chain(
  159. self,
  160. event_trigger: str,
  161. value: Union[
  162. Var, EventHandler, EventSpec, List[Union[EventHandler, EventSpec]], Callable
  163. ],
  164. ) -> Union[EventChain, Var]:
  165. """Create an event chain from a variety of input types.
  166. Args:
  167. event_trigger: The event trigger to bind the chain to.
  168. value: The value to create the event chain from.
  169. Returns:
  170. The event chain.
  171. Raises:
  172. ValueError: If the value is not a valid event chain.
  173. """
  174. # Check if the trigger is a controlled event.
  175. triggers = self.get_event_triggers()
  176. # If it's an event chain var, return it.
  177. if isinstance(value, Var):
  178. if value.type_ is not EventChain:
  179. raise ValueError(f"Invalid event chain: {value}")
  180. return value
  181. arg_spec = triggers.get(event_trigger, lambda: [])
  182. wrapped = False
  183. # If the input is a single event handler, wrap it in a list.
  184. if isinstance(value, (EventHandler, EventSpec)):
  185. wrapped = True
  186. value = [value]
  187. # If the input is a list of event handlers, create an event chain.
  188. if isinstance(value, List):
  189. if not wrapped:
  190. console.deprecate(
  191. feature_name="EventChain",
  192. reason="to avoid confusion, only use yield API",
  193. deprecation_version="0.2.8",
  194. removal_version="0.2.9",
  195. )
  196. events = []
  197. for v in value:
  198. if isinstance(v, EventHandler):
  199. # Call the event handler to get the event.
  200. event = call_event_handler(v, arg_spec) # type: ignore
  201. # Add the event to the chain.
  202. events.append(event)
  203. elif isinstance(v, EventSpec):
  204. # Add the event to the chain.
  205. events.append(v)
  206. elif isinstance(v, Callable):
  207. # Call the lambda to get the event chain.
  208. events.extend(call_event_fn(v, arg_spec)) # type: ignore
  209. else:
  210. raise ValueError(f"Invalid event: {v}")
  211. # If the input is a callable, create an event chain.
  212. elif isinstance(value, Callable):
  213. events = call_event_fn(value, arg_spec) # type: ignore
  214. # Otherwise, raise an error.
  215. else:
  216. raise ValueError(f"Invalid event chain: {value}")
  217. # Add args to the event specs if necessary.
  218. events = [
  219. EventSpec(
  220. handler=e.handler,
  221. args=get_handler_args(e),
  222. client_handler_name=e.client_handler_name,
  223. )
  224. for e in events
  225. ]
  226. # Return the event chain.
  227. if isinstance(arg_spec, Var):
  228. return EventChain(events=events, args_spec=None)
  229. else:
  230. return EventChain(events=events, args_spec=arg_spec) # type: ignore
  231. def get_event_triggers(self) -> Dict[str, Any]:
  232. """Get the event triggers for the component.
  233. Returns:
  234. The event triggers.
  235. """
  236. deprecated_triggers = self.get_triggers()
  237. if deprecated_triggers:
  238. console.deprecate(
  239. feature_name=f"get_triggers ({self.__class__.__name__})",
  240. reason="replaced by get_event_triggers",
  241. deprecation_version="0.2.8",
  242. removal_version="0.2.9",
  243. )
  244. deprecated_triggers = {
  245. trigger: lambda: [] for trigger in deprecated_triggers
  246. }
  247. else:
  248. deprecated_triggers = {}
  249. deprecated_controlled_triggers = self.get_controlled_triggers()
  250. if deprecated_controlled_triggers:
  251. console.deprecate(
  252. feature_name=f"get_controlled_triggers ({self.__class__.__name__})",
  253. reason="replaced by get_event_triggers",
  254. deprecation_version="0.2.8",
  255. removal_version="0.2.9",
  256. )
  257. return {
  258. EventTriggers.ON_FOCUS: lambda: [],
  259. EventTriggers.ON_BLUR: lambda: [],
  260. EventTriggers.ON_CLICK: lambda: [],
  261. EventTriggers.ON_CONTEXT_MENU: lambda: [],
  262. EventTriggers.ON_DOUBLE_CLICK: lambda: [],
  263. EventTriggers.ON_MOUSE_DOWN: lambda: [],
  264. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  265. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  266. EventTriggers.ON_MOUSE_MOVE: lambda: [],
  267. EventTriggers.ON_MOUSE_OUT: lambda: [],
  268. EventTriggers.ON_MOUSE_OVER: lambda: [],
  269. EventTriggers.ON_MOUSE_UP: lambda: [],
  270. EventTriggers.ON_SCROLL: lambda: [],
  271. EventTriggers.ON_MOUNT: lambda: [],
  272. EventTriggers.ON_UNMOUNT: lambda: [],
  273. **deprecated_triggers,
  274. **deprecated_controlled_triggers,
  275. }
  276. def get_triggers(self) -> Set[str]:
  277. """Get the triggers for non controlled events [DEPRECATED].
  278. Returns:
  279. A set of non controlled triggers.
  280. """
  281. return set()
  282. def get_controlled_triggers(self) -> Dict[str, Var]:
  283. """Get the event triggers that pass the component's value to the handler [DEPRECATED].
  284. Returns:
  285. A dict mapping the event trigger to the var that is passed to the handler.
  286. """
  287. return {}
  288. def __repr__(self) -> str:
  289. """Represent the component in React.
  290. Returns:
  291. The code to render the component.
  292. """
  293. return format.json_dumps(self.render())
  294. def __str__(self) -> str:
  295. """Represent the component in React.
  296. Returns:
  297. The code to render the component.
  298. """
  299. from reflex.compiler.compiler import _compile_component
  300. return _compile_component(self)
  301. def _render(self) -> Tag:
  302. """Define how to render the component in React.
  303. Returns:
  304. The tag to render.
  305. """
  306. # Create the base tag.
  307. tag = Tag(
  308. name=self.tag if not self.alias else self.alias,
  309. special_props=self.special_props,
  310. )
  311. # Add component props to the tag.
  312. props = {
  313. attr[:-1] if attr.endswith("_") else attr: getattr(self, attr)
  314. for attr in self.get_props()
  315. }
  316. # Add ref to element if `id` is not None.
  317. ref = self.get_ref()
  318. if ref is not None:
  319. props["ref"] = Var.create(ref, is_local=False)
  320. return tag.add_props(**props)
  321. @classmethod
  322. def get_props(cls) -> Set[str]:
  323. """Get the unique fields for the component.
  324. Returns:
  325. The unique fields.
  326. """
  327. return set(cls.get_fields()) - set(Component.get_fields())
  328. @classmethod
  329. def get_initial_props(cls) -> Set[str]:
  330. """Get the initial props to set for the component.
  331. Returns:
  332. The initial props to set.
  333. """
  334. return set()
  335. @classmethod
  336. def create(cls, *children, **props) -> Component:
  337. """Create the component.
  338. Args:
  339. *children: The children of the component.
  340. **props: The props of the component.
  341. Returns:
  342. The component.
  343. Raises:
  344. TypeError: If an invalid child is passed.
  345. """
  346. # Import here to avoid circular imports.
  347. from reflex.components.base.bare import Bare
  348. # Validate all the children.
  349. for child in children:
  350. # Make sure the child is a valid type.
  351. if not types._isinstance(child, ComponentChild):
  352. raise TypeError(
  353. "Children of Reflex components must be other components, "
  354. "state vars, or primitive Python types. "
  355. f"Got child {child} of type {type(child)}.",
  356. )
  357. children = [
  358. child
  359. if isinstance(child, Component)
  360. else Bare.create(contents=Var.create(child, is_string=True))
  361. for child in children
  362. ]
  363. return cls(children=children, **props)
  364. def _add_style(self, style: dict):
  365. """Add additional style to the component.
  366. Args:
  367. style: A style dict to apply.
  368. """
  369. self.style.update(style)
  370. def add_style(self, style: ComponentStyle) -> Component:
  371. """Add additional style to the component and its children.
  372. Args:
  373. style: A dict from component to styling.
  374. Returns:
  375. The component with the additional style.
  376. """
  377. if type(self) in style:
  378. # Extract the style for this component.
  379. component_style = Style(style[type(self)])
  380. # Only add style props that are not overridden.
  381. component_style = {
  382. k: v for k, v in component_style.items() if k not in self.style
  383. }
  384. # Add the style to the component.
  385. self._add_style(component_style)
  386. # Recursively add style to the children.
  387. for child in self.children:
  388. child.add_style(style)
  389. return self
  390. def render(self) -> Dict:
  391. """Render the component.
  392. Returns:
  393. The dictionary for template of component.
  394. """
  395. tag = self._render()
  396. rendered_dict = dict(
  397. tag.add_props(
  398. **self.event_triggers,
  399. key=self.key,
  400. sx=self.style,
  401. id=self.id,
  402. class_name=self.class_name,
  403. **self.custom_attrs,
  404. ).set(
  405. children=[child.render() for child in self.children],
  406. contents=str(tag.contents),
  407. props=tag.format_props(),
  408. ),
  409. autofocus=self.autofocus,
  410. )
  411. return rendered_dict
  412. def _validate_component_children(self, children: List[Component]):
  413. """Validate the children components.
  414. Args:
  415. children: The children of the component.
  416. """
  417. if not self.invalid_children and not self.valid_children:
  418. return
  419. comp_name = type(self).__name__
  420. def validate_invalid_child(child_name):
  421. if child_name in self.invalid_children:
  422. raise ValueError(
  423. f"The component `{comp_name}` cannot have `{child_name}` as a child component"
  424. )
  425. def validate_valid_child(child_name):
  426. if child_name not in self.valid_children:
  427. valid_child_list = ", ".join(
  428. [f"`{v_child}`" for v_child in self.valid_children]
  429. )
  430. raise ValueError(
  431. f"The component `{comp_name}` only allows the components: {valid_child_list} as children. Got `{child_name}` instead."
  432. )
  433. for child in children:
  434. name = type(child).__name__
  435. if self.invalid_children:
  436. validate_invalid_child(name)
  437. if self.valid_children:
  438. validate_valid_child(name)
  439. def _get_custom_code(self) -> Optional[str]:
  440. """Get custom code for the component.
  441. Returns:
  442. The custom code.
  443. """
  444. return None
  445. def get_custom_code(self) -> Set[str]:
  446. """Get custom code for the component and its children.
  447. Returns:
  448. The custom code.
  449. """
  450. # Store the code in a set to avoid duplicates.
  451. code = set()
  452. # Add the custom code for this component.
  453. custom_code = self._get_custom_code()
  454. if custom_code is not None:
  455. code.add(custom_code)
  456. # Add the custom code for the children.
  457. for child in self.children:
  458. code |= child.get_custom_code()
  459. # Return the code.
  460. return code
  461. def _get_dynamic_imports(self) -> Optional[str]:
  462. """Get dynamic import for the component.
  463. Returns:
  464. The dynamic import.
  465. """
  466. return None
  467. def get_dynamic_imports(self) -> Set[str]:
  468. """Get dynamic imports for the component and its children.
  469. Returns:
  470. The dynamic imports.
  471. """
  472. # Store the import in a set to avoid duplicates.
  473. dynamic_imports = set()
  474. # Get dynamic import for this component.
  475. dynamic_import = self._get_dynamic_imports()
  476. if dynamic_import:
  477. dynamic_imports.add(dynamic_import)
  478. # Get the dynamic imports from children
  479. for child in self.children:
  480. dynamic_imports |= child.get_dynamic_imports()
  481. # Return the dynamic imports
  482. return dynamic_imports
  483. def _get_dependencies_imports(self):
  484. return {
  485. dep: {ImportVar(tag=None, render=False)} for dep in self.lib_dependencies
  486. }
  487. def _get_imports(self) -> imports.ImportDict:
  488. imports = {}
  489. if self.library is not None and self.tag is not None:
  490. imports[self.library] = {self.import_var}
  491. return {**self._get_dependencies_imports(), **imports}
  492. def get_imports(self) -> imports.ImportDict:
  493. """Get all the libraries and fields that are used by the component.
  494. Returns:
  495. The import dict with the required imports.
  496. """
  497. return imports.merge_imports(
  498. self._get_imports(), *[child.get_imports() for child in self.children]
  499. )
  500. def _get_mount_lifecycle_hook(self) -> str | None:
  501. """Generate the component lifecycle hook.
  502. Returns:
  503. The useEffect hook for managing `on_mount` and `on_unmount` events.
  504. """
  505. # pop on_mount and on_unmount from event_triggers since these are handled by
  506. # hooks, not as actually props in the component
  507. on_mount = self.event_triggers.pop(EventTriggers.ON_MOUNT, None)
  508. on_unmount = self.event_triggers.pop(EventTriggers.ON_UNMOUNT, None)
  509. if on_mount:
  510. on_mount = format.format_event_chain(on_mount)
  511. if on_unmount:
  512. on_unmount = format.format_event_chain(on_unmount)
  513. if on_mount or on_unmount:
  514. return f"""
  515. useEffect(() => {{
  516. {on_mount or ""}
  517. return () => {{
  518. {on_unmount or ""}
  519. }}
  520. }}, []);"""
  521. def _get_ref_hook(self) -> str | None:
  522. """Generate the ref hook for the component.
  523. Returns:
  524. The useRef hook for managing refs.
  525. """
  526. ref = self.get_ref()
  527. if ref is not None:
  528. return f"const {ref} = useRef(null); refs['{ref}'] = {ref};"
  529. def _get_hooks_internal(self) -> Set[str]:
  530. """Get the React hooks for this component managed by the framework.
  531. Downstream components should NOT override this method to avoid breaking
  532. framework functionality.
  533. Returns:
  534. Set of internally managed hooks.
  535. """
  536. return set(
  537. hook
  538. for hook in [self._get_mount_lifecycle_hook(), self._get_ref_hook()]
  539. if hook
  540. )
  541. def _get_hooks(self) -> Optional[str]:
  542. """Get the React hooks for this component.
  543. Downstream components should override this method to add their own hooks.
  544. Returns:
  545. The hooks for just this component.
  546. """
  547. return
  548. def get_hooks(self) -> Set[str]:
  549. """Get the React hooks for this component and its children.
  550. Returns:
  551. The code that should appear just before returning the rendered component.
  552. """
  553. # Store the code in a set to avoid duplicates.
  554. code = self._get_hooks_internal()
  555. # Add the hook code for this component.
  556. hooks = self._get_hooks()
  557. if hooks is not None:
  558. code.add(hooks)
  559. # Add the hook code for the children.
  560. for child in self.children:
  561. code |= child.get_hooks()
  562. return code
  563. def get_ref(self) -> Optional[str]:
  564. """Get the name of the ref for the component.
  565. Returns:
  566. The ref name.
  567. """
  568. # do not create a ref if the id is dynamic or unspecified
  569. if self.id is None or isinstance(self.id, BaseVar):
  570. return None
  571. return format.format_ref(self.id)
  572. def get_refs(self) -> Set[str]:
  573. """Get the refs for the children of the component.
  574. Returns:
  575. The refs for the children.
  576. """
  577. refs = set()
  578. ref = self.get_ref()
  579. if ref is not None:
  580. refs.add(ref)
  581. for child in self.children:
  582. refs |= child.get_refs()
  583. return refs
  584. def get_custom_components(
  585. self, seen: Optional[Set[str]] = None
  586. ) -> Set[CustomComponent]:
  587. """Get all the custom components used by the component.
  588. Args:
  589. seen: The tags of the components that have already been seen.
  590. Returns:
  591. The set of custom components.
  592. """
  593. custom_components = set()
  594. # Store the seen components in a set to avoid infinite recursion.
  595. if seen is None:
  596. seen = set()
  597. for child in self.children:
  598. custom_components |= child.get_custom_components(seen=seen)
  599. return custom_components
  600. @property
  601. def import_var(self):
  602. """The tag to import.
  603. Returns:
  604. An import var.
  605. """
  606. return ImportVar(tag=self.tag, is_default=self.is_default, alias=self.alias)
  607. # Map from component to styling.
  608. ComponentStyle = Dict[Union[str, Type[Component]], Any]
  609. ComponentChild = Union[types.PrimitiveType, Var, Component]
  610. class CustomComponent(Component):
  611. """A custom user-defined component."""
  612. # Use the components library.
  613. library = f"/{constants.COMPONENTS_PATH}"
  614. # The function that creates the component.
  615. component_fn: Callable[..., Component] = Component.create
  616. # The props of the component.
  617. props: Dict[str, Any] = {}
  618. def __init__(self, *args, **kwargs):
  619. """Initialize the custom component.
  620. Args:
  621. *args: The args to pass to the component.
  622. **kwargs: The kwargs to pass to the component.
  623. """
  624. super().__init__(*args, **kwargs)
  625. # Unset the style.
  626. self.style = Style()
  627. # Set the tag to the name of the function.
  628. self.tag = format.to_title_case(self.component_fn.__name__)
  629. # Set the props.
  630. props = typing.get_type_hints(self.component_fn)
  631. for key, value in kwargs.items():
  632. # Skip kwargs that are not props.
  633. if key not in props:
  634. continue
  635. # Get the type based on the annotation.
  636. type_ = props[key]
  637. # Handle event chains.
  638. if types._issubclass(type_, EventChain):
  639. value = self._create_event_chain(key, value)
  640. self.props[format.to_camel_case(key)] = value
  641. continue
  642. # Convert the type to a Var, then get the type of the var.
  643. if not types._issubclass(type_, Var):
  644. type_ = Var[type_]
  645. type_ = types.get_args(type_)[0]
  646. # Handle subclasses of Base.
  647. if types._issubclass(type_, Base):
  648. try:
  649. value = BaseVar(name=value.json(), type_=type_, is_local=True)
  650. except Exception:
  651. value = Var.create(value)
  652. else:
  653. value = Var.create(value, is_string=type(value) is str)
  654. # Set the prop.
  655. self.props[format.to_camel_case(key)] = value
  656. def __eq__(self, other: Any) -> bool:
  657. """Check if the component is equal to another.
  658. Args:
  659. other: The other component.
  660. Returns:
  661. Whether the component is equal to the other.
  662. """
  663. return isinstance(other, CustomComponent) and self.tag == other.tag
  664. def __hash__(self) -> int:
  665. """Get the hash of the component.
  666. Returns:
  667. The hash of the component.
  668. """
  669. return hash(self.tag)
  670. @classmethod
  671. def get_props(cls) -> Set[str]:
  672. """Get the props for the component.
  673. Returns:
  674. The set of component props.
  675. """
  676. return set()
  677. def get_custom_components(
  678. self, seen: Optional[Set[str]] = None
  679. ) -> Set[CustomComponent]:
  680. """Get all the custom components used by the component.
  681. Args:
  682. seen: The tags of the components that have already been seen.
  683. Returns:
  684. The set of custom components.
  685. """
  686. assert self.tag is not None, "The tag must be set."
  687. # Store the seen components in a set to avoid infinite recursion.
  688. if seen is None:
  689. seen = set()
  690. custom_components = {self} | super().get_custom_components(seen=seen)
  691. # Avoid adding the same component twice.
  692. if self.tag not in seen:
  693. seen.add(self.tag)
  694. custom_components |= self.get_component().get_custom_components(seen=seen)
  695. return custom_components
  696. def _render(self) -> Tag:
  697. """Define how to render the component in React.
  698. Returns:
  699. The tag to render.
  700. """
  701. return Tag(name=self.tag).add_props(**self.props)
  702. def get_prop_vars(self) -> List[BaseVar]:
  703. """Get the prop vars.
  704. Returns:
  705. The prop vars.
  706. """
  707. return [
  708. BaseVar(
  709. name=name,
  710. type_=prop.type_ if types._isinstance(prop, Var) else type(prop),
  711. )
  712. for name, prop in self.props.items()
  713. ]
  714. def get_component(self) -> Component:
  715. """Render the component.
  716. Returns:
  717. The code to render the component.
  718. """
  719. return self.component_fn(*self.get_prop_vars())
  720. def custom_component(
  721. component_fn: Callable[..., Component]
  722. ) -> Callable[..., CustomComponent]:
  723. """Create a custom component from a function.
  724. Args:
  725. component_fn: The function that creates the component.
  726. Returns:
  727. The decorated function.
  728. """
  729. @wraps(component_fn)
  730. def wrapper(*children, **props) -> CustomComponent:
  731. return CustomComponent(component_fn=component_fn, children=children, **props)
  732. return wrapper
  733. class NoSSRComponent(Component):
  734. """A dynamic component that is not rendered on the server."""
  735. def _get_imports(self):
  736. imports = {"next/dynamic": {ImportVar(tag="dynamic", is_default=True)}}
  737. return {
  738. **imports,
  739. self.library: {ImportVar(tag=None, render=False)},
  740. **self._get_dependencies_imports(),
  741. }
  742. def _get_dynamic_imports(self) -> str:
  743. opts_fragment = ", { ssr: false });"
  744. # extract the correct import name from library name
  745. if self.library is None:
  746. raise ValueError("Undefined library for NoSSRComponent")
  747. import_name_parts = [p for p in self.library.rpartition("@") if p != ""]
  748. import_name = (
  749. import_name_parts[0] if import_name_parts[0] != "@" else self.library
  750. )
  751. library_import = f"const {self.tag} = dynamic(() => import('{import_name}')"
  752. mod_import = (
  753. # https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
  754. f".then((mod) => mod.{self.tag})"
  755. if not self.is_default
  756. else ""
  757. )
  758. return "".join((library_import, mod_import, opts_fragment))