component.py 55 KB

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