component.py 89 KB

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