component.py 88 KB

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