component.py 33 KB

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