component.py 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312
  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 types import SimpleNamespace
  9. from typing import (
  10. Any,
  11. Callable,
  12. ClassVar,
  13. Dict,
  14. Iterator,
  15. List,
  16. Optional,
  17. Set,
  18. Type,
  19. Union,
  20. )
  21. import reflex.state
  22. from reflex.base import Base
  23. from reflex.compiler.templates import STATEFUL_COMPONENT
  24. from reflex.components.tags import Tag
  25. from reflex.constants import (
  26. Dirs,
  27. EventTriggers,
  28. Hooks,
  29. Imports,
  30. MemoizationDisposition,
  31. MemoizationMode,
  32. PageNames,
  33. )
  34. from reflex.event import (
  35. EventChain,
  36. EventHandler,
  37. EventSpec,
  38. call_event_fn,
  39. call_event_handler,
  40. get_handler_args,
  41. )
  42. from reflex.style import Style, format_as_emotion
  43. from reflex.utils import console, format, imports, types
  44. from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports
  45. from reflex.utils.serializers import serializer
  46. from reflex.vars import BaseVar, Var, VarData
  47. class BaseComponent(Base, ABC):
  48. """The base class for all Reflex components.
  49. This is something that can be rendered as a Component via the Reflex compiler.
  50. """
  51. # The children nested within the component.
  52. children: List[BaseComponent] = []
  53. # The library that the component is based on.
  54. library: Optional[str] = None
  55. # List here the non-react dependency needed by `library`
  56. lib_dependencies: List[str] = []
  57. # List here the dependencies that need to be transpiled by Next.js
  58. transpile_packages: List[str] = []
  59. # The tag to use when rendering the component.
  60. tag: Optional[str] = None
  61. @abstractmethod
  62. def render(self) -> dict:
  63. """Render the component.
  64. Returns:
  65. The dictionary for template of the component.
  66. """
  67. @abstractmethod
  68. def _get_all_hooks_internal(self) -> dict[str, None]:
  69. """Get the reflex internal hooks for the component and its children.
  70. Returns:
  71. The code that should appear just before user-defined hooks.
  72. """
  73. @abstractmethod
  74. def _get_all_hooks(self) -> dict[str, None]:
  75. """Get the React hooks for this component.
  76. Returns:
  77. The code that should appear just before returning the rendered component.
  78. """
  79. @abstractmethod
  80. def _get_all_imports(self) -> ParsedImportDict:
  81. """Get all the libraries and fields that are used by the component.
  82. Returns:
  83. The import dict with the required imports.
  84. """
  85. @abstractmethod
  86. def _get_all_dynamic_imports(self) -> set[str]:
  87. """Get dynamic imports for the component.
  88. Returns:
  89. The dynamic imports.
  90. """
  91. @abstractmethod
  92. def _get_all_custom_code(self) -> set[str]:
  93. """Get custom code for the component.
  94. Returns:
  95. The custom code.
  96. """
  97. @abstractmethod
  98. def _get_all_refs(self) -> set[str]:
  99. """Get the refs for the children of the component.
  100. Returns:
  101. The refs for the children.
  102. """
  103. class ComponentNamespace(SimpleNamespace):
  104. """A namespace to manage components with subcomponents."""
  105. def __hash__(self) -> int:
  106. """Get the hash of the namespace.
  107. Returns:
  108. The hash of the namespace.
  109. """
  110. return hash(self.__class__.__name__)
  111. def evaluate_style_namespaces(style: ComponentStyle) -> dict:
  112. """Evaluate namespaces in the style.
  113. Args:
  114. style: The style to evaluate.
  115. Returns:
  116. The evaluated style.
  117. """
  118. return {
  119. k.__call__ if isinstance(k, ComponentNamespace) else k: v
  120. for k, v in style.items()
  121. }
  122. # Map from component to styling.
  123. ComponentStyle = Dict[
  124. Union[str, Type[BaseComponent], Callable, ComponentNamespace], Any
  125. ]
  126. ComponentChild = Union[types.PrimitiveType, Var, BaseComponent]
  127. class Component(BaseComponent, ABC):
  128. """A component with style, event trigger and other props."""
  129. # The style of the component.
  130. style: Style = Style()
  131. # A mapping from event triggers to event chains.
  132. event_triggers: Dict[str, Union[EventChain, Var]] = {}
  133. # The alias for the tag.
  134. alias: Optional[str] = None
  135. # Whether the import is default or named.
  136. is_default: Optional[bool] = False
  137. # A unique key for the component.
  138. key: Any = None
  139. # The id for the component.
  140. id: Any = None
  141. # The class name for the component.
  142. class_name: Any = None
  143. # Special component props.
  144. special_props: Set[Var] = set()
  145. # Whether the component should take the focus once the page is loaded
  146. autofocus: bool = False
  147. # components that cannot be children
  148. _invalid_children: List[str] = []
  149. # only components that are allowed as children
  150. _valid_children: List[str] = []
  151. # only components that are allowed as parent
  152. _valid_parents: List[str] = []
  153. # props to change the name of
  154. _rename_props: Dict[str, str] = {}
  155. # custom attribute
  156. custom_attrs: Dict[str, Union[Var, str]] = {}
  157. # When to memoize this component and its children.
  158. _memoization_mode: MemoizationMode = MemoizationMode()
  159. # State class associated with this component instance
  160. State: Optional[Type[reflex.state.State]] = None
  161. def add_imports(self) -> ImportDict | list[ImportDict]:
  162. """Add imports for the component.
  163. This method should be implemented by subclasses to add new imports for the component.
  164. Implementations do NOT need to call super(). The result of calling
  165. add_imports in each parent class will be merged internally.
  166. Returns:
  167. The additional imports for this component subclass.
  168. The format of the return value is a dictionary where the keys are the
  169. library names (with optional npm-style version specifications) mapping
  170. to a single name to be imported, or a list names to be imported.
  171. For advanced use cases, the values can be ImportVar instances (for
  172. example, to provide an alias or mark that an import is the default
  173. export from the given library).
  174. ```python
  175. return {
  176. "react": "useEffect",
  177. "react-draggable": ["DraggableCore", rx.ImportVar(tag="Draggable", is_default=True)],
  178. }
  179. ```
  180. """
  181. return {}
  182. def add_hooks(self) -> list[str | Var]:
  183. """Add hooks inside the component function.
  184. Hooks are pieces of literal Javascript code that is inserted inside the
  185. React component function.
  186. Each logical hook should be a separate string in the list.
  187. Common strings will be deduplicated and inserted into the component
  188. function only once, so define const variables and other identical code
  189. in their own strings to avoid defining the same const or hook multiple
  190. times.
  191. If a hook depends on specific data from the component instance, be sure
  192. to use unique values inside the string to _avoid_ deduplication.
  193. Implementations do NOT need to call super(). The result of calling
  194. add_hooks in each parent class will be merged and deduplicated internally.
  195. Returns:
  196. The additional hooks for this component subclass.
  197. ```python
  198. return [
  199. "const [count, setCount] = useState(0);",
  200. "useEffect(() => { setCount((prev) => prev + 1); console.log(`mounted ${count} times`); }, []);",
  201. ]
  202. ```
  203. """
  204. return []
  205. def add_custom_code(self) -> list[str]:
  206. """Add custom Javascript code into the page that contains this component.
  207. Custom code is inserted at module level, after any imports.
  208. Each string of custom code is deduplicated per-page, so take care to
  209. avoid defining the same const or function differently from different
  210. component instances.
  211. Custom code is useful for defining global functions or constants which
  212. can then be referenced inside hooks or used by component vars.
  213. Implementations do NOT need to call super(). The result of calling
  214. add_custom_code in each parent class will be merged and deduplicated internally.
  215. Returns:
  216. The additional custom code for this component subclass.
  217. ```python
  218. return [
  219. "const translatePoints = (event) => { return { x: event.clientX, y: event.clientY }; };",
  220. ]
  221. ```
  222. """
  223. return []
  224. @classmethod
  225. def __init_subclass__(cls, **kwargs):
  226. """Set default properties.
  227. Args:
  228. **kwargs: The kwargs to pass to the superclass.
  229. """
  230. super().__init_subclass__(**kwargs)
  231. # Get all the props for the component.
  232. props = cls.get_props()
  233. # Convert fields to props, setting default values.
  234. for field in cls.get_fields().values():
  235. # If the field is not a component prop, skip it.
  236. if field.name not in props:
  237. continue
  238. # Set default values for any props.
  239. if types._issubclass(field.type_, Var):
  240. field.required = False
  241. field.default = Var.create(
  242. field.default, _var_is_string=isinstance(field.default, str)
  243. )
  244. elif types._issubclass(field.type_, EventHandler):
  245. field.required = False
  246. # Ensure renamed props from parent classes are applied to the subclass.
  247. if cls._rename_props:
  248. inherited_rename_props = {}
  249. for parent in reversed(cls.mro()):
  250. if issubclass(parent, Component) and parent._rename_props:
  251. inherited_rename_props.update(parent._rename_props)
  252. cls._rename_props = inherited_rename_props
  253. def __init__(self, *args, **kwargs):
  254. """Initialize the component.
  255. Args:
  256. *args: Args to initialize the component.
  257. **kwargs: Kwargs to initialize the component.
  258. Raises:
  259. TypeError: If an invalid prop is passed.
  260. ValueError: If an event trigger passed is not valid.
  261. """
  262. # Set the id and children initially.
  263. children = kwargs.get("children", [])
  264. initial_kwargs = {
  265. "id": kwargs.get("id"),
  266. "children": children,
  267. **{
  268. prop: Var.create(
  269. kwargs[prop],
  270. _var_is_string=False if isinstance(kwargs[prop], str) else None,
  271. )
  272. for prop in self.get_initial_props()
  273. if prop in kwargs
  274. },
  275. }
  276. super().__init__(**initial_kwargs)
  277. self._validate_component_children(children)
  278. # Get the component fields, triggers, and props.
  279. fields = self.get_fields()
  280. component_specific_triggers = self.get_event_triggers()
  281. props = self.get_props()
  282. # Add any events triggers.
  283. if "event_triggers" not in kwargs:
  284. kwargs["event_triggers"] = {}
  285. kwargs["event_triggers"] = kwargs["event_triggers"].copy()
  286. # Iterate through the kwargs and set the props.
  287. for key, value in kwargs.items():
  288. if (
  289. key.startswith("on_")
  290. and key not in component_specific_triggers
  291. and key not in props
  292. ):
  293. raise ValueError(
  294. f"The {(comp_name := type(self).__name__)} does not take in an `{key}` event trigger. If {comp_name}"
  295. f" is a third party component make sure to add `{key}` to the component's event triggers. "
  296. f"visit https://reflex.dev/docs/wrapping-react/guide/#event-triggers for more info."
  297. )
  298. if key in component_specific_triggers:
  299. # Event triggers are bound to event chains.
  300. field_type = EventChain
  301. elif key in props:
  302. # Set the field type.
  303. field_type = fields[key].type_
  304. else:
  305. continue
  306. # Check whether the key is a component prop.
  307. if types._issubclass(field_type, Var):
  308. # Used to store the passed types if var type is a union.
  309. passed_types = None
  310. try:
  311. # Try to create a var from the value.
  312. kwargs[key] = Var.create(
  313. value,
  314. _var_is_string=False if isinstance(value, str) else None,
  315. )
  316. # Check that the var type is not None.
  317. if kwargs[key] is None:
  318. raise TypeError
  319. expected_type = fields[key].outer_type_.__args__[0]
  320. # validate literal fields.
  321. types.validate_literal(
  322. key, value, expected_type, type(self).__name__
  323. )
  324. # Get the passed type and the var type.
  325. passed_type = kwargs[key]._var_type
  326. expected_type = (
  327. type(expected_type.__args__[0])
  328. if types.is_literal(expected_type)
  329. else expected_type
  330. )
  331. except TypeError:
  332. # If it is not a valid var, check the base types.
  333. passed_type = type(value)
  334. expected_type = fields[key].outer_type_
  335. if types.is_union(passed_type):
  336. # We need to check all possible types in the union.
  337. passed_types = (
  338. arg
  339. for arg in passed_type.__args__ # type: ignore
  340. if arg is not type(None)
  341. )
  342. if (
  343. # If the passed var is a union, check if all possible types are valid.
  344. passed_types
  345. and not all(
  346. types._issubclass(pt, expected_type) for pt in passed_types
  347. )
  348. ) or (
  349. # Else just check if the passed var type is valid.
  350. not passed_types
  351. and not types._issubclass(passed_type, expected_type)
  352. ):
  353. value_name = value._var_name if isinstance(value, Var) else value
  354. raise TypeError(
  355. f"Invalid var passed for prop {type(self).__name__}.{key}, expected type {expected_type}, got value {value_name} of type {passed_types or passed_type}."
  356. )
  357. # Check if the key is an event trigger.
  358. if key in component_specific_triggers:
  359. # Temporarily disable full control for event triggers.
  360. kwargs["event_triggers"][key] = self._create_event_chain(
  361. value=value, # type: ignore
  362. args_spec=component_specific_triggers[key],
  363. )
  364. # Remove any keys that were added as events.
  365. for key in kwargs["event_triggers"]:
  366. del kwargs[key]
  367. # Add style props to the component.
  368. style = kwargs.get("style", {})
  369. if isinstance(style, List):
  370. # Merge styles, the later ones overriding keys in the earlier ones.
  371. style = {k: v for style_dict in style for k, v in style_dict.items()}
  372. kwargs["style"] = Style(
  373. {
  374. **self.get_fields()["style"].default,
  375. **style,
  376. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  377. }
  378. )
  379. if "custom_attrs" not in kwargs:
  380. kwargs["custom_attrs"] = {}
  381. # Convert class_name to str if it's list
  382. class_name = kwargs.get("class_name", "")
  383. if isinstance(class_name, (List, tuple)):
  384. kwargs["class_name"] = " ".join(class_name)
  385. # Construct the component.
  386. super().__init__(*args, **kwargs)
  387. def _create_event_chain(
  388. self,
  389. args_spec: Any,
  390. value: Union[
  391. Var, EventHandler, EventSpec, List[Union[EventHandler, EventSpec]], Callable
  392. ],
  393. ) -> Union[EventChain, Var]:
  394. """Create an event chain from a variety of input types.
  395. Args:
  396. args_spec: The args_spec of the event trigger being bound.
  397. value: The value to create the event chain from.
  398. Returns:
  399. The event chain.
  400. Raises:
  401. ValueError: If the value is not a valid event chain.
  402. """
  403. # If it's an event chain var, return it.
  404. if isinstance(value, Var):
  405. if value._var_type is not EventChain:
  406. raise ValueError(f"Invalid event chain: {value}")
  407. return value
  408. elif isinstance(value, EventChain):
  409. # Trust that the caller knows what they're doing passing an EventChain directly
  410. return value
  411. # If the input is a single event handler, wrap it in a list.
  412. if isinstance(value, (EventHandler, EventSpec)):
  413. value = [value]
  414. # If the input is a list of event handlers, create an event chain.
  415. if isinstance(value, List):
  416. events: list[EventSpec] = []
  417. for v in value:
  418. if isinstance(v, (EventHandler, EventSpec)):
  419. # Call the event handler to get the event.
  420. try:
  421. event = call_event_handler(v, args_spec)
  422. except ValueError as err:
  423. raise ValueError(
  424. f" {err} defined in the `{type(self).__name__}` component"
  425. ) from err
  426. # Add the event to the chain.
  427. events.append(event)
  428. elif isinstance(v, Callable):
  429. # Call the lambda to get the event chain.
  430. result = call_event_fn(v, args_spec)
  431. if isinstance(result, Var):
  432. raise ValueError(
  433. f"Invalid event chain: {v}. Cannot use a Var-returning "
  434. "lambda inside an EventChain list."
  435. )
  436. events.extend(result)
  437. else:
  438. raise ValueError(f"Invalid event: {v}")
  439. # If the input is a callable, create an event chain.
  440. elif isinstance(value, Callable):
  441. result = call_event_fn(value, args_spec)
  442. if isinstance(result, Var):
  443. # Recursively call this function if the lambda returned an EventChain Var.
  444. return self._create_event_chain(args_spec, result)
  445. events = result
  446. # Otherwise, raise an error.
  447. else:
  448. raise ValueError(f"Invalid event chain: {value}")
  449. # Add args to the event specs if necessary.
  450. events = [e.with_args(get_handler_args(e)) for e in events]
  451. # Collect event_actions from each spec
  452. event_actions = {}
  453. for e in events:
  454. event_actions.update(e.event_actions)
  455. # Return the event chain.
  456. if isinstance(args_spec, Var):
  457. return EventChain(
  458. events=events,
  459. args_spec=None,
  460. event_actions=event_actions,
  461. )
  462. else:
  463. return EventChain(
  464. events=events,
  465. args_spec=args_spec,
  466. event_actions=event_actions,
  467. )
  468. def get_event_triggers(self) -> Dict[str, Any]:
  469. """Get the event triggers for the component.
  470. Returns:
  471. The event triggers.
  472. """
  473. default_triggers = {
  474. EventTriggers.ON_FOCUS: lambda: [],
  475. EventTriggers.ON_BLUR: lambda: [],
  476. EventTriggers.ON_CLICK: lambda: [],
  477. EventTriggers.ON_CONTEXT_MENU: lambda: [],
  478. EventTriggers.ON_DOUBLE_CLICK: lambda: [],
  479. EventTriggers.ON_MOUSE_DOWN: lambda: [],
  480. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  481. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  482. EventTriggers.ON_MOUSE_MOVE: lambda: [],
  483. EventTriggers.ON_MOUSE_OUT: lambda: [],
  484. EventTriggers.ON_MOUSE_OVER: lambda: [],
  485. EventTriggers.ON_MOUSE_UP: lambda: [],
  486. EventTriggers.ON_SCROLL: lambda: [],
  487. EventTriggers.ON_MOUNT: lambda: [],
  488. EventTriggers.ON_UNMOUNT: lambda: [],
  489. }
  490. # Look for component specific triggers,
  491. # e.g. variable declared as EventHandler types.
  492. for field in self.get_fields().values():
  493. if types._issubclass(field.type_, EventHandler):
  494. args_spec = None
  495. annotation = field.annotation
  496. if hasattr(annotation, "__metadata__"):
  497. args_spec = annotation.__metadata__[0]
  498. default_triggers[field.name] = args_spec or (lambda: [])
  499. return default_triggers
  500. def __repr__(self) -> str:
  501. """Represent the component in React.
  502. Returns:
  503. The code to render the component.
  504. """
  505. return format.json_dumps(self.render())
  506. def __str__(self) -> str:
  507. """Represent the component in React.
  508. Returns:
  509. The code to render the component.
  510. """
  511. from reflex.compiler.compiler import _compile_component
  512. return _compile_component(self)
  513. def _apply_theme(self, theme: Optional[Component]):
  514. """Apply the theme to this component.
  515. Deprecated. Use add_style instead.
  516. Args:
  517. theme: The theme to apply.
  518. """
  519. pass
  520. def apply_theme(self, theme: Optional[Component]):
  521. """Apply a theme to the component and its children.
  522. Args:
  523. theme: The theme to apply.
  524. """
  525. self._apply_theme(theme)
  526. for child in self.children:
  527. if isinstance(child, Component):
  528. child.apply_theme(theme)
  529. def _exclude_props(self) -> list[str]:
  530. """Props to exclude when adding the component props to the Tag.
  531. Returns:
  532. A list of component props to exclude.
  533. """
  534. return []
  535. def _render(self, props: dict[str, Any] | None = None) -> Tag:
  536. """Define how to render the component in React.
  537. Args:
  538. props: The props to render (if None, then use get_props).
  539. Returns:
  540. The tag to render.
  541. """
  542. # Create the base tag.
  543. tag = Tag(
  544. name=self.tag if not self.alias else self.alias,
  545. special_props=self.special_props,
  546. )
  547. if props is None:
  548. # Add component props to the tag.
  549. props = {
  550. attr[:-1] if attr.endswith("_") else attr: getattr(self, attr)
  551. for attr in self.get_props()
  552. }
  553. # Add ref to element if `id` is not None.
  554. ref = self.get_ref()
  555. if ref is not None:
  556. props["ref"] = Var.create(
  557. ref, _var_is_local=False, _var_is_string=False
  558. )
  559. else:
  560. props = props.copy()
  561. props.update(
  562. **{
  563. trigger: handler
  564. for trigger, handler in self.event_triggers.items()
  565. if trigger not in {EventTriggers.ON_MOUNT, EventTriggers.ON_UNMOUNT}
  566. },
  567. key=self.key,
  568. id=self.id,
  569. class_name=self.class_name,
  570. )
  571. props.update(self._get_style())
  572. props.update(self.custom_attrs)
  573. # remove excluded props from prop dict before adding to tag.
  574. for prop_to_exclude in self._exclude_props():
  575. props.pop(prop_to_exclude, None)
  576. return tag.add_props(**props)
  577. @classmethod
  578. @lru_cache(maxsize=None)
  579. def get_props(cls) -> Set[str]:
  580. """Get the unique fields for the component.
  581. Returns:
  582. The unique fields.
  583. """
  584. return set(cls.get_fields()) - set(Component.get_fields())
  585. @classmethod
  586. @lru_cache(maxsize=None)
  587. def get_initial_props(cls) -> Set[str]:
  588. """Get the initial props to set for the component.
  589. Returns:
  590. The initial props to set.
  591. """
  592. return set()
  593. @classmethod
  594. @lru_cache(maxsize=None)
  595. def get_component_props(cls) -> set[str]:
  596. """Get the props that expected a component as value.
  597. Returns:
  598. The components props.
  599. """
  600. return {
  601. name
  602. for name, field in cls.get_fields().items()
  603. if name in cls.get_props()
  604. and types._issubclass(field.outer_type_, Component)
  605. }
  606. @classmethod
  607. def create(cls, *children, **props) -> Component:
  608. """Create the component.
  609. Args:
  610. *children: The children of the component.
  611. **props: The props of the component.
  612. Returns:
  613. The component.
  614. """
  615. # Import here to avoid circular imports.
  616. from reflex.components.base.bare import Bare
  617. from reflex.components.base.fragment import Fragment
  618. from reflex.utils.exceptions import ComponentTypeError
  619. # Translate deprecated props to new names.
  620. new_prop_names = [
  621. prop for prop in cls.get_props() if prop in ["type", "min", "max"]
  622. ]
  623. for prop in new_prop_names:
  624. under_prop = f"{prop}_"
  625. if under_prop in props:
  626. console.deprecate(
  627. f"Underscore suffix for prop `{under_prop}`",
  628. reason=f"for consistency. Use `{prop}` instead.",
  629. deprecation_version="0.4.0",
  630. removal_version="0.6.0",
  631. dedupe=False,
  632. )
  633. props[prop] = props.pop(under_prop)
  634. # Filter out None props
  635. props = {key: value for key, value in props.items() if value is not None}
  636. def validate_children(children):
  637. for child in children:
  638. if isinstance(child, tuple):
  639. validate_children(child)
  640. # Make sure the child is a valid type.
  641. if not types._isinstance(child, ComponentChild):
  642. raise ComponentTypeError(
  643. "Children of Reflex components must be other components, "
  644. "state vars, or primitive Python types. "
  645. f"Got child {child} of type {type(child)}.",
  646. )
  647. # Validate all the children.
  648. validate_children(children)
  649. children = [
  650. (
  651. child
  652. if isinstance(child, Component)
  653. else (
  654. Fragment.create(*child)
  655. if isinstance(child, tuple)
  656. else Bare.create(contents=Var.create(child, _var_is_string=True))
  657. )
  658. )
  659. for child in children
  660. ]
  661. return cls(children=children, **props)
  662. def add_style(self) -> dict[str, Any] | None:
  663. """Add style to the component.
  664. Downstream components can override this method to return a style dict
  665. that will be applied to the component.
  666. Returns:
  667. The style to add.
  668. """
  669. return None
  670. def _add_style(self) -> Style:
  671. """Call add_style for all bases in the MRO.
  672. Downstream components should NOT override. Use add_style instead.
  673. Returns:
  674. The style to add.
  675. """
  676. styles = []
  677. # Walk the MRO to call all `add_style` methods.
  678. for base in self._iter_parent_classes_with_method("add_style"):
  679. s = base.add_style(self) # type: ignore
  680. if s is not None:
  681. styles.append(s)
  682. _style = Style()
  683. for s in reversed(styles):
  684. _style.update(s)
  685. return _style
  686. def _get_component_style(self, styles: ComponentStyle) -> Style | None:
  687. """Get the style to the component from `App.style`.
  688. Args:
  689. styles: The style to apply.
  690. Returns:
  691. The style of the component.
  692. """
  693. component_style = None
  694. if type(self) in styles:
  695. component_style = Style(styles[type(self)])
  696. if self.create in styles:
  697. component_style = Style(styles[self.create])
  698. return component_style
  699. def _add_style_recursive(
  700. self, style: ComponentStyle, theme: Optional[Component] = None
  701. ) -> Component:
  702. """Add additional style to the component and its children.
  703. Apply order is as follows (with the latest overriding the earliest):
  704. 1. Default style from `_add_style`/`add_style`.
  705. 2. User-defined style from `App.style`.
  706. 3. User-defined style from `Component.style`.
  707. 4. style dict and css props passed to the component instance.
  708. Args:
  709. style: A dict from component to styling.
  710. theme: The theme to apply. (for retro-compatibility with deprecated _apply_theme API)
  711. Raises:
  712. UserWarning: If `_add_style` has been overridden.
  713. Returns:
  714. The component with the additional style.
  715. """
  716. # 1. Default style from `_add_style`/`add_style`.
  717. if type(self)._add_style != Component._add_style:
  718. raise UserWarning(
  719. "Do not override _add_style directly. Use add_style instead."
  720. )
  721. new_style = self._add_style()
  722. style_vars = [new_style._var_data]
  723. # 2. User-defined style from `App.style`.
  724. component_style = self._get_component_style(style)
  725. if component_style:
  726. new_style.update(component_style)
  727. style_vars.append(component_style._var_data)
  728. # 3. User-defined style from `Component.style`.
  729. # Apply theme for retro-compatibility with deprecated _apply_theme API
  730. if type(self)._apply_theme != Component._apply_theme:
  731. console.deprecate(
  732. f"{self.__class__.__name__}._apply_theme",
  733. reason="use add_style instead",
  734. deprecation_version="0.5.0",
  735. removal_version="0.6.0",
  736. )
  737. self._apply_theme(theme)
  738. # 4. style dict and css props passed to the component instance.
  739. new_style.update(self.style)
  740. style_vars.append(self.style._var_data)
  741. new_style._var_data = VarData.merge(*style_vars)
  742. # Assign the new style
  743. self.style = new_style
  744. # Recursively add style to the children.
  745. for child in self.children:
  746. # Skip BaseComponent and StatefulComponent children.
  747. if not isinstance(child, Component):
  748. continue
  749. child._add_style_recursive(style, theme)
  750. return self
  751. def _get_style(self) -> dict:
  752. """Get the style for the component.
  753. Returns:
  754. The dictionary of the component style as value and the style notation as key.
  755. """
  756. if isinstance(self.style, Var):
  757. return {"css": self.style}
  758. return {"css": Var.create(format_as_emotion(self.style))}
  759. def render(self) -> Dict:
  760. """Render the component.
  761. Returns:
  762. The dictionary for template of component.
  763. """
  764. tag = self._render()
  765. rendered_dict = dict(
  766. tag.set(
  767. children=[child.render() for child in self.children],
  768. contents=str(tag.contents),
  769. props=tag.format_props(),
  770. ),
  771. autofocus=self.autofocus,
  772. )
  773. self._replace_prop_names(rendered_dict)
  774. return rendered_dict
  775. def _replace_prop_names(self, rendered_dict) -> None:
  776. """Replace the prop names in the render dictionary.
  777. Args:
  778. rendered_dict: The render dictionary with all the component props and event handlers.
  779. """
  780. # fast path
  781. if not self._rename_props:
  782. return
  783. for ix, prop in enumerate(rendered_dict["props"]):
  784. for old_prop, new_prop in self._rename_props.items():
  785. if prop.startswith(old_prop):
  786. rendered_dict["props"][ix] = prop.replace(old_prop, new_prop, 1)
  787. def _validate_component_children(self, children: List[Component]):
  788. """Validate the children components.
  789. Args:
  790. children: The children of the component.
  791. """
  792. from reflex.components.base.fragment import Fragment
  793. from reflex.components.core.cond import Cond
  794. from reflex.components.core.foreach import Foreach
  795. from reflex.components.core.match import Match
  796. no_valid_parents_defined = all(child._valid_parents == [] for child in children)
  797. if (
  798. not self._invalid_children
  799. and not self._valid_children
  800. and no_valid_parents_defined
  801. ):
  802. return
  803. comp_name = type(self).__name__
  804. allowed_components = [
  805. comp.__name__ for comp in (Fragment, Foreach, Cond, Match)
  806. ]
  807. def validate_child(child):
  808. child_name = type(child).__name__
  809. # Iterate through the immediate children of fragment
  810. if isinstance(child, Fragment):
  811. for c in child.children:
  812. validate_child(c)
  813. if isinstance(child, Cond):
  814. validate_child(child.comp1)
  815. validate_child(child.comp2)
  816. if isinstance(child, Match):
  817. for cases in child.match_cases:
  818. validate_child(cases[-1])
  819. validate_child(child.default)
  820. if self._invalid_children and child_name in self._invalid_children:
  821. raise ValueError(
  822. f"The component `{comp_name}` cannot have `{child_name}` as a child component"
  823. )
  824. if self._valid_children and child_name not in [
  825. *self._valid_children,
  826. *allowed_components,
  827. ]:
  828. valid_child_list = ", ".join(
  829. [f"`{v_child}`" for v_child in self._valid_children]
  830. )
  831. raise ValueError(
  832. f"The component `{comp_name}` only allows the components: {valid_child_list} as children. Got `{child_name}` instead."
  833. )
  834. if child._valid_parents and comp_name not in [
  835. *child._valid_parents,
  836. *allowed_components,
  837. ]:
  838. valid_parent_list = ", ".join(
  839. [f"`{v_parent}`" for v_parent in child._valid_parents]
  840. )
  841. raise ValueError(
  842. f"The component `{child_name}` can only be a child of the components: {valid_parent_list}. Got `{comp_name}` instead."
  843. )
  844. for child in children:
  845. validate_child(child)
  846. @staticmethod
  847. def _get_vars_from_event_triggers(
  848. event_triggers: dict[str, EventChain | Var],
  849. ) -> Iterator[tuple[str, list[Var]]]:
  850. """Get the Vars associated with each event trigger.
  851. Args:
  852. event_triggers: The event triggers from the component instance.
  853. Yields:
  854. tuple of (event_name, event_vars)
  855. """
  856. for event_trigger, event in event_triggers.items():
  857. if isinstance(event, Var):
  858. yield event_trigger, [event]
  859. elif isinstance(event, EventChain):
  860. event_args = []
  861. for spec in event.events:
  862. for args in spec.args:
  863. event_args.extend(args)
  864. yield event_trigger, event_args
  865. def _get_vars(self, include_children: bool = False) -> list[Var]:
  866. """Walk all Vars used in this component.
  867. Args:
  868. include_children: Whether to include Vars from children.
  869. Returns:
  870. Each var referenced by the component (props, styles, event handlers).
  871. """
  872. vars = getattr(self, "__vars", None)
  873. if vars is not None:
  874. return vars
  875. vars = self.__vars = []
  876. # Get Vars associated with event trigger arguments.
  877. for _, event_vars in self._get_vars_from_event_triggers(self.event_triggers):
  878. vars.extend(event_vars)
  879. # Get Vars associated with component props.
  880. for prop in self.get_props():
  881. prop_var = getattr(self, prop)
  882. if isinstance(prop_var, Var):
  883. vars.append(prop_var)
  884. # Style keeps track of its own VarData instance, so embed in a temp Var that is yielded.
  885. if isinstance(self.style, dict) and self.style or isinstance(self.style, Var):
  886. vars.append(
  887. BaseVar(
  888. _var_name="style",
  889. _var_type=str,
  890. _var_data=self.style._var_data,
  891. )
  892. )
  893. # Special props are always Var instances.
  894. vars.extend(self.special_props)
  895. # Get Vars associated with common Component props.
  896. for comp_prop in (
  897. self.class_name,
  898. self.id,
  899. self.key,
  900. self.autofocus,
  901. *self.custom_attrs.values(),
  902. ):
  903. if isinstance(comp_prop, Var):
  904. vars.append(comp_prop)
  905. elif isinstance(comp_prop, str):
  906. # Collapse VarData encoded in f-strings.
  907. var = Var.create_safe(
  908. comp_prop, _var_is_string=isinstance(comp_prop, str)
  909. )
  910. if var._var_data is not None:
  911. vars.append(var)
  912. # Get Vars associated with children.
  913. if include_children:
  914. for child in self.children:
  915. if not isinstance(child, Component):
  916. continue
  917. vars.extend(child._get_vars(include_children=include_children))
  918. return vars
  919. def _event_trigger_values_use_state(self) -> bool:
  920. """Check if the values of a component's event trigger use state.
  921. Returns:
  922. True if any of the component's event trigger values uses State.
  923. """
  924. for trigger in self.event_triggers.values():
  925. if isinstance(trigger, EventChain):
  926. for event in trigger.events:
  927. if event.handler.state_full_name:
  928. return True
  929. elif isinstance(trigger, Var) and trigger._var_state:
  930. return True
  931. return False
  932. def _has_stateful_event_triggers(self):
  933. """Check if component or children have any event triggers that use state.
  934. Returns:
  935. True if the component or children have any event triggers that uses state.
  936. """
  937. if self.event_triggers and self._event_trigger_values_use_state():
  938. return True
  939. else:
  940. for child in self.children:
  941. if (
  942. isinstance(child, Component)
  943. and child._has_stateful_event_triggers()
  944. ):
  945. return True
  946. return False
  947. @classmethod
  948. def _iter_parent_classes_with_method(cls, method: str) -> Iterator[Type[Component]]:
  949. """Iterate through parent classes that define a given method.
  950. Used for handling the `add_*` API functions that internally simulate a super() call chain.
  951. Args:
  952. method: The method to look for.
  953. Yields:
  954. The parent classes that define the method (differently than the base).
  955. """
  956. seen_methods = set([getattr(Component, method)])
  957. for clz in cls.mro():
  958. if clz is Component:
  959. break
  960. if not issubclass(clz, Component):
  961. continue
  962. method_func = getattr(clz, method, None)
  963. if not callable(method_func) or method_func in seen_methods:
  964. continue
  965. seen_methods.add(method_func)
  966. yield clz
  967. def _get_custom_code(self) -> str | None:
  968. """Get custom code for the component.
  969. Returns:
  970. The custom code.
  971. """
  972. return None
  973. def _get_all_custom_code(self) -> set[str]:
  974. """Get custom code for the component and its children.
  975. Returns:
  976. The custom code.
  977. """
  978. # Store the code in a set to avoid duplicates.
  979. code = set()
  980. # Add the custom code for this component.
  981. custom_code = self._get_custom_code()
  982. if custom_code is not None:
  983. code.add(custom_code)
  984. # Add the custom code from add_custom_code method.
  985. for clz in self._iter_parent_classes_with_method("add_custom_code"):
  986. for item in clz.add_custom_code(self):
  987. code.add(item)
  988. # Add the custom code for the children.
  989. for child in self.children:
  990. code |= child._get_all_custom_code()
  991. # Return the code.
  992. return code
  993. def _get_dynamic_imports(self) -> str | None:
  994. """Get dynamic import for the component.
  995. Returns:
  996. The dynamic import.
  997. """
  998. return None
  999. def _get_all_dynamic_imports(self) -> Set[str]:
  1000. """Get dynamic imports for the component and its children.
  1001. Returns:
  1002. The dynamic imports.
  1003. """
  1004. # Store the import in a set to avoid duplicates.
  1005. dynamic_imports = set()
  1006. # Get dynamic import for this component.
  1007. dynamic_import = self._get_dynamic_imports()
  1008. if dynamic_import:
  1009. dynamic_imports.add(dynamic_import)
  1010. # Get the dynamic imports from children
  1011. for child in self.children:
  1012. dynamic_imports |= child._get_all_dynamic_imports()
  1013. for prop in self.get_component_props():
  1014. if getattr(self, prop) is not None:
  1015. dynamic_imports |= getattr(self, prop)._get_all_dynamic_imports()
  1016. # Return the dynamic imports
  1017. return dynamic_imports
  1018. def _get_props_imports(self) -> List[ParsedImportDict]:
  1019. """Get the imports needed for components props.
  1020. Returns:
  1021. The imports for the components props of the component.
  1022. """
  1023. return [
  1024. getattr(self, prop)._get_all_imports()
  1025. for prop in self.get_component_props()
  1026. if getattr(self, prop) is not None
  1027. ]
  1028. def _should_transpile(self, dep: str | None) -> bool:
  1029. """Check if a dependency should be transpiled.
  1030. Args:
  1031. dep: The dependency to check.
  1032. Returns:
  1033. True if the dependency should be transpiled.
  1034. """
  1035. return (
  1036. dep in self.transpile_packages
  1037. or format.format_library_name(dep or "") in self.transpile_packages
  1038. )
  1039. def _get_dependencies_imports(self) -> ParsedImportDict:
  1040. """Get the imports from lib_dependencies for installing.
  1041. Returns:
  1042. The dependencies imports of the component.
  1043. """
  1044. return {
  1045. dep: [
  1046. ImportVar(
  1047. tag=None,
  1048. render=False,
  1049. transpile=self._should_transpile(dep),
  1050. )
  1051. ]
  1052. for dep in self.lib_dependencies
  1053. }
  1054. def _get_hooks_imports(self) -> ParsedImportDict:
  1055. """Get the imports required by certain hooks.
  1056. Returns:
  1057. The imports required for all selected hooks.
  1058. """
  1059. _imports = {}
  1060. if self._get_ref_hook():
  1061. # Handle hooks needed for attaching react refs to DOM nodes.
  1062. _imports.setdefault("react", set()).add(ImportVar(tag="useRef"))
  1063. _imports.setdefault(f"/{Dirs.STATE_PATH}", set()).add(ImportVar(tag="refs"))
  1064. if self._get_mount_lifecycle_hook():
  1065. # Handle hooks for `on_mount` / `on_unmount`.
  1066. _imports.setdefault("react", set()).add(ImportVar(tag="useEffect"))
  1067. if self._get_special_hooks():
  1068. # Handle additional internal hooks (autofocus, etc).
  1069. _imports.setdefault("react", set()).update(
  1070. {
  1071. ImportVar(tag="useRef"),
  1072. ImportVar(tag="useEffect"),
  1073. },
  1074. )
  1075. other_imports = []
  1076. user_hooks = self._get_hooks()
  1077. if (
  1078. user_hooks is not None
  1079. and isinstance(user_hooks, Var)
  1080. and user_hooks._var_data is not None
  1081. and user_hooks._var_data.imports
  1082. ):
  1083. other_imports.append(user_hooks._var_data.imports)
  1084. other_imports.extend(
  1085. hook_imports for hook_imports in self._get_added_hooks().values()
  1086. )
  1087. return imports.merge_imports(_imports, *other_imports)
  1088. def _get_imports(self) -> ParsedImportDict:
  1089. """Get all the libraries and fields that are used by the component.
  1090. Returns:
  1091. The imports needed by the component.
  1092. """
  1093. _imports = {}
  1094. # Import this component's tag from the main library.
  1095. if self.library is not None and self.tag is not None:
  1096. _imports[self.library] = {self.import_var}
  1097. # Get static imports required for event processing.
  1098. event_imports = Imports.EVENTS if self.event_triggers else {}
  1099. # Collect imports from Vars used directly by this component.
  1100. var_imports = [
  1101. var._var_data.imports for var in self._get_vars() if var._var_data
  1102. ]
  1103. added_import_dicts: list[ParsedImportDict] = []
  1104. for clz in self._iter_parent_classes_with_method("add_imports"):
  1105. list_of_import_dict = clz.add_imports(self)
  1106. if not isinstance(list_of_import_dict, list):
  1107. list_of_import_dict = [list_of_import_dict]
  1108. for import_dict in list_of_import_dict:
  1109. added_import_dicts.append(parse_imports(import_dict))
  1110. return imports.merge_imports(
  1111. *self._get_props_imports(),
  1112. self._get_dependencies_imports(),
  1113. self._get_hooks_imports(),
  1114. _imports,
  1115. event_imports,
  1116. *var_imports,
  1117. *added_import_dicts,
  1118. )
  1119. def _get_all_imports(self, collapse: bool = False) -> ParsedImportDict:
  1120. """Get all the libraries and fields that are used by the component and its children.
  1121. Args:
  1122. collapse: Whether to collapse the imports by removing duplicates.
  1123. Returns:
  1124. The import dict with the required imports.
  1125. """
  1126. _imports = imports.merge_imports(
  1127. self._get_imports(), *[child._get_all_imports() for child in self.children]
  1128. )
  1129. return imports.collapse_imports(_imports) if collapse else _imports
  1130. def _get_mount_lifecycle_hook(self) -> str | None:
  1131. """Generate the component lifecycle hook.
  1132. Returns:
  1133. The useEffect hook for managing `on_mount` and `on_unmount` events.
  1134. """
  1135. # pop on_mount and on_unmount from event_triggers since these are handled by
  1136. # hooks, not as actually props in the component
  1137. on_mount = self.event_triggers.get(EventTriggers.ON_MOUNT, None)
  1138. on_unmount = self.event_triggers.get(EventTriggers.ON_UNMOUNT, None)
  1139. if on_mount is not None:
  1140. on_mount = format.format_event_chain(on_mount)
  1141. if on_unmount is not None:
  1142. on_unmount = format.format_event_chain(on_unmount)
  1143. if on_mount is not None or on_unmount is not None:
  1144. return f"""
  1145. useEffect(() => {{
  1146. {on_mount or ""}
  1147. return () => {{
  1148. {on_unmount or ""}
  1149. }}
  1150. }}, []);"""
  1151. def _get_ref_hook(self) -> str | None:
  1152. """Generate the ref hook for the component.
  1153. Returns:
  1154. The useRef hook for managing refs.
  1155. """
  1156. ref = self.get_ref()
  1157. if ref is not None:
  1158. return f"const {ref} = useRef(null); {str(Var.create_safe(ref, _var_is_string=False).as_ref())} = {ref};"
  1159. def _get_vars_hooks(self) -> dict[str, None]:
  1160. """Get the hooks required by vars referenced in this component.
  1161. Returns:
  1162. The hooks for the vars.
  1163. """
  1164. vars_hooks = {}
  1165. for var in self._get_vars():
  1166. if var._var_data:
  1167. vars_hooks.update(var._var_data.hooks)
  1168. return vars_hooks
  1169. def _get_events_hooks(self) -> dict[str, None]:
  1170. """Get the hooks required by events referenced in this component.
  1171. Returns:
  1172. The hooks for the events.
  1173. """
  1174. return {Hooks.EVENTS: None} if self.event_triggers else {}
  1175. def _get_special_hooks(self) -> dict[str, None]:
  1176. """Get the hooks required by special actions referenced in this component.
  1177. Returns:
  1178. The hooks for special actions.
  1179. """
  1180. return {Hooks.AUTOFOCUS: None} if self.autofocus else {}
  1181. def _get_hooks_internal(self) -> dict[str, None]:
  1182. """Get the React hooks for this component managed by the framework.
  1183. Downstream components should NOT override this method to avoid breaking
  1184. framework functionality.
  1185. Returns:
  1186. The internally managed hooks.
  1187. """
  1188. return {
  1189. **{
  1190. hook: None
  1191. for hook in [self._get_ref_hook(), self._get_mount_lifecycle_hook()]
  1192. if hook is not None
  1193. },
  1194. **self._get_vars_hooks(),
  1195. **self._get_events_hooks(),
  1196. **self._get_special_hooks(),
  1197. }
  1198. def _get_added_hooks(self) -> dict[str, ImportDict]:
  1199. """Get the hooks added via `add_hooks` method.
  1200. Returns:
  1201. The deduplicated hooks and imports added by the component and parent components.
  1202. """
  1203. code = {}
  1204. def extract_var_hooks(hook: Var):
  1205. _imports = {}
  1206. if hook._var_data is not None:
  1207. for sub_hook in hook._var_data.hooks:
  1208. code[sub_hook] = {}
  1209. if hook._var_data.imports:
  1210. _imports = hook._var_data.imports
  1211. if str(hook) in code:
  1212. code[str(hook)] = imports.merge_imports(code[str(hook)], _imports)
  1213. else:
  1214. code[str(hook)] = _imports
  1215. # Add the hook code from add_hooks for each parent class (this is reversed to preserve
  1216. # the order of the hooks in the final output)
  1217. for clz in reversed(tuple(self._iter_parent_classes_with_method("add_hooks"))):
  1218. for hook in clz.add_hooks(self):
  1219. if isinstance(hook, Var):
  1220. extract_var_hooks(hook)
  1221. else:
  1222. code[hook] = {}
  1223. return code
  1224. def _get_hooks(self) -> str | None:
  1225. """Get the React hooks for this component.
  1226. Downstream components should override this method to add their own hooks.
  1227. Returns:
  1228. The hooks for just this component.
  1229. """
  1230. return
  1231. def _get_all_hooks_internal(self) -> dict[str, None]:
  1232. """Get the reflex internal hooks for the component and its children.
  1233. Returns:
  1234. The code that should appear just before user-defined hooks.
  1235. """
  1236. # Store the code in a set to avoid duplicates.
  1237. code = self._get_hooks_internal()
  1238. # Add the hook code for the children.
  1239. for child in self.children:
  1240. code = {**code, **child._get_all_hooks_internal()}
  1241. return code
  1242. def _get_all_hooks(self) -> dict[str, None]:
  1243. """Get the React hooks for this component and its children.
  1244. Returns:
  1245. The code that should appear just before returning the rendered component.
  1246. """
  1247. code = {}
  1248. # Add the hook code for this component.
  1249. hooks = self._get_hooks()
  1250. if hooks is not None:
  1251. code[hooks] = None
  1252. code.update(self._get_added_hooks())
  1253. # Add the hook code for the children.
  1254. for child in self.children:
  1255. code = {**code, **child._get_all_hooks()}
  1256. return code
  1257. def get_ref(self) -> str | None:
  1258. """Get the name of the ref for the component.
  1259. Returns:
  1260. The ref name.
  1261. """
  1262. # do not create a ref if the id is dynamic or unspecified
  1263. if self.id is None or isinstance(self.id, BaseVar):
  1264. return None
  1265. return format.format_ref(self.id)
  1266. def _get_all_refs(self) -> set[str]:
  1267. """Get the refs for the children of the component.
  1268. Returns:
  1269. The refs for the children.
  1270. """
  1271. refs = set()
  1272. ref = self.get_ref()
  1273. if ref is not None:
  1274. refs.add(ref)
  1275. for child in self.children:
  1276. refs |= child._get_all_refs()
  1277. return refs
  1278. def _get_all_custom_components(
  1279. self, seen: set[str] | None = None
  1280. ) -> Set[CustomComponent]:
  1281. """Get all the custom components used by the component.
  1282. Args:
  1283. seen: The tags of the components that have already been seen.
  1284. Returns:
  1285. The set of custom components.
  1286. """
  1287. custom_components = set()
  1288. # Store the seen components in a set to avoid infinite recursion.
  1289. if seen is None:
  1290. seen = set()
  1291. for child in self.children:
  1292. # Skip BaseComponent and StatefulComponent children.
  1293. if not isinstance(child, Component):
  1294. continue
  1295. custom_components |= child._get_all_custom_components(seen=seen)
  1296. return custom_components
  1297. @property
  1298. def import_var(self):
  1299. """The tag to import.
  1300. Returns:
  1301. An import var.
  1302. """
  1303. # If the tag is dot-qualified, only import the left-most name.
  1304. tag = self.tag.partition(".")[0] if self.tag else None
  1305. alias = self.alias.partition(".")[0] if self.alias else None
  1306. return ImportVar(
  1307. tag=tag,
  1308. is_default=self.is_default,
  1309. alias=alias,
  1310. transpile=self._should_transpile(self.library),
  1311. )
  1312. @staticmethod
  1313. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  1314. """Get the app wrap components for the component.
  1315. Returns:
  1316. The app wrap components.
  1317. """
  1318. return {}
  1319. def _get_all_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  1320. """Get the app wrap components for the component and its children.
  1321. Returns:
  1322. The app wrap components.
  1323. """
  1324. # Store the components in a set to avoid duplicates.
  1325. components = self._get_app_wrap_components()
  1326. for component in tuple(components.values()):
  1327. components.update(component._get_all_app_wrap_components())
  1328. # Add the app wrap components for the children.
  1329. for child in self.children:
  1330. # Skip BaseComponent and StatefulComponent children.
  1331. if not isinstance(child, Component):
  1332. continue
  1333. components.update(child._get_all_app_wrap_components())
  1334. # Return the components.
  1335. return components
  1336. class CustomComponent(Component):
  1337. """A custom user-defined component."""
  1338. # Use the components library.
  1339. library = f"/{Dirs.COMPONENTS_PATH}"
  1340. # The function that creates the component.
  1341. component_fn: Callable[..., Component] = Component.create
  1342. # The props of the component.
  1343. props: Dict[str, Any] = {}
  1344. # Props that reference other components.
  1345. component_props: Dict[str, Component] = {}
  1346. def __init__(self, *args, **kwargs):
  1347. """Initialize the custom component.
  1348. Args:
  1349. *args: The args to pass to the component.
  1350. **kwargs: The kwargs to pass to the component.
  1351. """
  1352. super().__init__(*args, **kwargs)
  1353. # Unset the style.
  1354. self.style = Style()
  1355. # Set the tag to the name of the function.
  1356. self.tag = format.to_title_case(self.component_fn.__name__)
  1357. # Get the event triggers defined in the component declaration.
  1358. event_triggers_in_component_declaration = self.get_event_triggers()
  1359. # Set the props.
  1360. props = typing.get_type_hints(self.component_fn)
  1361. for key, value in kwargs.items():
  1362. # Skip kwargs that are not props.
  1363. if key not in props:
  1364. continue
  1365. # Get the type based on the annotation.
  1366. type_ = props[key]
  1367. # Handle event chains.
  1368. if types._issubclass(type_, EventChain):
  1369. value = self._create_event_chain(
  1370. value=value,
  1371. args_spec=event_triggers_in_component_declaration.get(
  1372. key, lambda: []
  1373. ),
  1374. )
  1375. self.props[format.to_camel_case(key)] = value
  1376. continue
  1377. # Handle subclasses of Base.
  1378. if isinstance(value, Base):
  1379. base_value = Var.create(value)
  1380. # Track hooks and imports associated with Component instances.
  1381. if base_value is not None and isinstance(value, Component):
  1382. self.component_props[key] = value
  1383. value = base_value._replace(
  1384. merge_var_data=VarData( # type: ignore
  1385. imports=value._get_all_imports(),
  1386. hooks=value._get_all_hooks(),
  1387. )
  1388. )
  1389. else:
  1390. value = base_value
  1391. else:
  1392. value = Var.create(value, _var_is_string=isinstance(value, str))
  1393. # Set the prop.
  1394. self.props[format.to_camel_case(key)] = value
  1395. def __eq__(self, other: Any) -> bool:
  1396. """Check if the component is equal to another.
  1397. Args:
  1398. other: The other component.
  1399. Returns:
  1400. Whether the component is equal to the other.
  1401. """
  1402. return isinstance(other, CustomComponent) and self.tag == other.tag
  1403. def __hash__(self) -> int:
  1404. """Get the hash of the component.
  1405. Returns:
  1406. The hash of the component.
  1407. """
  1408. return hash(self.tag)
  1409. @classmethod
  1410. def get_props(cls) -> Set[str]:
  1411. """Get the props for the component.
  1412. Returns:
  1413. The set of component props.
  1414. """
  1415. return set()
  1416. def _get_all_custom_components(
  1417. self, seen: set[str] | None = None
  1418. ) -> Set[CustomComponent]:
  1419. """Get all the custom components used by the component.
  1420. Args:
  1421. seen: The tags of the components that have already been seen.
  1422. Returns:
  1423. The set of custom components.
  1424. """
  1425. assert self.tag is not None, "The tag must be set."
  1426. # Store the seen components in a set to avoid infinite recursion.
  1427. if seen is None:
  1428. seen = set()
  1429. custom_components = {self} | super()._get_all_custom_components(seen=seen)
  1430. # Avoid adding the same component twice.
  1431. if self.tag not in seen:
  1432. seen.add(self.tag)
  1433. custom_components |= self.get_component(self)._get_all_custom_components(
  1434. seen=seen
  1435. )
  1436. # Fetch custom components from props as well.
  1437. for child_component in self.component_props.values():
  1438. if child_component.tag is None:
  1439. continue
  1440. if child_component.tag not in seen:
  1441. seen.add(child_component.tag)
  1442. if isinstance(child_component, CustomComponent):
  1443. custom_components |= {child_component}
  1444. custom_components |= child_component._get_all_custom_components(
  1445. seen=seen
  1446. )
  1447. return custom_components
  1448. def _render(self) -> Tag:
  1449. """Define how to render the component in React.
  1450. Returns:
  1451. The tag to render.
  1452. """
  1453. return super()._render(props=self.props)
  1454. def get_prop_vars(self) -> List[BaseVar]:
  1455. """Get the prop vars.
  1456. Returns:
  1457. The prop vars.
  1458. """
  1459. return [
  1460. BaseVar(
  1461. _var_name=name,
  1462. _var_type=(
  1463. prop._var_type if types._isinstance(prop, Var) else type(prop)
  1464. ),
  1465. )
  1466. for name, prop in self.props.items()
  1467. ]
  1468. def _get_vars(self, include_children: bool = False) -> list[Var]:
  1469. """Walk all Vars used in this component.
  1470. Args:
  1471. include_children: Whether to include Vars from children.
  1472. Returns:
  1473. Each var referenced by the component (props, styles, event handlers).
  1474. """
  1475. return super()._get_vars(include_children=include_children) + [
  1476. prop for prop in self.props.values() if isinstance(prop, Var)
  1477. ]
  1478. @lru_cache(maxsize=None) # noqa
  1479. def get_component(self) -> Component:
  1480. """Render the component.
  1481. Returns:
  1482. The code to render the component.
  1483. """
  1484. return self.component_fn(*self.get_prop_vars())
  1485. def custom_component(
  1486. component_fn: Callable[..., Component],
  1487. ) -> Callable[..., CustomComponent]:
  1488. """Create a custom component from a function.
  1489. Args:
  1490. component_fn: The function that creates the component.
  1491. Returns:
  1492. The decorated function.
  1493. """
  1494. @wraps(component_fn)
  1495. def wrapper(*children, **props) -> CustomComponent:
  1496. # Remove the children from the props.
  1497. props.pop("children", None)
  1498. return CustomComponent(component_fn=component_fn, children=children, **props)
  1499. return wrapper
  1500. # Alias memo to custom_component.
  1501. memo = custom_component
  1502. class NoSSRComponent(Component):
  1503. """A dynamic component that is not rendered on the server."""
  1504. def _get_imports(self) -> ParsedImportDict:
  1505. """Get the imports for the component.
  1506. Returns:
  1507. The imports for dynamically importing the component at module load time.
  1508. """
  1509. # Next.js dynamic import mechanism.
  1510. dynamic_import = {"next/dynamic": [ImportVar(tag="dynamic", is_default=True)]}
  1511. # The normal imports for this component.
  1512. _imports = super()._get_imports()
  1513. # Do NOT import the main library/tag statically.
  1514. if self.library is not None:
  1515. _imports[self.library] = [
  1516. imports.ImportVar(
  1517. tag=None,
  1518. render=False,
  1519. transpile=self._should_transpile(self.library),
  1520. ),
  1521. ]
  1522. return imports.merge_imports(
  1523. dynamic_import,
  1524. _imports,
  1525. self._get_dependencies_imports(),
  1526. )
  1527. def _get_dynamic_imports(self) -> str:
  1528. opts_fragment = ", { ssr: false });"
  1529. # extract the correct import name from library name
  1530. if self.library is None:
  1531. raise ValueError("Undefined library for NoSSRComponent")
  1532. import_name = format.format_library_name(self.library)
  1533. library_import = f"const {self.alias if self.alias else self.tag} = dynamic(() => import('{import_name}')"
  1534. mod_import = (
  1535. # https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
  1536. f".then((mod) => mod.{self.tag})" if not self.is_default else ""
  1537. )
  1538. return "".join((library_import, mod_import, opts_fragment))
  1539. @serializer
  1540. def serialize_component(comp: Component):
  1541. """Serialize a component.
  1542. Args:
  1543. comp: The component to serialize.
  1544. Returns:
  1545. The serialized component.
  1546. """
  1547. return str(comp)
  1548. class StatefulComponent(BaseComponent):
  1549. """A component that depends on state and is rendered outside of the page component.
  1550. If a StatefulComponent is used in multiple pages, it will be rendered to a common file and
  1551. imported into each page that uses it.
  1552. A stateful component has a tag name that includes a hash of the code that it renders
  1553. to. This tag name refers to the specific component with the specific props that it
  1554. was created with.
  1555. """
  1556. # A lookup table to caching memoized component instances.
  1557. tag_to_stateful_component: ClassVar[Dict[str, StatefulComponent]] = {}
  1558. # Reference to the original component that was memoized into this component.
  1559. component: Component
  1560. # The rendered (memoized) code that will be emitted.
  1561. code: str
  1562. # How many times this component is referenced in the app.
  1563. references: int = 0
  1564. # Whether the component has already been rendered to a shared file.
  1565. rendered_as_shared: bool = False
  1566. @classmethod
  1567. def create(cls, component: Component) -> StatefulComponent | None:
  1568. """Create a stateful component from a component.
  1569. Args:
  1570. component: The component to memoize.
  1571. Returns:
  1572. The stateful component or None if the component should not be memoized.
  1573. """
  1574. from reflex.components.core.foreach import Foreach
  1575. if component._memoization_mode.disposition == MemoizationDisposition.NEVER:
  1576. # Never memoize this component.
  1577. return None
  1578. if component.tag is None:
  1579. # Only memoize components with a tag.
  1580. return None
  1581. # If _var_data is found in this component, it is a candidate for auto-memoization.
  1582. should_memoize = False
  1583. # If the component requests to be memoized, then ignore other checks.
  1584. if component._memoization_mode.disposition == MemoizationDisposition.ALWAYS:
  1585. should_memoize = True
  1586. if not should_memoize:
  1587. # Determine if any Vars have associated data.
  1588. for prop_var in component._get_vars():
  1589. if prop_var._var_data:
  1590. should_memoize = True
  1591. break
  1592. if not should_memoize:
  1593. # Check for special-cases in child components.
  1594. for child in component.children:
  1595. # Skip BaseComponent and StatefulComponent children.
  1596. if not isinstance(child, Component):
  1597. continue
  1598. # Always consider Foreach something that must be memoized by the parent.
  1599. if isinstance(child, Foreach):
  1600. should_memoize = True
  1601. break
  1602. child = cls._child_var(child)
  1603. if isinstance(child, Var) and child._var_data:
  1604. should_memoize = True
  1605. break
  1606. if should_memoize or component.event_triggers:
  1607. # Render the component to determine tag+hash based on component code.
  1608. tag_name = cls._get_tag_name(component)
  1609. if tag_name is None:
  1610. return None
  1611. # Look up the tag in the cache
  1612. stateful_component = cls.tag_to_stateful_component.get(tag_name)
  1613. if stateful_component is None:
  1614. # Render the component as a string of javascript code.
  1615. code = cls._render_stateful_code(component, tag_name=tag_name)
  1616. # Set the stateful component in the cache for the given tag.
  1617. stateful_component = cls.tag_to_stateful_component.setdefault(
  1618. tag_name,
  1619. cls(
  1620. children=component.children,
  1621. component=component,
  1622. tag=tag_name,
  1623. code=code,
  1624. ),
  1625. )
  1626. # Bump the reference count -- multiple pages referencing the same component
  1627. # will result in writing it to a common file.
  1628. stateful_component.references += 1
  1629. return stateful_component
  1630. # Return None to indicate this component should not be memoized.
  1631. return None
  1632. @staticmethod
  1633. def _child_var(child: Component) -> Var | Component:
  1634. """Get the Var from a child component.
  1635. This method is used for special cases when the StatefulComponent should actually
  1636. wrap the parent component of the child instead of recursing into the children
  1637. and memoizing them independently.
  1638. Args:
  1639. child: The child component.
  1640. Returns:
  1641. The Var from the child component or the child itself (for regular cases).
  1642. """
  1643. from reflex.components.base.bare import Bare
  1644. from reflex.components.core.cond import Cond
  1645. from reflex.components.core.foreach import Foreach
  1646. if isinstance(child, Bare):
  1647. return child.contents
  1648. if isinstance(child, Cond):
  1649. return child.cond
  1650. if isinstance(child, Foreach):
  1651. return child.iterable
  1652. return child
  1653. @classmethod
  1654. def _get_tag_name(cls, component: Component) -> str | None:
  1655. """Get the tag based on rendering the given component.
  1656. Args:
  1657. component: The component to render.
  1658. Returns:
  1659. The tag for the stateful component.
  1660. """
  1661. # Get the render dict for the component.
  1662. rendered_code = component.render()
  1663. if not rendered_code:
  1664. # Never memoize non-visual components.
  1665. return None
  1666. # Compute the hash based on the rendered code.
  1667. code_hash = md5(str(rendered_code).encode("utf-8")).hexdigest()
  1668. # Format the tag name including the hash.
  1669. return format.format_state_name(
  1670. f"{component.tag or 'Comp'}_{code_hash}"
  1671. ).capitalize()
  1672. @classmethod
  1673. def _render_stateful_code(
  1674. cls,
  1675. component: Component,
  1676. tag_name: str,
  1677. ) -> str:
  1678. """Render the code for a stateful component.
  1679. Args:
  1680. component: The component to render.
  1681. tag_name: The tag name for the stateful component (see _get_tag_name).
  1682. Returns:
  1683. The rendered code.
  1684. """
  1685. # Memoize event triggers useCallback to avoid unnecessary re-renders.
  1686. memo_event_triggers = tuple(cls._get_memoized_event_triggers(component).items())
  1687. # Trigger hooks stored separately to write after the normal hooks (see stateful_component.js.jinja2)
  1688. memo_trigger_hooks = []
  1689. if memo_event_triggers:
  1690. # Copy the component to avoid mutating the original.
  1691. component = copy.copy(component)
  1692. for event_trigger, (
  1693. memo_trigger,
  1694. memo_trigger_hook,
  1695. ) in memo_event_triggers:
  1696. # Replace the event trigger with the memoized version.
  1697. memo_trigger_hooks.append(memo_trigger_hook)
  1698. component.event_triggers[event_trigger] = memo_trigger
  1699. # Render the code for this component and hooks.
  1700. return STATEFUL_COMPONENT.render(
  1701. tag_name=tag_name,
  1702. memo_trigger_hooks=memo_trigger_hooks,
  1703. component=component,
  1704. )
  1705. @staticmethod
  1706. def _get_hook_deps(hook: str) -> list[str]:
  1707. """Extract var deps from a hook.
  1708. Args:
  1709. hook: The hook line to extract deps from.
  1710. Returns:
  1711. A list of var names created by the hook declaration.
  1712. """
  1713. var_name = hook.partition("=")[0].strip().split(None, 1)[1].strip()
  1714. if var_name.startswith("["):
  1715. # Break up array destructuring.
  1716. return [v.strip() for v in var_name.strip("[]").split(",")]
  1717. return [var_name]
  1718. @classmethod
  1719. def _get_memoized_event_triggers(
  1720. cls,
  1721. component: Component,
  1722. ) -> dict[str, tuple[Var, str]]:
  1723. """Memoize event handler functions with useCallback to avoid unnecessary re-renders.
  1724. Args:
  1725. component: The component with events to memoize.
  1726. Returns:
  1727. A dict of event trigger name to a tuple of the memoized event trigger Var and
  1728. the hook code that memoizes the event handler.
  1729. """
  1730. trigger_memo = {}
  1731. for event_trigger, event_args in component._get_vars_from_event_triggers(
  1732. component.event_triggers
  1733. ):
  1734. if event_trigger in {
  1735. EventTriggers.ON_MOUNT,
  1736. EventTriggers.ON_UNMOUNT,
  1737. EventTriggers.ON_SUBMIT,
  1738. }:
  1739. # Do not memoize lifecycle or submit events.
  1740. continue
  1741. # Get the actual EventSpec and render it.
  1742. event = component.event_triggers[event_trigger]
  1743. rendered_chain = format.format_prop(event)
  1744. if isinstance(rendered_chain, str):
  1745. rendered_chain = rendered_chain.strip("{}")
  1746. # Hash the rendered EventChain to get a deterministic function name.
  1747. chain_hash = md5(str(rendered_chain).encode("utf-8")).hexdigest()
  1748. memo_name = f"{event_trigger}_{chain_hash}"
  1749. # Calculate Var dependencies accessed by the handler for useCallback dep array.
  1750. var_deps = ["addEvents", "Event"]
  1751. for arg in event_args:
  1752. if arg._var_data is None:
  1753. continue
  1754. for hook in arg._var_data.hooks:
  1755. var_deps.extend(cls._get_hook_deps(hook))
  1756. memo_var_data = VarData.merge(
  1757. *[var._var_data for var in event_args],
  1758. VarData(
  1759. imports={"react": [ImportVar(tag="useCallback")]},
  1760. ),
  1761. )
  1762. # Store the memoized function name and hook code for this event trigger.
  1763. trigger_memo[event_trigger] = (
  1764. Var.create_safe(memo_name, _var_is_string=False)._replace(
  1765. _var_type=EventChain, merge_var_data=memo_var_data
  1766. ),
  1767. f"const {memo_name} = useCallback({rendered_chain}, [{', '.join(var_deps)}])",
  1768. )
  1769. return trigger_memo
  1770. def _get_all_hooks_internal(self) -> dict[str, None]:
  1771. """Get the reflex internal hooks for the component and its children.
  1772. Returns:
  1773. The code that should appear just before user-defined hooks.
  1774. """
  1775. return {}
  1776. def _get_all_hooks(self) -> dict[str, None]:
  1777. """Get the React hooks for this component.
  1778. Returns:
  1779. The code that should appear just before returning the rendered component.
  1780. """
  1781. return {}
  1782. def _get_all_imports(self) -> ParsedImportDict:
  1783. """Get all the libraries and fields that are used by the component.
  1784. Returns:
  1785. The import dict with the required imports.
  1786. """
  1787. if self.rendered_as_shared:
  1788. return {
  1789. f"/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
  1790. ImportVar(tag=self.tag)
  1791. ]
  1792. }
  1793. return self.component._get_all_imports()
  1794. def _get_all_dynamic_imports(self) -> set[str]:
  1795. """Get dynamic imports for the component.
  1796. Returns:
  1797. The dynamic imports.
  1798. """
  1799. if self.rendered_as_shared:
  1800. return set()
  1801. return self.component._get_all_dynamic_imports()
  1802. def _get_all_custom_code(self) -> set[str]:
  1803. """Get custom code for the component.
  1804. Returns:
  1805. The custom code.
  1806. """
  1807. if self.rendered_as_shared:
  1808. return set()
  1809. return self.component._get_all_custom_code().union({self.code})
  1810. def _get_all_refs(self) -> set[str]:
  1811. """Get the refs for the children of the component.
  1812. Returns:
  1813. The refs for the children.
  1814. """
  1815. if self.rendered_as_shared:
  1816. return set()
  1817. return self.component._get_all_refs()
  1818. def render(self) -> dict:
  1819. """Define how to render the component in React.
  1820. Returns:
  1821. The tag to render.
  1822. """
  1823. return dict(Tag(name=self.tag))
  1824. def __str__(self) -> str:
  1825. """Represent the component in React.
  1826. Returns:
  1827. The code to render the component.
  1828. """
  1829. from reflex.compiler.compiler import _compile_component
  1830. return _compile_component(self)
  1831. @classmethod
  1832. def compile_from(cls, component: BaseComponent) -> BaseComponent:
  1833. """Walk through the component tree and memoize all stateful components.
  1834. Args:
  1835. component: The component to memoize.
  1836. Returns:
  1837. The memoized component tree.
  1838. """
  1839. if isinstance(component, Component):
  1840. if component._memoization_mode.recursive:
  1841. # Recursively memoize stateful children (default).
  1842. component.children = [
  1843. cls.compile_from(child) for child in component.children
  1844. ]
  1845. # Memoize this component if it depends on state.
  1846. stateful_component = cls.create(component)
  1847. if stateful_component is not None:
  1848. return stateful_component
  1849. return component
  1850. class MemoizationLeaf(Component):
  1851. """A component that does not separately memoize its children.
  1852. Any component which depends on finding the exact names of children
  1853. components within it, should be a memoization leaf so the compiler
  1854. does not replace the provided child tags with memoized tags.
  1855. During creation, a memoization leaf will mark itself as wanting to be
  1856. memoized if any of its children return any hooks.
  1857. """
  1858. _memoization_mode = MemoizationMode(recursive=False)
  1859. @classmethod
  1860. def create(cls, *children, **props) -> Component:
  1861. """Create a new memoization leaf component.
  1862. Args:
  1863. *children: The children of the component.
  1864. **props: The props of the component.
  1865. Returns:
  1866. The memoization leaf
  1867. """
  1868. comp = super().create(*children, **props)
  1869. if comp._get_all_hooks() or comp._get_all_hooks_internal():
  1870. comp._memoization_mode = cls._memoization_mode.copy(
  1871. update={"disposition": MemoizationDisposition.ALWAYS}
  1872. )
  1873. return comp