test_component.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207
  1. from contextlib import nullcontext
  2. from typing import Any, Dict, List, Optional, Type, Union
  3. import pytest
  4. import reflex as rx
  5. from reflex.base import Base
  6. from reflex.compiler.compiler import compile_components
  7. from reflex.components.base.bare import Bare
  8. from reflex.components.base.fragment import Fragment
  9. from reflex.components.component import (
  10. Component,
  11. CustomComponent,
  12. StatefulComponent,
  13. custom_component,
  14. )
  15. from reflex.components.radix.themes.layout.box import Box
  16. from reflex.constants import EventTriggers
  17. from reflex.event import EventChain, EventHandler, parse_args_spec
  18. from reflex.ivars.base import ImmutableVar, LiteralVar
  19. from reflex.state import BaseState
  20. from reflex.style import Style
  21. from reflex.utils import imports
  22. from reflex.utils.exceptions import EventFnArgMismatch, EventHandlerArgMismatch
  23. from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports
  24. from reflex.vars import Var, VarData
  25. @pytest.fixture
  26. def test_state():
  27. class TestState(BaseState):
  28. num: int
  29. def do_something(self):
  30. pass
  31. def do_something_arg(self, arg):
  32. pass
  33. return TestState
  34. @pytest.fixture
  35. def component1() -> Type[Component]:
  36. """A test component.
  37. Returns:
  38. A test component.
  39. """
  40. class TestComponent1(Component):
  41. # A test string prop.
  42. text: Var[str]
  43. # A test number prop.
  44. number: Var[int]
  45. # A test string/number prop.
  46. text_or_number: Var[Union[int, str]]
  47. def _get_imports(self) -> ParsedImportDict:
  48. return {"react": [ImportVar(tag="Component")]}
  49. def _get_custom_code(self) -> str:
  50. return "console.log('component1')"
  51. return TestComponent1
  52. @pytest.fixture
  53. def component2() -> Type[Component]:
  54. """A test component.
  55. Returns:
  56. A test component.
  57. """
  58. class TestComponent2(Component):
  59. # A test list prop.
  60. arr: Var[List[str]]
  61. on_prop_event: EventHandler[lambda e0: [e0]]
  62. def get_event_triggers(self) -> Dict[str, Any]:
  63. """Test controlled triggers.
  64. Returns:
  65. Test controlled triggers.
  66. """
  67. return {
  68. **super().get_event_triggers(),
  69. "on_open": lambda e0: [e0],
  70. "on_close": lambda e0: [e0],
  71. }
  72. def _get_imports(self) -> ParsedImportDict:
  73. return {"react-redux": [ImportVar(tag="connect")]}
  74. def _get_custom_code(self) -> str:
  75. return "console.log('component2')"
  76. return TestComponent2
  77. @pytest.fixture
  78. def component3() -> Type[Component]:
  79. """A test component with hook defined.
  80. Returns:
  81. A test component.
  82. """
  83. class TestComponent3(Component):
  84. def _get_hooks(self) -> str:
  85. return "const a = () => true"
  86. return TestComponent3
  87. @pytest.fixture
  88. def component4() -> Type[Component]:
  89. """A test component with hook defined.
  90. Returns:
  91. A test component.
  92. """
  93. class TestComponent4(Component):
  94. def _get_hooks(self) -> str:
  95. return "const b = () => false"
  96. return TestComponent4
  97. @pytest.fixture
  98. def component5() -> Type[Component]:
  99. """A test component.
  100. Returns:
  101. A test component.
  102. """
  103. class TestComponent5(Component):
  104. tag = "RandomComponent"
  105. _invalid_children: List[str] = ["Text"]
  106. _valid_children: List[str] = ["Text"]
  107. _valid_parents: List[str] = ["Text"]
  108. return TestComponent5
  109. @pytest.fixture
  110. def component6() -> Type[Component]:
  111. """A test component.
  112. Returns:
  113. A test component.
  114. """
  115. class TestComponent6(Component):
  116. tag = "RandomComponent"
  117. _invalid_children: List[str] = ["Text"]
  118. return TestComponent6
  119. @pytest.fixture
  120. def component7() -> Type[Component]:
  121. """A test component.
  122. Returns:
  123. A test component.
  124. """
  125. class TestComponent7(Component):
  126. tag = "RandomComponent"
  127. _valid_children: List[str] = ["Text"]
  128. return TestComponent7
  129. @pytest.fixture
  130. def on_click1() -> EventHandler:
  131. """A sample on click function.
  132. Returns:
  133. A sample on click function.
  134. """
  135. def on_click1():
  136. pass
  137. return EventHandler(fn=on_click1)
  138. @pytest.fixture
  139. def on_click2() -> EventHandler:
  140. """A sample on click function.
  141. Returns:
  142. A sample on click function.
  143. """
  144. def on_click2():
  145. pass
  146. return EventHandler(fn=on_click2)
  147. @pytest.fixture
  148. def my_component():
  149. """A test component function.
  150. Returns:
  151. A test component function.
  152. """
  153. def my_component(prop1: Var[str], prop2: Var[int]):
  154. return Box.create(prop1, prop2)
  155. return my_component
  156. def test_set_style_attrs(component1):
  157. """Test that style attributes are set in the dict.
  158. Args:
  159. component1: A test component.
  160. """
  161. component = component1(color="white", text_align="center")
  162. assert str(component.style["color"]) == '"white"'
  163. assert str(component.style["textAlign"]) == '"center"'
  164. def test_custom_attrs(component1):
  165. """Test that custom attributes are set in the dict.
  166. Args:
  167. component1: A test component.
  168. """
  169. component = component1(custom_attrs={"attr1": "1", "attr2": "attr2"})
  170. assert component.custom_attrs == {"attr1": "1", "attr2": "attr2"}
  171. def test_create_component(component1):
  172. """Test that the component is created correctly.
  173. Args:
  174. component1: A test component.
  175. """
  176. children = [component1() for _ in range(3)]
  177. attrs = {"color": "white", "text_align": "center"}
  178. c = component1.create(*children, **attrs)
  179. assert isinstance(c, component1)
  180. assert c.children == children
  181. assert (
  182. str(LiteralVar.create(c.style))
  183. == '({ ["color"] : "white", ["textAlign"] : "center" })'
  184. )
  185. @pytest.mark.parametrize(
  186. "prop_name,var,expected",
  187. [
  188. pytest.param(
  189. "text",
  190. LiteralVar.create("hello"),
  191. None,
  192. id="text",
  193. ),
  194. pytest.param(
  195. "text",
  196. ImmutableVar(_var_name="hello", _var_type=Optional[str]),
  197. None,
  198. id="text-optional",
  199. ),
  200. pytest.param(
  201. "text",
  202. ImmutableVar(_var_name="hello", _var_type=Union[str, None]),
  203. None,
  204. id="text-union-str-none",
  205. ),
  206. pytest.param(
  207. "text",
  208. ImmutableVar(_var_name="hello", _var_type=Union[None, str]),
  209. None,
  210. id="text-union-none-str",
  211. ),
  212. pytest.param(
  213. "text",
  214. LiteralVar.create(1),
  215. TypeError,
  216. id="text-int",
  217. ),
  218. pytest.param(
  219. "number",
  220. LiteralVar.create(1),
  221. None,
  222. id="number",
  223. ),
  224. pytest.param(
  225. "number",
  226. ImmutableVar(_var_name="1", _var_type=Optional[int]),
  227. None,
  228. id="number-optional",
  229. ),
  230. pytest.param(
  231. "number",
  232. ImmutableVar(_var_name="1", _var_type=Union[int, None]),
  233. None,
  234. id="number-union-int-none",
  235. ),
  236. pytest.param(
  237. "number",
  238. ImmutableVar(_var_name="1", _var_type=Union[None, int]),
  239. None,
  240. id="number-union-none-int",
  241. ),
  242. pytest.param(
  243. "number",
  244. LiteralVar.create("1"),
  245. TypeError,
  246. id="number-str",
  247. ),
  248. pytest.param(
  249. "text_or_number",
  250. LiteralVar.create("hello"),
  251. None,
  252. id="text_or_number-str",
  253. ),
  254. pytest.param(
  255. "text_or_number",
  256. LiteralVar.create(1),
  257. None,
  258. id="text_or_number-int",
  259. ),
  260. pytest.param(
  261. "text_or_number",
  262. ImmutableVar(_var_name="hello", _var_type=Optional[str]),
  263. None,
  264. id="text_or_number-optional-str",
  265. ),
  266. pytest.param(
  267. "text_or_number",
  268. ImmutableVar(_var_name="hello", _var_type=Union[str, None]),
  269. None,
  270. id="text_or_number-union-str-none",
  271. ),
  272. pytest.param(
  273. "text_or_number",
  274. ImmutableVar(_var_name="hello", _var_type=Union[None, str]),
  275. None,
  276. id="text_or_number-union-none-str",
  277. ),
  278. pytest.param(
  279. "text_or_number",
  280. ImmutableVar(_var_name="1", _var_type=Optional[int]),
  281. None,
  282. id="text_or_number-optional-int",
  283. ),
  284. pytest.param(
  285. "text_or_number",
  286. ImmutableVar(_var_name="1", _var_type=Union[int, None]),
  287. None,
  288. id="text_or_number-union-int-none",
  289. ),
  290. pytest.param(
  291. "text_or_number",
  292. ImmutableVar(_var_name="1", _var_type=Union[None, int]),
  293. None,
  294. id="text_or_number-union-none-int",
  295. ),
  296. pytest.param(
  297. "text_or_number",
  298. LiteralVar.create(1.0),
  299. TypeError,
  300. id="text_or_number-float",
  301. ),
  302. pytest.param(
  303. "text_or_number",
  304. ImmutableVar(_var_name="hello", _var_type=Optional[Union[str, int]]),
  305. None,
  306. id="text_or_number-optional-union-str-int",
  307. ),
  308. ],
  309. )
  310. def test_create_component_prop_validation(
  311. component1: Type[Component],
  312. prop_name: str,
  313. var: Union[ImmutableVar, str, int],
  314. expected: Type[Exception],
  315. ):
  316. """Test that component props are validated correctly.
  317. Args:
  318. component1: A test component.
  319. prop_name: The name of the prop.
  320. var: The value of the prop.
  321. expected: The expected exception.
  322. """
  323. ctx = pytest.raises(expected) if expected else nullcontext()
  324. kwargs = {prop_name: var}
  325. with ctx:
  326. c = component1.create(**kwargs)
  327. assert isinstance(c, component1)
  328. assert c.children == []
  329. assert c.style == {}
  330. def test_add_style(component1, component2):
  331. """Test adding a style to a component.
  332. Args:
  333. component1: A test component.
  334. component2: A test component.
  335. """
  336. style = {
  337. component1: Style({"color": "white"}),
  338. component2: Style({"color": "black"}),
  339. }
  340. c1 = component1()._add_style_recursive(style) # type: ignore
  341. c2 = component2()._add_style_recursive(style) # type: ignore
  342. assert str(c1.style["color"]) == '"white"'
  343. assert str(c2.style["color"]) == '"black"'
  344. def test_add_style_create(component1, component2):
  345. """Test that adding style works with the create method.
  346. Args:
  347. component1: A test component.
  348. component2: A test component.
  349. """
  350. style = {
  351. component1.create: Style({"color": "white"}),
  352. component2.create: Style({"color": "black"}),
  353. }
  354. c1 = component1()._add_style_recursive(style) # type: ignore
  355. c2 = component2()._add_style_recursive(style) # type: ignore
  356. assert str(c1.style["color"]) == '"white"'
  357. assert str(c2.style["color"]) == '"black"'
  358. def test_get_imports(component1, component2):
  359. """Test getting the imports of a component.
  360. Args:
  361. component1: A test component.
  362. component2: A test component.
  363. """
  364. c1 = component1.create()
  365. c2 = component2.create(c1)
  366. assert c1._get_all_imports() == {"react": [ImportVar(tag="Component")]}
  367. assert c2._get_all_imports() == {
  368. "react-redux": [ImportVar(tag="connect")],
  369. "react": [ImportVar(tag="Component")],
  370. }
  371. def test_get_custom_code(component1, component2):
  372. """Test getting the custom code of a component.
  373. Args:
  374. component1: A test component.
  375. component2: A test component.
  376. """
  377. # Check that the code gets compiled correctly.
  378. c1 = component1.create()
  379. c2 = component2.create()
  380. assert c1._get_all_custom_code() == {"console.log('component1')"}
  381. assert c2._get_all_custom_code() == {"console.log('component2')"}
  382. # Check that nesting components compiles both codes.
  383. c1 = component1.create(c2)
  384. assert c1._get_all_custom_code() == {
  385. "console.log('component1')",
  386. "console.log('component2')",
  387. }
  388. # Check that code is not duplicated.
  389. c1 = component1.create(c2, c2, c1, c1)
  390. assert c1._get_all_custom_code() == {
  391. "console.log('component1')",
  392. "console.log('component2')",
  393. }
  394. def test_get_props(component1, component2):
  395. """Test that the props are set correctly.
  396. Args:
  397. component1: A test component.
  398. component2: A test component.
  399. """
  400. assert component1.get_props() == {"text", "number", "text_or_number"}
  401. assert component2.get_props() == {"arr", "on_prop_event"}
  402. @pytest.mark.parametrize(
  403. "text,number",
  404. [
  405. ("", 0),
  406. ("test", 1),
  407. ("hi", -13),
  408. ],
  409. )
  410. def test_valid_props(component1, text: str, number: int):
  411. """Test that we can construct a component with valid props.
  412. Args:
  413. component1: A test component.
  414. text: A test string.
  415. number: A test number.
  416. """
  417. c = component1.create(text=text, number=number)
  418. assert c.text._decode() == text
  419. assert c.number._decode() == number
  420. @pytest.mark.parametrize(
  421. "text,number", [("", "bad_string"), (13, 1), ("test", [1, 2, 3])]
  422. )
  423. def test_invalid_prop_type(component1, text: str, number: int):
  424. """Test that an invalid prop type raises an error.
  425. Args:
  426. component1: A test component.
  427. text: A test string.
  428. number: A test number.
  429. """
  430. # Check that
  431. with pytest.raises(TypeError):
  432. component1.create(text=text, number=number)
  433. def test_var_props(component1, test_state):
  434. """Test that we can set a Var prop.
  435. Args:
  436. component1: A test component.
  437. test_state: A test state.
  438. """
  439. c1 = component1.create(text="hello", number=test_state.num)
  440. assert c1.number.equals(test_state.num)
  441. def test_get_event_triggers(component1, component2):
  442. """Test that we can get the triggers of a component.
  443. Args:
  444. component1: A test component.
  445. component2: A test component.
  446. """
  447. default_triggers = {
  448. EventTriggers.ON_FOCUS,
  449. EventTriggers.ON_BLUR,
  450. EventTriggers.ON_CLICK,
  451. EventTriggers.ON_CONTEXT_MENU,
  452. EventTriggers.ON_DOUBLE_CLICK,
  453. EventTriggers.ON_MOUSE_DOWN,
  454. EventTriggers.ON_MOUSE_ENTER,
  455. EventTriggers.ON_MOUSE_LEAVE,
  456. EventTriggers.ON_MOUSE_MOVE,
  457. EventTriggers.ON_MOUSE_OUT,
  458. EventTriggers.ON_MOUSE_OVER,
  459. EventTriggers.ON_MOUSE_UP,
  460. EventTriggers.ON_SCROLL,
  461. EventTriggers.ON_MOUNT,
  462. EventTriggers.ON_UNMOUNT,
  463. }
  464. assert component1().get_event_triggers().keys() == default_triggers
  465. assert (
  466. component2().get_event_triggers().keys()
  467. == {"on_open", "on_close", "on_prop_event"} | default_triggers
  468. )
  469. @pytest.fixture
  470. def test_component() -> Type[Component]:
  471. """A test component.
  472. Returns:
  473. A test component.
  474. """
  475. class TestComponent(Component):
  476. pass
  477. return TestComponent
  478. # Write a test case to check if the create method filters out None props
  479. def test_create_filters_none_props(test_component):
  480. child1 = test_component()
  481. child2 = test_component()
  482. props = {
  483. "prop1": "value1",
  484. "prop2": None,
  485. "prop3": "value3",
  486. "prop4": None,
  487. "style": {"color": "white", "text-align": "center"}, # Adding a style prop
  488. }
  489. component = test_component.create(child1, child2, **props)
  490. # Assert that None props are not present in the component's props
  491. assert "prop2" not in component.get_props()
  492. assert "prop4" not in component.get_props()
  493. # Assert that the style prop is present in the component's props
  494. assert str(component.style["color"]) == '"white"'
  495. assert str(component.style["text-align"]) == '"center"'
  496. @pytest.mark.parametrize("children", [((None,),), ("foo", ("bar", (None,)))])
  497. def test_component_create_unallowed_types(children, test_component):
  498. with pytest.raises(TypeError) as err:
  499. test_component.create(*children)
  500. assert (
  501. err.value.args[0]
  502. == "Children of Reflex components must be other components, state vars, or primitive Python types. Got child None of type <class 'NoneType'>."
  503. )
  504. @pytest.mark.parametrize(
  505. "element, expected",
  506. [
  507. (
  508. (rx.text("first_text"),),
  509. {
  510. "name": "Fragment",
  511. "props": [],
  512. "contents": "",
  513. "args": None,
  514. "special_props": set(),
  515. "children": [
  516. {
  517. "name": "RadixThemesText",
  518. "props": ['as={"p"}'],
  519. "contents": "",
  520. "args": None,
  521. "special_props": set(),
  522. "children": [
  523. {
  524. "name": "",
  525. "props": [],
  526. "contents": '{"first_text"}',
  527. "args": None,
  528. "special_props": set(),
  529. "children": [],
  530. "autofocus": False,
  531. }
  532. ],
  533. "autofocus": False,
  534. }
  535. ],
  536. "autofocus": False,
  537. },
  538. ),
  539. (
  540. (rx.text("first_text"), rx.text("second_text")),
  541. {
  542. "args": None,
  543. "autofocus": False,
  544. "children": [
  545. {
  546. "args": None,
  547. "autofocus": False,
  548. "children": [
  549. {
  550. "args": None,
  551. "autofocus": False,
  552. "children": [],
  553. "contents": '{"first_text"}',
  554. "name": "",
  555. "props": [],
  556. "special_props": set(),
  557. }
  558. ],
  559. "contents": "",
  560. "name": "RadixThemesText",
  561. "props": ['as={"p"}'],
  562. "special_props": set(),
  563. },
  564. {
  565. "args": None,
  566. "autofocus": False,
  567. "children": [
  568. {
  569. "args": None,
  570. "autofocus": False,
  571. "children": [],
  572. "contents": '{"second_text"}',
  573. "name": "",
  574. "props": [],
  575. "special_props": set(),
  576. }
  577. ],
  578. "contents": "",
  579. "name": "RadixThemesText",
  580. "props": ['as={"p"}'],
  581. "special_props": set(),
  582. },
  583. ],
  584. "contents": "",
  585. "name": "Fragment",
  586. "props": [],
  587. "special_props": set(),
  588. },
  589. ),
  590. (
  591. (rx.text("first_text"), rx.box((rx.text("second_text"),))),
  592. {
  593. "args": None,
  594. "autofocus": False,
  595. "children": [
  596. {
  597. "args": None,
  598. "autofocus": False,
  599. "children": [
  600. {
  601. "args": None,
  602. "autofocus": False,
  603. "children": [],
  604. "contents": '{"first_text"}',
  605. "name": "",
  606. "props": [],
  607. "special_props": set(),
  608. }
  609. ],
  610. "contents": "",
  611. "name": "RadixThemesText",
  612. "props": ['as={"p"}'],
  613. "special_props": set(),
  614. },
  615. {
  616. "args": None,
  617. "autofocus": False,
  618. "children": [
  619. {
  620. "args": None,
  621. "autofocus": False,
  622. "children": [
  623. {
  624. "args": None,
  625. "autofocus": False,
  626. "children": [
  627. {
  628. "args": None,
  629. "autofocus": False,
  630. "children": [],
  631. "contents": '{"second_text"}',
  632. "name": "",
  633. "props": [],
  634. "special_props": set(),
  635. }
  636. ],
  637. "contents": "",
  638. "name": "RadixThemesText",
  639. "props": ['as={"p"}'],
  640. "special_props": set(),
  641. }
  642. ],
  643. "contents": "",
  644. "name": "Fragment",
  645. "props": [],
  646. "special_props": set(),
  647. }
  648. ],
  649. "contents": "",
  650. "name": "RadixThemesBox",
  651. "props": [],
  652. "special_props": set(),
  653. },
  654. ],
  655. "contents": "",
  656. "name": "Fragment",
  657. "props": [],
  658. "special_props": set(),
  659. },
  660. ),
  661. ],
  662. )
  663. def test_component_create_unpack_tuple_child(test_component, element, expected):
  664. """Test that component in tuples are unwrapped into an rx.Fragment.
  665. Args:
  666. test_component: Component fixture.
  667. element: The children to pass to the component.
  668. expected: The expected render dict.
  669. """
  670. comp = test_component.create(element)
  671. assert len(comp.children) == 1
  672. assert isinstance((fragment_wrapper := comp.children[0]), Fragment)
  673. assert fragment_wrapper.render() == expected
  674. class C1State(BaseState):
  675. """State for testing C1 component."""
  676. def mock_handler(self, _e, _bravo, _charlie):
  677. """Mock handler."""
  678. pass
  679. def test_component_event_trigger_arbitrary_args():
  680. """Test that we can define arbitrary types for the args of an event trigger."""
  681. class Obj(Base):
  682. custom: int = 0
  683. def on_foo_spec(_e, alpha: str, bravo: Dict[str, Any], charlie: Obj):
  684. return [_e.target.value, bravo["nested"], charlie.custom + 42]
  685. class C1(Component):
  686. library = "/local"
  687. tag = "C1"
  688. def get_event_triggers(self) -> Dict[str, Any]:
  689. return {
  690. **super().get_event_triggers(),
  691. "on_foo": on_foo_spec,
  692. }
  693. comp = C1.create(on_foo=C1State.mock_handler)
  694. assert comp.render()["props"][0] == (
  695. "onFoo={((__e, _alpha, _bravo, _charlie) => ((addEvents("
  696. f'[(Event("{C1State.get_full_name()}.mock_handler", ({{ ["_e"] : __e["target"]["value"], ["_bravo"] : _bravo["nested"], ["_charlie"] : (_charlie["custom"] + 42) }})))], '
  697. "[__e, _alpha, _bravo, _charlie], ({ })))))}"
  698. )
  699. def test_create_custom_component(my_component):
  700. """Test that we can create a custom component.
  701. Args:
  702. my_component: A test custom component.
  703. """
  704. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  705. assert component.tag == "MyComponent"
  706. assert component.get_props() == set()
  707. assert component._get_all_custom_components() == {component}
  708. def test_custom_component_hash(my_component):
  709. """Test that the hash of a custom component is correct.
  710. Args:
  711. my_component: A test custom component.
  712. """
  713. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  714. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  715. assert {component1, component2} == {component1}
  716. def test_custom_component_wrapper():
  717. """Test that the wrapper of a custom component is correct."""
  718. @custom_component
  719. def my_component(width: Var[int], color: Var[str]):
  720. return rx.box(
  721. width=width,
  722. color=color,
  723. )
  724. from reflex.components.radix.themes.typography.text import Text
  725. ccomponent = my_component(
  726. rx.text("child"), width=LiteralVar.create(1), color=LiteralVar.create("red")
  727. )
  728. assert isinstance(ccomponent, CustomComponent)
  729. assert len(ccomponent.children) == 1
  730. assert isinstance(ccomponent.children[0], Text)
  731. component = ccomponent.get_component(ccomponent)
  732. assert isinstance(component, Box)
  733. def test_invalid_event_handler_args(component2, test_state):
  734. """Test that an invalid event handler raises an error.
  735. Args:
  736. component2: A test component.
  737. test_state: A test state.
  738. """
  739. # EventHandler args must match
  740. with pytest.raises(EventHandlerArgMismatch):
  741. component2.create(on_click=test_state.do_something_arg)
  742. with pytest.raises(EventHandlerArgMismatch):
  743. component2.create(on_open=test_state.do_something)
  744. with pytest.raises(EventHandlerArgMismatch):
  745. component2.create(on_prop_event=test_state.do_something)
  746. # Multiple EventHandler args: all must match
  747. with pytest.raises(EventHandlerArgMismatch):
  748. component2.create(
  749. on_click=[test_state.do_something_arg, test_state.do_something]
  750. )
  751. with pytest.raises(EventHandlerArgMismatch):
  752. component2.create(
  753. on_open=[test_state.do_something_arg, test_state.do_something]
  754. )
  755. with pytest.raises(EventHandlerArgMismatch):
  756. component2.create(
  757. on_prop_event=[test_state.do_something_arg, test_state.do_something]
  758. )
  759. # lambda cannot return weird values.
  760. with pytest.raises(ValueError):
  761. component2.create(on_click=lambda: 1)
  762. with pytest.raises(ValueError):
  763. component2.create(on_click=lambda: [1])
  764. with pytest.raises(ValueError):
  765. component2.create(
  766. on_click=lambda: (test_state.do_something_arg(1), test_state.do_something)
  767. )
  768. # lambda signature must match event trigger.
  769. with pytest.raises(EventFnArgMismatch):
  770. component2.create(on_click=lambda _: test_state.do_something_arg(1))
  771. with pytest.raises(EventFnArgMismatch):
  772. component2.create(on_open=lambda: test_state.do_something)
  773. with pytest.raises(EventFnArgMismatch):
  774. component2.create(on_prop_event=lambda: test_state.do_something)
  775. # lambda returning EventHandler must match spec
  776. with pytest.raises(EventHandlerArgMismatch):
  777. component2.create(on_click=lambda: test_state.do_something_arg)
  778. with pytest.raises(EventHandlerArgMismatch):
  779. component2.create(on_open=lambda _: test_state.do_something)
  780. with pytest.raises(EventHandlerArgMismatch):
  781. component2.create(on_prop_event=lambda _: test_state.do_something)
  782. # Mixed EventSpec and EventHandler must match spec.
  783. with pytest.raises(EventHandlerArgMismatch):
  784. component2.create(
  785. on_click=lambda: [
  786. test_state.do_something_arg(1),
  787. test_state.do_something_arg,
  788. ]
  789. )
  790. with pytest.raises(EventHandlerArgMismatch):
  791. component2.create(
  792. on_open=lambda _: [test_state.do_something_arg(1), test_state.do_something]
  793. )
  794. with pytest.raises(EventHandlerArgMismatch):
  795. component2.create(
  796. on_prop_event=lambda _: [
  797. test_state.do_something_arg(1),
  798. test_state.do_something,
  799. ]
  800. )
  801. def test_valid_event_handler_args(component2, test_state):
  802. """Test that an valid event handler args do not raise exception.
  803. Args:
  804. component2: A test component.
  805. test_state: A test state.
  806. """
  807. # Uncontrolled event handlers should not take args.
  808. component2.create(on_click=test_state.do_something)
  809. component2.create(on_click=test_state.do_something_arg(1))
  810. # Controlled event handlers should take args.
  811. component2.create(on_open=test_state.do_something_arg)
  812. component2.create(on_prop_event=test_state.do_something_arg)
  813. # Using a partial event spec bypasses arg validation (ignoring the args).
  814. component2.create(on_open=test_state.do_something())
  815. component2.create(on_prop_event=test_state.do_something())
  816. # lambda returning EventHandler is okay if the spec matches.
  817. component2.create(on_click=lambda: test_state.do_something)
  818. component2.create(on_open=lambda _: test_state.do_something_arg)
  819. component2.create(on_prop_event=lambda _: test_state.do_something_arg)
  820. # lambda can always return an EventSpec.
  821. component2.create(on_click=lambda: test_state.do_something_arg(1))
  822. component2.create(on_open=lambda _: test_state.do_something_arg(1))
  823. component2.create(on_prop_event=lambda _: test_state.do_something_arg(1))
  824. # Return EventSpec and EventHandler (no arg).
  825. component2.create(
  826. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
  827. )
  828. component2.create(
  829. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
  830. )
  831. # Return 2 EventSpec.
  832. component2.create(
  833. on_open=lambda _: [test_state.do_something_arg(1), test_state.do_something()]
  834. )
  835. component2.create(
  836. on_prop_event=lambda _: [
  837. test_state.do_something_arg(1),
  838. test_state.do_something(),
  839. ]
  840. )
  841. # Return EventHandler (1 arg) and EventSpec.
  842. component2.create(
  843. on_open=lambda _: [test_state.do_something_arg, test_state.do_something()]
  844. )
  845. component2.create(
  846. on_prop_event=lambda _: [test_state.do_something_arg, test_state.do_something()]
  847. )
  848. def test_get_hooks_nested(component1, component2, component3):
  849. """Test that a component returns hooks from child components.
  850. Args:
  851. component1: test component.
  852. component2: another component.
  853. component3: component with hooks defined.
  854. """
  855. c = component1.create(
  856. component2.create(arr=[]),
  857. component3.create(),
  858. component3.create(),
  859. component3.create(),
  860. text="a",
  861. number=1,
  862. )
  863. assert c._get_all_hooks() == component3()._get_all_hooks()
  864. def test_get_hooks_nested2(component3, component4):
  865. """Test that a component returns both when parent and child have hooks.
  866. Args:
  867. component3: component with hooks defined.
  868. component4: component with different hooks defined.
  869. """
  870. exp_hooks = {**component3()._get_all_hooks(), **component4()._get_all_hooks()}
  871. assert component3.create(component4.create())._get_all_hooks() == exp_hooks
  872. assert component4.create(component3.create())._get_all_hooks() == exp_hooks
  873. assert (
  874. component4.create(
  875. component3.create(),
  876. component4.create(),
  877. component3.create(),
  878. )._get_all_hooks()
  879. == exp_hooks
  880. )
  881. @pytest.mark.parametrize("fixture", ["component5", "component6"])
  882. def test_unsupported_child_components(fixture, request):
  883. """Test that a value error is raised when an unsupported component (a child component found in the
  884. component's invalid children list) is provided as a child.
  885. Args:
  886. fixture: the test component as a fixture.
  887. request: Pytest request.
  888. """
  889. component = request.getfixturevalue(fixture)
  890. with pytest.raises(ValueError) as err:
  891. comp = component.create(rx.text("testing component"))
  892. comp.render()
  893. assert (
  894. err.value.args[0]
  895. == f"The component `{component.__name__}` cannot have `Text` as a child component"
  896. )
  897. def test_unsupported_parent_components(component5):
  898. """Test that a value error is raised when an component is not in _valid_parents of one of its children.
  899. Args:
  900. component5: component with valid parent of "Text" only
  901. """
  902. with pytest.raises(ValueError) as err:
  903. rx.box(component5.create())
  904. assert (
  905. err.value.args[0]
  906. == f"The component `{component5.__name__}` can only be a child of the components: `{component5._valid_parents[0]}`. Got `Box` instead."
  907. )
  908. @pytest.mark.parametrize("fixture", ["component5", "component7"])
  909. def test_component_with_only_valid_children(fixture, request):
  910. """Test that a value error is raised when an unsupported component (a child component not found in the
  911. component's valid children list) is provided as a child.
  912. Args:
  913. fixture: the test component as a fixture.
  914. request: Pytest request.
  915. """
  916. component = request.getfixturevalue(fixture)
  917. with pytest.raises(ValueError) as err:
  918. comp = component.create(rx.box("testing component"))
  919. comp.render()
  920. assert (
  921. err.value.args[0]
  922. == f"The component `{component.__name__}` only allows the components: `Text` as children. "
  923. f"Got `Box` instead."
  924. )
  925. @pytest.mark.parametrize(
  926. "component,rendered",
  927. [
  928. (rx.text("hi"), '<RadixThemesText as={"p"}>\n {"hi"}\n</RadixThemesText>'),
  929. (
  930. rx.box(rx.heading("test", size="3")),
  931. '<RadixThemesBox>\n <RadixThemesHeading size={"3"}>\n {"test"}\n</RadixThemesHeading>\n</RadixThemesBox>',
  932. ),
  933. ],
  934. )
  935. def test_format_component(component, rendered):
  936. """Test that a component is formatted correctly.
  937. Args:
  938. component: The component to format.
  939. rendered: The expected rendered component.
  940. """
  941. assert str(component) == rendered
  942. def test_stateful_component(test_state):
  943. """Test that a stateful component is created correctly.
  944. Args:
  945. test_state: A test state.
  946. """
  947. text_component = rx.text(test_state.num)
  948. stateful_component = StatefulComponent.compile_from(text_component)
  949. assert isinstance(stateful_component, StatefulComponent)
  950. assert stateful_component.tag is not None
  951. assert stateful_component.tag.startswith("Text_")
  952. assert stateful_component.references == 1
  953. sc2 = StatefulComponent.compile_from(rx.text(test_state.num))
  954. assert isinstance(sc2, StatefulComponent)
  955. assert stateful_component.references == 2
  956. assert sc2.references == 2
  957. def test_stateful_component_memoize_event_trigger(test_state):
  958. """Test that a stateful component is created correctly with events.
  959. Args:
  960. test_state: A test state.
  961. """
  962. button_component = rx.button("Click me", on_click=test_state.do_something)
  963. stateful_component = StatefulComponent.compile_from(button_component)
  964. assert isinstance(stateful_component, StatefulComponent)
  965. # No event trigger? No StatefulComponent
  966. assert not isinstance(
  967. StatefulComponent.compile_from(rx.button("Click me")), StatefulComponent
  968. )
  969. def test_stateful_banner():
  970. """Test that a stateful component is created correctly with events."""
  971. connection_modal_component = rx.connection_modal()
  972. stateful_component = StatefulComponent.compile_from(connection_modal_component)
  973. assert isinstance(stateful_component, StatefulComponent)
  974. TEST_VAR = LiteralVar.create("test")._replace(
  975. merge_var_data=VarData(
  976. hooks={"useTest": None},
  977. imports={"test": [ImportVar(tag="test")]},
  978. state="Test",
  979. )
  980. )
  981. FORMATTED_TEST_VAR = LiteralVar.create(f"foo{TEST_VAR}bar")
  982. STYLE_VAR = TEST_VAR._replace(_var_name="style")
  983. EVENT_CHAIN_VAR = TEST_VAR._replace(_var_type=EventChain)
  984. ARG_VAR = ImmutableVar.create_safe("arg")
  985. TEST_VAR_DICT_OF_DICT = LiteralVar.create({"a": {"b": "test"}})._replace(
  986. merge_var_data=TEST_VAR._var_data
  987. )
  988. FORMATTED_TEST_VAR_DICT_OF_DICT = LiteralVar.create(
  989. {"a": {"b": f"footestbar"}}
  990. )._replace(merge_var_data=TEST_VAR._var_data)
  991. TEST_VAR_LIST_OF_LIST = LiteralVar.create([["test"]])._replace(
  992. merge_var_data=TEST_VAR._var_data
  993. )
  994. FORMATTED_TEST_VAR_LIST_OF_LIST = LiteralVar.create([["footestbar"]])._replace(
  995. merge_var_data=TEST_VAR._var_data
  996. )
  997. TEST_VAR_LIST_OF_LIST_OF_LIST = LiteralVar.create([[["test"]]])._replace(
  998. merge_var_data=TEST_VAR._var_data
  999. )
  1000. FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST = LiteralVar.create(
  1001. [[["footestbar"]]]
  1002. )._replace(merge_var_data=TEST_VAR._var_data)
  1003. TEST_VAR_LIST_OF_DICT = LiteralVar.create([{"a": "test"}])._replace(
  1004. merge_var_data=TEST_VAR._var_data
  1005. )
  1006. FORMATTED_TEST_VAR_LIST_OF_DICT = LiteralVar.create([{"a": "footestbar"}])._replace(
  1007. merge_var_data=TEST_VAR._var_data
  1008. )
  1009. class ComponentNestedVar(Component):
  1010. """A component with nested Var types."""
  1011. dict_of_dict: Var[Dict[str, Dict[str, str]]]
  1012. list_of_list: Var[List[List[str]]]
  1013. list_of_list_of_list: Var[List[List[List[str]]]]
  1014. list_of_dict: Var[List[Dict[str, str]]]
  1015. class EventState(rx.State):
  1016. """State for testing event handlers with _get_vars."""
  1017. v: int = 42
  1018. def handler(self):
  1019. """A handler that does nothing."""
  1020. def handler2(self, arg):
  1021. """A handler that takes an arg.
  1022. Args:
  1023. arg: An arg.
  1024. """
  1025. @pytest.mark.parametrize(
  1026. ("component", "exp_vars"),
  1027. (
  1028. pytest.param(
  1029. Bare.create(TEST_VAR),
  1030. [TEST_VAR],
  1031. id="direct-bare",
  1032. ),
  1033. pytest.param(
  1034. Bare.create(f"foo{TEST_VAR}bar"),
  1035. [FORMATTED_TEST_VAR],
  1036. id="fstring-bare",
  1037. ),
  1038. pytest.param(
  1039. rx.text(as_=TEST_VAR),
  1040. [TEST_VAR],
  1041. id="direct-prop",
  1042. ),
  1043. pytest.param(
  1044. rx.heading(as_=f"foo{TEST_VAR}bar"),
  1045. [FORMATTED_TEST_VAR],
  1046. id="fstring-prop",
  1047. ),
  1048. pytest.param(
  1049. rx.fragment(id=TEST_VAR),
  1050. [TEST_VAR],
  1051. id="direct-id",
  1052. ),
  1053. pytest.param(
  1054. rx.fragment(id=f"foo{TEST_VAR}bar"),
  1055. [FORMATTED_TEST_VAR],
  1056. id="fstring-id",
  1057. ),
  1058. pytest.param(
  1059. rx.fragment(key=TEST_VAR),
  1060. [TEST_VAR],
  1061. id="direct-key",
  1062. ),
  1063. pytest.param(
  1064. rx.fragment(key=f"foo{TEST_VAR}bar"),
  1065. [FORMATTED_TEST_VAR],
  1066. id="fstring-key",
  1067. ),
  1068. pytest.param(
  1069. rx.fragment(class_name=TEST_VAR),
  1070. [TEST_VAR],
  1071. id="direct-class_name",
  1072. ),
  1073. pytest.param(
  1074. rx.fragment(class_name=f"foo{TEST_VAR}bar"),
  1075. [FORMATTED_TEST_VAR],
  1076. id="fstring-class_name",
  1077. ),
  1078. pytest.param(
  1079. rx.fragment(special_props={TEST_VAR}),
  1080. [TEST_VAR],
  1081. id="direct-special_props",
  1082. ),
  1083. pytest.param(
  1084. rx.fragment(special_props={LiteralVar.create(f"foo{TEST_VAR}bar")}),
  1085. [FORMATTED_TEST_VAR],
  1086. id="fstring-special_props",
  1087. ),
  1088. pytest.param(
  1089. # custom_attrs cannot accept a Var directly as a value
  1090. rx.fragment(custom_attrs={"href": f"{TEST_VAR}"}),
  1091. [TEST_VAR],
  1092. id="fstring-custom_attrs-nofmt",
  1093. ),
  1094. pytest.param(
  1095. rx.fragment(custom_attrs={"href": f"foo{TEST_VAR}bar"}),
  1096. [FORMATTED_TEST_VAR],
  1097. id="fstring-custom_attrs",
  1098. ),
  1099. pytest.param(
  1100. rx.fragment(background_color=TEST_VAR),
  1101. [STYLE_VAR],
  1102. id="direct-background_color",
  1103. ),
  1104. pytest.param(
  1105. rx.fragment(background_color=f"foo{TEST_VAR}bar"),
  1106. [STYLE_VAR],
  1107. id="fstring-background_color",
  1108. ),
  1109. pytest.param(
  1110. rx.fragment(style={"background_color": TEST_VAR}), # type: ignore
  1111. [STYLE_VAR],
  1112. id="direct-style-background_color",
  1113. ),
  1114. pytest.param(
  1115. rx.fragment(style={"background_color": f"foo{TEST_VAR}bar"}), # type: ignore
  1116. [STYLE_VAR],
  1117. id="fstring-style-background_color",
  1118. ),
  1119. pytest.param(
  1120. rx.fragment(on_click=EVENT_CHAIN_VAR), # type: ignore
  1121. [EVENT_CHAIN_VAR],
  1122. id="direct-event-chain",
  1123. ),
  1124. pytest.param(
  1125. rx.fragment(on_click=EventState.handler),
  1126. [],
  1127. id="direct-event-handler",
  1128. ),
  1129. pytest.param(
  1130. rx.fragment(on_click=EventState.handler2(TEST_VAR)), # type: ignore
  1131. [ARG_VAR, TEST_VAR],
  1132. id="direct-event-handler-arg",
  1133. ),
  1134. pytest.param(
  1135. rx.fragment(on_click=EventState.handler2(EventState.v)), # type: ignore
  1136. [ARG_VAR, EventState.v],
  1137. id="direct-event-handler-arg2",
  1138. ),
  1139. pytest.param(
  1140. rx.fragment(on_click=lambda: EventState.handler2(TEST_VAR)), # type: ignore
  1141. [ARG_VAR, TEST_VAR],
  1142. id="direct-event-handler-lambda",
  1143. ),
  1144. pytest.param(
  1145. ComponentNestedVar.create(dict_of_dict={"a": {"b": TEST_VAR}}),
  1146. [TEST_VAR_DICT_OF_DICT],
  1147. id="direct-dict_of_dict",
  1148. ),
  1149. pytest.param(
  1150. ComponentNestedVar.create(dict_of_dict={"a": {"b": f"foo{TEST_VAR}bar"}}),
  1151. [FORMATTED_TEST_VAR_DICT_OF_DICT],
  1152. id="fstring-dict_of_dict",
  1153. ),
  1154. pytest.param(
  1155. ComponentNestedVar.create(list_of_list=[[TEST_VAR]]),
  1156. [TEST_VAR_LIST_OF_LIST],
  1157. id="direct-list_of_list",
  1158. ),
  1159. pytest.param(
  1160. ComponentNestedVar.create(list_of_list=[[f"foo{TEST_VAR}bar"]]),
  1161. [FORMATTED_TEST_VAR_LIST_OF_LIST],
  1162. id="fstring-list_of_list",
  1163. ),
  1164. pytest.param(
  1165. ComponentNestedVar.create(list_of_list_of_list=[[[TEST_VAR]]]),
  1166. [TEST_VAR_LIST_OF_LIST_OF_LIST],
  1167. id="direct-list_of_list_of_list",
  1168. ),
  1169. pytest.param(
  1170. ComponentNestedVar.create(list_of_list_of_list=[[[f"foo{TEST_VAR}bar"]]]),
  1171. [FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST],
  1172. id="fstring-list_of_list_of_list",
  1173. ),
  1174. pytest.param(
  1175. ComponentNestedVar.create(list_of_dict=[{"a": TEST_VAR}]),
  1176. [TEST_VAR_LIST_OF_DICT],
  1177. id="direct-list_of_dict",
  1178. ),
  1179. pytest.param(
  1180. ComponentNestedVar.create(list_of_dict=[{"a": f"foo{TEST_VAR}bar"}]),
  1181. [FORMATTED_TEST_VAR_LIST_OF_DICT],
  1182. id="fstring-list_of_dict",
  1183. ),
  1184. ),
  1185. )
  1186. def test_get_vars(component, exp_vars):
  1187. comp_vars = sorted(component._get_vars(), key=lambda v: v._var_name)
  1188. assert len(comp_vars) == len(exp_vars)
  1189. print(comp_vars, exp_vars)
  1190. for comp_var, exp_var in zip(
  1191. comp_vars,
  1192. sorted(exp_vars, key=lambda v: v._var_name),
  1193. ):
  1194. # print(str(comp_var), str(exp_var))
  1195. # print(comp_var._get_all_var_data(), exp_var._get_all_var_data())
  1196. assert comp_var.equals(exp_var)
  1197. def test_instantiate_all_components():
  1198. """Test that all components can be instantiated."""
  1199. # These components all have required arguments and cannot be trivially instantiated.
  1200. untested_components = {
  1201. "Card",
  1202. "Cond",
  1203. "DebounceInput",
  1204. "Foreach",
  1205. "FormControl",
  1206. "Html",
  1207. "Icon",
  1208. "Match",
  1209. "Markdown",
  1210. "MultiSelect",
  1211. "Option",
  1212. "Popover",
  1213. "Radio",
  1214. "Script",
  1215. "Tag",
  1216. "Tfoot",
  1217. "Thead",
  1218. }
  1219. component_nested_list = [
  1220. *rx.RADIX_MAPPING.values(),
  1221. *rx.COMPONENTS_BASE_MAPPING.values(),
  1222. *rx.COMPONENTS_CORE_MAPPING.values(),
  1223. ]
  1224. for component_name in [
  1225. comp_name
  1226. for submodule_list in component_nested_list
  1227. for comp_name in submodule_list
  1228. ]: # type: ignore
  1229. if component_name in untested_components:
  1230. continue
  1231. component = getattr(
  1232. rx,
  1233. (
  1234. component_name
  1235. if not isinstance(component_name, tuple)
  1236. else component_name[1]
  1237. ),
  1238. )
  1239. if isinstance(component, type) and issubclass(component, Component):
  1240. component.create()
  1241. class InvalidParentComponent(Component):
  1242. """Invalid Parent Component."""
  1243. ...
  1244. class ValidComponent1(Component):
  1245. """Test valid component."""
  1246. _valid_children = ["ValidComponent2"]
  1247. class ValidComponent2(Component):
  1248. """Test valid component."""
  1249. ...
  1250. class ValidComponent3(Component):
  1251. """Test valid component."""
  1252. _valid_parents = ["ValidComponent2"]
  1253. class ValidComponent4(Component):
  1254. """Test valid component."""
  1255. _invalid_children = ["InvalidComponent"]
  1256. class InvalidComponent(Component):
  1257. """Test invalid component."""
  1258. ...
  1259. valid_component1 = ValidComponent1.create
  1260. valid_component2 = ValidComponent2.create
  1261. invalid_component = InvalidComponent.create
  1262. valid_component3 = ValidComponent3.create
  1263. invalid_parent = InvalidParentComponent.create
  1264. valid_component4 = ValidComponent4.create
  1265. def test_validate_valid_children():
  1266. valid_component1(valid_component2())
  1267. valid_component1(
  1268. rx.fragment(valid_component2()),
  1269. )
  1270. valid_component1(
  1271. rx.fragment(
  1272. rx.fragment(
  1273. rx.fragment(valid_component2()),
  1274. ),
  1275. ),
  1276. )
  1277. valid_component1(
  1278. rx.cond( # type: ignore
  1279. True,
  1280. rx.fragment(valid_component2()),
  1281. rx.fragment(
  1282. rx.foreach(LiteralVar.create([1, 2, 3]), lambda x: valid_component2(x)) # type: ignore
  1283. ),
  1284. )
  1285. )
  1286. valid_component1(
  1287. rx.cond(
  1288. True,
  1289. valid_component2(),
  1290. rx.fragment(
  1291. rx.match(
  1292. "condition",
  1293. ("first", valid_component2()),
  1294. rx.fragment(valid_component2(rx.text("default"))),
  1295. )
  1296. ),
  1297. )
  1298. )
  1299. valid_component1(
  1300. rx.match(
  1301. "condition",
  1302. ("first", valid_component2()),
  1303. ("second", "third", rx.fragment(valid_component2())),
  1304. (
  1305. "fourth",
  1306. rx.cond(True, valid_component2(), rx.fragment(valid_component2())),
  1307. ),
  1308. (
  1309. "fifth",
  1310. rx.match(
  1311. "nested_condition",
  1312. ("nested_first", valid_component2()),
  1313. rx.fragment(valid_component2()),
  1314. ),
  1315. valid_component2(),
  1316. ),
  1317. )
  1318. )
  1319. def test_validate_valid_parents():
  1320. valid_component2(valid_component3())
  1321. valid_component2(
  1322. rx.fragment(valid_component3()),
  1323. )
  1324. valid_component1(
  1325. rx.fragment(
  1326. valid_component2(
  1327. rx.fragment(valid_component3()),
  1328. ),
  1329. ),
  1330. )
  1331. valid_component2(
  1332. rx.cond( # type: ignore
  1333. True,
  1334. rx.fragment(valid_component3()),
  1335. rx.fragment(
  1336. rx.foreach(
  1337. LiteralVar.create([1, 2, 3]), # type: ignore
  1338. lambda x: valid_component2(valid_component3(x)),
  1339. )
  1340. ),
  1341. )
  1342. )
  1343. valid_component2(
  1344. rx.cond(
  1345. True,
  1346. valid_component3(),
  1347. rx.fragment(
  1348. rx.match(
  1349. "condition",
  1350. ("first", valid_component3()),
  1351. rx.fragment(valid_component3(rx.text("default"))),
  1352. )
  1353. ),
  1354. )
  1355. )
  1356. valid_component2(
  1357. rx.match(
  1358. "condition",
  1359. ("first", valid_component3()),
  1360. ("second", "third", rx.fragment(valid_component3())),
  1361. (
  1362. "fourth",
  1363. rx.cond(True, valid_component3(), rx.fragment(valid_component3())),
  1364. ),
  1365. (
  1366. "fifth",
  1367. rx.match(
  1368. "nested_condition",
  1369. ("nested_first", valid_component3()),
  1370. rx.fragment(valid_component3()),
  1371. ),
  1372. valid_component3(),
  1373. ),
  1374. )
  1375. )
  1376. def test_validate_invalid_children():
  1377. with pytest.raises(ValueError):
  1378. valid_component4(invalid_component())
  1379. with pytest.raises(ValueError):
  1380. valid_component4(
  1381. rx.fragment(invalid_component()),
  1382. )
  1383. with pytest.raises(ValueError):
  1384. valid_component2(
  1385. rx.fragment(
  1386. valid_component4(
  1387. rx.fragment(invalid_component()),
  1388. ),
  1389. ),
  1390. )
  1391. with pytest.raises(ValueError):
  1392. valid_component4(
  1393. rx.cond( # type: ignore
  1394. True,
  1395. rx.fragment(invalid_component()),
  1396. rx.fragment(
  1397. rx.foreach(
  1398. LiteralVar.create([1, 2, 3]), lambda x: invalid_component(x)
  1399. ) # type: ignore
  1400. ),
  1401. )
  1402. )
  1403. with pytest.raises(ValueError):
  1404. valid_component4(
  1405. rx.cond(
  1406. True,
  1407. invalid_component(),
  1408. rx.fragment(
  1409. rx.match(
  1410. "condition",
  1411. ("first", invalid_component()),
  1412. rx.fragment(invalid_component(rx.text("default"))),
  1413. )
  1414. ),
  1415. )
  1416. )
  1417. with pytest.raises(ValueError):
  1418. valid_component4(
  1419. rx.match(
  1420. "condition",
  1421. ("first", invalid_component()),
  1422. ("second", "third", rx.fragment(invalid_component())),
  1423. (
  1424. "fourth",
  1425. rx.cond(True, invalid_component(), rx.fragment(valid_component2())),
  1426. ),
  1427. (
  1428. "fifth",
  1429. rx.match(
  1430. "nested_condition",
  1431. ("nested_first", invalid_component()),
  1432. rx.fragment(invalid_component()),
  1433. ),
  1434. invalid_component(),
  1435. ),
  1436. )
  1437. )
  1438. def test_rename_props():
  1439. """Test that _rename_props works and is inherited."""
  1440. class C1(Component):
  1441. tag = "C1"
  1442. prop1: Var[str]
  1443. prop2: Var[str]
  1444. _rename_props = {"prop1": "renamed_prop1", "prop2": "renamed_prop2"}
  1445. class C2(C1):
  1446. tag = "C2"
  1447. prop3: Var[str]
  1448. _rename_props = {"prop2": "subclass_prop2", "prop3": "renamed_prop3"}
  1449. c1 = C1.create(prop1="prop1_1", prop2="prop2_1")
  1450. rendered_c1 = c1.render()
  1451. assert 'renamed_prop1={"prop1_1"}' in rendered_c1["props"]
  1452. assert 'renamed_prop2={"prop2_1"}' in rendered_c1["props"]
  1453. c2 = C2.create(prop1="prop1_2", prop2="prop2_2", prop3="prop3_2")
  1454. rendered_c2 = c2.render()
  1455. assert 'renamed_prop1={"prop1_2"}' in rendered_c2["props"]
  1456. assert 'subclass_prop2={"prop2_2"}' in rendered_c2["props"]
  1457. assert 'renamed_prop3={"prop3_2"}' in rendered_c2["props"]
  1458. def test_custom_component_get_imports():
  1459. class Inner(Component):
  1460. tag = "Inner"
  1461. library = "inner"
  1462. class Other(Component):
  1463. tag = "Other"
  1464. library = "other"
  1465. @rx.memo
  1466. def wrapper():
  1467. return Inner.create()
  1468. @rx.memo
  1469. def outer(c: Component):
  1470. return Other.create(c)
  1471. custom_comp = wrapper()
  1472. # Inner is not imported directly, but it is imported by the custom component.
  1473. assert "inner" not in custom_comp._get_all_imports()
  1474. # The imports are only resolved during compilation.
  1475. _, _, imports_inner = compile_components(custom_comp._get_all_custom_components())
  1476. assert "inner" in imports_inner
  1477. outer_comp = outer(c=wrapper())
  1478. # Libraries are not imported directly, but are imported by the custom component.
  1479. assert "inner" not in outer_comp._get_all_imports()
  1480. assert "other" not in outer_comp._get_all_imports()
  1481. # The imports are only resolved during compilation.
  1482. _, _, imports_outer = compile_components(outer_comp._get_all_custom_components())
  1483. assert "inner" in imports_outer
  1484. assert "other" in imports_outer
  1485. def test_custom_component_declare_event_handlers_in_fields():
  1486. class ReferenceComponent(Component):
  1487. def get_event_triggers(self) -> Dict[str, Any]:
  1488. """Test controlled triggers.
  1489. Returns:
  1490. Test controlled triggers.
  1491. """
  1492. return {
  1493. **super().get_event_triggers(),
  1494. "on_a": lambda e0: [e0],
  1495. "on_b": lambda e0: [e0.target.value],
  1496. "on_c": lambda e0: [],
  1497. "on_d": lambda: [],
  1498. "on_e": lambda: [],
  1499. "on_f": lambda a, b, c: [c, b, a],
  1500. }
  1501. class TestComponent(Component):
  1502. on_a: EventHandler[lambda e0: [e0]]
  1503. on_b: EventHandler[lambda e0: [e0.target.value]]
  1504. on_c: EventHandler[lambda e0: []]
  1505. on_d: EventHandler[lambda: []]
  1506. on_e: EventHandler
  1507. on_f: EventHandler[lambda a, b, c: [c, b, a]]
  1508. custom_component = ReferenceComponent.create()
  1509. test_component = TestComponent.create()
  1510. custom_triggers = custom_component.get_event_triggers()
  1511. test_triggers = test_component.get_event_triggers()
  1512. assert custom_triggers.keys() == test_triggers.keys()
  1513. for trigger_name in custom_component.get_event_triggers():
  1514. for v1, v2 in zip(
  1515. parse_args_spec(test_triggers[trigger_name]),
  1516. parse_args_spec(custom_triggers[trigger_name]),
  1517. ):
  1518. assert v1.equals(v2)
  1519. def test_invalid_event_trigger():
  1520. class TriggerComponent(Component):
  1521. on_push: Var[bool]
  1522. def get_event_triggers(self) -> Dict[str, Any]:
  1523. """Test controlled triggers.
  1524. Returns:
  1525. Test controlled triggers.
  1526. """
  1527. return {
  1528. **super().get_event_triggers(),
  1529. "on_a": lambda: [],
  1530. }
  1531. trigger_comp = TriggerComponent.create
  1532. # test that these do not throw errors.
  1533. trigger_comp(on_push=True)
  1534. trigger_comp(on_a=rx.console_log("log"))
  1535. with pytest.raises(ValueError):
  1536. trigger_comp(on_b=rx.console_log("log"))
  1537. @pytest.mark.parametrize(
  1538. "tags",
  1539. (
  1540. ["Component"],
  1541. ["Component", "useState"],
  1542. [ImportVar(tag="Component")],
  1543. [ImportVar(tag="Component"), ImportVar(tag="useState")],
  1544. ["Component", ImportVar(tag="useState")],
  1545. ),
  1546. )
  1547. def test_component_add_imports(tags):
  1548. class BaseComponent(Component):
  1549. def _get_imports(self) -> ImportDict:
  1550. return {}
  1551. class Reference(Component):
  1552. def _get_imports(self) -> ParsedImportDict:
  1553. return imports.merge_imports(
  1554. super()._get_imports(),
  1555. parse_imports({"react": tags}),
  1556. {"foo": [ImportVar(tag="bar")]},
  1557. )
  1558. class TestBase(Component):
  1559. def add_imports(
  1560. self,
  1561. ) -> Dict[str, Union[str, ImportVar, List[str], List[ImportVar]]]:
  1562. return {"foo": "bar"}
  1563. class Test(TestBase):
  1564. def add_imports(
  1565. self,
  1566. ) -> Dict[str, Union[str, ImportVar, List[str], List[ImportVar]]]:
  1567. return {"react": (tags[0] if len(tags) == 1 else tags)}
  1568. baseline = Reference.create()
  1569. test = Test.create()
  1570. assert baseline._get_all_imports() == parse_imports(
  1571. {
  1572. "react": tags,
  1573. "foo": [ImportVar(tag="bar")],
  1574. }
  1575. )
  1576. assert test._get_all_imports() == baseline._get_all_imports()
  1577. def test_component_add_hooks():
  1578. class BaseComponent(Component):
  1579. def _get_hooks(self):
  1580. return "const hook1 = 42"
  1581. class ChildComponent1(BaseComponent):
  1582. pass
  1583. class GrandchildComponent1(ChildComponent1):
  1584. def add_hooks(self):
  1585. return [
  1586. "const hook2 = 43",
  1587. "const hook3 = 44",
  1588. ]
  1589. class GreatGrandchildComponent1(GrandchildComponent1):
  1590. def add_hooks(self):
  1591. return [
  1592. "const hook4 = 45",
  1593. ]
  1594. class GrandchildComponent2(ChildComponent1):
  1595. def _get_hooks(self):
  1596. return "const hook5 = 46"
  1597. class GreatGrandchildComponent2(GrandchildComponent2):
  1598. def add_hooks(self):
  1599. return [
  1600. "const hook2 = 43",
  1601. "const hook6 = 47",
  1602. ]
  1603. assert list(BaseComponent()._get_all_hooks()) == ["const hook1 = 42"]
  1604. assert list(ChildComponent1()._get_all_hooks()) == ["const hook1 = 42"]
  1605. assert list(GrandchildComponent1()._get_all_hooks()) == [
  1606. "const hook1 = 42",
  1607. "const hook2 = 43",
  1608. "const hook3 = 44",
  1609. ]
  1610. assert list(GreatGrandchildComponent1()._get_all_hooks()) == [
  1611. "const hook1 = 42",
  1612. "const hook2 = 43",
  1613. "const hook3 = 44",
  1614. "const hook4 = 45",
  1615. ]
  1616. assert list(GrandchildComponent2()._get_all_hooks()) == ["const hook5 = 46"]
  1617. assert list(GreatGrandchildComponent2()._get_all_hooks()) == [
  1618. "const hook5 = 46",
  1619. "const hook2 = 43",
  1620. "const hook6 = 47",
  1621. ]
  1622. assert list(
  1623. BaseComponent.create(
  1624. GrandchildComponent1.create(GreatGrandchildComponent2()),
  1625. GreatGrandchildComponent1(),
  1626. )._get_all_hooks(),
  1627. ) == [
  1628. "const hook1 = 42",
  1629. "const hook2 = 43",
  1630. "const hook3 = 44",
  1631. "const hook5 = 46",
  1632. "const hook6 = 47",
  1633. "const hook4 = 45",
  1634. ]
  1635. assert list(
  1636. Fragment.create(
  1637. GreatGrandchildComponent2(),
  1638. GreatGrandchildComponent1(),
  1639. )._get_all_hooks()
  1640. ) == [
  1641. "const hook5 = 46",
  1642. "const hook2 = 43",
  1643. "const hook6 = 47",
  1644. "const hook1 = 42",
  1645. "const hook3 = 44",
  1646. "const hook4 = 45",
  1647. ]
  1648. def test_component_add_custom_code():
  1649. class BaseComponent(Component):
  1650. def _get_custom_code(self):
  1651. return "const custom_code1 = 42"
  1652. class ChildComponent1(BaseComponent):
  1653. pass
  1654. class GrandchildComponent1(ChildComponent1):
  1655. def add_custom_code(self):
  1656. return [
  1657. "const custom_code2 = 43",
  1658. "const custom_code3 = 44",
  1659. ]
  1660. class GreatGrandchildComponent1(GrandchildComponent1):
  1661. def add_custom_code(self):
  1662. return [
  1663. "const custom_code4 = 45",
  1664. ]
  1665. class GrandchildComponent2(ChildComponent1):
  1666. def _get_custom_code(self):
  1667. return "const custom_code5 = 46"
  1668. class GreatGrandchildComponent2(GrandchildComponent2):
  1669. def add_custom_code(self):
  1670. return [
  1671. "const custom_code2 = 43",
  1672. "const custom_code6 = 47",
  1673. ]
  1674. assert BaseComponent()._get_all_custom_code() == {"const custom_code1 = 42"}
  1675. assert ChildComponent1()._get_all_custom_code() == {"const custom_code1 = 42"}
  1676. assert GrandchildComponent1()._get_all_custom_code() == {
  1677. "const custom_code1 = 42",
  1678. "const custom_code2 = 43",
  1679. "const custom_code3 = 44",
  1680. }
  1681. assert GreatGrandchildComponent1()._get_all_custom_code() == {
  1682. "const custom_code1 = 42",
  1683. "const custom_code2 = 43",
  1684. "const custom_code3 = 44",
  1685. "const custom_code4 = 45",
  1686. }
  1687. assert GrandchildComponent2()._get_all_custom_code() == {"const custom_code5 = 46"}
  1688. assert GreatGrandchildComponent2()._get_all_custom_code() == {
  1689. "const custom_code2 = 43",
  1690. "const custom_code5 = 46",
  1691. "const custom_code6 = 47",
  1692. }
  1693. assert BaseComponent.create(
  1694. GrandchildComponent1.create(GreatGrandchildComponent2()),
  1695. GreatGrandchildComponent1(),
  1696. )._get_all_custom_code() == {
  1697. "const custom_code1 = 42",
  1698. "const custom_code2 = 43",
  1699. "const custom_code3 = 44",
  1700. "const custom_code4 = 45",
  1701. "const custom_code5 = 46",
  1702. "const custom_code6 = 47",
  1703. }
  1704. assert Fragment.create(
  1705. GreatGrandchildComponent2(),
  1706. GreatGrandchildComponent1(),
  1707. )._get_all_custom_code() == {
  1708. "const custom_code1 = 42",
  1709. "const custom_code2 = 43",
  1710. "const custom_code3 = 44",
  1711. "const custom_code4 = 45",
  1712. "const custom_code5 = 46",
  1713. "const custom_code6 = 47",
  1714. }
  1715. def test_component_add_hooks_var():
  1716. class HookComponent(Component):
  1717. def add_hooks(self):
  1718. return [
  1719. "const hook3 = useRef(null)",
  1720. "const hook1 = 42",
  1721. ImmutableVar.create(
  1722. "useEffect(() => () => {}, [])",
  1723. _var_data=VarData(
  1724. hooks={
  1725. "const hook2 = 43": None,
  1726. "const hook3 = useRef(null)": None,
  1727. },
  1728. imports={"react": [ImportVar(tag="useEffect")]},
  1729. ),
  1730. ),
  1731. ImmutableVar.create(
  1732. "const hook3 = useRef(null)",
  1733. _var_data=VarData(
  1734. imports={"react": [ImportVar(tag="useRef")]},
  1735. ),
  1736. ),
  1737. ]
  1738. assert list(HookComponent()._get_all_hooks()) == [
  1739. "const hook3 = useRef(null)",
  1740. "const hook1 = 42",
  1741. "const hook2 = 43",
  1742. "useEffect(() => () => {}, [])",
  1743. ]
  1744. imports = HookComponent()._get_all_imports()
  1745. assert len(imports) == 1
  1746. assert "react" in imports
  1747. assert len(imports["react"]) == 2
  1748. assert ImportVar(tag="useRef") in imports["react"]
  1749. assert ImportVar(tag="useEffect") in imports["react"]
  1750. def test_add_style_embedded_vars(test_state: BaseState):
  1751. """Test that add_style works with embedded vars when returning a plain dict.
  1752. Args:
  1753. test_state: A test state.
  1754. """
  1755. v0 = LiteralVar.create("parent")._replace(
  1756. merge_var_data=VarData(hooks={"useParent": None}), # type: ignore
  1757. )
  1758. v1 = rx.color("plum", 10)
  1759. v2 = LiteralVar.create("text")._replace(
  1760. merge_var_data=VarData(hooks={"useText": None}), # type: ignore
  1761. )
  1762. class ParentComponent(Component):
  1763. def add_style(self):
  1764. return Style(
  1765. {
  1766. "fake_parent": v0,
  1767. }
  1768. )
  1769. class StyledComponent(ParentComponent):
  1770. tag = "StyledComponent"
  1771. def add_style(self):
  1772. return {
  1773. "color": v1,
  1774. "fake": v2,
  1775. "margin": f"{test_state.num}%",
  1776. }
  1777. page = rx.vstack(StyledComponent.create())
  1778. page._add_style_recursive(Style())
  1779. assert (
  1780. f"const {test_state.get_name()} = useContext(StateContexts.{test_state.get_name()})"
  1781. in page._get_all_hooks_internal()
  1782. )
  1783. assert "useText" in page._get_all_hooks_internal()
  1784. assert "useParent" in page._get_all_hooks_internal()
  1785. assert (
  1786. str(page).count(
  1787. f'css={{({{ ["fakeParent"] : "parent", ["color"] : "var(--plum-10)", ["fake"] : "text", ["margin"] : ({test_state.get_name()}.num+"%") }})}}'
  1788. )
  1789. == 1
  1790. )
  1791. def test_add_style_foreach():
  1792. class StyledComponent(Component):
  1793. tag = "StyledComponent"
  1794. ix: Var[int]
  1795. def add_style(self):
  1796. return Style({"color": "red"})
  1797. page = rx.vstack(rx.foreach(Var.range(3), lambda i: StyledComponent.create(i)))
  1798. page._add_style_recursive(Style())
  1799. # Expect only a single child of the foreach on the python side
  1800. assert len(page.children[0].children) == 1
  1801. # Expect the style to be added to the child of the foreach
  1802. assert 'css={({ ["color"] : "red" })}' in str(page.children[0].children[0])
  1803. # Expect only one instance of this CSS dict in the rendered page
  1804. assert str(page).count('css={({ ["color"] : "red" })}') == 1
  1805. class TriggerState(rx.State):
  1806. """Test state with event handlers."""
  1807. def do_something(self):
  1808. """Sample event handler."""
  1809. pass
  1810. @pytest.mark.parametrize(
  1811. "component, output",
  1812. [
  1813. (rx.box(rx.text("random text")), False),
  1814. (
  1815. rx.box(rx.text("random text", on_click=rx.console_log("log"))),
  1816. False,
  1817. ),
  1818. (
  1819. rx.box(
  1820. rx.text("random text", on_click=TriggerState.do_something),
  1821. rx.text(
  1822. "random text",
  1823. on_click=ImmutableVar(
  1824. _var_name="toggleColorMode", _var_type=EventChain
  1825. ),
  1826. ),
  1827. ),
  1828. True,
  1829. ),
  1830. (
  1831. rx.box(
  1832. rx.text("random text", on_click=rx.console_log("log")),
  1833. rx.text(
  1834. "random text",
  1835. on_click=ImmutableVar(
  1836. _var_name="toggleColorMode", _var_type=EventChain
  1837. ),
  1838. ),
  1839. ),
  1840. False,
  1841. ),
  1842. (
  1843. rx.box(rx.text("random text", on_click=TriggerState.do_something)),
  1844. True,
  1845. ),
  1846. (
  1847. rx.box(
  1848. rx.text(
  1849. "random text",
  1850. on_click=[rx.console_log("log"), rx.window_alert("alert")],
  1851. ),
  1852. ),
  1853. False,
  1854. ),
  1855. (
  1856. rx.box(
  1857. rx.text(
  1858. "random text",
  1859. on_click=[rx.console_log("log"), TriggerState.do_something],
  1860. ),
  1861. ),
  1862. True,
  1863. ),
  1864. (
  1865. rx.box(
  1866. rx.text(
  1867. "random text",
  1868. on_blur=lambda: TriggerState.do_something,
  1869. ),
  1870. ),
  1871. True,
  1872. ),
  1873. ],
  1874. )
  1875. def test_has_state_event_triggers(component, output):
  1876. assert component._has_stateful_event_triggers() == output