sequence.py 38 KB

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