component.py 85 KB

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