component.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. """Base component definitions."""
  2. from __future__ import annotations
  3. import typing
  4. from abc import ABC
  5. from functools import lru_cache, wraps
  6. from typing import Any, Callable, Dict, Iterator, 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, Hooks, Imports
  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.imports import ImportVar
  21. from reflex.utils.serializers import serializer
  22. from reflex.vars import BaseVar, 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. # List here the non-react dependency needed by `library`
  34. lib_dependencies: List[str] = []
  35. # The tag to use when rendering the component.
  36. tag: Optional[str] = None
  37. # The alias for the tag.
  38. alias: Optional[str] = None
  39. # Whether the import is default or named.
  40. is_default: Optional[bool] = False
  41. # A unique key for the component.
  42. key: Any = None
  43. # The id for the component.
  44. id: Any = None
  45. # The class name for the component.
  46. class_name: Any = None
  47. # Special component props.
  48. special_props: Set[Var] = set()
  49. # Whether the component should take the focus once the page is loaded
  50. autofocus: bool = False
  51. # components that cannot be children
  52. _invalid_children: List[str] = []
  53. # only components that are allowed as children
  54. _valid_children: List[str] = []
  55. # custom attribute
  56. custom_attrs: Dict[str, str] = {}
  57. @classmethod
  58. def __init_subclass__(cls, **kwargs):
  59. """Set default properties.
  60. Args:
  61. **kwargs: The kwargs to pass to the superclass.
  62. """
  63. super().__init_subclass__(**kwargs)
  64. # Get all the props for the component.
  65. props = cls.get_props()
  66. # Convert fields to props, setting default values.
  67. for field in cls.get_fields().values():
  68. # If the field is not a component prop, skip it.
  69. if field.name not in props:
  70. continue
  71. # Set default values for any props.
  72. if types._issubclass(field.type_, Var):
  73. field.required = False
  74. field.default = Var.create(field.default)
  75. def __init__(self, *args, **kwargs):
  76. """Initialize the component.
  77. Args:
  78. *args: Args to initialize the component.
  79. **kwargs: Kwargs to initialize the component.
  80. Raises:
  81. TypeError: If an invalid prop is passed.
  82. ValueError: If a prop value is invalid.
  83. """
  84. # Set the id and children initially.
  85. children = kwargs.get("children", [])
  86. initial_kwargs = {
  87. "id": kwargs.get("id"),
  88. "children": children,
  89. **{
  90. prop: Var.create(kwargs[prop])
  91. for prop in self.get_initial_props()
  92. if prop in kwargs
  93. },
  94. }
  95. super().__init__(**initial_kwargs)
  96. self._validate_component_children(children)
  97. # Get the component fields, triggers, and props.
  98. fields = self.get_fields()
  99. triggers = self.get_event_triggers().keys()
  100. props = self.get_props()
  101. # Add any events triggers.
  102. if "event_triggers" not in kwargs:
  103. kwargs["event_triggers"] = {}
  104. kwargs["event_triggers"] = kwargs["event_triggers"].copy()
  105. # Iterate through the kwargs and set the props.
  106. for key, value in kwargs.items():
  107. if key in triggers:
  108. # Event triggers are bound to event chains.
  109. field_type = EventChain
  110. elif key in props:
  111. # Set the field type.
  112. field_type = fields[key].type_
  113. else:
  114. continue
  115. # Check whether the key is a component prop.
  116. if types._issubclass(field_type, Var):
  117. try:
  118. # Try to create a var from the value.
  119. kwargs[key] = Var.create(value)
  120. # Check that the var type is not None.
  121. if kwargs[key] is None:
  122. raise TypeError
  123. expected_type = fields[key].outer_type_.__args__[0]
  124. if (
  125. types.is_literal(expected_type)
  126. and value not in expected_type.__args__
  127. ):
  128. allowed_values = expected_type.__args__
  129. if value not in allowed_values:
  130. raise ValueError(
  131. f"prop value for {key} of the `{type(self).__name__}` component should be one of the following: {','.join(allowed_values)}. Got '{value}' instead"
  132. )
  133. # Get the passed type and the var type.
  134. passed_type = kwargs[key]._var_type
  135. expected_type = (
  136. type(expected_type.__args__[0])
  137. if types.is_literal(expected_type)
  138. else expected_type
  139. )
  140. except TypeError:
  141. # If it is not a valid var, check the base types.
  142. passed_type = type(value)
  143. expected_type = fields[key].outer_type_
  144. if not types._issubclass(passed_type, expected_type):
  145. raise TypeError(
  146. f"Invalid var passed for prop {key}, expected type {expected_type}, got value {value} of type {passed_type}."
  147. )
  148. # Check if the key is an event trigger.
  149. if key in triggers:
  150. # Temporarily disable full control for event triggers.
  151. kwargs["event_triggers"][key] = self._create_event_chain(key, value)
  152. # Remove any keys that were added as events.
  153. for key in kwargs["event_triggers"]:
  154. del kwargs[key]
  155. # Add style props to the component.
  156. style = kwargs.get("style", {})
  157. if isinstance(style, List):
  158. # Merge styles, the later ones overriding keys in the earlier ones.
  159. style = {k: v for style_dict in style for k, v in style_dict.items()}
  160. kwargs["style"] = Style(
  161. {
  162. **style,
  163. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  164. }
  165. )
  166. if "custom_attrs" not in kwargs:
  167. kwargs["custom_attrs"] = {}
  168. # Convert class_name to str if it's list
  169. class_name = kwargs.get("class_name", "")
  170. if isinstance(class_name, (List, tuple)):
  171. kwargs["class_name"] = " ".join(class_name)
  172. # Construct the component.
  173. super().__init__(*args, **kwargs)
  174. def _create_event_chain(
  175. self,
  176. event_trigger: str,
  177. value: Union[
  178. Var, EventHandler, EventSpec, List[Union[EventHandler, EventSpec]], Callable
  179. ],
  180. ) -> Union[EventChain, Var]:
  181. """Create an event chain from a variety of input types.
  182. Args:
  183. event_trigger: The event trigger to bind the chain to.
  184. value: The value to create the event chain from.
  185. Returns:
  186. The event chain.
  187. Raises:
  188. ValueError: If the value is not a valid event chain.
  189. """
  190. # Check if the trigger is a controlled event.
  191. triggers = self.get_event_triggers()
  192. # If it's an event chain var, return it.
  193. if isinstance(value, Var):
  194. if value._var_type is not EventChain:
  195. raise ValueError(f"Invalid event chain: {value}")
  196. return value
  197. elif isinstance(value, EventChain):
  198. # Trust that the caller knows what they're doing passing an EventChain directly
  199. return value
  200. arg_spec = triggers.get(event_trigger, lambda: [])
  201. wrapped = False
  202. # If the input is a single event handler, wrap it in a list.
  203. if isinstance(value, (EventHandler, EventSpec)):
  204. wrapped = True
  205. value = [value]
  206. # If the input is a list of event handlers, create an event chain.
  207. if isinstance(value, List):
  208. if not wrapped:
  209. console.deprecate(
  210. feature_name="EventChain",
  211. reason="to avoid confusion, only use yield API",
  212. deprecation_version="0.2.8",
  213. removal_version="0.4.0",
  214. )
  215. events: list[EventSpec] = []
  216. for v in value:
  217. if isinstance(v, EventHandler):
  218. # Call the event handler to get the event.
  219. try:
  220. event = call_event_handler(v, arg_spec) # type: ignore
  221. except ValueError as err:
  222. raise ValueError(
  223. f" {err} defined in the `{type(self).__name__}` component"
  224. ) from err
  225. # Add the event to the chain.
  226. events.append(event)
  227. elif isinstance(v, EventSpec):
  228. # Add the event to the chain.
  229. events.append(v)
  230. elif isinstance(v, Callable):
  231. # Call the lambda to get the event chain.
  232. events.extend(call_event_fn(v, arg_spec)) # type: ignore
  233. else:
  234. raise ValueError(f"Invalid event: {v}")
  235. # If the input is a callable, create an event chain.
  236. elif isinstance(value, Callable):
  237. events = call_event_fn(value, arg_spec) # type: ignore
  238. # Otherwise, raise an error.
  239. else:
  240. raise ValueError(f"Invalid event chain: {value}")
  241. # Add args to the event specs if necessary.
  242. events = [e.with_args(get_handler_args(e)) for e in events]
  243. # Collect event_actions from each spec
  244. event_actions = {}
  245. for e in events:
  246. event_actions.update(e.event_actions)
  247. # Return the event chain.
  248. if isinstance(arg_spec, Var):
  249. return EventChain(
  250. events=events,
  251. args_spec=None,
  252. event_actions=event_actions,
  253. )
  254. else:
  255. return EventChain(
  256. events=events,
  257. args_spec=arg_spec, # type: ignore
  258. event_actions=event_actions,
  259. )
  260. def get_event_triggers(self) -> Dict[str, Any]:
  261. """Get the event triggers for the component.
  262. Returns:
  263. The event triggers.
  264. """
  265. return {
  266. EventTriggers.ON_FOCUS: lambda: [],
  267. EventTriggers.ON_BLUR: lambda: [],
  268. EventTriggers.ON_CLICK: lambda: [],
  269. EventTriggers.ON_CONTEXT_MENU: lambda: [],
  270. EventTriggers.ON_DOUBLE_CLICK: lambda: [],
  271. EventTriggers.ON_MOUSE_DOWN: lambda: [],
  272. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  273. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  274. EventTriggers.ON_MOUSE_MOVE: lambda: [],
  275. EventTriggers.ON_MOUSE_OUT: lambda: [],
  276. EventTriggers.ON_MOUSE_OVER: lambda: [],
  277. EventTriggers.ON_MOUSE_UP: lambda: [],
  278. EventTriggers.ON_SCROLL: lambda: [],
  279. EventTriggers.ON_MOUNT: lambda: [],
  280. EventTriggers.ON_UNMOUNT: lambda: [],
  281. }
  282. def __repr__(self) -> str:
  283. """Represent the component in React.
  284. Returns:
  285. The code to render the component.
  286. """
  287. return format.json_dumps(self.render())
  288. def __str__(self) -> str:
  289. """Represent the component in React.
  290. Returns:
  291. The code to render the component.
  292. """
  293. from reflex.compiler.compiler import _compile_component
  294. return _compile_component(self)
  295. def _render(self, props: dict[str, Any] | None = None) -> Tag:
  296. """Define how to render the component in React.
  297. Args:
  298. props: The props to render (if None, then use get_props).
  299. Returns:
  300. The tag to render.
  301. """
  302. # Create the base tag.
  303. tag = Tag(
  304. name=self.tag if not self.alias else self.alias,
  305. special_props=self.special_props,
  306. )
  307. if props is None:
  308. # Add component props to the tag.
  309. props = {
  310. attr[:-1] if attr.endswith("_") else attr: getattr(self, attr)
  311. for attr in self.get_props()
  312. }
  313. # Add ref to element if `id` is not None.
  314. ref = self.get_ref()
  315. if ref is not None:
  316. props["ref"] = Var.create(ref, _var_is_local=False)
  317. else:
  318. props = props.copy()
  319. props.update(
  320. **{
  321. trigger: handler
  322. for trigger, handler in self.event_triggers.items()
  323. if trigger not in {EventTriggers.ON_MOUNT, EventTriggers.ON_UNMOUNT}
  324. },
  325. key=self.key,
  326. id=self.id,
  327. class_name=self.class_name,
  328. )
  329. props.update(self._get_style())
  330. props.update(self.custom_attrs)
  331. return tag.add_props(**props)
  332. @classmethod
  333. @lru_cache(maxsize=None)
  334. def get_props(cls) -> Set[str]:
  335. """Get the unique fields for the component.
  336. Returns:
  337. The unique fields.
  338. """
  339. return set(cls.get_fields()) - set(Component.get_fields())
  340. @classmethod
  341. @lru_cache(maxsize=None)
  342. def get_initial_props(cls) -> Set[str]:
  343. """Get the initial props to set for the component.
  344. Returns:
  345. The initial props to set.
  346. """
  347. return set()
  348. @classmethod
  349. @lru_cache(maxsize=None)
  350. def get_component_props(cls) -> set[str]:
  351. """Get the props that expected a component as value.
  352. Returns:
  353. The components props.
  354. """
  355. return {
  356. name
  357. for name, field in cls.get_fields().items()
  358. if name in cls.get_props()
  359. and types._issubclass(field.outer_type_, Component)
  360. }
  361. @classmethod
  362. def create(cls, *children, **props) -> Component:
  363. """Create the component.
  364. Args:
  365. *children: The children of the component.
  366. **props: The props of the component.
  367. Returns:
  368. The component.
  369. Raises:
  370. TypeError: If an invalid child is passed.
  371. """
  372. # Import here to avoid circular imports.
  373. from reflex.components.base.bare import Bare
  374. # Validate all the children.
  375. for child in children:
  376. # Make sure the child is a valid type.
  377. if not types._isinstance(child, ComponentChild):
  378. raise TypeError(
  379. "Children of Reflex components must be other components, "
  380. "state vars, or primitive Python types. "
  381. f"Got child {child} of type {type(child)}.",
  382. )
  383. children = [
  384. child
  385. if isinstance(child, Component)
  386. else Bare.create(contents=Var.create(child, _var_is_string=True))
  387. for child in children
  388. ]
  389. return cls(children=children, **props)
  390. def _add_style(self, style: dict):
  391. """Add additional style to the component.
  392. Args:
  393. style: A style dict to apply.
  394. """
  395. self.style.update(style)
  396. def add_style(self, style: ComponentStyle) -> Component:
  397. """Add additional style to the component and its children.
  398. Args:
  399. style: A dict from component to styling.
  400. Returns:
  401. The component with the additional style.
  402. """
  403. if type(self) in style:
  404. # Extract the style for this component.
  405. component_style = style[type(self)]
  406. # Only add style props that are not overridden.
  407. component_style = {
  408. k: v for k, v in component_style.items() if k not in self.style
  409. }
  410. # Add the style to the component.
  411. self._add_style(component_style)
  412. # Recursively add style to the children.
  413. for child in self.children:
  414. child.add_style(style)
  415. return self
  416. def _get_style(self) -> dict:
  417. """Get the style for the component.
  418. Returns:
  419. The dictionary of the component style as value and the style notation as key.
  420. """
  421. return {"sx": self.style}
  422. def render(self) -> Dict:
  423. """Render the component.
  424. Returns:
  425. The dictionary for template of component.
  426. """
  427. tag = self._render()
  428. rendered_dict = dict(
  429. tag.set(
  430. children=[child.render() for child in self.children],
  431. contents=str(tag.contents),
  432. props=tag.format_props(),
  433. ),
  434. autofocus=self.autofocus,
  435. )
  436. return rendered_dict
  437. def _validate_component_children(self, children: List[Component]):
  438. """Validate the children components.
  439. Args:
  440. children: The children of the component.
  441. """
  442. if not self._invalid_children and not self._valid_children:
  443. return
  444. comp_name = type(self).__name__
  445. def validate_invalid_child(child_name):
  446. if child_name in self._invalid_children:
  447. raise ValueError(
  448. f"The component `{comp_name}` cannot have `{child_name}` as a child component"
  449. )
  450. def validate_valid_child(child_name):
  451. if child_name not in self._valid_children:
  452. valid_child_list = ", ".join(
  453. [f"`{v_child}`" for v_child in self._valid_children]
  454. )
  455. raise ValueError(
  456. f"The component `{comp_name}` only allows the components: {valid_child_list} as children. Got `{child_name}` instead."
  457. )
  458. for child in children:
  459. name = type(child).__name__
  460. if self._invalid_children:
  461. validate_invalid_child(name)
  462. if self._valid_children:
  463. validate_valid_child(name)
  464. @staticmethod
  465. def _get_vars_from_event_triggers(
  466. event_triggers: dict[str, EventChain | Var],
  467. ) -> Iterator[tuple[str, list[Var]]]:
  468. """Get the Vars associated with each event trigger.
  469. Args:
  470. event_triggers: The event triggers from the component instance.
  471. Yields:
  472. tuple of (event_name, event_vars)
  473. """
  474. for event_trigger, event in event_triggers.items():
  475. if isinstance(event, Var):
  476. yield event_trigger, [event]
  477. elif isinstance(event, EventChain):
  478. event_args = []
  479. for spec in event.events:
  480. for args in spec.args:
  481. event_args.extend(args)
  482. yield event_trigger, event_args
  483. def _get_vars(self) -> list[Var]:
  484. """Walk all Vars used in this component.
  485. Returns:
  486. Each var referenced by the component (props, styles, event handlers).
  487. """
  488. vars = getattr(self, "__vars", None)
  489. if vars is not None:
  490. return vars
  491. vars = self.__vars = []
  492. # Get Vars associated with event trigger arguments.
  493. for _, event_vars in self._get_vars_from_event_triggers(self.event_triggers):
  494. vars.extend(event_vars)
  495. # Get Vars associated with component props.
  496. for prop in self.get_props():
  497. prop_var = getattr(self, prop)
  498. if isinstance(prop_var, Var):
  499. vars.append(prop_var)
  500. # Style keeps track of its own VarData instance, so embed in a temp Var that is yielded.
  501. if self.style:
  502. vars.append(
  503. BaseVar(
  504. _var_name="style",
  505. _var_type=str,
  506. _var_data=self.style._var_data,
  507. )
  508. )
  509. # Special props are always Var instances.
  510. vars.extend(self.special_props)
  511. # Get Vars associated with common Component props.
  512. for comp_prop in (
  513. self.class_name,
  514. self.id,
  515. self.key,
  516. self.autofocus,
  517. *self.custom_attrs.values(),
  518. ):
  519. if isinstance(comp_prop, Var):
  520. vars.append(comp_prop)
  521. elif isinstance(comp_prop, str):
  522. # Collapse VarData encoded in f-strings.
  523. var = Var.create_safe(comp_prop)
  524. if var._var_data is not None:
  525. vars.append(var)
  526. return vars
  527. def _get_custom_code(self) -> str | None:
  528. """Get custom code for the component.
  529. Returns:
  530. The custom code.
  531. """
  532. return None
  533. def get_custom_code(self) -> Set[str]:
  534. """Get custom code for the component and its children.
  535. Returns:
  536. The custom code.
  537. """
  538. # Store the code in a set to avoid duplicates.
  539. code = set()
  540. # Add the custom code for this component.
  541. custom_code = self._get_custom_code()
  542. if custom_code is not None:
  543. code.add(custom_code)
  544. # Add the custom code for the children.
  545. for child in self.children:
  546. code |= child.get_custom_code()
  547. # Return the code.
  548. return code
  549. def _get_dynamic_imports(self) -> str | None:
  550. """Get dynamic import for the component.
  551. Returns:
  552. The dynamic import.
  553. """
  554. return None
  555. def get_dynamic_imports(self) -> Set[str]:
  556. """Get dynamic imports for the component and its children.
  557. Returns:
  558. The dynamic imports.
  559. """
  560. # Store the import in a set to avoid duplicates.
  561. dynamic_imports = set()
  562. # Get dynamic import for this component.
  563. dynamic_import = self._get_dynamic_imports()
  564. if dynamic_import:
  565. dynamic_imports.add(dynamic_import)
  566. # Get the dynamic imports from children
  567. for child in self.children:
  568. dynamic_imports |= child.get_dynamic_imports()
  569. # Return the dynamic imports
  570. return dynamic_imports
  571. def _get_props_imports(self) -> List[str]:
  572. """Get the imports needed for components props.
  573. Returns:
  574. The imports for the components props of the component.
  575. """
  576. return [
  577. getattr(self, prop).get_imports()
  578. for prop in self.get_component_props()
  579. if getattr(self, prop) is not None
  580. ]
  581. def _get_dependencies_imports(self) -> imports.ImportDict:
  582. """Get the imports from lib_dependencies for installing.
  583. Returns:
  584. The dependencies imports of the component.
  585. """
  586. return {
  587. dep: [ImportVar(tag=None, render=False)] for dep in self.lib_dependencies
  588. }
  589. def _get_hooks_imports(self) -> imports.ImportDict:
  590. """Get the imports required by certain hooks.
  591. Returns:
  592. The imports required for all selected hooks.
  593. """
  594. _imports = {}
  595. if self._get_ref_hook():
  596. # Handle hooks needed for attaching react refs to DOM nodes.
  597. _imports.setdefault("react", set()).add(ImportVar(tag="useRef"))
  598. _imports.setdefault(f"/{Dirs.STATE_PATH}", set()).add(ImportVar(tag="refs"))
  599. if self._get_mount_lifecycle_hook():
  600. # Handle hooks for `on_mount` / `on_unmount`.
  601. _imports.setdefault("react", set()).add(ImportVar(tag="useEffect"))
  602. if self._get_special_hooks():
  603. # Handle additional internal hooks (autofocus, etc).
  604. _imports.setdefault("react", set()).update(
  605. {
  606. ImportVar(tag="useRef"),
  607. ImportVar(tag="useEffect"),
  608. },
  609. )
  610. return _imports
  611. def _get_imports(self) -> imports.ImportDict:
  612. """Get all the libraries and fields that are used by the component.
  613. Returns:
  614. The imports needed by the component.
  615. """
  616. _imports = {}
  617. # Import this component's tag from the main library.
  618. if self.library is not None and self.tag is not None:
  619. _imports[self.library] = {self.import_var}
  620. # Get static imports required for event processing.
  621. event_imports = Imports.EVENTS if self.event_triggers else {}
  622. # Collect imports from Vars used directly by this component.
  623. var_imports = [
  624. var._var_data.imports for var in self._get_vars() if var._var_data
  625. ]
  626. return imports.merge_imports(
  627. *self._get_props_imports(),
  628. self._get_dependencies_imports(),
  629. self._get_hooks_imports(),
  630. _imports,
  631. event_imports,
  632. *var_imports,
  633. )
  634. def get_imports(self) -> imports.ImportDict:
  635. """Get all the libraries and fields that are used by the component and its children.
  636. Returns:
  637. The import dict with the required imports.
  638. """
  639. return imports.merge_imports(
  640. self._get_imports(), *[child.get_imports() for child in self.children]
  641. )
  642. def _get_mount_lifecycle_hook(self) -> str | None:
  643. """Generate the component lifecycle hook.
  644. Returns:
  645. The useEffect hook for managing `on_mount` and `on_unmount` events.
  646. """
  647. # pop on_mount and on_unmount from event_triggers since these are handled by
  648. # hooks, not as actually props in the component
  649. on_mount = self.event_triggers.get(EventTriggers.ON_MOUNT, None)
  650. on_unmount = self.event_triggers.get(EventTriggers.ON_UNMOUNT, None)
  651. if on_mount is not None:
  652. on_mount = format.format_event_chain(on_mount)
  653. if on_unmount is not None:
  654. on_unmount = format.format_event_chain(on_unmount)
  655. if on_mount is not None or on_unmount is not None:
  656. return f"""
  657. useEffect(() => {{
  658. {on_mount or ""}
  659. return () => {{
  660. {on_unmount or ""}
  661. }}
  662. }}, []);"""
  663. def _get_ref_hook(self) -> str | None:
  664. """Generate the ref hook for the component.
  665. Returns:
  666. The useRef hook for managing refs.
  667. """
  668. ref = self.get_ref()
  669. if ref is not None:
  670. return f"const {ref} = useRef(null); refs['{ref}'] = {ref};"
  671. def _get_vars_hooks(self) -> set[str]:
  672. """Get the hooks required by vars referenced in this component.
  673. Returns:
  674. The hooks for the vars.
  675. """
  676. vars_hooks = set()
  677. for var in self._get_vars():
  678. if var._var_data:
  679. vars_hooks.update(var._var_data.hooks)
  680. return vars_hooks
  681. def _get_events_hooks(self) -> set[str]:
  682. """Get the hooks required by events referenced in this component.
  683. Returns:
  684. The hooks for the events.
  685. """
  686. if self.event_triggers:
  687. return {Hooks.EVENTS}
  688. return set()
  689. def _get_special_hooks(self) -> set[str]:
  690. """Get the hooks required by special actions referenced in this component.
  691. Returns:
  692. The hooks for special actions.
  693. """
  694. if self.autofocus:
  695. return {
  696. """
  697. // Set focus to the specified element.
  698. const focusRef = useRef(null)
  699. useEffect(() => {
  700. if (focusRef.current) {
  701. focusRef.current.focus();
  702. }
  703. })""",
  704. }
  705. return set()
  706. def _get_hooks_internal(self) -> Set[str]:
  707. """Get the React hooks for this component managed by the framework.
  708. Downstream components should NOT override this method to avoid breaking
  709. framework functionality.
  710. Returns:
  711. Set of internally managed hooks.
  712. """
  713. return (
  714. set(
  715. hook
  716. for hook in [self._get_mount_lifecycle_hook(), self._get_ref_hook()]
  717. if hook
  718. )
  719. | self._get_vars_hooks()
  720. | self._get_events_hooks()
  721. | self._get_special_hooks()
  722. )
  723. def _get_hooks(self) -> str | None:
  724. """Get the React hooks for this component.
  725. Downstream components should override this method to add their own hooks.
  726. Returns:
  727. The hooks for just this component.
  728. """
  729. return
  730. def get_hooks(self) -> Set[str]:
  731. """Get the React hooks for this component and its children.
  732. Returns:
  733. The code that should appear just before returning the rendered component.
  734. """
  735. # Store the code in a set to avoid duplicates.
  736. code = self._get_hooks_internal()
  737. # Add the hook code for this component.
  738. hooks = self._get_hooks()
  739. if hooks is not None:
  740. code.add(hooks)
  741. # Add the hook code for the children.
  742. for child in self.children:
  743. code |= child.get_hooks()
  744. return code
  745. def get_ref(self) -> str | None:
  746. """Get the name of the ref for the component.
  747. Returns:
  748. The ref name.
  749. """
  750. # do not create a ref if the id is dynamic or unspecified
  751. if self.id is None or isinstance(self.id, BaseVar):
  752. return None
  753. return format.format_ref(self.id)
  754. def get_refs(self) -> Set[str]:
  755. """Get the refs for the children of the component.
  756. Returns:
  757. The refs for the children.
  758. """
  759. refs = set()
  760. ref = self.get_ref()
  761. if ref is not None:
  762. refs.add(ref)
  763. for child in self.children:
  764. refs |= child.get_refs()
  765. return refs
  766. def get_custom_components(
  767. self, seen: set[str] | None = None
  768. ) -> Set[CustomComponent]:
  769. """Get all the custom components used by the component.
  770. Args:
  771. seen: The tags of the components that have already been seen.
  772. Returns:
  773. The set of custom components.
  774. """
  775. custom_components = set()
  776. # Store the seen components in a set to avoid infinite recursion.
  777. if seen is None:
  778. seen = set()
  779. for child in self.children:
  780. custom_components |= child.get_custom_components(seen=seen)
  781. return custom_components
  782. @property
  783. def import_var(self):
  784. """The tag to import.
  785. Returns:
  786. An import var.
  787. """
  788. # If the tag is dot-qualified, only import the left-most name.
  789. tag = self.tag.partition(".")[0] if self.tag else None
  790. alias = self.alias.partition(".")[0] if self.alias else None
  791. return ImportVar(tag=tag, is_default=self.is_default, alias=alias)
  792. @staticmethod
  793. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  794. """Get the app wrap components for the component.
  795. Returns:
  796. The app wrap components.
  797. """
  798. return {}
  799. def get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  800. """Get the app wrap components for the component and its children.
  801. Returns:
  802. The app wrap components.
  803. """
  804. # Store the components in a set to avoid duplicates.
  805. components = self._get_app_wrap_components()
  806. for component in tuple(components.values()):
  807. components.update(component.get_app_wrap_components())
  808. # Add the app wrap components for the children.
  809. for child in self.children:
  810. components.update(child.get_app_wrap_components())
  811. # Return the components.
  812. return components
  813. # Map from component to styling.
  814. ComponentStyle = Dict[Union[str, Type[Component]], Any]
  815. ComponentChild = Union[types.PrimitiveType, Var, Component]
  816. class CustomComponent(Component):
  817. """A custom user-defined component."""
  818. # Use the components library.
  819. library = f"/{Dirs.COMPONENTS_PATH}"
  820. # The function that creates the component.
  821. component_fn: Callable[..., Component] = Component.create
  822. # The props of the component.
  823. props: Dict[str, Any] = {}
  824. def __init__(self, *args, **kwargs):
  825. """Initialize the custom component.
  826. Args:
  827. *args: The args to pass to the component.
  828. **kwargs: The kwargs to pass to the component.
  829. """
  830. super().__init__(*args, **kwargs)
  831. # Unset the style.
  832. self.style = Style()
  833. # Set the tag to the name of the function.
  834. self.tag = format.to_title_case(self.component_fn.__name__)
  835. # Set the props.
  836. props = typing.get_type_hints(self.component_fn)
  837. for key, value in kwargs.items():
  838. # Skip kwargs that are not props.
  839. if key not in props:
  840. continue
  841. # Get the type based on the annotation.
  842. type_ = props[key]
  843. # Handle event chains.
  844. if types._issubclass(type_, EventChain):
  845. value = self._create_event_chain(key, value)
  846. self.props[format.to_camel_case(key)] = value
  847. continue
  848. # Convert the type to a Var, then get the type of the var.
  849. if not types._issubclass(type_, Var):
  850. type_ = Var[type_]
  851. type_ = types.get_args(type_)[0]
  852. # Handle subclasses of Base.
  853. if types._issubclass(type_, Base):
  854. try:
  855. value = BaseVar(
  856. _var_name=value.json(), _var_type=type_, _var_is_local=True
  857. )
  858. except Exception:
  859. value = Var.create(value)
  860. else:
  861. value = Var.create(value, _var_is_string=type(value) is str)
  862. # Set the prop.
  863. self.props[format.to_camel_case(key)] = value
  864. def __eq__(self, other: Any) -> bool:
  865. """Check if the component is equal to another.
  866. Args:
  867. other: The other component.
  868. Returns:
  869. Whether the component is equal to the other.
  870. """
  871. return isinstance(other, CustomComponent) and self.tag == other.tag
  872. def __hash__(self) -> int:
  873. """Get the hash of the component.
  874. Returns:
  875. The hash of the component.
  876. """
  877. return hash(self.tag)
  878. @classmethod
  879. def get_props(cls) -> Set[str]:
  880. """Get the props for the component.
  881. Returns:
  882. The set of component props.
  883. """
  884. return set()
  885. def get_custom_components(
  886. self, seen: set[str] | None = None
  887. ) -> Set[CustomComponent]:
  888. """Get all the custom components used by the component.
  889. Args:
  890. seen: The tags of the components that have already been seen.
  891. Returns:
  892. The set of custom components.
  893. """
  894. assert self.tag is not None, "The tag must be set."
  895. # Store the seen components in a set to avoid infinite recursion.
  896. if seen is None:
  897. seen = set()
  898. custom_components = {self} | super().get_custom_components(seen=seen)
  899. # Avoid adding the same component twice.
  900. if self.tag not in seen:
  901. seen.add(self.tag)
  902. custom_components |= self.get_component(self).get_custom_components(
  903. seen=seen
  904. )
  905. return custom_components
  906. def _render(self) -> Tag:
  907. """Define how to render the component in React.
  908. Returns:
  909. The tag to render.
  910. """
  911. return super()._render(props=self.props)
  912. def get_prop_vars(self) -> List[BaseVar]:
  913. """Get the prop vars.
  914. Returns:
  915. The prop vars.
  916. """
  917. return [
  918. BaseVar(
  919. _var_name=name,
  920. _var_type=prop._var_type
  921. if types._isinstance(prop, Var)
  922. else type(prop),
  923. )
  924. for name, prop in self.props.items()
  925. ]
  926. @lru_cache(maxsize=None) # noqa
  927. def get_component(self) -> Component:
  928. """Render the component.
  929. Returns:
  930. The code to render the component.
  931. """
  932. return self.component_fn(*self.get_prop_vars())
  933. def custom_component(
  934. component_fn: Callable[..., Component]
  935. ) -> Callable[..., CustomComponent]:
  936. """Create a custom component from a function.
  937. Args:
  938. component_fn: The function that creates the component.
  939. Returns:
  940. The decorated function.
  941. """
  942. @wraps(component_fn)
  943. def wrapper(*children, **props) -> CustomComponent:
  944. # Remove the children from the props.
  945. props.pop("children", None)
  946. return CustomComponent(component_fn=component_fn, children=children, **props)
  947. return wrapper
  948. # Alias memo to custom_component.
  949. memo = custom_component
  950. class NoSSRComponent(Component):
  951. """A dynamic component that is not rendered on the server."""
  952. def _get_imports(self) -> imports.ImportDict:
  953. """Get the imports for the component.
  954. Returns:
  955. The imports for dynamically importing the component at module load time.
  956. """
  957. # Next.js dynamic import mechanism.
  958. dynamic_import = {"next/dynamic": [ImportVar(tag="dynamic", is_default=True)]}
  959. # The normal imports for this component.
  960. _imports = super()._get_imports()
  961. # Do NOT import the main library/tag statically.
  962. if self.library is not None:
  963. _imports[self.library] = [imports.ImportVar(tag=None, render=False)]
  964. return imports.merge_imports(
  965. dynamic_import,
  966. _imports,
  967. self._get_dependencies_imports(),
  968. )
  969. def _get_dynamic_imports(self) -> str:
  970. opts_fragment = ", { ssr: false });"
  971. # extract the correct import name from library name
  972. if self.library is None:
  973. raise ValueError("Undefined library for NoSSRComponent")
  974. import_name_parts = [p for p in self.library.rpartition("@") if p != ""]
  975. import_name = (
  976. import_name_parts[0] if import_name_parts[0] != "@" else self.library
  977. )
  978. library_import = f"const {self.alias if self.alias else self.tag} = dynamic(() => import('{import_name}')"
  979. mod_import = (
  980. # https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
  981. f".then((mod) => mod.{self.tag})"
  982. if not self.is_default
  983. else ""
  984. )
  985. return "".join((library_import, mod_import, opts_fragment))
  986. @serializer
  987. def serialize_component(comp: Component):
  988. """Serialize a component.
  989. Args:
  990. comp: The component to serialize.
  991. Returns:
  992. The serialized component.
  993. """
  994. return str(comp)