sequence.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. """Collection of string classes and utilities."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import functools
  5. import inspect
  6. import json
  7. import re
  8. import sys
  9. import typing
  10. from typing import (
  11. TYPE_CHECKING,
  12. Any,
  13. Callable,
  14. ClassVar,
  15. List,
  16. Sequence,
  17. Set,
  18. Tuple,
  19. Type,
  20. Union,
  21. cast,
  22. )
  23. from typing_extensions import TypeAliasType, TypeVar
  24. from reflex import constants
  25. from reflex.constants.base import REFLEX_VAR_OPENING_TAG
  26. from reflex.constants.colors import Color
  27. from reflex.utils.exceptions import VarTypeError
  28. from reflex.utils.types import GenericType, get_origin
  29. from .base import (
  30. CachedVarOperation,
  31. CustomVarOperationReturn,
  32. LiteralVar,
  33. ReflexCallable,
  34. Var,
  35. VarData,
  36. VarWithDefault,
  37. _global_vars,
  38. cached_property_no_lock,
  39. figure_out_type,
  40. get_python_literal,
  41. get_unique_variable_name,
  42. nary_type_computer,
  43. passthrough_unary_type_computer,
  44. unionize,
  45. unwrap_reflex_callalbe,
  46. var_operation,
  47. var_operation_return,
  48. )
  49. from .number import (
  50. _AT_SLICE_IMPORT,
  51. _IS_TRUE_IMPORT,
  52. _RANGE_IMPORT,
  53. LiteralNumberVar,
  54. NumberVar,
  55. raise_unsupported_operand_types,
  56. ternary_operation,
  57. )
  58. if TYPE_CHECKING:
  59. from .function import FunctionVar
  60. STRING_TYPE = TypeVar("STRING_TYPE", default=str)
  61. ARRAY_VAR_TYPE = TypeVar("ARRAY_VAR_TYPE", bound=Union[Set, Tuple, Sequence])
  62. OTHER_ARRAY_VAR_TYPE = TypeVar(
  63. "OTHER_ARRAY_VAR_TYPE", bound=Union[Set, Tuple, Sequence]
  64. )
  65. INNER_ARRAY_VAR = TypeVar("INNER_ARRAY_VAR", covariant=True)
  66. ANOTHER_ARRAY_VAR = TypeVar("ANOTHER_ARRAY_VAR", covariant=True)
  67. KEY_TYPE = TypeVar("KEY_TYPE")
  68. VALUE_TYPE = TypeVar("VALUE_TYPE")
  69. @var_operation
  70. def string_lt_operation(lhs: Var[str], rhs: Var[str]):
  71. """Check if a string is less than another string.
  72. Args:
  73. lhs: The left-hand side string.
  74. rhs: The right-hand side string.
  75. Returns:
  76. The string less than operation.
  77. """
  78. return var_operation_return(js_expression=f"{lhs} < {rhs}", var_type=bool)
  79. @var_operation
  80. def string_gt_operation(lhs: Var[str], rhs: Var[str]):
  81. """Check if a string is greater than another string.
  82. Args:
  83. lhs: The left-hand side string.
  84. rhs: The right-hand side string.
  85. Returns:
  86. The string greater than operation.
  87. """
  88. return var_operation_return(js_expression=f"{lhs} > {rhs}", var_type=bool)
  89. @var_operation
  90. def string_le_operation(lhs: Var[str], rhs: Var[str]):
  91. """Check if a string is less than or equal to another string.
  92. Args:
  93. lhs: The left-hand side string.
  94. rhs: The right-hand side string.
  95. Returns:
  96. The string less than or equal operation.
  97. """
  98. return var_operation_return(js_expression=f"{lhs} <= {rhs}", var_type=bool)
  99. @var_operation
  100. def string_ge_operation(lhs: Var[str], rhs: Var[str]):
  101. """Check if a string is greater than or equal to another string.
  102. Args:
  103. lhs: The left-hand side string.
  104. rhs: The right-hand side string.
  105. Returns:
  106. The string greater than or equal operation.
  107. """
  108. return var_operation_return(js_expression=f"{lhs} >= {rhs}", var_type=bool)
  109. @var_operation
  110. def string_lower_operation(string: Var[str]):
  111. """Convert a string to lowercase.
  112. Args:
  113. string: The string to convert.
  114. Returns:
  115. The lowercase string.
  116. """
  117. return var_operation_return(js_expression=f"{string}.toLowerCase()", var_type=str)
  118. @var_operation
  119. def string_upper_operation(string: Var[str]):
  120. """Convert a string to uppercase.
  121. Args:
  122. string: The string to convert.
  123. Returns:
  124. The uppercase string.
  125. """
  126. return var_operation_return(js_expression=f"{string}.toUpperCase()", var_type=str)
  127. @var_operation
  128. def string_strip_operation(string: Var[str]):
  129. """Strip a string.
  130. Args:
  131. string: The string to strip.
  132. Returns:
  133. The stripped string.
  134. """
  135. return var_operation_return(js_expression=f"{string}.trim()", var_type=str)
  136. @var_operation
  137. def string_contains_field_operation(
  138. haystack: Var[str],
  139. needle: Var[str],
  140. field: VarWithDefault[str] = VarWithDefault(""),
  141. ):
  142. """Check if a string contains another string.
  143. Args:
  144. haystack: The haystack.
  145. needle: The needle.
  146. field: The field to check.
  147. Returns:
  148. The string contains operation.
  149. """
  150. return var_operation_return(
  151. js_expression=f"isTrue({field}) ? {haystack}.some(obj => obj[{field}] === {needle}) : {haystack}.some(obj => obj === {needle})",
  152. var_type=bool,
  153. var_data=VarData(
  154. imports=_IS_TRUE_IMPORT,
  155. ),
  156. )
  157. @var_operation
  158. def string_contains_operation(haystack: Var[str], needle: Var[str]):
  159. """Check if a string contains another string.
  160. Args:
  161. haystack: The haystack.
  162. needle: The needle.
  163. Returns:
  164. The string contains operation.
  165. """
  166. return var_operation_return(
  167. js_expression=f"{haystack}.includes({needle})", var_type=bool
  168. )
  169. @var_operation
  170. def string_starts_with_operation(full_string: Var[str], prefix: Var[str]):
  171. """Check if a string starts with a prefix.
  172. Args:
  173. full_string: The full string.
  174. prefix: The prefix.
  175. Returns:
  176. Whether the string starts with the prefix.
  177. """
  178. return var_operation_return(
  179. js_expression=f"{full_string}.startsWith({prefix})", var_type=bool
  180. )
  181. @var_operation
  182. def string_item_operation(string: Var[str], index: Var[int]):
  183. """Get an item from a string.
  184. Args:
  185. string: The string.
  186. index: The index of the item.
  187. Returns:
  188. The item from the string.
  189. """
  190. return var_operation_return(js_expression=f"{string}.at({index})", var_type=str)
  191. @var_operation
  192. def string_replace_operation(
  193. string: Var[str], search_value: Var[str], new_value: Var[str]
  194. ):
  195. """Replace a string with a value.
  196. Args:
  197. string: The string.
  198. search_value: The string to search.
  199. new_value: The value to be replaced with.
  200. Returns:
  201. The string replace operation.
  202. """
  203. return var_operation_return(
  204. js_expression=f"{string}.replace({search_value}, {new_value})",
  205. var_type=str,
  206. )
  207. @var_operation
  208. def array_pluck_operation(
  209. array: Var[Sequence[Any]],
  210. field: Var[str],
  211. ) -> CustomVarOperationReturn[Sequence[Any]]:
  212. """Pluck a field from an array of objects.
  213. Args:
  214. array: The array to pluck from.
  215. field: The field to pluck from the objects in the array.
  216. Returns:
  217. The reversed array.
  218. """
  219. return var_operation_return(
  220. js_expression=f"{array}.map(e=>e?.[{field}])",
  221. var_type=List[Any],
  222. )
  223. @var_operation
  224. def array_join_operation(
  225. array: Var[Sequence[Any]], sep: VarWithDefault[str] = VarWithDefault("")
  226. ):
  227. """Join the elements of an array.
  228. Args:
  229. array: The array.
  230. sep: The separator.
  231. Returns:
  232. The joined elements.
  233. """
  234. return var_operation_return(js_expression=f"{array}.join({sep})", var_type=str)
  235. @var_operation
  236. def array_reverse_operation(
  237. array: Var[Sequence[INNER_ARRAY_VAR]],
  238. ) -> CustomVarOperationReturn[Sequence[INNER_ARRAY_VAR]]:
  239. """Reverse an array.
  240. Args:
  241. array: The array to reverse.
  242. Returns:
  243. The reversed array.
  244. """
  245. return var_operation_return(
  246. js_expression=f"{array}.slice().reverse()",
  247. type_computer=passthrough_unary_type_computer(ReflexCallable[[List], List]),
  248. )
  249. @var_operation
  250. def array_lt_operation(lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]):
  251. """Check if an array is less than another array.
  252. Args:
  253. lhs: The left-hand side array.
  254. rhs: The right-hand side array.
  255. Returns:
  256. The array less than operation.
  257. """
  258. return var_operation_return(js_expression=f"{lhs} < {rhs}", var_type=bool)
  259. @var_operation
  260. def array_gt_operation(lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]):
  261. """Check if an array is greater than another array.
  262. Args:
  263. lhs: The left-hand side array.
  264. rhs: The right-hand side array.
  265. Returns:
  266. The array greater than operation.
  267. """
  268. return var_operation_return(js_expression=f"{lhs} > {rhs}", var_type=bool)
  269. @var_operation
  270. def array_le_operation(lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]):
  271. """Check if an array is less than or equal to another array.
  272. Args:
  273. lhs: The left-hand side array.
  274. rhs: The right-hand side array.
  275. Returns:
  276. The array less than or equal operation.
  277. """
  278. return var_operation_return(js_expression=f"{lhs} <= {rhs}", var_type=bool)
  279. @var_operation
  280. def array_ge_operation(lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]):
  281. """Check if an array is greater than or equal to another array.
  282. Args:
  283. lhs: The left-hand side array.
  284. rhs: The right-hand side array.
  285. Returns:
  286. The array greater than or equal operation.
  287. """
  288. return var_operation_return(js_expression=f"{lhs} >= {rhs}", var_type=bool)
  289. @var_operation
  290. def array_length_operation(array: Var[ARRAY_VAR_TYPE]):
  291. """Get the length of an array.
  292. Args:
  293. array: The array.
  294. Returns:
  295. The length of the array.
  296. """
  297. return var_operation_return(
  298. js_expression=f"{array}.length",
  299. var_type=int,
  300. )
  301. @var_operation
  302. def string_split_operation(
  303. string: Var[str], sep: VarWithDefault[str] = VarWithDefault("")
  304. ):
  305. """Split a string.
  306. Args:
  307. string: The string to split.
  308. sep: The separator.
  309. Returns:
  310. The split string.
  311. """
  312. return var_operation_return(
  313. js_expression=f"isTrue({sep}) ? {string}.split({sep}) : [...{string}]",
  314. var_type=Sequence[str],
  315. var_data=VarData(imports=_IS_TRUE_IMPORT),
  316. )
  317. def _element_type(array: Var, index: Var) -> Any:
  318. array_args = typing.get_args(array._var_type)
  319. if (
  320. array_args
  321. and isinstance(index, LiteralNumberVar)
  322. and is_tuple_type(array._var_type)
  323. ):
  324. index_value = int(index._var_value)
  325. return array_args[index_value % len(array_args)]
  326. return unionize(*(array_arg for array_arg in array_args if array_arg is not ...))
  327. @var_operation
  328. def array_item_or_slice_operation(
  329. array: Var[Sequence[INNER_ARRAY_VAR]],
  330. index_or_slice: Var[Union[int, slice]],
  331. ) -> CustomVarOperationReturn[Union[INNER_ARRAY_VAR, Sequence[INNER_ARRAY_VAR]]]:
  332. """Get an item or slice from an array.
  333. Args:
  334. array: The array.
  335. index_or_slice: The index or slice.
  336. Returns:
  337. The item or slice from the array.
  338. """
  339. return var_operation_return(
  340. js_expression=f"Array.isArray({index_or_slice}) ? at_slice({array}, {index_or_slice}) : {array}.at({index_or_slice})",
  341. type_computer=nary_type_computer(
  342. ReflexCallable[[Sequence, Union[int, slice]], Any],
  343. ReflexCallable[[Union[int, slice]], Any],
  344. computer=lambda args: (
  345. args[0]._var_type
  346. if args[1]._var_type is slice
  347. else (_element_type(args[0], args[1]))
  348. ),
  349. ),
  350. var_data=VarData(
  351. imports=_AT_SLICE_IMPORT,
  352. ),
  353. )
  354. @var_operation
  355. def array_slice_operation(
  356. array: Var[Sequence[INNER_ARRAY_VAR]],
  357. slice: Var[slice],
  358. ) -> CustomVarOperationReturn[Sequence[INNER_ARRAY_VAR]]:
  359. """Get a slice from an array.
  360. Args:
  361. array: The array.
  362. slice: The slice.
  363. Returns:
  364. The item or slice from the array.
  365. """
  366. return var_operation_return(
  367. js_expression=f"atSlice({array}, {slice})",
  368. type_computer=nary_type_computer(
  369. ReflexCallable[[List, slice], Any],
  370. ReflexCallable[[slice], Any],
  371. computer=lambda args: args[0]._var_type,
  372. ),
  373. var_data=VarData(
  374. imports=_AT_SLICE_IMPORT,
  375. ),
  376. )
  377. @var_operation
  378. def array_item_operation(
  379. array: Var[Sequence[INNER_ARRAY_VAR]], index: Var[int]
  380. ) -> CustomVarOperationReturn[INNER_ARRAY_VAR]:
  381. """Get an item from an array.
  382. Args:
  383. array: The array.
  384. index: The index of the item.
  385. Returns:
  386. The item from the array.
  387. """
  388. def type_computer(*args):
  389. if len(args) == 0:
  390. return (
  391. ReflexCallable[[List[Any], int], Any],
  392. functools.partial(type_computer, *args),
  393. )
  394. array = args[0]
  395. array_args = typing.get_args(array._var_type)
  396. if len(args) == 1:
  397. return (
  398. ReflexCallable[[int], unionize(*array_args)],
  399. functools.partial(type_computer, *args),
  400. )
  401. index = args[1]
  402. if (
  403. array_args
  404. and isinstance(index, LiteralNumberVar)
  405. and is_tuple_type(array._var_type)
  406. ):
  407. index_value = int(index._var_value)
  408. element_type = array_args[index_value % len(array_args)]
  409. else:
  410. element_type = unionize(*array_args)
  411. return (ReflexCallable[[], element_type], None)
  412. return var_operation_return(
  413. js_expression=f"{array}.at({index})",
  414. type_computer=type_computer,
  415. )
  416. @var_operation
  417. def array_range_operation(
  418. e1: Var[int],
  419. e2: VarWithDefault[int | None] = VarWithDefault(None),
  420. step: VarWithDefault[int] = VarWithDefault(1),
  421. ) -> CustomVarOperationReturn[Sequence[int]]:
  422. """Create a range of numbers.
  423. Args:
  424. e1: The end of the range if e2 is not provided, otherwise the start of the range.
  425. e2: The end of the range.
  426. step: The step of the range.
  427. Returns:
  428. The range of numbers.
  429. """
  430. return var_operation_return(
  431. js_expression=f"range({e1}, {e2}, {step})",
  432. var_type=List[int],
  433. var_data=VarData(
  434. imports=_RANGE_IMPORT,
  435. ),
  436. )
  437. @var_operation
  438. def array_contains_field_operation(
  439. haystack: Var[ARRAY_VAR_TYPE],
  440. needle: Var[Any],
  441. field: VarWithDefault[str] = VarWithDefault(""),
  442. ):
  443. """Check if an array contains an element.
  444. Args:
  445. haystack: The array to check.
  446. needle: The element to check for.
  447. field: The field to check.
  448. Returns:
  449. The array contains operation.
  450. """
  451. return var_operation_return(
  452. js_expression=f"isTrue({field}) ? {haystack}.some(obj => obj[{field}] === {needle}) : {haystack}.some(obj => obj === {needle})",
  453. var_type=bool,
  454. var_data=VarData(
  455. imports=_IS_TRUE_IMPORT,
  456. ),
  457. )
  458. @var_operation
  459. def array_contains_operation(haystack: Var[ARRAY_VAR_TYPE], needle: Var):
  460. """Check if an array contains an element.
  461. Args:
  462. haystack: The array to check.
  463. needle: The element to check for.
  464. Returns:
  465. The array contains operation.
  466. """
  467. return var_operation_return(
  468. js_expression=f"{haystack}.includes({needle})",
  469. var_type=bool,
  470. )
  471. @var_operation
  472. def repeat_array_operation(
  473. array: Var[Sequence[INNER_ARRAY_VAR]], count: Var[int]
  474. ) -> CustomVarOperationReturn[Sequence[INNER_ARRAY_VAR]]:
  475. """Repeat an array a number of times.
  476. Args:
  477. array: The array to repeat.
  478. count: The number of times to repeat the array.
  479. Returns:
  480. The repeated array.
  481. """
  482. def type_computer(*args: Var):
  483. if not args:
  484. return (
  485. ReflexCallable[[List[Any], int], List[Any]],
  486. type_computer,
  487. )
  488. if len(args) == 1:
  489. return (
  490. ReflexCallable[[int], args[0]._var_type],
  491. functools.partial(type_computer, *args),
  492. )
  493. return (ReflexCallable[[], args[0]._var_type], None)
  494. return var_operation_return(
  495. js_expression=f"Array.from({{ length: {count} }}).flatMap(() => {array})",
  496. type_computer=type_computer,
  497. )
  498. @var_operation
  499. def repeat_string_operation(
  500. string: Var[str], count: Var[int]
  501. ) -> CustomVarOperationReturn[str]:
  502. """Repeat a string a number of times.
  503. Args:
  504. string: The string to repeat.
  505. count: The number of times to repeat the string.
  506. Returns:
  507. The repeated string.
  508. """
  509. return var_operation_return(
  510. js_expression=f"{string}.repeat({count})",
  511. var_type=str,
  512. )
  513. if TYPE_CHECKING:
  514. pass
  515. @var_operation
  516. def map_array_operation(
  517. array: Var[Sequence[INNER_ARRAY_VAR]],
  518. function: Var[
  519. ReflexCallable[[INNER_ARRAY_VAR], ANOTHER_ARRAY_VAR]
  520. | ReflexCallable[[], ANOTHER_ARRAY_VAR]
  521. ],
  522. ) -> CustomVarOperationReturn[Sequence[ANOTHER_ARRAY_VAR]]:
  523. """Map a function over an array.
  524. Args:
  525. array: The array.
  526. function: The function to map.
  527. Returns:
  528. The mapped array.
  529. """
  530. def type_computer(*args: Var):
  531. if not args:
  532. return (
  533. ReflexCallable[[List[Any], ReflexCallable], List[Any]],
  534. type_computer,
  535. )
  536. if len(args) == 1:
  537. return (
  538. ReflexCallable[[ReflexCallable], List[Any]],
  539. functools.partial(type_computer, *args),
  540. )
  541. return (ReflexCallable[[], List[args[0]._var_type]], None)
  542. return var_operation_return(
  543. js_expression=f"{array}.map({function})",
  544. type_computer=nary_type_computer(
  545. ReflexCallable[[List[Any], ReflexCallable], List[Any]],
  546. ReflexCallable[[ReflexCallable], List[Any]],
  547. computer=lambda args: List[unwrap_reflex_callalbe(args[1]._var_type)[1]], # type: ignore
  548. ),
  549. )
  550. @var_operation
  551. def array_concat_operation(
  552. lhs: Var[Sequence[INNER_ARRAY_VAR]], rhs: Var[Sequence[ANOTHER_ARRAY_VAR]]
  553. ) -> CustomVarOperationReturn[Sequence[INNER_ARRAY_VAR | ANOTHER_ARRAY_VAR]]:
  554. """Concatenate two arrays.
  555. Args:
  556. lhs: The left-hand side array.
  557. rhs: The right-hand side array.
  558. Returns:
  559. The concatenated array.
  560. """
  561. return var_operation_return(
  562. js_expression=f"[...{lhs}, ...{rhs}]",
  563. type_computer=nary_type_computer(
  564. ReflexCallable[[List[Any], List[Any]], List[Any]],
  565. ReflexCallable[[List[Any]], List[Any]],
  566. computer=lambda args: unionize(args[0]._var_type, args[1]._var_type),
  567. ),
  568. )
  569. @var_operation
  570. def string_concat_operation(
  571. lhs: Var[str], rhs: Var[str]
  572. ) -> CustomVarOperationReturn[str]:
  573. """Concatenate two strings.
  574. Args:
  575. lhs: The left-hand side string.
  576. rhs: The right-hand side string.
  577. Returns:
  578. The concatenated string.
  579. """
  580. return var_operation_return(
  581. js_expression=f"{lhs} + {rhs}",
  582. var_type=str,
  583. )
  584. @var_operation
  585. def reverse_string_concat_operation(
  586. lhs: Var[str], rhs: Var[str]
  587. ) -> CustomVarOperationReturn[str]:
  588. """Concatenate two strings in reverse order.
  589. Args:
  590. lhs: The left-hand side string.
  591. rhs: The right-hand side string.
  592. Returns:
  593. The concatenated string.
  594. """
  595. return var_operation_return(
  596. js_expression=f"{rhs} + {lhs}",
  597. var_type=str,
  598. )
  599. class SliceVar(Var[slice], python_types=slice):
  600. """Base class for immutable slice vars."""
  601. @dataclasses.dataclass(
  602. eq=False,
  603. frozen=True,
  604. **{"slots": True} if sys.version_info >= (3, 10) else {},
  605. )
  606. class LiteralSliceVar(CachedVarOperation, LiteralVar, SliceVar):
  607. """Base class for immutable literal slice vars."""
  608. _var_value: slice = dataclasses.field(default_factory=lambda: slice(None))
  609. @cached_property_no_lock
  610. def _cached_var_name(self) -> str:
  611. """The name of the var.
  612. Returns:
  613. The name of the var.
  614. """
  615. return f"[{LiteralVar.create(self._var_value.start)!s}, {LiteralVar.create(self._var_value.stop)!s}, {LiteralVar.create(self._var_value.step)!s}]"
  616. @cached_property_no_lock
  617. def _cached_get_all_var_data(self) -> VarData | None:
  618. """Get all the VarData asVarDatae Var.
  619. Returns:
  620. The VarData associated with the Var.
  621. """
  622. return VarData.merge(
  623. *[
  624. var._get_all_var_data()
  625. for var in [
  626. self._var_value.start,
  627. self._var_value.stop,
  628. self._var_value.step,
  629. ]
  630. if isinstance(var, Var)
  631. ],
  632. self._var_data,
  633. )
  634. @classmethod
  635. def create(
  636. cls,
  637. value: slice,
  638. _var_type: Type[slice] | None = None,
  639. _var_data: VarData | None = None,
  640. ) -> SliceVar:
  641. """Create a var from a slice value.
  642. Args:
  643. value: The value to create the var from.
  644. _var_type: The type of the var.
  645. _var_data: Additional hooks and imports associated with the Var.
  646. Returns:
  647. The var.
  648. """
  649. return cls(
  650. _js_expr="",
  651. _var_type=slice if _var_type is None else _var_type,
  652. _var_data=_var_data,
  653. _var_value=value,
  654. )
  655. def __hash__(self) -> int:
  656. """Get the hash of the var.
  657. Returns:
  658. The hash of the var.
  659. """
  660. return hash(
  661. (
  662. self.__class__.__name__,
  663. self._var_value.start,
  664. self._var_value.stop,
  665. self._var_value.step,
  666. )
  667. )
  668. def json(self) -> str:
  669. """Get the JSON representation of the var.
  670. Returns:
  671. The JSON representation of the var.
  672. """
  673. return json.dumps(
  674. [self._var_value.start, self._var_value.stop, self._var_value.step]
  675. )
  676. class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(Sequence, set)):
  677. """Base class for immutable array vars."""
  678. join = array_join_operation
  679. reverse = array_reverse_operation
  680. __add__ = array_concat_operation
  681. __getitem__ = array_item_or_slice_operation
  682. at = array_item_operation
  683. slice = array_slice_operation
  684. length = array_length_operation
  685. range: ClassVar[
  686. FunctionVar[
  687. ReflexCallable[
  688. [int, VarWithDefault[int | None], VarWithDefault[int]], Sequence[int]
  689. ]
  690. ]
  691. ] = array_range_operation
  692. contains = array_contains_field_operation
  693. pluck = array_pluck_operation
  694. __rmul__ = __mul__ = repeat_array_operation
  695. __lt__ = array_lt_operation
  696. __gt__ = array_gt_operation
  697. __le__ = array_le_operation
  698. __ge__ = array_ge_operation
  699. def foreach(
  700. self: ArrayVar[Sequence[INNER_ARRAY_VAR]],
  701. fn: Callable[[Var[INNER_ARRAY_VAR]], ANOTHER_ARRAY_VAR]
  702. | Callable[[], ANOTHER_ARRAY_VAR],
  703. ) -> ArrayVar[Sequence[ANOTHER_ARRAY_VAR]]:
  704. """Apply a function to each element of the array.
  705. Args:
  706. fn: The function to apply.
  707. Returns:
  708. The array after applying the function.
  709. Raises:
  710. VarTypeError: If the function takes more than one argument.
  711. """
  712. from .function import ArgsFunctionOperation
  713. if not callable(fn):
  714. raise_unsupported_operand_types("foreach", (type(self), type(fn)))
  715. # get the number of arguments of the function
  716. num_args = len(inspect.signature(fn).parameters)
  717. if num_args > 1:
  718. raise VarTypeError(
  719. "The function passed to foreach should take at most one argument."
  720. )
  721. if num_args == 0:
  722. return_value = fn() # type: ignore
  723. simple_function_var: FunctionVar[ReflexCallable[[], ANOTHER_ARRAY_VAR]] = (
  724. ArgsFunctionOperation.create((), return_value)
  725. )
  726. return map_array_operation(self, simple_function_var).guess_type()
  727. # generic number var
  728. number_var = Var("").to(NumberVar, int)
  729. first_arg_type = self.__getitem__(number_var)._var_type
  730. arg_name = get_unique_variable_name()
  731. # get first argument type
  732. first_arg = cast(
  733. Var[Any],
  734. Var(
  735. _js_expr=arg_name,
  736. _var_type=first_arg_type,
  737. ).guess_type(),
  738. )
  739. function_var = cast(
  740. Var[ReflexCallable[[INNER_ARRAY_VAR], ANOTHER_ARRAY_VAR]],
  741. ArgsFunctionOperation.create(
  742. (arg_name,),
  743. Var.create(fn(first_arg)), # type: ignore
  744. ),
  745. )
  746. return map_array_operation.call(self, function_var).guess_type()
  747. LIST_ELEMENT = TypeVar("LIST_ELEMENT", covariant=True)
  748. ARRAY_VAR_OF_LIST_ELEMENT = TypeAliasType(
  749. "ARRAY_VAR_OF_LIST_ELEMENT",
  750. Union[
  751. ArrayVar[Sequence[LIST_ELEMENT]],
  752. ArrayVar[Set[LIST_ELEMENT]],
  753. ],
  754. type_params=(LIST_ELEMENT,),
  755. )
  756. @dataclasses.dataclass(
  757. eq=False,
  758. frozen=True,
  759. **{"slots": True} if sys.version_info >= (3, 10) else {},
  760. )
  761. class LiteralArrayVar(CachedVarOperation, LiteralVar, ArrayVar[ARRAY_VAR_TYPE]):
  762. """Base class for immutable literal array vars."""
  763. _var_value: Union[
  764. Sequence[Union[Var, Any]],
  765. Set[Union[Var, Any]],
  766. ] = dataclasses.field(default_factory=list)
  767. @cached_property_no_lock
  768. def _cached_var_name(self) -> str:
  769. """The name of the var.
  770. Returns:
  771. The name of the var.
  772. """
  773. return (
  774. "["
  775. + ", ".join(
  776. [str(LiteralVar.create(element)) for element in self._var_value]
  777. )
  778. + "]"
  779. )
  780. @cached_property_no_lock
  781. def _cached_get_all_var_data(self) -> VarData | None:
  782. """Get all the VarData associated with the Var.
  783. Returns:
  784. The VarData associated with the Var.
  785. """
  786. return VarData.merge(
  787. *[
  788. LiteralVar.create(element)._get_all_var_data()
  789. for element in self._var_value
  790. ],
  791. self._var_data,
  792. )
  793. def __hash__(self) -> int:
  794. """Get the hash of the var.
  795. Returns:
  796. The hash of the var.
  797. """
  798. return hash((self.__class__.__name__, self._js_expr))
  799. def json(self) -> str:
  800. """Get the JSON representation of the var.
  801. Returns:
  802. The JSON representation of the var.
  803. """
  804. return (
  805. "["
  806. + ", ".join(
  807. [LiteralVar.create(element).json() for element in self._var_value]
  808. )
  809. + "]"
  810. )
  811. @classmethod
  812. def create(
  813. cls,
  814. value: ARRAY_VAR_TYPE,
  815. _var_type: Type[ARRAY_VAR_TYPE] | None = None,
  816. _var_data: VarData | None = None,
  817. ) -> LiteralArrayVar[ARRAY_VAR_TYPE]:
  818. """Create a var from a string value.
  819. Args:
  820. value: The value to create the var from.
  821. _var_data: Additional hooks and imports associated with the Var.
  822. Returns:
  823. The var.
  824. """
  825. return cls(
  826. _js_expr="",
  827. _var_type=figure_out_type(value) if _var_type is None else _var_type,
  828. _var_data=_var_data,
  829. _var_value=value,
  830. )
  831. class StringVar(Var[STRING_TYPE], python_types=str):
  832. """Base class for immutable string vars."""
  833. __add__ = string_concat_operation
  834. __radd__ = reverse_string_concat_operation
  835. __getitem__ = string_item_operation
  836. lower = string_lower_operation
  837. upper = string_upper_operation
  838. strip = string_strip_operation
  839. contains = string_contains_field_operation
  840. split = string_split_operation
  841. length = split.chain(array_length_operation)
  842. reversed = split.chain(array_reverse_operation).chain(array_join_operation)
  843. startswith = string_starts_with_operation
  844. __rmul__ = __mul__ = repeat_string_operation
  845. __lt__ = string_lt_operation
  846. __gt__ = string_gt_operation
  847. __le__ = string_le_operation
  848. __ge__ = string_ge_operation
  849. # Compile regex for finding reflex var tags.
  850. _decode_var_pattern_re = (
  851. rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
  852. )
  853. _decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
  854. @dataclasses.dataclass(
  855. eq=False,
  856. frozen=True,
  857. **{"slots": True} if sys.version_info >= (3, 10) else {},
  858. )
  859. class LiteralStringVar(LiteralVar, StringVar[str]):
  860. """Base class for immutable literal string vars."""
  861. _var_value: str = dataclasses.field(default="")
  862. @classmethod
  863. def create(
  864. cls,
  865. value: str,
  866. _var_type: GenericType | None = None,
  867. _var_data: VarData | None = None,
  868. ) -> StringVar:
  869. """Create a var from a string value.
  870. Args:
  871. value: The value to create the var from.
  872. _var_type: The type of the var.
  873. _var_data: Additional hooks and imports associated with the Var.
  874. Returns:
  875. The var.
  876. """
  877. # Determine var type in case the value is inherited from str.
  878. _var_type = _var_type or type(value) or str
  879. if REFLEX_VAR_OPENING_TAG in value:
  880. strings_and_vals: list[Var | str] = []
  881. offset = 0
  882. # Find all tags
  883. while m := _decode_var_pattern.search(value):
  884. start, end = m.span()
  885. strings_and_vals.append(value[:start])
  886. serialized_data = m.group(1)
  887. if serialized_data.isnumeric() or (
  888. serialized_data[0] == "-" and serialized_data[1:].isnumeric()
  889. ):
  890. # This is a global immutable var.
  891. var = _global_vars[int(serialized_data)]
  892. strings_and_vals.append(var)
  893. value = value[(end + len(var._js_expr)) :]
  894. offset += end - start
  895. strings_and_vals.append(value)
  896. filtered_strings_and_vals = [
  897. s for s in strings_and_vals if isinstance(s, Var) or s
  898. ]
  899. if len(filtered_strings_and_vals) == 1:
  900. only_string = filtered_strings_and_vals[0]
  901. if isinstance(only_string, str):
  902. return LiteralVar.create(only_string).to(StringVar, _var_type)
  903. else:
  904. return only_string.to(StringVar, only_string._var_type)
  905. if len(
  906. literal_strings := [
  907. s
  908. for s in filtered_strings_and_vals
  909. if isinstance(s, (str, LiteralStringVar))
  910. ]
  911. ) == len(filtered_strings_and_vals):
  912. return LiteralStringVar.create(
  913. "".join(
  914. s._var_value if isinstance(s, LiteralStringVar) else s
  915. for s in literal_strings
  916. ),
  917. _var_type=_var_type,
  918. _var_data=VarData.merge(
  919. _var_data,
  920. *(
  921. s._get_all_var_data()
  922. for s in filtered_strings_and_vals
  923. if isinstance(s, Var)
  924. ),
  925. ),
  926. )
  927. concat_result = ConcatVarOperation.create(
  928. *filtered_strings_and_vals,
  929. _var_data=_var_data,
  930. )
  931. return (
  932. concat_result
  933. if _var_type is str
  934. else concat_result.to(StringVar, _var_type)
  935. )
  936. return LiteralStringVar(
  937. _js_expr=json.dumps(value),
  938. _var_type=_var_type,
  939. _var_data=_var_data,
  940. _var_value=value,
  941. )
  942. def __hash__(self) -> int:
  943. """Get the hash of the var.
  944. Returns:
  945. The hash of the var.
  946. """
  947. return hash((self.__class__.__name__, self._var_value))
  948. def json(self) -> str:
  949. """Get the JSON representation of the var.
  950. Returns:
  951. The JSON representation of the var.
  952. """
  953. return json.dumps(self._var_value)
  954. @dataclasses.dataclass(
  955. eq=False,
  956. frozen=True,
  957. **{"slots": True} if sys.version_info >= (3, 10) else {},
  958. )
  959. class ConcatVarOperation(CachedVarOperation, StringVar[str]):
  960. """Representing a concatenation of literal string vars."""
  961. _var_value: Tuple[Var, ...] = dataclasses.field(default_factory=tuple)
  962. @cached_property_no_lock
  963. def _cached_var_name(self) -> str:
  964. """The name of the var.
  965. Returns:
  966. The name of the var.
  967. """
  968. list_of_strs: List[Union[str, Var]] = []
  969. last_string = ""
  970. for var in self._var_value:
  971. if isinstance(var, LiteralStringVar):
  972. last_string += var._var_value
  973. else:
  974. if last_string:
  975. list_of_strs.append(last_string)
  976. last_string = ""
  977. list_of_strs.append(var)
  978. if last_string:
  979. list_of_strs.append(last_string)
  980. list_of_strs_filtered = [
  981. str(LiteralVar.create(s)) for s in list_of_strs if isinstance(s, Var) or s
  982. ]
  983. if len(list_of_strs_filtered) == 1:
  984. return list_of_strs_filtered[0]
  985. return "(" + "+".join(list_of_strs_filtered) + ")"
  986. @cached_property_no_lock
  987. def _cached_get_all_var_data(self) -> VarData | None:
  988. """Get all the VarData asVarDatae Var.
  989. Returns:
  990. The VarData associated with the Var.
  991. """
  992. return VarData.merge(
  993. *[
  994. var._get_all_var_data()
  995. for var in self._var_value
  996. if isinstance(var, Var)
  997. ],
  998. self._var_data,
  999. )
  1000. @classmethod
  1001. def create(
  1002. cls,
  1003. *value: Var | str,
  1004. _var_data: VarData | None = None,
  1005. ) -> ConcatVarOperation:
  1006. """Create a var from a string value.
  1007. Args:
  1008. value: The values to concatenate.
  1009. _var_data: Additional hooks and imports associated with the Var.
  1010. Returns:
  1011. The var.
  1012. """
  1013. return cls(
  1014. _js_expr="",
  1015. _var_type=str,
  1016. _var_data=_var_data,
  1017. _var_value=tuple(map(LiteralVar.create, value)),
  1018. )
  1019. def is_tuple_type(t: GenericType) -> bool:
  1020. """Check if a type is a tuple type.
  1021. Args:
  1022. t: The type to check.
  1023. Returns:
  1024. Whether the type is a tuple type.
  1025. """
  1026. if inspect.isclass(t):
  1027. return issubclass(t, tuple)
  1028. return get_origin(t) is tuple
  1029. class ColorVar(StringVar[Color], python_types=Color):
  1030. """Base class for immutable color vars."""
  1031. @dataclasses.dataclass(
  1032. eq=False,
  1033. frozen=True,
  1034. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1035. )
  1036. class LiteralColorVar(CachedVarOperation, LiteralVar, ColorVar):
  1037. """Base class for immutable literal color vars."""
  1038. _var_value: Color = dataclasses.field(default_factory=lambda: Color(color="black"))
  1039. @classmethod
  1040. def create(
  1041. cls,
  1042. value: Color,
  1043. _var_type: Type[Color] | None = None,
  1044. _var_data: VarData | None = None,
  1045. ) -> ColorVar:
  1046. """Create a var from a string value.
  1047. Args:
  1048. value: The value to create the var from.
  1049. _var_type: The type of the var.
  1050. _var_data: Additional hooks and imports associated with the Var.
  1051. Returns:
  1052. The var.
  1053. """
  1054. return cls(
  1055. _js_expr="",
  1056. _var_type=_var_type or Color,
  1057. _var_data=_var_data,
  1058. _var_value=value,
  1059. )
  1060. def __hash__(self) -> int:
  1061. """Get the hash of the var.
  1062. Returns:
  1063. The hash of the var.
  1064. """
  1065. return hash(
  1066. (
  1067. self.__class__.__name__,
  1068. self._var_value.color,
  1069. self._var_value.alpha,
  1070. self._var_value.shade,
  1071. )
  1072. )
  1073. @cached_property_no_lock
  1074. def _cached_var_name(self) -> str:
  1075. """The name of the var.
  1076. Returns:
  1077. The name of the var.
  1078. """
  1079. alpha = cast(Union[Var[bool], bool], self._var_value.alpha)
  1080. alpha = (
  1081. ternary_operation(
  1082. alpha,
  1083. LiteralStringVar.create("a"),
  1084. LiteralStringVar.create(""),
  1085. )
  1086. if isinstance(alpha, Var)
  1087. else LiteralStringVar.create("a" if alpha else "")
  1088. )
  1089. shade = self._var_value.shade
  1090. shade = (
  1091. shade.to_string(use_json=False)
  1092. if isinstance(shade, Var)
  1093. else LiteralStringVar.create(str(shade))
  1094. )
  1095. return str(
  1096. ConcatVarOperation.create(
  1097. LiteralStringVar.create("var(--"),
  1098. self._var_value.color,
  1099. LiteralStringVar.create("-"),
  1100. alpha,
  1101. shade,
  1102. LiteralStringVar.create(")"),
  1103. )
  1104. )
  1105. @cached_property_no_lock
  1106. def _cached_get_all_var_data(self) -> VarData | None:
  1107. """Get all the var data.
  1108. Returns:
  1109. The var data.
  1110. """
  1111. return VarData.merge(
  1112. *[
  1113. LiteralVar.create(var)._get_all_var_data()
  1114. for var in (
  1115. self._var_value.color,
  1116. self._var_value.alpha,
  1117. self._var_value.shade,
  1118. )
  1119. ],
  1120. self._var_data,
  1121. )
  1122. def json(self) -> str:
  1123. """Get the JSON representation of the var.
  1124. Returns:
  1125. The JSON representation of the var.
  1126. Raises:
  1127. TypeError: If the color is not a valid color.
  1128. """
  1129. color, alpha, shade = map(
  1130. get_python_literal,
  1131. (self._var_value.color, self._var_value.alpha, self._var_value.shade),
  1132. )
  1133. if color is None or alpha is None or shade is None:
  1134. raise TypeError("Cannot serialize color that contains non-literal vars.")
  1135. if (
  1136. not isinstance(color, str)
  1137. or not isinstance(alpha, bool)
  1138. or not isinstance(shade, int)
  1139. ):
  1140. raise TypeError("Color is not a valid color.")
  1141. return f"var(--{color}-{'a' if alpha else ''}{shade})"