sequence.py 36 KB

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