sequence.py 36 KB

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