component.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  1. """Base component definitions."""
  2. from __future__ import annotations
  3. import copy
  4. import typing
  5. from abc import ABC, abstractmethod
  6. from functools import lru_cache, wraps
  7. from hashlib import md5
  8. from typing import (
  9. Any,
  10. Callable,
  11. ClassVar,
  12. Dict,
  13. Iterator,
  14. List,
  15. Optional,
  16. Set,
  17. Type,
  18. Union,
  19. )
  20. from reflex.base import Base
  21. from reflex.compiler.templates import STATEFUL_COMPONENT
  22. from reflex.components.tags import Tag
  23. from reflex.constants import (
  24. Dirs,
  25. EventTriggers,
  26. Hooks,
  27. Imports,
  28. MemoizationDisposition,
  29. MemoizationMode,
  30. PageNames,
  31. )
  32. from reflex.event import (
  33. EventChain,
  34. EventHandler,
  35. EventSpec,
  36. call_event_fn,
  37. call_event_handler,
  38. get_handler_args,
  39. )
  40. from reflex.style import Style, format_as_emotion
  41. from reflex.utils import console, format, imports, types
  42. from reflex.utils.imports import ImportVar
  43. from reflex.utils.serializers import serializer
  44. from reflex.vars import BaseVar, Var, VarData
  45. class BaseComponent(Base, ABC):
  46. """The base class for all Reflex components.
  47. This is something that can be rendered as a Component via the Reflex compiler.
  48. """
  49. # The children nested within the component.
  50. children: List[BaseComponent] = []
  51. # The library that the component is based on.
  52. library: Optional[str] = None
  53. # List here the non-react dependency needed by `library`
  54. lib_dependencies: List[str] = []
  55. # The tag to use when rendering the component.
  56. tag: Optional[str] = None
  57. @abstractmethod
  58. def render(self) -> dict:
  59. """Render the component.
  60. Returns:
  61. The dictionary for template of the component.
  62. """
  63. @abstractmethod
  64. def get_hooks(self) -> set[str]:
  65. """Get the React hooks for this component.
  66. Returns:
  67. The code that should appear just before returning the rendered component.
  68. """
  69. @abstractmethod
  70. def get_imports(self) -> imports.ImportDict:
  71. """Get all the libraries and fields that are used by the component.
  72. Returns:
  73. The import dict with the required imports.
  74. """
  75. @abstractmethod
  76. def get_dynamic_imports(self) -> set[str]:
  77. """Get dynamic imports for the component.
  78. Returns:
  79. The dynamic imports.
  80. """
  81. @abstractmethod
  82. def get_custom_code(self) -> set[str]:
  83. """Get custom code for the component.
  84. Returns:
  85. The custom code.
  86. """
  87. @abstractmethod
  88. def get_refs(self) -> set[str]:
  89. """Get the refs for the children of the component.
  90. Returns:
  91. The refs for the children.
  92. """
  93. # Map from component to styling.
  94. ComponentStyle = Dict[Union[str, Type[BaseComponent]], Any]
  95. ComponentChild = Union[types.PrimitiveType, Var, BaseComponent]
  96. class Component(BaseComponent, ABC):
  97. """A component with style, event trigger and other props."""
  98. # The style of the component.
  99. style: Style = Style()
  100. # A mapping from event triggers to event chains.
  101. event_triggers: Dict[str, Union[EventChain, Var]] = {}
  102. # The alias for the tag.
  103. alias: Optional[str] = None
  104. # Whether the import is default or named.
  105. is_default: Optional[bool] = False
  106. # A unique key for the component.
  107. key: Any = None
  108. # The id for the component.
  109. id: Any = None
  110. # The class name for the component.
  111. class_name: Any = None
  112. # Special component props.
  113. special_props: Set[Var] = set()
  114. # Whether the component should take the focus once the page is loaded
  115. autofocus: bool = False
  116. # components that cannot be children
  117. _invalid_children: List[str] = []
  118. # only components that are allowed as children
  119. _valid_children: List[str] = []
  120. # only components that are allowed as parent
  121. _valid_parents: List[str] = []
  122. # custom attribute
  123. custom_attrs: Dict[str, Union[Var, str]] = {}
  124. # When to memoize this component and its children.
  125. _memoization_mode: MemoizationMode = MemoizationMode()
  126. @classmethod
  127. def __init_subclass__(cls, **kwargs):
  128. """Set default properties.
  129. Args:
  130. **kwargs: The kwargs to pass to the superclass.
  131. """
  132. super().__init_subclass__(**kwargs)
  133. # Get all the props for the component.
  134. props = cls.get_props()
  135. # Convert fields to props, setting default values.
  136. for field in cls.get_fields().values():
  137. # If the field is not a component prop, skip it.
  138. if field.name not in props:
  139. continue
  140. # Set default values for any props.
  141. if types._issubclass(field.type_, Var):
  142. field.required = False
  143. field.default = Var.create(field.default)
  144. def __init__(self, *args, **kwargs):
  145. """Initialize the component.
  146. Args:
  147. *args: Args to initialize the component.
  148. **kwargs: Kwargs to initialize the component.
  149. Raises:
  150. TypeError: If an invalid prop is passed.
  151. ValueError: If a prop value is invalid.
  152. """
  153. # Set the id and children initially.
  154. children = kwargs.get("children", [])
  155. initial_kwargs = {
  156. "id": kwargs.get("id"),
  157. "children": children,
  158. **{
  159. prop: Var.create(kwargs[prop])
  160. for prop in self.get_initial_props()
  161. if prop in kwargs
  162. },
  163. }
  164. super().__init__(**initial_kwargs)
  165. self._validate_component_children(children)
  166. # Get the component fields, triggers, and props.
  167. fields = self.get_fields()
  168. triggers = self.get_event_triggers().keys()
  169. props = self.get_props()
  170. # Add any events triggers.
  171. if "event_triggers" not in kwargs:
  172. kwargs["event_triggers"] = {}
  173. kwargs["event_triggers"] = kwargs["event_triggers"].copy()
  174. # Iterate through the kwargs and set the props.
  175. for key, value in kwargs.items():
  176. if key in triggers:
  177. # Event triggers are bound to event chains.
  178. field_type = EventChain
  179. elif key in props:
  180. # Set the field type.
  181. field_type = fields[key].type_
  182. else:
  183. continue
  184. # Check whether the key is a component prop.
  185. if types._issubclass(field_type, Var):
  186. try:
  187. # Try to create a var from the value.
  188. kwargs[key] = Var.create(value)
  189. # Check that the var type is not None.
  190. if kwargs[key] is None:
  191. raise TypeError
  192. expected_type = fields[key].outer_type_.__args__[0]
  193. if (
  194. types.is_literal(expected_type)
  195. and value not in expected_type.__args__
  196. ):
  197. allowed_values = expected_type.__args__
  198. if value not in allowed_values:
  199. raise ValueError(
  200. f"prop value for {key} of the `{type(self).__name__}` component should be one of the following: {','.join(allowed_values)}. Got '{value}' instead"
  201. )
  202. # Get the passed type and the var type.
  203. passed_type = kwargs[key]._var_type
  204. expected_type = (
  205. type(expected_type.__args__[0])
  206. if types.is_literal(expected_type)
  207. else expected_type
  208. )
  209. except TypeError:
  210. # If it is not a valid var, check the base types.
  211. passed_type = type(value)
  212. expected_type = fields[key].outer_type_
  213. if not types._issubclass(passed_type, expected_type):
  214. value_name = value._var_name if isinstance(value, Var) else value
  215. raise TypeError(
  216. f"Invalid var passed for prop {key}, expected type {expected_type}, got value {value_name} of type {passed_type}."
  217. )
  218. # Check if the key is an event trigger.
  219. if key in triggers:
  220. # Temporarily disable full control for event triggers.
  221. kwargs["event_triggers"][key] = self._create_event_chain(key, value)
  222. # Remove any keys that were added as events.
  223. for key in kwargs["event_triggers"]:
  224. del kwargs[key]
  225. # Add style props to the component.
  226. style = kwargs.get("style", {})
  227. if isinstance(style, List):
  228. # Merge styles, the later ones overriding keys in the earlier ones.
  229. style = {k: v for style_dict in style for k, v in style_dict.items()}
  230. kwargs["style"] = Style(
  231. {
  232. **self.get_fields()["style"].default,
  233. **style,
  234. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  235. }
  236. )
  237. if "custom_attrs" not in kwargs:
  238. kwargs["custom_attrs"] = {}
  239. # Convert class_name to str if it's list
  240. class_name = kwargs.get("class_name", "")
  241. if isinstance(class_name, (List, tuple)):
  242. kwargs["class_name"] = " ".join(class_name)
  243. # Construct the component.
  244. super().__init__(*args, **kwargs)
  245. def _create_event_chain(
  246. self,
  247. event_trigger: str,
  248. value: Union[
  249. Var, EventHandler, EventSpec, List[Union[EventHandler, EventSpec]], Callable
  250. ],
  251. ) -> Union[EventChain, Var]:
  252. """Create an event chain from a variety of input types.
  253. Args:
  254. event_trigger: The event trigger to bind the chain to.
  255. value: The value to create the event chain from.
  256. Returns:
  257. The event chain.
  258. Raises:
  259. ValueError: If the value is not a valid event chain.
  260. """
  261. # Check if the trigger is a controlled event.
  262. triggers = self.get_event_triggers()
  263. # If it's an event chain var, return it.
  264. if isinstance(value, Var):
  265. if value._var_type is not EventChain:
  266. raise ValueError(f"Invalid event chain: {value}")
  267. return value
  268. elif isinstance(value, EventChain):
  269. # Trust that the caller knows what they're doing passing an EventChain directly
  270. return value
  271. arg_spec = triggers.get(event_trigger, lambda: [])
  272. wrapped = False
  273. # If the input is a single event handler, wrap it in a list.
  274. if isinstance(value, (EventHandler, EventSpec)):
  275. wrapped = True
  276. value = [value]
  277. # If the input is a list of event handlers, create an event chain.
  278. if isinstance(value, List):
  279. if not wrapped:
  280. console.deprecate(
  281. feature_name="EventChain",
  282. reason="to avoid confusion, only use yield API",
  283. deprecation_version="0.2.8",
  284. removal_version="0.4.0",
  285. )
  286. events: list[EventSpec] = []
  287. for v in value:
  288. if isinstance(v, EventHandler):
  289. # Call the event handler to get the event.
  290. try:
  291. event = call_event_handler(v, arg_spec) # type: ignore
  292. except ValueError as err:
  293. raise ValueError(
  294. f" {err} defined in the `{type(self).__name__}` component"
  295. ) from err
  296. # Add the event to the chain.
  297. events.append(event)
  298. elif isinstance(v, EventSpec):
  299. # Add the event to the chain.
  300. events.append(v)
  301. elif isinstance(v, Callable):
  302. # Call the lambda to get the event chain.
  303. events.extend(call_event_fn(v, arg_spec)) # type: ignore
  304. else:
  305. raise ValueError(f"Invalid event: {v}")
  306. # If the input is a callable, create an event chain.
  307. elif isinstance(value, Callable):
  308. events = call_event_fn(value, arg_spec) # type: ignore
  309. # Otherwise, raise an error.
  310. else:
  311. raise ValueError(f"Invalid event chain: {value}")
  312. # Add args to the event specs if necessary.
  313. events = [e.with_args(get_handler_args(e)) for e in events]
  314. # Collect event_actions from each spec
  315. event_actions = {}
  316. for e in events:
  317. event_actions.update(e.event_actions)
  318. # Return the event chain.
  319. if isinstance(arg_spec, Var):
  320. return EventChain(
  321. events=events,
  322. args_spec=None,
  323. event_actions=event_actions,
  324. )
  325. else:
  326. return EventChain(
  327. events=events,
  328. args_spec=arg_spec, # type: ignore
  329. event_actions=event_actions,
  330. )
  331. def get_event_triggers(self) -> Dict[str, Any]:
  332. """Get the event triggers for the component.
  333. Returns:
  334. The event triggers.
  335. """
  336. return {
  337. EventTriggers.ON_FOCUS: lambda: [],
  338. EventTriggers.ON_BLUR: lambda: [],
  339. EventTriggers.ON_CLICK: lambda: [],
  340. EventTriggers.ON_CONTEXT_MENU: lambda: [],
  341. EventTriggers.ON_DOUBLE_CLICK: lambda: [],
  342. EventTriggers.ON_MOUSE_DOWN: lambda: [],
  343. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  344. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  345. EventTriggers.ON_MOUSE_MOVE: lambda: [],
  346. EventTriggers.ON_MOUSE_OUT: lambda: [],
  347. EventTriggers.ON_MOUSE_OVER: lambda: [],
  348. EventTriggers.ON_MOUSE_UP: lambda: [],
  349. EventTriggers.ON_SCROLL: lambda: [],
  350. EventTriggers.ON_MOUNT: lambda: [],
  351. EventTriggers.ON_UNMOUNT: lambda: [],
  352. }
  353. def __repr__(self) -> str:
  354. """Represent the component in React.
  355. Returns:
  356. The code to render the component.
  357. """
  358. return format.json_dumps(self.render())
  359. def __str__(self) -> str:
  360. """Represent the component in React.
  361. Returns:
  362. The code to render the component.
  363. """
  364. from reflex.compiler.compiler import _compile_component
  365. return _compile_component(self)
  366. def _apply_theme(self, theme: Optional[Component]):
  367. """Apply the theme to this component.
  368. Args:
  369. theme: The theme to apply.
  370. """
  371. pass
  372. def apply_theme(self, theme: Optional[Component]):
  373. """Apply a theme to the component and its children.
  374. Args:
  375. theme: The theme to apply.
  376. """
  377. self._apply_theme(theme)
  378. for child in self.children:
  379. if isinstance(child, Component):
  380. child.apply_theme(theme)
  381. def _render(self, props: dict[str, Any] | None = None) -> Tag:
  382. """Define how to render the component in React.
  383. Args:
  384. props: The props to render (if None, then use get_props).
  385. Returns:
  386. The tag to render.
  387. """
  388. # Create the base tag.
  389. tag = Tag(
  390. name=self.tag if not self.alias else self.alias,
  391. special_props=self.special_props,
  392. )
  393. if props is None:
  394. # Add component props to the tag.
  395. props = {
  396. attr[:-1] if attr.endswith("_") else attr: getattr(self, attr)
  397. for attr in self.get_props()
  398. }
  399. # Add ref to element if `id` is not None.
  400. ref = self.get_ref()
  401. if ref is not None:
  402. props["ref"] = Var.create(ref, _var_is_local=False)
  403. else:
  404. props = props.copy()
  405. props.update(
  406. **{
  407. trigger: handler
  408. for trigger, handler in self.event_triggers.items()
  409. if trigger not in {EventTriggers.ON_MOUNT, EventTriggers.ON_UNMOUNT}
  410. },
  411. key=self.key,
  412. id=self.id,
  413. class_name=self.class_name,
  414. )
  415. props.update(self._get_style())
  416. props.update(self.custom_attrs)
  417. return tag.add_props(**props)
  418. @classmethod
  419. @lru_cache(maxsize=None)
  420. def get_props(cls) -> Set[str]:
  421. """Get the unique fields for the component.
  422. Returns:
  423. The unique fields.
  424. """
  425. return set(cls.get_fields()) - set(Component.get_fields())
  426. @classmethod
  427. @lru_cache(maxsize=None)
  428. def get_initial_props(cls) -> Set[str]:
  429. """Get the initial props to set for the component.
  430. Returns:
  431. The initial props to set.
  432. """
  433. return set()
  434. @classmethod
  435. @lru_cache(maxsize=None)
  436. def get_component_props(cls) -> set[str]:
  437. """Get the props that expected a component as value.
  438. Returns:
  439. The components props.
  440. """
  441. return {
  442. name
  443. for name, field in cls.get_fields().items()
  444. if name in cls.get_props()
  445. and types._issubclass(field.outer_type_, Component)
  446. }
  447. @classmethod
  448. def create(cls, *children, **props) -> Component:
  449. """Create the component.
  450. Args:
  451. *children: The children of the component.
  452. **props: The props of the component.
  453. Returns:
  454. The component.
  455. Raises:
  456. TypeError: If an invalid child is passed.
  457. """
  458. # Import here to avoid circular imports.
  459. from reflex.components.base.bare import Bare
  460. # Validate all the children.
  461. for child in children:
  462. # Make sure the child is a valid type.
  463. if not types._isinstance(child, ComponentChild):
  464. raise TypeError(
  465. "Children of Reflex components must be other components, "
  466. "state vars, or primitive Python types. "
  467. f"Got child {child} of type {type(child)}.",
  468. )
  469. children = [
  470. child
  471. if isinstance(child, Component)
  472. else Bare.create(contents=Var.create(child, _var_is_string=True))
  473. for child in children
  474. ]
  475. return cls(children=children, **props)
  476. def _add_style(self, style: dict):
  477. """Add additional style to the component.
  478. Args:
  479. style: A style dict to apply.
  480. """
  481. self.style.update(style)
  482. def add_style(self, style: ComponentStyle) -> Component:
  483. """Add additional style to the component and its children.
  484. Args:
  485. style: A dict from component to styling.
  486. Returns:
  487. The component with the additional style.
  488. """
  489. if type(self) in style:
  490. # Extract the style for this component.
  491. component_style = Style(style[type(self)])
  492. # Only add style props that are not overridden.
  493. component_style = {
  494. k: v for k, v in component_style.items() if k not in self.style
  495. }
  496. # Add the style to the component.
  497. self._add_style(component_style)
  498. # Recursively add style to the children.
  499. for child in self.children:
  500. # Skip BaseComponent and StatefulComponent children.
  501. if not isinstance(child, Component):
  502. continue
  503. child.add_style(style)
  504. return self
  505. def _get_style(self) -> dict:
  506. """Get the style for the component.
  507. Returns:
  508. The dictionary of the component style as value and the style notation as key.
  509. """
  510. if isinstance(self.style, Var):
  511. return {"css": self.style}
  512. return {"css": Var.create(format_as_emotion(self.style))}
  513. def render(self) -> Dict:
  514. """Render the component.
  515. Returns:
  516. The dictionary for template of component.
  517. """
  518. tag = self._render()
  519. rendered_dict = dict(
  520. tag.set(
  521. children=[child.render() for child in self.children],
  522. contents=str(tag.contents),
  523. props=tag.format_props(),
  524. ),
  525. autofocus=self.autofocus,
  526. )
  527. return rendered_dict
  528. def _validate_component_children(self, children: List[Component]):
  529. """Validate the children components.
  530. Args:
  531. children: The children of the component.
  532. """
  533. skip_parentable = all(child._valid_parents == [] for child in children)
  534. if not self._invalid_children and not self._valid_children and skip_parentable:
  535. return
  536. comp_name = type(self).__name__
  537. def validate_invalid_child(child_name):
  538. if child_name in self._invalid_children:
  539. raise ValueError(
  540. f"The component `{comp_name}` cannot have `{child_name}` as a child component"
  541. )
  542. def validate_valid_child(child_name):
  543. if child_name not in self._valid_children:
  544. valid_child_list = ", ".join(
  545. [f"`{v_child}`" for v_child in self._valid_children]
  546. )
  547. raise ValueError(
  548. f"The component `{comp_name}` only allows the components: {valid_child_list} as children. Got `{child_name}` instead."
  549. )
  550. def validate_vaild_parent(child_name, valid_parents):
  551. if comp_name not in valid_parents:
  552. valid_parent_list = ", ".join(
  553. [f"`{v_parent}`" for v_parent in valid_parents]
  554. )
  555. raise ValueError(
  556. f"The component `{child_name}` can only be a child of the components: {valid_parent_list}. Got `{comp_name}` instead."
  557. )
  558. for child in children:
  559. name = type(child).__name__
  560. if self._invalid_children:
  561. validate_invalid_child(name)
  562. if self._valid_children:
  563. validate_valid_child(name)
  564. if child._valid_parents:
  565. validate_vaild_parent(name, child._valid_parents)
  566. @staticmethod
  567. def _get_vars_from_event_triggers(
  568. event_triggers: dict[str, EventChain | Var],
  569. ) -> Iterator[tuple[str, list[Var]]]:
  570. """Get the Vars associated with each event trigger.
  571. Args:
  572. event_triggers: The event triggers from the component instance.
  573. Yields:
  574. tuple of (event_name, event_vars)
  575. """
  576. for event_trigger, event in event_triggers.items():
  577. if isinstance(event, Var):
  578. yield event_trigger, [event]
  579. elif isinstance(event, EventChain):
  580. event_args = []
  581. for spec in event.events:
  582. for args in spec.args:
  583. event_args.extend(args)
  584. yield event_trigger, event_args
  585. def _get_vars(self) -> list[Var]:
  586. """Walk all Vars used in this component.
  587. Returns:
  588. Each var referenced by the component (props, styles, event handlers).
  589. """
  590. vars = getattr(self, "__vars", None)
  591. if vars is not None:
  592. return vars
  593. vars = self.__vars = []
  594. # Get Vars associated with event trigger arguments.
  595. for _, event_vars in self._get_vars_from_event_triggers(self.event_triggers):
  596. vars.extend(event_vars)
  597. # Get Vars associated with component props.
  598. for prop in self.get_props():
  599. prop_var = getattr(self, prop)
  600. if isinstance(prop_var, Var):
  601. vars.append(prop_var)
  602. # Style keeps track of its own VarData instance, so embed in a temp Var that is yielded.
  603. if self.style:
  604. vars.append(
  605. BaseVar(
  606. _var_name="style",
  607. _var_type=str,
  608. _var_data=self.style._var_data,
  609. )
  610. )
  611. # Special props are always Var instances.
  612. vars.extend(self.special_props)
  613. # Get Vars associated with common Component props.
  614. for comp_prop in (
  615. self.class_name,
  616. self.id,
  617. self.key,
  618. self.autofocus,
  619. *self.custom_attrs.values(),
  620. ):
  621. if isinstance(comp_prop, Var):
  622. vars.append(comp_prop)
  623. elif isinstance(comp_prop, str):
  624. # Collapse VarData encoded in f-strings.
  625. var = Var.create_safe(comp_prop)
  626. if var._var_data is not None:
  627. vars.append(var)
  628. return vars
  629. def _get_custom_code(self) -> str | None:
  630. """Get custom code for the component.
  631. Returns:
  632. The custom code.
  633. """
  634. return None
  635. def get_custom_code(self) -> Set[str]:
  636. """Get custom code for the component and its children.
  637. Returns:
  638. The custom code.
  639. """
  640. # Store the code in a set to avoid duplicates.
  641. code = set()
  642. # Add the custom code for this component.
  643. custom_code = self._get_custom_code()
  644. if custom_code is not None:
  645. code.add(custom_code)
  646. # Add the custom code for the children.
  647. for child in self.children:
  648. code |= child.get_custom_code()
  649. # Return the code.
  650. return code
  651. def _get_dynamic_imports(self) -> str | None:
  652. """Get dynamic import for the component.
  653. Returns:
  654. The dynamic import.
  655. """
  656. return None
  657. def get_dynamic_imports(self) -> Set[str]:
  658. """Get dynamic imports for the component and its children.
  659. Returns:
  660. The dynamic imports.
  661. """
  662. # Store the import in a set to avoid duplicates.
  663. dynamic_imports = set()
  664. # Get dynamic import for this component.
  665. dynamic_import = self._get_dynamic_imports()
  666. if dynamic_import:
  667. dynamic_imports.add(dynamic_import)
  668. # Get the dynamic imports from children
  669. for child in self.children:
  670. dynamic_imports |= child.get_dynamic_imports()
  671. for prop in self.get_component_props():
  672. if getattr(self, prop) is not None:
  673. dynamic_imports |= getattr(self, prop).get_dynamic_imports()
  674. # Return the dynamic imports
  675. return dynamic_imports
  676. def _get_props_imports(self) -> List[str]:
  677. """Get the imports needed for components props.
  678. Returns:
  679. The imports for the components props of the component.
  680. """
  681. return [
  682. getattr(self, prop).get_imports()
  683. for prop in self.get_component_props()
  684. if getattr(self, prop) is not None
  685. ]
  686. def _get_dependencies_imports(self) -> imports.ImportDict:
  687. """Get the imports from lib_dependencies for installing.
  688. Returns:
  689. The dependencies imports of the component.
  690. """
  691. return {
  692. dep: [ImportVar(tag=None, render=False)] for dep in self.lib_dependencies
  693. }
  694. def _get_hooks_imports(self) -> imports.ImportDict:
  695. """Get the imports required by certain hooks.
  696. Returns:
  697. The imports required for all selected hooks.
  698. """
  699. _imports = {}
  700. if self._get_ref_hook():
  701. # Handle hooks needed for attaching react refs to DOM nodes.
  702. _imports.setdefault("react", set()).add(ImportVar(tag="useRef"))
  703. _imports.setdefault(f"/{Dirs.STATE_PATH}", set()).add(ImportVar(tag="refs"))
  704. if self._get_mount_lifecycle_hook():
  705. # Handle hooks for `on_mount` / `on_unmount`.
  706. _imports.setdefault("react", set()).add(ImportVar(tag="useEffect"))
  707. if self._get_special_hooks():
  708. # Handle additional internal hooks (autofocus, etc).
  709. _imports.setdefault("react", set()).update(
  710. {
  711. ImportVar(tag="useRef"),
  712. ImportVar(tag="useEffect"),
  713. },
  714. )
  715. return _imports
  716. def _get_imports(self) -> imports.ImportDict:
  717. """Get all the libraries and fields that are used by the component.
  718. Returns:
  719. The imports needed by the component.
  720. """
  721. _imports = {}
  722. # Import this component's tag from the main library.
  723. if self.library is not None and self.tag is not None:
  724. _imports[self.library] = {self.import_var}
  725. # Get static imports required for event processing.
  726. event_imports = Imports.EVENTS if self.event_triggers else {}
  727. # Collect imports from Vars used directly by this component.
  728. var_imports = [
  729. var._var_data.imports for var in self._get_vars() if var._var_data
  730. ]
  731. return imports.merge_imports(
  732. *self._get_props_imports(),
  733. self._get_dependencies_imports(),
  734. self._get_hooks_imports(),
  735. _imports,
  736. event_imports,
  737. *var_imports,
  738. )
  739. def get_imports(self) -> imports.ImportDict:
  740. """Get all the libraries and fields that are used by the component and its children.
  741. Returns:
  742. The import dict with the required imports.
  743. """
  744. return imports.merge_imports(
  745. self._get_imports(), *[child.get_imports() for child in self.children]
  746. )
  747. def _get_mount_lifecycle_hook(self) -> str | None:
  748. """Generate the component lifecycle hook.
  749. Returns:
  750. The useEffect hook for managing `on_mount` and `on_unmount` events.
  751. """
  752. # pop on_mount and on_unmount from event_triggers since these are handled by
  753. # hooks, not as actually props in the component
  754. on_mount = self.event_triggers.get(EventTriggers.ON_MOUNT, None)
  755. on_unmount = self.event_triggers.get(EventTriggers.ON_UNMOUNT, None)
  756. if on_mount is not None:
  757. on_mount = format.format_event_chain(on_mount)
  758. if on_unmount is not None:
  759. on_unmount = format.format_event_chain(on_unmount)
  760. if on_mount is not None or on_unmount is not None:
  761. return f"""
  762. useEffect(() => {{
  763. {on_mount or ""}
  764. return () => {{
  765. {on_unmount or ""}
  766. }}
  767. }}, []);"""
  768. def _get_ref_hook(self) -> str | None:
  769. """Generate the ref hook for the component.
  770. Returns:
  771. The useRef hook for managing refs.
  772. """
  773. ref = self.get_ref()
  774. if ref is not None:
  775. return f"const {ref} = useRef(null); {str(Var.create_safe(ref).as_ref())} = {ref};"
  776. def _get_vars_hooks(self) -> set[str]:
  777. """Get the hooks required by vars referenced in this component.
  778. Returns:
  779. The hooks for the vars.
  780. """
  781. vars_hooks = set()
  782. for var in self._get_vars():
  783. if var._var_data:
  784. vars_hooks.update(var._var_data.hooks)
  785. return vars_hooks
  786. def _get_events_hooks(self) -> set[str]:
  787. """Get the hooks required by events referenced in this component.
  788. Returns:
  789. The hooks for the events.
  790. """
  791. if self.event_triggers:
  792. return {Hooks.EVENTS}
  793. return set()
  794. def _get_special_hooks(self) -> set[str]:
  795. """Get the hooks required by special actions referenced in this component.
  796. Returns:
  797. The hooks for special actions.
  798. """
  799. if self.autofocus:
  800. return {
  801. """
  802. // Set focus to the specified element.
  803. const focusRef = useRef(null)
  804. useEffect(() => {
  805. if (focusRef.current) {
  806. focusRef.current.focus();
  807. }
  808. })""",
  809. }
  810. return set()
  811. def _get_hooks_internal(self) -> Set[str]:
  812. """Get the React hooks for this component managed by the framework.
  813. Downstream components should NOT override this method to avoid breaking
  814. framework functionality.
  815. Returns:
  816. Set of internally managed hooks.
  817. """
  818. return (
  819. set(
  820. hook
  821. for hook in [self._get_mount_lifecycle_hook(), self._get_ref_hook()]
  822. if hook
  823. )
  824. | self._get_vars_hooks()
  825. | self._get_events_hooks()
  826. | self._get_special_hooks()
  827. )
  828. def _get_hooks(self) -> str | None:
  829. """Get the React hooks for this component.
  830. Downstream components should override this method to add their own hooks.
  831. Returns:
  832. The hooks for just this component.
  833. """
  834. return
  835. def get_hooks(self) -> Set[str]:
  836. """Get the React hooks for this component and its children.
  837. Returns:
  838. The code that should appear just before returning the rendered component.
  839. """
  840. # Store the code in a set to avoid duplicates.
  841. code = self._get_hooks_internal()
  842. # Add the hook code for this component.
  843. hooks = self._get_hooks()
  844. if hooks is not None:
  845. code.add(hooks)
  846. # Add the hook code for the children.
  847. for child in self.children:
  848. code |= child.get_hooks()
  849. return code
  850. def get_ref(self) -> str | None:
  851. """Get the name of the ref for the component.
  852. Returns:
  853. The ref name.
  854. """
  855. # do not create a ref if the id is dynamic or unspecified
  856. if self.id is None or isinstance(self.id, BaseVar):
  857. return None
  858. return format.format_ref(self.id)
  859. def get_refs(self) -> Set[str]:
  860. """Get the refs for the children of the component.
  861. Returns:
  862. The refs for the children.
  863. """
  864. refs = set()
  865. ref = self.get_ref()
  866. if ref is not None:
  867. refs.add(ref)
  868. for child in self.children:
  869. refs |= child.get_refs()
  870. return refs
  871. def get_custom_components(
  872. self, seen: set[str] | None = None
  873. ) -> Set[CustomComponent]:
  874. """Get all the custom components used by the component.
  875. Args:
  876. seen: The tags of the components that have already been seen.
  877. Returns:
  878. The set of custom components.
  879. """
  880. custom_components = set()
  881. # Store the seen components in a set to avoid infinite recursion.
  882. if seen is None:
  883. seen = set()
  884. for child in self.children:
  885. # Skip BaseComponent and StatefulComponent children.
  886. if not isinstance(child, Component):
  887. continue
  888. custom_components |= child.get_custom_components(seen=seen)
  889. return custom_components
  890. @property
  891. def import_var(self):
  892. """The tag to import.
  893. Returns:
  894. An import var.
  895. """
  896. # If the tag is dot-qualified, only import the left-most name.
  897. tag = self.tag.partition(".")[0] if self.tag else None
  898. alias = self.alias.partition(".")[0] if self.alias else None
  899. return ImportVar(tag=tag, is_default=self.is_default, alias=alias)
  900. @staticmethod
  901. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  902. """Get the app wrap components for the component.
  903. Returns:
  904. The app wrap components.
  905. """
  906. return {}
  907. def get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  908. """Get the app wrap components for the component and its children.
  909. Returns:
  910. The app wrap components.
  911. """
  912. # Store the components in a set to avoid duplicates.
  913. components = self._get_app_wrap_components()
  914. for component in tuple(components.values()):
  915. components.update(component.get_app_wrap_components())
  916. # Add the app wrap components for the children.
  917. for child in self.children:
  918. # Skip BaseComponent and StatefulComponent children.
  919. if not isinstance(child, Component):
  920. continue
  921. components.update(child.get_app_wrap_components())
  922. # Return the components.
  923. return components
  924. class CustomComponent(Component):
  925. """A custom user-defined component."""
  926. # Use the components library.
  927. library = f"/{Dirs.COMPONENTS_PATH}"
  928. # The function that creates the component.
  929. component_fn: Callable[..., Component] = Component.create
  930. # The props of the component.
  931. props: Dict[str, Any] = {}
  932. def __init__(self, *args, **kwargs):
  933. """Initialize the custom component.
  934. Args:
  935. *args: The args to pass to the component.
  936. **kwargs: The kwargs to pass to the component.
  937. """
  938. super().__init__(*args, **kwargs)
  939. # Unset the style.
  940. self.style = Style()
  941. # Set the tag to the name of the function.
  942. self.tag = format.to_title_case(self.component_fn.__name__)
  943. # Set the props.
  944. props = typing.get_type_hints(self.component_fn)
  945. for key, value in kwargs.items():
  946. # Skip kwargs that are not props.
  947. if key not in props:
  948. continue
  949. # Get the type based on the annotation.
  950. type_ = props[key]
  951. # Handle event chains.
  952. if types._issubclass(type_, EventChain):
  953. value = self._create_event_chain(key, value)
  954. self.props[format.to_camel_case(key)] = value
  955. continue
  956. # Convert the type to a Var, then get the type of the var.
  957. if not types._issubclass(type_, Var):
  958. type_ = Var[type_]
  959. type_ = types.get_args(type_)[0]
  960. # Handle subclasses of Base.
  961. if types._issubclass(type_, Base):
  962. try:
  963. value = BaseVar(
  964. _var_name=value.json(), _var_type=type_, _var_is_local=True
  965. )
  966. except Exception:
  967. value = Var.create(value)
  968. else:
  969. value = Var.create(value, _var_is_string=type(value) is str)
  970. # Set the prop.
  971. self.props[format.to_camel_case(key)] = value
  972. def __eq__(self, other: Any) -> bool:
  973. """Check if the component is equal to another.
  974. Args:
  975. other: The other component.
  976. Returns:
  977. Whether the component is equal to the other.
  978. """
  979. return isinstance(other, CustomComponent) and self.tag == other.tag
  980. def __hash__(self) -> int:
  981. """Get the hash of the component.
  982. Returns:
  983. The hash of the component.
  984. """
  985. return hash(self.tag)
  986. @classmethod
  987. def get_props(cls) -> Set[str]:
  988. """Get the props for the component.
  989. Returns:
  990. The set of component props.
  991. """
  992. return set()
  993. def get_custom_components(
  994. self, seen: set[str] | None = None
  995. ) -> Set[CustomComponent]:
  996. """Get all the custom components used by the component.
  997. Args:
  998. seen: The tags of the components that have already been seen.
  999. Returns:
  1000. The set of custom components.
  1001. """
  1002. assert self.tag is not None, "The tag must be set."
  1003. # Store the seen components in a set to avoid infinite recursion.
  1004. if seen is None:
  1005. seen = set()
  1006. custom_components = {self} | super().get_custom_components(seen=seen)
  1007. # Avoid adding the same component twice.
  1008. if self.tag not in seen:
  1009. seen.add(self.tag)
  1010. custom_components |= self.get_component(self).get_custom_components(
  1011. seen=seen
  1012. )
  1013. return custom_components
  1014. def _render(self) -> Tag:
  1015. """Define how to render the component in React.
  1016. Returns:
  1017. The tag to render.
  1018. """
  1019. return super()._render(props=self.props)
  1020. def get_prop_vars(self) -> List[BaseVar]:
  1021. """Get the prop vars.
  1022. Returns:
  1023. The prop vars.
  1024. """
  1025. return [
  1026. BaseVar(
  1027. _var_name=name,
  1028. _var_type=prop._var_type
  1029. if types._isinstance(prop, Var)
  1030. else type(prop),
  1031. )
  1032. for name, prop in self.props.items()
  1033. ]
  1034. @lru_cache(maxsize=None) # noqa
  1035. def get_component(self) -> Component:
  1036. """Render the component.
  1037. Returns:
  1038. The code to render the component.
  1039. """
  1040. return self.component_fn(*self.get_prop_vars())
  1041. def custom_component(
  1042. component_fn: Callable[..., Component]
  1043. ) -> Callable[..., CustomComponent]:
  1044. """Create a custom component from a function.
  1045. Args:
  1046. component_fn: The function that creates the component.
  1047. Returns:
  1048. The decorated function.
  1049. """
  1050. @wraps(component_fn)
  1051. def wrapper(*children, **props) -> CustomComponent:
  1052. # Remove the children from the props.
  1053. props.pop("children", None)
  1054. return CustomComponent(component_fn=component_fn, children=children, **props)
  1055. return wrapper
  1056. # Alias memo to custom_component.
  1057. memo = custom_component
  1058. class NoSSRComponent(Component):
  1059. """A dynamic component that is not rendered on the server."""
  1060. def _get_imports(self) -> imports.ImportDict:
  1061. """Get the imports for the component.
  1062. Returns:
  1063. The imports for dynamically importing the component at module load time.
  1064. """
  1065. # Next.js dynamic import mechanism.
  1066. dynamic_import = {"next/dynamic": [ImportVar(tag="dynamic", is_default=True)]}
  1067. # The normal imports for this component.
  1068. _imports = super()._get_imports()
  1069. # Do NOT import the main library/tag statically.
  1070. if self.library is not None:
  1071. _imports[self.library] = [imports.ImportVar(tag=None, render=False)]
  1072. return imports.merge_imports(
  1073. dynamic_import,
  1074. _imports,
  1075. self._get_dependencies_imports(),
  1076. )
  1077. def _get_dynamic_imports(self) -> str:
  1078. opts_fragment = ", { ssr: false });"
  1079. # extract the correct import name from library name
  1080. if self.library is None:
  1081. raise ValueError("Undefined library for NoSSRComponent")
  1082. import_name_parts = [p for p in self.library.rpartition("@") if p != ""]
  1083. import_name = (
  1084. import_name_parts[0] if import_name_parts[0] != "@" else self.library
  1085. )
  1086. library_import = f"const {self.alias if self.alias else self.tag} = dynamic(() => import('{import_name}')"
  1087. mod_import = (
  1088. # https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
  1089. f".then((mod) => mod.{self.tag})"
  1090. if not self.is_default
  1091. else ""
  1092. )
  1093. return "".join((library_import, mod_import, opts_fragment))
  1094. @serializer
  1095. def serialize_component(comp: Component):
  1096. """Serialize a component.
  1097. Args:
  1098. comp: The component to serialize.
  1099. Returns:
  1100. The serialized component.
  1101. """
  1102. return str(comp)
  1103. class StatefulComponent(BaseComponent):
  1104. """A component that depends on state and is rendered outside of the page component.
  1105. If a StatefulComponent is used in multiple pages, it will be rendered to a common file and
  1106. imported into each page that uses it.
  1107. A stateful component has a tag name that includes a hash of the code that it renders
  1108. to. This tag name refers to the specific component with the specific props that it
  1109. was created with.
  1110. """
  1111. # A lookup table to caching memoized component instances.
  1112. tag_to_stateful_component: ClassVar[Dict[str, StatefulComponent]] = {}
  1113. # Reference to the original component that was memoized into this component.
  1114. component: Component
  1115. # The rendered (memoized) code that will be emitted.
  1116. code: str
  1117. # How many times this component is referenced in the app.
  1118. references: int = 0
  1119. # Whether the component has already been rendered to a shared file.
  1120. rendered_as_shared: bool = False
  1121. @classmethod
  1122. def create(cls, component: Component) -> StatefulComponent | None:
  1123. """Create a stateful component from a component.
  1124. Args:
  1125. component: The component to memoize.
  1126. Returns:
  1127. The stateful component or None if the component should not be memoized.
  1128. """
  1129. from reflex.components.core.foreach import Foreach
  1130. if component._memoization_mode.disposition == MemoizationDisposition.NEVER:
  1131. # Never memoize this component.
  1132. return None
  1133. if component.tag is None:
  1134. # Only memoize components with a tag.
  1135. return None
  1136. # If _var_data is found in this component, it is a candidate for auto-memoization.
  1137. should_memoize = False
  1138. # If the component requests to be memoized, then ignore other checks.
  1139. if component._memoization_mode.disposition == MemoizationDisposition.ALWAYS:
  1140. should_memoize = True
  1141. if not should_memoize:
  1142. # Determine if any Vars have associated data.
  1143. for prop_var in component._get_vars():
  1144. if prop_var._var_data:
  1145. should_memoize = True
  1146. break
  1147. if not should_memoize:
  1148. # Check for special-cases in child components.
  1149. for child in component.children:
  1150. # Skip BaseComponent and StatefulComponent children.
  1151. if not isinstance(child, Component):
  1152. continue
  1153. # Always consider Foreach something that must be memoized by the parent.
  1154. if isinstance(child, Foreach):
  1155. should_memoize = True
  1156. break
  1157. child = cls._child_var(child)
  1158. if isinstance(child, Var) and child._var_data:
  1159. should_memoize = True
  1160. break
  1161. if should_memoize or component.event_triggers:
  1162. # Render the component to determine tag+hash based on component code.
  1163. tag_name = cls._get_tag_name(component)
  1164. if tag_name is None:
  1165. return None
  1166. # Look up the tag in the cache
  1167. stateful_component = cls.tag_to_stateful_component.get(tag_name)
  1168. if stateful_component is None:
  1169. # Render the component as a string of javascript code.
  1170. code = cls._render_stateful_code(component, tag_name=tag_name)
  1171. # Set the stateful component in the cache for the given tag.
  1172. stateful_component = cls.tag_to_stateful_component.setdefault(
  1173. tag_name,
  1174. cls(
  1175. children=component.children,
  1176. component=component,
  1177. tag=tag_name,
  1178. code=code,
  1179. ),
  1180. )
  1181. # Bump the reference count -- multiple pages referencing the same component
  1182. # will result in writing it to a common file.
  1183. stateful_component.references += 1
  1184. return stateful_component
  1185. # Return None to indicate this component should not be memoized.
  1186. return None
  1187. @staticmethod
  1188. def _child_var(child: Component) -> Var | Component:
  1189. """Get the Var from a child component.
  1190. This method is used for special cases when the StatefulComponent should actually
  1191. wrap the parent component of the child instead of recursing into the children
  1192. and memoizing them independently.
  1193. Args:
  1194. child: The child component.
  1195. Returns:
  1196. The Var from the child component or the child itself (for regular cases).
  1197. """
  1198. from reflex.components.base.bare import Bare
  1199. from reflex.components.core.cond import Cond
  1200. from reflex.components.core.foreach import Foreach
  1201. if isinstance(child, Bare):
  1202. return child.contents
  1203. if isinstance(child, Cond):
  1204. return child.cond
  1205. if isinstance(child, Foreach):
  1206. return child.iterable
  1207. return child
  1208. @classmethod
  1209. def _get_tag_name(cls, component: Component) -> str | None:
  1210. """Get the tag based on rendering the given component.
  1211. Args:
  1212. component: The component to render.
  1213. Returns:
  1214. The tag for the stateful component.
  1215. """
  1216. # Get the render dict for the component.
  1217. rendered_code = component.render()
  1218. if not rendered_code:
  1219. # Never memoize non-visual components.
  1220. return None
  1221. # Compute the hash based on the rendered code.
  1222. code_hash = md5(str(rendered_code).encode("utf-8")).hexdigest()
  1223. # Format the tag name including the hash.
  1224. return format.format_state_name(
  1225. f"{component.tag or 'Comp'}_{code_hash}"
  1226. ).capitalize()
  1227. @classmethod
  1228. def _render_stateful_code(
  1229. cls,
  1230. component: Component,
  1231. tag_name: str,
  1232. ) -> str:
  1233. """Render the code for a stateful component.
  1234. Args:
  1235. component: The component to render.
  1236. tag_name: The tag name for the stateful component (see _get_tag_name).
  1237. Returns:
  1238. The rendered code.
  1239. """
  1240. # Memoize event triggers useCallback to avoid unnecessary re-renders.
  1241. memo_event_triggers = tuple(cls._get_memoized_event_triggers(component).items())
  1242. # Trigger hooks stored separately to write after the normal hooks (see stateful_component.js.jinja2)
  1243. memo_trigger_hooks = []
  1244. if memo_event_triggers:
  1245. # Copy the component to avoid mutating the original.
  1246. component = copy.copy(component)
  1247. for event_trigger, (
  1248. memo_trigger,
  1249. memo_trigger_hook,
  1250. ) in memo_event_triggers:
  1251. # Replace the event trigger with the memoized version.
  1252. memo_trigger_hooks.append(memo_trigger_hook)
  1253. component.event_triggers[event_trigger] = memo_trigger
  1254. # Render the code for this component and hooks.
  1255. return STATEFUL_COMPONENT.render(
  1256. tag_name=tag_name,
  1257. memo_trigger_hooks=memo_trigger_hooks,
  1258. component=component,
  1259. )
  1260. @staticmethod
  1261. def _get_hook_deps(hook: str) -> list[str]:
  1262. """Extract var deps from a hook.
  1263. Args:
  1264. hook: The hook line to extract deps from.
  1265. Returns:
  1266. A list of var names created by the hook declaration.
  1267. """
  1268. var_name = hook.partition("=")[0].strip().split(None, 1)[1].strip()
  1269. if var_name.startswith("["):
  1270. # Break up array destructuring.
  1271. return [v.strip() for v in var_name.strip("[]").split(",")]
  1272. return [var_name]
  1273. @classmethod
  1274. def _get_memoized_event_triggers(
  1275. cls,
  1276. component: Component,
  1277. ) -> dict[str, tuple[Var, str]]:
  1278. """Memoize event handler functions with useCallback to avoid unnecessary re-renders.
  1279. Args:
  1280. component: The component with events to memoize.
  1281. Returns:
  1282. A dict of event trigger name to a tuple of the memoized event trigger Var and
  1283. the hook code that memoizes the event handler.
  1284. """
  1285. trigger_memo = {}
  1286. for event_trigger, event_args in component._get_vars_from_event_triggers(
  1287. component.event_triggers
  1288. ):
  1289. if event_trigger in {
  1290. EventTriggers.ON_MOUNT,
  1291. EventTriggers.ON_UNMOUNT,
  1292. EventTriggers.ON_SUBMIT,
  1293. }:
  1294. # Do not memoize lifecycle or submit events.
  1295. continue
  1296. # Get the actual EventSpec and render it.
  1297. event = component.event_triggers[event_trigger]
  1298. rendered_chain = format.format_prop(event)
  1299. if isinstance(rendered_chain, str):
  1300. rendered_chain = rendered_chain.strip("{}")
  1301. # Hash the rendered EventChain to get a deterministic function name.
  1302. chain_hash = md5(str(rendered_chain).encode("utf-8")).hexdigest()
  1303. memo_name = f"{event_trigger}_{chain_hash}"
  1304. # Calculate Var dependencies accessed by the handler for useCallback dep array.
  1305. var_deps = ["addEvents", "Event"]
  1306. for arg in event_args:
  1307. if arg._var_data is None:
  1308. continue
  1309. for hook in arg._var_data.hooks:
  1310. var_deps.extend(cls._get_hook_deps(hook))
  1311. memo_var_data = VarData.merge(
  1312. *[var._var_data for var in event_args],
  1313. VarData( # type: ignore
  1314. imports={"react": {ImportVar(tag="useCallback")}},
  1315. ),
  1316. )
  1317. # Store the memoized function name and hook code for this event trigger.
  1318. trigger_memo[event_trigger] = (
  1319. Var.create_safe(memo_name)._replace(
  1320. _var_type=EventChain, merge_var_data=memo_var_data
  1321. ),
  1322. f"const {memo_name} = useCallback({rendered_chain}, [{', '.join(var_deps)}])",
  1323. )
  1324. return trigger_memo
  1325. def get_hooks(self) -> set[str]:
  1326. """Get the React hooks for this component.
  1327. Returns:
  1328. The code that should appear just before returning the rendered component.
  1329. """
  1330. return set()
  1331. def get_imports(self) -> imports.ImportDict:
  1332. """Get all the libraries and fields that are used by the component.
  1333. Returns:
  1334. The import dict with the required imports.
  1335. """
  1336. if self.rendered_as_shared:
  1337. return {
  1338. f"/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
  1339. ImportVar(tag=self.tag)
  1340. ]
  1341. }
  1342. return self.component.get_imports()
  1343. def get_dynamic_imports(self) -> set[str]:
  1344. """Get dynamic imports for the component.
  1345. Returns:
  1346. The dynamic imports.
  1347. """
  1348. if self.rendered_as_shared:
  1349. return set()
  1350. return self.component.get_dynamic_imports()
  1351. def get_custom_code(self) -> set[str]:
  1352. """Get custom code for the component.
  1353. Returns:
  1354. The custom code.
  1355. """
  1356. if self.rendered_as_shared:
  1357. return set()
  1358. return self.component.get_custom_code().union({self.code})
  1359. def get_refs(self) -> set[str]:
  1360. """Get the refs for the children of the component.
  1361. Returns:
  1362. The refs for the children.
  1363. """
  1364. if self.rendered_as_shared:
  1365. return set()
  1366. return self.component.get_refs()
  1367. def render(self) -> dict:
  1368. """Define how to render the component in React.
  1369. Returns:
  1370. The tag to render.
  1371. """
  1372. return dict(Tag(name=self.tag))
  1373. @classmethod
  1374. def compile_from(cls, component: BaseComponent) -> BaseComponent:
  1375. """Walk through the component tree and memoize all stateful components.
  1376. Args:
  1377. component: The component to memoize.
  1378. Returns:
  1379. The memoized component tree.
  1380. """
  1381. if isinstance(component, Component):
  1382. if component._memoization_mode.recursive:
  1383. # Recursively memoize stateful children (default).
  1384. component.children = [
  1385. cls.compile_from(child) for child in component.children
  1386. ]
  1387. # Memoize this component if it depends on state.
  1388. stateful_component = cls.create(component)
  1389. if stateful_component is not None:
  1390. return stateful_component
  1391. return component
  1392. class MemoizationLeaf(Component):
  1393. """A component that does not separately memoize its children.
  1394. Any component which depends on finding the exact names of children
  1395. components within it, should be a memoization leaf so the compiler
  1396. does not replace the provided child tags with memoized tags.
  1397. During creation, a memoization leaf will mark itself as wanting to be
  1398. memoized if any of its children return any hooks.
  1399. """
  1400. _memoization_mode = MemoizationMode(recursive=False)
  1401. @classmethod
  1402. def create(cls, *children, **props) -> Component:
  1403. """Create a new memoization leaf component.
  1404. Args:
  1405. *children: The children of the component.
  1406. **props: The props of the component.
  1407. Returns:
  1408. The memoization leaf
  1409. """
  1410. comp = super().create(*children, **props)
  1411. if comp.get_hooks():
  1412. comp._memoization_mode = cls._memoization_mode.copy(
  1413. update={"disposition": MemoizationDisposition.ALWAYS}
  1414. )
  1415. return comp