sequence.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  1. """Collection of string classes and utilities."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import inspect
  5. import json
  6. import re
  7. import typing
  8. from typing import (
  9. TYPE_CHECKING,
  10. Any,
  11. Dict,
  12. List,
  13. Literal,
  14. NoReturn,
  15. Sequence,
  16. Tuple,
  17. Type,
  18. Union,
  19. overload,
  20. )
  21. from typing_extensions import TypeVar
  22. from reflex import constants
  23. from reflex.constants.base import REFLEX_VAR_OPENING_TAG
  24. from reflex.constants.colors import Color
  25. from reflex.utils.exceptions import VarTypeError
  26. from reflex.utils.types import GenericType, get_origin
  27. from .base import (
  28. CachedVarOperation,
  29. CustomVarOperationReturn,
  30. LiteralVar,
  31. Var,
  32. VarData,
  33. _global_vars,
  34. cached_property_no_lock,
  35. figure_out_type,
  36. get_python_literal,
  37. get_unique_variable_name,
  38. unionize,
  39. var_operation,
  40. var_operation_return,
  41. )
  42. from .number import (
  43. BooleanVar,
  44. LiteralNumberVar,
  45. NumberVar,
  46. raise_unsupported_operand_types,
  47. ternary_operation,
  48. )
  49. if TYPE_CHECKING:
  50. from .object import ObjectVar
  51. STRING_TYPE = TypeVar("STRING_TYPE", default=str)
  52. class StringVar(Var[STRING_TYPE], python_types=str):
  53. """Base class for immutable string vars."""
  54. @overload
  55. def __add__(self, other: StringVar | str) -> ConcatVarOperation: ...
  56. @overload
  57. def __add__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  58. def __add__(self, other: Any) -> ConcatVarOperation:
  59. """Concatenate two strings.
  60. Args:
  61. other: The other string.
  62. Returns:
  63. The string concatenation operation.
  64. """
  65. if not isinstance(other, (StringVar, str)):
  66. raise_unsupported_operand_types("+", (type(self), type(other)))
  67. return ConcatVarOperation.create(self, other)
  68. @overload
  69. def __radd__(self, other: StringVar | str) -> ConcatVarOperation: ...
  70. @overload
  71. def __radd__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  72. def __radd__(self, other: Any) -> ConcatVarOperation:
  73. """Concatenate two strings.
  74. Args:
  75. other: The other string.
  76. Returns:
  77. The string concatenation operation.
  78. """
  79. if not isinstance(other, (StringVar, str)):
  80. raise_unsupported_operand_types("+", (type(other), type(self)))
  81. return ConcatVarOperation.create(other, self)
  82. @overload
  83. def __mul__(self, other: NumberVar | int) -> StringVar: ...
  84. @overload
  85. def __mul__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  86. def __mul__(self, other: Any) -> StringVar:
  87. """Multiply the sequence by a number or an integer.
  88. Args:
  89. other: The number or integer to multiply the sequence by.
  90. Returns:
  91. StringVar: The resulting sequence after multiplication.
  92. """
  93. if not isinstance(other, (NumberVar, int)):
  94. raise_unsupported_operand_types("*", (type(self), type(other)))
  95. return (self.split() * other).join()
  96. @overload
  97. def __rmul__(self, other: NumberVar | int) -> StringVar: ...
  98. @overload
  99. def __rmul__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  100. def __rmul__(self, other: Any) -> StringVar:
  101. """Multiply the sequence by a number or an integer.
  102. Args:
  103. other: The number or integer to multiply the sequence by.
  104. Returns:
  105. StringVar: The resulting sequence after multiplication.
  106. """
  107. if not isinstance(other, (NumberVar, int)):
  108. raise_unsupported_operand_types("*", (type(other), type(self)))
  109. return (self.split() * other).join()
  110. @overload
  111. def __getitem__(self, i: slice) -> StringVar: ...
  112. @overload
  113. def __getitem__(self, i: int | NumberVar) -> StringVar: ...
  114. def __getitem__(self, i: Any) -> StringVar:
  115. """Get a slice of the string.
  116. Args:
  117. i: The slice.
  118. Returns:
  119. The string slice operation.
  120. """
  121. if isinstance(i, slice):
  122. return self.split()[i].join()
  123. if not isinstance(i, (int, NumberVar)) or (
  124. isinstance(i, NumberVar) and i._is_strict_float()
  125. ):
  126. raise_unsupported_operand_types("[]", (type(self), type(i)))
  127. return string_item_operation(self, i)
  128. def length(self) -> NumberVar:
  129. """Get the length of the string.
  130. Returns:
  131. The string length operation.
  132. """
  133. return self.split().length()
  134. def lower(self) -> StringVar:
  135. """Convert the string to lowercase.
  136. Returns:
  137. The string lower operation.
  138. """
  139. return string_lower_operation(self)
  140. def upper(self) -> StringVar:
  141. """Convert the string to uppercase.
  142. Returns:
  143. The string upper operation.
  144. """
  145. return string_upper_operation(self)
  146. def strip(self) -> StringVar:
  147. """Strip the string.
  148. Returns:
  149. The string strip operation.
  150. """
  151. return string_strip_operation(self)
  152. def reversed(self) -> StringVar:
  153. """Reverse the string.
  154. Returns:
  155. The string reverse operation.
  156. """
  157. return self.split().reverse().join()
  158. @overload
  159. def contains(
  160. self, other: StringVar | str, field: StringVar | str | None = None
  161. ) -> BooleanVar: ...
  162. @overload
  163. def contains( # pyright: ignore [reportOverlappingOverload]
  164. self, other: NoReturn, field: StringVar | str | None = None
  165. ) -> NoReturn: ...
  166. def contains(self, other: Any, field: Any = None) -> BooleanVar:
  167. """Check if the string contains another string.
  168. Args:
  169. other: The other string.
  170. field: The field to check.
  171. Returns:
  172. The string contains operation.
  173. """
  174. if not isinstance(other, (StringVar, str)):
  175. raise_unsupported_operand_types("contains", (type(self), type(other)))
  176. if field is not None:
  177. if not isinstance(field, (StringVar, str)):
  178. raise_unsupported_operand_types("contains", (type(self), type(field)))
  179. return string_contains_field_operation(self, other, field)
  180. return string_contains_operation(self, other)
  181. @overload
  182. def split(self, separator: StringVar | str = "") -> ArrayVar[List[str]]: ...
  183. @overload
  184. def split(self, separator: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  185. def split(self, separator: Any = "") -> ArrayVar[List[str]]:
  186. """Split the string.
  187. Args:
  188. separator: The separator.
  189. Returns:
  190. The string split operation.
  191. """
  192. if not isinstance(separator, (StringVar, str)):
  193. raise_unsupported_operand_types("split", (type(self), type(separator)))
  194. return string_split_operation(self, separator)
  195. @overload
  196. def startswith(self, prefix: StringVar | str) -> BooleanVar: ...
  197. @overload
  198. def startswith(self, prefix: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  199. def startswith(self, prefix: Any) -> BooleanVar:
  200. """Check if the string starts with a prefix.
  201. Args:
  202. prefix: The prefix.
  203. Returns:
  204. The string starts with operation.
  205. """
  206. if not isinstance(prefix, (StringVar, str)):
  207. raise_unsupported_operand_types("startswith", (type(self), type(prefix)))
  208. return string_starts_with_operation(self, prefix)
  209. @overload
  210. def endswith(self, suffix: StringVar | str) -> BooleanVar: ...
  211. @overload
  212. def endswith(self, suffix: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  213. def endswith(self, suffix: Any) -> BooleanVar:
  214. """Check if the string ends with a suffix.
  215. Args:
  216. suffix: The suffix.
  217. Returns:
  218. The string ends with operation.
  219. """
  220. if not isinstance(suffix, (StringVar, str)):
  221. raise_unsupported_operand_types("endswith", (type(self), type(suffix)))
  222. return string_ends_with_operation(self, suffix)
  223. @overload
  224. def __lt__(self, other: StringVar | str) -> BooleanVar: ...
  225. @overload
  226. def __lt__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  227. def __lt__(self, other: Any):
  228. """Check if the string is less than another string.
  229. Args:
  230. other: The other string.
  231. Returns:
  232. The string less than operation.
  233. """
  234. if not isinstance(other, (StringVar, str)):
  235. raise_unsupported_operand_types("<", (type(self), type(other)))
  236. return string_lt_operation(self, other)
  237. @overload
  238. def __gt__(self, other: StringVar | str) -> BooleanVar: ...
  239. @overload
  240. def __gt__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  241. def __gt__(self, other: Any):
  242. """Check if the string is greater than another string.
  243. Args:
  244. other: The other string.
  245. Returns:
  246. The string greater than operation.
  247. """
  248. if not isinstance(other, (StringVar, str)):
  249. raise_unsupported_operand_types(">", (type(self), type(other)))
  250. return string_gt_operation(self, other)
  251. @overload
  252. def __le__(self, other: StringVar | str) -> BooleanVar: ...
  253. @overload
  254. def __le__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  255. def __le__(self, other: Any):
  256. """Check if the string is less than or equal to another string.
  257. Args:
  258. other: The other string.
  259. Returns:
  260. The string less than or equal operation.
  261. """
  262. if not isinstance(other, (StringVar, str)):
  263. raise_unsupported_operand_types("<=", (type(self), type(other)))
  264. return string_le_operation(self, other)
  265. @overload
  266. def __ge__(self, other: StringVar | str) -> BooleanVar: ...
  267. @overload
  268. def __ge__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  269. def __ge__(self, other: Any):
  270. """Check if the string is greater than or equal to another string.
  271. Args:
  272. other: The other string.
  273. Returns:
  274. The string greater than or equal operation.
  275. """
  276. if not isinstance(other, (StringVar, str)):
  277. raise_unsupported_operand_types(">=", (type(self), type(other)))
  278. return string_ge_operation(self, other)
  279. @var_operation
  280. def string_lt_operation(lhs: StringVar[Any] | str, rhs: StringVar[Any] | str):
  281. """Check if a string is less than another string.
  282. Args:
  283. lhs: The left-hand side string.
  284. rhs: The right-hand side string.
  285. Returns:
  286. The string less than operation.
  287. """
  288. return var_operation_return(js_expression=f"{lhs} < {rhs}", var_type=bool)
  289. @var_operation
  290. def string_gt_operation(lhs: StringVar[Any] | str, rhs: StringVar[Any] | str):
  291. """Check if a string is greater than another string.
  292. Args:
  293. lhs: The left-hand side string.
  294. rhs: The right-hand side string.
  295. Returns:
  296. The string greater than operation.
  297. """
  298. return var_operation_return(js_expression=f"{lhs} > {rhs}", var_type=bool)
  299. @var_operation
  300. def string_le_operation(lhs: StringVar[Any] | str, rhs: StringVar[Any] | str):
  301. """Check if a string is less than or equal to another string.
  302. Args:
  303. lhs: The left-hand side string.
  304. rhs: The right-hand side string.
  305. Returns:
  306. The string less than or equal operation.
  307. """
  308. return var_operation_return(js_expression=f"{lhs} <= {rhs}", var_type=bool)
  309. @var_operation
  310. def string_ge_operation(lhs: StringVar[Any] | str, rhs: StringVar[Any] | str):
  311. """Check if a string is greater than or equal to another string.
  312. Args:
  313. lhs: The left-hand side string.
  314. rhs: The right-hand side string.
  315. Returns:
  316. The string greater than or equal operation.
  317. """
  318. return var_operation_return(js_expression=f"{lhs} >= {rhs}", var_type=bool)
  319. @var_operation
  320. def string_lower_operation(string: StringVar[Any]):
  321. """Convert a string to lowercase.
  322. Args:
  323. string: The string to convert.
  324. Returns:
  325. The lowercase string.
  326. """
  327. return var_operation_return(js_expression=f"{string}.toLowerCase()", var_type=str)
  328. @var_operation
  329. def string_upper_operation(string: StringVar[Any]):
  330. """Convert a string to uppercase.
  331. Args:
  332. string: The string to convert.
  333. Returns:
  334. The uppercase string.
  335. """
  336. return var_operation_return(js_expression=f"{string}.toUpperCase()", var_type=str)
  337. @var_operation
  338. def string_strip_operation(string: StringVar[Any]):
  339. """Strip a string.
  340. Args:
  341. string: The string to strip.
  342. Returns:
  343. The stripped string.
  344. """
  345. return var_operation_return(js_expression=f"{string}.trim()", var_type=str)
  346. @var_operation
  347. def string_contains_field_operation(
  348. haystack: StringVar[Any], needle: StringVar[Any] | str, field: StringVar[Any] | str
  349. ):
  350. """Check if a string contains another string.
  351. Args:
  352. haystack: The haystack.
  353. needle: The needle.
  354. field: The field to check.
  355. Returns:
  356. The string contains operation.
  357. """
  358. return var_operation_return(
  359. js_expression=f"{haystack}.some(obj => obj[{field}] === {needle})",
  360. var_type=bool,
  361. )
  362. @var_operation
  363. def string_contains_operation(haystack: StringVar[Any], needle: StringVar[Any] | str):
  364. """Check if a string contains another string.
  365. Args:
  366. haystack: The haystack.
  367. needle: The needle.
  368. Returns:
  369. The string contains operation.
  370. """
  371. return var_operation_return(
  372. js_expression=f"{haystack}.includes({needle})", var_type=bool
  373. )
  374. @var_operation
  375. def string_starts_with_operation(
  376. full_string: StringVar[Any], prefix: StringVar[Any] | str
  377. ):
  378. """Check if a string starts with a prefix.
  379. Args:
  380. full_string: The full string.
  381. prefix: The prefix.
  382. Returns:
  383. Whether the string starts with the prefix.
  384. """
  385. return var_operation_return(
  386. js_expression=f"{full_string}.startsWith({prefix})", var_type=bool
  387. )
  388. @var_operation
  389. def string_ends_with_operation(
  390. full_string: StringVar[Any], suffix: StringVar[Any] | str
  391. ):
  392. """Check if a string ends with a suffix.
  393. Args:
  394. full_string: The full string.
  395. suffix: The suffix.
  396. Returns:
  397. Whether the string ends with the suffix.
  398. """
  399. return var_operation_return(
  400. js_expression=f"{full_string}.endsWith({suffix})", var_type=bool
  401. )
  402. @var_operation
  403. def string_item_operation(string: StringVar[Any], index: NumberVar | int):
  404. """Get an item from a string.
  405. Args:
  406. string: The string.
  407. index: The index of the item.
  408. Returns:
  409. The item from the string.
  410. """
  411. return var_operation_return(js_expression=f"{string}.at({index})", var_type=str)
  412. @var_operation
  413. def array_join_operation(array: ArrayVar, sep: StringVar[Any] | str = ""):
  414. """Join the elements of an array.
  415. Args:
  416. array: The array.
  417. sep: The separator.
  418. Returns:
  419. The joined elements.
  420. """
  421. return var_operation_return(js_expression=f"{array}.join({sep})", var_type=str)
  422. @var_operation
  423. def string_replace_operation(
  424. string: StringVar, search_value: StringVar | str, new_value: StringVar | str
  425. ):
  426. """Replace a string with a value.
  427. Args:
  428. string: The string.
  429. search_value: The string to search.
  430. new_value: The value to be replaced with.
  431. Returns:
  432. The string replace operation.
  433. """
  434. return var_operation_return(
  435. js_expression=f"{string}.replace({search_value}, {new_value})",
  436. var_type=str,
  437. )
  438. # Compile regex for finding reflex var tags.
  439. _decode_var_pattern_re = (
  440. rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
  441. )
  442. _decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
  443. @dataclasses.dataclass(
  444. eq=False,
  445. frozen=True,
  446. slots=True,
  447. )
  448. class LiteralStringVar(LiteralVar, StringVar[str]):
  449. """Base class for immutable literal string vars."""
  450. _var_value: str = dataclasses.field(default="")
  451. @classmethod
  452. def create(
  453. cls,
  454. value: str,
  455. _var_type: GenericType | None = None,
  456. _var_data: VarData | None = None,
  457. ) -> StringVar:
  458. """Create a var from a string value.
  459. Args:
  460. value: The value to create the var from.
  461. _var_type: The type of the var.
  462. _var_data: Additional hooks and imports associated with the Var.
  463. Returns:
  464. The var.
  465. """
  466. # Determine var type in case the value is inherited from str.
  467. _var_type = _var_type or type(value) or str
  468. if REFLEX_VAR_OPENING_TAG in value:
  469. strings_and_vals: list[Var | str] = []
  470. offset = 0
  471. # Find all tags
  472. while m := _decode_var_pattern.search(value):
  473. start, end = m.span()
  474. strings_and_vals.append(value[:start])
  475. serialized_data = m.group(1)
  476. if serialized_data.isnumeric() or (
  477. serialized_data[0] == "-" and serialized_data[1:].isnumeric()
  478. ):
  479. # This is a global immutable var.
  480. var = _global_vars[int(serialized_data)]
  481. strings_and_vals.append(var)
  482. value = value[(end + len(var._js_expr)) :]
  483. offset += end - start
  484. strings_and_vals.append(value)
  485. filtered_strings_and_vals = [
  486. s for s in strings_and_vals if isinstance(s, Var) or s
  487. ]
  488. if len(filtered_strings_and_vals) == 1:
  489. only_string = filtered_strings_and_vals[0]
  490. if isinstance(only_string, str):
  491. return LiteralVar.create(only_string).to(StringVar, _var_type)
  492. else:
  493. return only_string.to(StringVar, only_string._var_type)
  494. if len(
  495. literal_strings := [
  496. s
  497. for s in filtered_strings_and_vals
  498. if isinstance(s, (str, LiteralStringVar))
  499. ]
  500. ) == len(filtered_strings_and_vals):
  501. return LiteralStringVar.create(
  502. "".join(
  503. s._var_value if isinstance(s, LiteralStringVar) else s
  504. for s in literal_strings
  505. ),
  506. _var_type=_var_type,
  507. _var_data=VarData.merge(
  508. _var_data,
  509. *(
  510. s._get_all_var_data()
  511. for s in filtered_strings_and_vals
  512. if isinstance(s, Var)
  513. ),
  514. ),
  515. )
  516. concat_result = ConcatVarOperation.create(
  517. *filtered_strings_and_vals,
  518. _var_data=_var_data,
  519. )
  520. return (
  521. concat_result
  522. if _var_type is str
  523. else concat_result.to(StringVar, _var_type)
  524. )
  525. return LiteralStringVar(
  526. _js_expr=json.dumps(value),
  527. _var_type=_var_type,
  528. _var_data=_var_data,
  529. _var_value=value,
  530. )
  531. def __hash__(self) -> int:
  532. """Get the hash of the var.
  533. Returns:
  534. The hash of the var.
  535. """
  536. return hash((type(self).__name__, self._var_value))
  537. def json(self) -> str:
  538. """Get the JSON representation of the var.
  539. Returns:
  540. The JSON representation of the var.
  541. """
  542. return json.dumps(self._var_value)
  543. @dataclasses.dataclass(
  544. eq=False,
  545. frozen=True,
  546. slots=True,
  547. )
  548. class ConcatVarOperation(CachedVarOperation, StringVar[str]):
  549. """Representing a concatenation of literal string vars."""
  550. _var_value: Tuple[Var, ...] = dataclasses.field(default_factory=tuple)
  551. @cached_property_no_lock
  552. def _cached_var_name(self) -> str:
  553. """The name of the var.
  554. Returns:
  555. The name of the var.
  556. """
  557. list_of_strs: List[Union[str, Var]] = []
  558. last_string = ""
  559. for var in self._var_value:
  560. if isinstance(var, LiteralStringVar):
  561. last_string += var._var_value
  562. else:
  563. if last_string:
  564. list_of_strs.append(last_string)
  565. last_string = ""
  566. list_of_strs.append(var)
  567. if last_string:
  568. list_of_strs.append(last_string)
  569. list_of_strs_filtered = [
  570. str(LiteralVar.create(s)) for s in list_of_strs if isinstance(s, Var) or s
  571. ]
  572. if len(list_of_strs_filtered) == 1:
  573. return list_of_strs_filtered[0]
  574. return "(" + "+".join(list_of_strs_filtered) + ")"
  575. @cached_property_no_lock
  576. def _cached_get_all_var_data(self) -> VarData | None:
  577. """Get all the VarData asVarDatae Var.
  578. Returns:
  579. The VarData associated with the Var.
  580. """
  581. return VarData.merge(
  582. *[
  583. var._get_all_var_data()
  584. for var in self._var_value
  585. if isinstance(var, Var)
  586. ],
  587. self._var_data,
  588. )
  589. @classmethod
  590. def create(
  591. cls,
  592. *value: Var | str,
  593. _var_data: VarData | None = None,
  594. ) -> ConcatVarOperation:
  595. """Create a var from a string value.
  596. Args:
  597. *value: The values to concatenate.
  598. _var_data: Additional hooks and imports associated with the Var.
  599. Returns:
  600. The var.
  601. """
  602. return cls(
  603. _js_expr="",
  604. _var_type=str,
  605. _var_data=_var_data,
  606. _var_value=tuple(map(LiteralVar.create, value)),
  607. )
  608. ARRAY_VAR_TYPE = TypeVar("ARRAY_VAR_TYPE", bound=Sequence, covariant=True)
  609. OTHER_ARRAY_VAR_TYPE = TypeVar("OTHER_ARRAY_VAR_TYPE", bound=Sequence)
  610. OTHER_TUPLE = TypeVar("OTHER_TUPLE")
  611. INNER_ARRAY_VAR = TypeVar("INNER_ARRAY_VAR")
  612. KEY_TYPE = TypeVar("KEY_TYPE")
  613. VALUE_TYPE = TypeVar("VALUE_TYPE")
  614. class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)):
  615. """Base class for immutable array vars."""
  616. @overload
  617. def join(self, sep: StringVar | str = "") -> StringVar: ...
  618. @overload
  619. def join(self, sep: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  620. def join(self, sep: Any = "") -> StringVar:
  621. """Join the elements of the array.
  622. Args:
  623. sep: The separator between elements.
  624. Returns:
  625. The joined elements.
  626. """
  627. if not isinstance(sep, (StringVar, str)):
  628. raise_unsupported_operand_types("join", (type(self), type(sep)))
  629. if (
  630. isinstance(self, LiteralArrayVar)
  631. and (
  632. len(
  633. args := [
  634. x
  635. for x in self._var_value
  636. if isinstance(x, (LiteralStringVar, str))
  637. ]
  638. )
  639. == len(self._var_value)
  640. )
  641. and isinstance(sep, (LiteralStringVar, str))
  642. ):
  643. sep_str = sep._var_value if isinstance(sep, LiteralStringVar) else sep
  644. return LiteralStringVar.create(
  645. sep_str.join(
  646. i._var_value if isinstance(i, LiteralStringVar) else i for i in args
  647. )
  648. )
  649. return array_join_operation(self, sep)
  650. def reverse(self) -> ArrayVar[ARRAY_VAR_TYPE]:
  651. """Reverse the array.
  652. Returns:
  653. The reversed array.
  654. """
  655. return array_reverse_operation(self)
  656. @overload
  657. def __add__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> ArrayVar[ARRAY_VAR_TYPE]: ...
  658. @overload
  659. def __add__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  660. def __add__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]:
  661. """Concatenate two arrays.
  662. Parameters:
  663. other: The other array to concatenate.
  664. Returns:
  665. ArrayConcatOperation: The concatenation of the two arrays.
  666. """
  667. if not isinstance(other, ArrayVar):
  668. raise_unsupported_operand_types("+", (type(self), type(other)))
  669. return array_concat_operation(self, other)
  670. @overload
  671. def __getitem__(self, i: slice) -> ArrayVar[ARRAY_VAR_TYPE]: ...
  672. @overload
  673. def __getitem__(
  674. self: (
  675. ArrayVar[Tuple[int, OTHER_TUPLE]]
  676. | ArrayVar[Tuple[float, OTHER_TUPLE]]
  677. | ArrayVar[Tuple[int | float, OTHER_TUPLE]]
  678. ),
  679. i: Literal[0, -2],
  680. ) -> NumberVar: ...
  681. @overload
  682. def __getitem__(
  683. self: ArrayVar[Tuple[Any, bool]], i: Literal[1, -1]
  684. ) -> BooleanVar: ...
  685. @overload
  686. def __getitem__(
  687. self: (
  688. ArrayVar[Tuple[Any, int]]
  689. | ArrayVar[Tuple[Any, float]]
  690. | ArrayVar[Tuple[Any, int | float]]
  691. ),
  692. i: Literal[1, -1],
  693. ) -> NumberVar: ...
  694. @overload
  695. def __getitem__(
  696. self: ArrayVar[Tuple[str, Any]], i: Literal[0, -2]
  697. ) -> StringVar: ...
  698. @overload
  699. def __getitem__(
  700. self: ArrayVar[Tuple[Any, str]], i: Literal[1, -1]
  701. ) -> StringVar: ...
  702. @overload
  703. def __getitem__(
  704. self: ArrayVar[Tuple[bool, Any]], i: Literal[0, -2]
  705. ) -> BooleanVar: ...
  706. @overload
  707. def __getitem__(
  708. self: ARRAY_VAR_OF_LIST_ELEMENT[bool], i: int | NumberVar
  709. ) -> BooleanVar: ...
  710. @overload
  711. def __getitem__(
  712. self: (
  713. ARRAY_VAR_OF_LIST_ELEMENT[int]
  714. | ARRAY_VAR_OF_LIST_ELEMENT[float]
  715. | ARRAY_VAR_OF_LIST_ELEMENT[int | float]
  716. ),
  717. i: int | NumberVar,
  718. ) -> NumberVar: ...
  719. @overload
  720. def __getitem__(
  721. self: ARRAY_VAR_OF_LIST_ELEMENT[str], i: int | NumberVar
  722. ) -> StringVar: ...
  723. @overload
  724. def __getitem__(
  725. self: ARRAY_VAR_OF_LIST_ELEMENT[List[INNER_ARRAY_VAR]],
  726. i: int | NumberVar,
  727. ) -> ArrayVar[List[INNER_ARRAY_VAR]]: ...
  728. @overload
  729. def __getitem__(
  730. self: ARRAY_VAR_OF_LIST_ELEMENT[Tuple[KEY_TYPE, VALUE_TYPE]],
  731. i: int | NumberVar,
  732. ) -> ArrayVar[Tuple[KEY_TYPE, VALUE_TYPE]]: ...
  733. @overload
  734. def __getitem__(
  735. self: ARRAY_VAR_OF_LIST_ELEMENT[Tuple[INNER_ARRAY_VAR, ...]],
  736. i: int | NumberVar,
  737. ) -> ArrayVar[Tuple[INNER_ARRAY_VAR, ...]]: ...
  738. @overload
  739. def __getitem__(
  740. self: ARRAY_VAR_OF_LIST_ELEMENT[Dict[KEY_TYPE, VALUE_TYPE]],
  741. i: int | NumberVar,
  742. ) -> ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]]: ...
  743. @overload
  744. def __getitem__(self, i: int | NumberVar) -> Var: ...
  745. def __getitem__(self, i: Any) -> ArrayVar[ARRAY_VAR_TYPE] | Var:
  746. """Get a slice of the array.
  747. Args:
  748. i: The slice.
  749. Returns:
  750. The array slice operation.
  751. """
  752. if isinstance(i, slice):
  753. return ArraySliceOperation.create(self, i)
  754. if not isinstance(i, (int, NumberVar)) or (
  755. isinstance(i, NumberVar) and i._is_strict_float()
  756. ):
  757. raise_unsupported_operand_types("[]", (type(self), type(i)))
  758. return array_item_operation(self, i)
  759. def length(self) -> NumberVar[int]:
  760. """Get the length of the array.
  761. Returns:
  762. The length of the array.
  763. """
  764. return array_length_operation(self)
  765. @overload
  766. @classmethod
  767. def range(cls, stop: int | NumberVar, /) -> ArrayVar[List[int]]: ...
  768. @overload
  769. @classmethod
  770. def range(
  771. cls,
  772. start: int | NumberVar,
  773. end: int | NumberVar,
  774. step: int | NumberVar = 1,
  775. /,
  776. ) -> ArrayVar[List[int]]: ...
  777. @overload
  778. @classmethod
  779. def range(
  780. cls,
  781. first_endpoint: int | NumberVar,
  782. second_endpoint: int | NumberVar | None = None,
  783. step: int | NumberVar | None = None,
  784. ) -> ArrayVar[List[int]]: ...
  785. @classmethod
  786. def range(
  787. cls,
  788. first_endpoint: int | NumberVar,
  789. second_endpoint: int | NumberVar | None = None,
  790. step: int | NumberVar | None = None,
  791. ) -> ArrayVar[List[int]]:
  792. """Create a range of numbers.
  793. Args:
  794. first_endpoint: The end of the range if second_endpoint is not provided, otherwise the start of the range.
  795. second_endpoint: The end of the range.
  796. step: The step of the range.
  797. Returns:
  798. The range of numbers.
  799. """
  800. if any(
  801. not isinstance(i, (int, NumberVar))
  802. for i in (first_endpoint, second_endpoint, step)
  803. if i is not None
  804. ):
  805. raise_unsupported_operand_types(
  806. "range", (type(first_endpoint), type(second_endpoint), type(step))
  807. )
  808. if second_endpoint is None:
  809. start = 0
  810. end = first_endpoint
  811. else:
  812. start = first_endpoint
  813. end = second_endpoint
  814. return array_range_operation(start, end, step or 1)
  815. @overload
  816. def contains(self, other: Any) -> BooleanVar: ...
  817. @overload
  818. def contains(self, other: Any, field: StringVar | str) -> BooleanVar: ...
  819. def contains(self, other: Any, field: Any = None) -> BooleanVar:
  820. """Check if the array contains an element.
  821. Args:
  822. other: The element to check for.
  823. field: The field to check.
  824. Returns:
  825. The array contains operation.
  826. """
  827. if field is not None:
  828. if not isinstance(field, (StringVar, str)):
  829. raise_unsupported_operand_types("contains", (type(self), type(field)))
  830. return array_contains_field_operation(self, other, field)
  831. return array_contains_operation(self, other)
  832. def pluck(self, field: StringVar | str) -> ArrayVar:
  833. """Pluck a field from the array.
  834. Args:
  835. field: The field to pluck from the array.
  836. Returns:
  837. The array pluck operation.
  838. """
  839. return array_pluck_operation(self, field)
  840. @overload
  841. def __mul__(self, other: NumberVar | int) -> ArrayVar[ARRAY_VAR_TYPE]: ...
  842. @overload
  843. def __mul__(self, other: NoReturn) -> NoReturn: ... # pyright: ignore [reportOverlappingOverload]
  844. def __mul__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]:
  845. """Multiply the sequence by a number or integer.
  846. Parameters:
  847. other: The number or integer to multiply the sequence by.
  848. Returns:
  849. ArrayVar[ARRAY_VAR_TYPE]: The result of multiplying the sequence by the given number or integer.
  850. """
  851. if not isinstance(other, (NumberVar, int)) or (
  852. isinstance(other, NumberVar) and other._is_strict_float()
  853. ):
  854. raise_unsupported_operand_types("*", (type(self), type(other)))
  855. return repeat_array_operation(self, other)
  856. __rmul__ = __mul__
  857. @overload
  858. def __lt__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
  859. @overload
  860. def __lt__(self, other: list | tuple) -> BooleanVar: ...
  861. def __lt__(self, other: Any):
  862. """Check if the array is less than another array.
  863. Args:
  864. other: The other array.
  865. Returns:
  866. The array less than operation.
  867. """
  868. if not isinstance(other, (ArrayVar, list, tuple)):
  869. raise_unsupported_operand_types("<", (type(self), type(other)))
  870. return array_lt_operation(self, other)
  871. @overload
  872. def __gt__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
  873. @overload
  874. def __gt__(self, other: list | tuple) -> BooleanVar: ...
  875. def __gt__(self, other: Any):
  876. """Check if the array is greater than another array.
  877. Args:
  878. other: The other array.
  879. Returns:
  880. The array greater than operation.
  881. """
  882. if not isinstance(other, (ArrayVar, list, tuple)):
  883. raise_unsupported_operand_types(">", (type(self), type(other)))
  884. return array_gt_operation(self, other)
  885. @overload
  886. def __le__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
  887. @overload
  888. def __le__(self, other: list | tuple) -> BooleanVar: ...
  889. def __le__(self, other: Any):
  890. """Check if the array is less than or equal to another array.
  891. Args:
  892. other: The other array.
  893. Returns:
  894. The array less than or equal operation.
  895. """
  896. if not isinstance(other, (ArrayVar, list, tuple)):
  897. raise_unsupported_operand_types("<=", (type(self), type(other)))
  898. return array_le_operation(self, other)
  899. @overload
  900. def __ge__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
  901. @overload
  902. def __ge__(self, other: list | tuple) -> BooleanVar: ...
  903. def __ge__(self, other: Any):
  904. """Check if the array is greater than or equal to another array.
  905. Args:
  906. other: The other array.
  907. Returns:
  908. The array greater than or equal operation.
  909. """
  910. if not isinstance(other, (ArrayVar, list, tuple)):
  911. raise_unsupported_operand_types(">=", (type(self), type(other)))
  912. return array_ge_operation(self, other)
  913. def foreach(self, fn: Any):
  914. """Apply a function to each element of the array.
  915. Args:
  916. fn: The function to apply.
  917. Returns:
  918. The array after applying the function.
  919. Raises:
  920. VarTypeError: If the function takes more than one argument.
  921. """
  922. from .function import ArgsFunctionOperation
  923. if not callable(fn):
  924. raise_unsupported_operand_types("foreach", (type(self), type(fn)))
  925. # get the number of arguments of the function
  926. num_args = len(inspect.signature(fn).parameters)
  927. if num_args > 1:
  928. raise VarTypeError(
  929. "The function passed to foreach should take at most one argument."
  930. )
  931. if num_args == 0:
  932. return_value = fn()
  933. function_var = ArgsFunctionOperation.create((), return_value)
  934. else:
  935. # generic number var
  936. number_var = Var("").to(NumberVar, int)
  937. first_arg_type = self[number_var]._var_type
  938. arg_name = get_unique_variable_name()
  939. # get first argument type
  940. first_arg = Var(
  941. _js_expr=arg_name,
  942. _var_type=first_arg_type,
  943. ).guess_type()
  944. function_var = ArgsFunctionOperation.create(
  945. (arg_name,),
  946. Var.create(fn(first_arg)),
  947. )
  948. return map_array_operation(self, function_var)
  949. LIST_ELEMENT = TypeVar("LIST_ELEMENT")
  950. ARRAY_VAR_OF_LIST_ELEMENT = ArrayVar[Sequence[LIST_ELEMENT]]
  951. @dataclasses.dataclass(
  952. eq=False,
  953. frozen=True,
  954. slots=True,
  955. )
  956. class LiteralArrayVar(CachedVarOperation, LiteralVar, ArrayVar[ARRAY_VAR_TYPE]):
  957. """Base class for immutable literal array vars."""
  958. _var_value: Sequence[Union[Var, Any]] = dataclasses.field(default=())
  959. @cached_property_no_lock
  960. def _cached_var_name(self) -> str:
  961. """The name of the var.
  962. Returns:
  963. The name of the var.
  964. """
  965. return (
  966. "["
  967. + ", ".join(
  968. [str(LiteralVar.create(element)) for element in self._var_value]
  969. )
  970. + "]"
  971. )
  972. @cached_property_no_lock
  973. def _cached_get_all_var_data(self) -> VarData | None:
  974. """Get all the VarData associated with the Var.
  975. Returns:
  976. The VarData associated with the Var.
  977. """
  978. return VarData.merge(
  979. *[
  980. LiteralVar.create(element)._get_all_var_data()
  981. for element in self._var_value
  982. ],
  983. self._var_data,
  984. )
  985. def __hash__(self) -> int:
  986. """Get the hash of the var.
  987. Returns:
  988. The hash of the var.
  989. """
  990. return hash((self.__class__.__name__, self._js_expr))
  991. def json(self) -> str:
  992. """Get the JSON representation of the var.
  993. Returns:
  994. The JSON representation of the var.
  995. Raises:
  996. TypeError: If the array elements are not of type LiteralVar.
  997. """
  998. elements = []
  999. for element in self._var_value:
  1000. element_var = LiteralVar.create(element)
  1001. if not isinstance(element_var, LiteralVar):
  1002. raise TypeError(
  1003. f"Array elements must be of type LiteralVar, not {type(element_var)}"
  1004. )
  1005. elements.append(element_var.json())
  1006. return "[" + ", ".join(elements) + "]"
  1007. @classmethod
  1008. def create(
  1009. cls,
  1010. value: OTHER_ARRAY_VAR_TYPE,
  1011. _var_type: Type[OTHER_ARRAY_VAR_TYPE] | None = None,
  1012. _var_data: VarData | None = None,
  1013. ) -> LiteralArrayVar[OTHER_ARRAY_VAR_TYPE]:
  1014. """Create a var from a string value.
  1015. Args:
  1016. value: The value to create the var from.
  1017. _var_type: The type of the var.
  1018. _var_data: Additional hooks and imports associated with the Var.
  1019. Returns:
  1020. The var.
  1021. """
  1022. return LiteralArrayVar(
  1023. _js_expr="",
  1024. _var_type=figure_out_type(value) if _var_type is None else _var_type,
  1025. _var_data=_var_data,
  1026. _var_value=value,
  1027. )
  1028. @var_operation
  1029. def string_split_operation(string: StringVar[Any], sep: StringVar | str = ""):
  1030. """Split a string.
  1031. Args:
  1032. string: The string to split.
  1033. sep: The separator.
  1034. Returns:
  1035. The split string.
  1036. """
  1037. return var_operation_return(
  1038. js_expression=f"{string}.split({sep})", var_type=List[str]
  1039. )
  1040. @dataclasses.dataclass(
  1041. eq=False,
  1042. frozen=True,
  1043. slots=True,
  1044. )
  1045. class ArraySliceOperation(CachedVarOperation, ArrayVar):
  1046. """Base class for immutable string vars that are the result of a string slice operation."""
  1047. _array: ArrayVar = dataclasses.field(
  1048. default_factory=lambda: LiteralArrayVar.create([])
  1049. )
  1050. _start: NumberVar | int = dataclasses.field(default_factory=lambda: 0)
  1051. _stop: NumberVar | int = dataclasses.field(default_factory=lambda: 0)
  1052. _step: NumberVar | int = dataclasses.field(default_factory=lambda: 1)
  1053. @cached_property_no_lock
  1054. def _cached_var_name(self) -> str:
  1055. """The name of the var.
  1056. Returns:
  1057. The name of the var.
  1058. Raises:
  1059. ValueError: If the slice step is zero.
  1060. """
  1061. start, end, step = self._start, self._stop, self._step
  1062. normalized_start = (
  1063. LiteralVar.create(start) if start is not None else Var(_js_expr="undefined")
  1064. )
  1065. normalized_end = (
  1066. LiteralVar.create(end) if end is not None else Var(_js_expr="undefined")
  1067. )
  1068. if step is None:
  1069. return f"{self._array!s}.slice({normalized_start!s}, {normalized_end!s})"
  1070. if not isinstance(step, Var):
  1071. if step < 0:
  1072. actual_start = end + 1 if end is not None else 0
  1073. actual_end = start + 1 if start is not None else self._array.length()
  1074. return str(self._array[actual_start:actual_end].reverse()[::-step])
  1075. if step == 0:
  1076. raise ValueError("slice step cannot be zero")
  1077. return f"{self._array!s}.slice({normalized_start!s}, {normalized_end!s}).filter((_, i) => i % {step!s} === 0)"
  1078. actual_start_reverse = end + 1 if end is not None else 0
  1079. actual_end_reverse = start + 1 if start is not None else self._array.length()
  1080. return f"{self.step!s} > 0 ? {self._array!s}.slice({normalized_start!s}, {normalized_end!s}).filter((_, i) => i % {step!s} === 0) : {self._array!s}.slice({actual_start_reverse!s}, {actual_end_reverse!s}).reverse().filter((_, i) => i % {-step!s} === 0)"
  1081. @classmethod
  1082. def create(
  1083. cls,
  1084. array: ArrayVar,
  1085. slice: slice,
  1086. _var_data: VarData | None = None,
  1087. ) -> ArraySliceOperation:
  1088. """Create a var from a string value.
  1089. Args:
  1090. array: The array.
  1091. slice: The slice.
  1092. _var_data: Additional hooks and imports associated with the Var.
  1093. Returns:
  1094. The var.
  1095. """
  1096. return cls(
  1097. _js_expr="",
  1098. _var_type=array._var_type,
  1099. _var_data=_var_data,
  1100. _array=array,
  1101. _start=slice.start,
  1102. _stop=slice.stop,
  1103. _step=slice.step,
  1104. )
  1105. @var_operation
  1106. def array_pluck_operation(
  1107. array: ArrayVar[ARRAY_VAR_TYPE],
  1108. field: StringVar | str,
  1109. ) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
  1110. """Pluck a field from an array of objects.
  1111. Args:
  1112. array: The array to pluck from.
  1113. field: The field to pluck from the objects in the array.
  1114. Returns:
  1115. The reversed array.
  1116. """
  1117. return var_operation_return(
  1118. js_expression=f"{array}.map(e=>e?.[{field}])",
  1119. var_type=array._var_type,
  1120. )
  1121. @var_operation
  1122. def array_reverse_operation(
  1123. array: ArrayVar[ARRAY_VAR_TYPE],
  1124. ) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
  1125. """Reverse an array.
  1126. Args:
  1127. array: The array to reverse.
  1128. Returns:
  1129. The reversed array.
  1130. """
  1131. return var_operation_return(
  1132. js_expression=f"{array}.slice().reverse()",
  1133. var_type=array._var_type,
  1134. )
  1135. @var_operation
  1136. def array_lt_operation(lhs: ArrayVar | list | tuple, rhs: ArrayVar | list | tuple):
  1137. """Check if an array is less than another array.
  1138. Args:
  1139. lhs: The left-hand side array.
  1140. rhs: The right-hand side array.
  1141. Returns:
  1142. The array less than operation.
  1143. """
  1144. return var_operation_return(js_expression=f"{lhs} < {rhs}", var_type=bool)
  1145. @var_operation
  1146. def array_gt_operation(lhs: ArrayVar | list | tuple, rhs: ArrayVar | list | tuple):
  1147. """Check if an array is greater than another array.
  1148. Args:
  1149. lhs: The left-hand side array.
  1150. rhs: The right-hand side array.
  1151. Returns:
  1152. The array greater than operation.
  1153. """
  1154. return var_operation_return(js_expression=f"{lhs} > {rhs}", var_type=bool)
  1155. @var_operation
  1156. def array_le_operation(lhs: ArrayVar | list | tuple, rhs: ArrayVar | list | tuple):
  1157. """Check if an array is less than or equal to another array.
  1158. Args:
  1159. lhs: The left-hand side array.
  1160. rhs: The right-hand side array.
  1161. Returns:
  1162. The array less than or equal operation.
  1163. """
  1164. return var_operation_return(js_expression=f"{lhs} <= {rhs}", var_type=bool)
  1165. @var_operation
  1166. def array_ge_operation(lhs: ArrayVar | list | tuple, rhs: ArrayVar | list | tuple):
  1167. """Check if an array is greater than or equal to another array.
  1168. Args:
  1169. lhs: The left-hand side array.
  1170. rhs: The right-hand side array.
  1171. Returns:
  1172. The array greater than or equal operation.
  1173. """
  1174. return var_operation_return(js_expression=f"{lhs} >= {rhs}", var_type=bool)
  1175. @var_operation
  1176. def array_length_operation(array: ArrayVar):
  1177. """Get the length of an array.
  1178. Args:
  1179. array: The array.
  1180. Returns:
  1181. The length of the array.
  1182. """
  1183. return var_operation_return(
  1184. js_expression=f"{array}.length",
  1185. var_type=int,
  1186. )
  1187. def is_tuple_type(t: GenericType) -> bool:
  1188. """Check if a type is a tuple type.
  1189. Args:
  1190. t: The type to check.
  1191. Returns:
  1192. Whether the type is a tuple type.
  1193. """
  1194. if inspect.isclass(t):
  1195. return issubclass(t, tuple)
  1196. return get_origin(t) is tuple
  1197. @var_operation
  1198. def array_item_operation(array: ArrayVar, index: NumberVar | int):
  1199. """Get an item from an array.
  1200. Args:
  1201. array: The array.
  1202. index: The index of the item.
  1203. Returns:
  1204. The item from the array.
  1205. """
  1206. args = typing.get_args(array._var_type)
  1207. if args and isinstance(index, LiteralNumberVar) and is_tuple_type(array._var_type):
  1208. index_value = int(index._var_value)
  1209. element_type = args[index_value % len(args)]
  1210. else:
  1211. element_type = unionize(*args)
  1212. return var_operation_return(
  1213. js_expression=f"{array!s}.at({index!s})",
  1214. var_type=element_type,
  1215. )
  1216. @var_operation
  1217. def array_range_operation(
  1218. start: NumberVar | int, stop: NumberVar | int, step: NumberVar | int
  1219. ):
  1220. """Create a range of numbers.
  1221. Args:
  1222. start: The start of the range.
  1223. stop: The end of the range.
  1224. step: The step of the range.
  1225. Returns:
  1226. The range of numbers.
  1227. """
  1228. return var_operation_return(
  1229. js_expression=f"Array.from({{ length: Math.ceil(({stop!s} - {start!s}) / {step!s}) }}, (_, i) => {start!s} + i * {step!s})",
  1230. var_type=List[int],
  1231. )
  1232. @var_operation
  1233. def array_contains_field_operation(
  1234. haystack: ArrayVar, needle: Any | Var, field: StringVar | str
  1235. ):
  1236. """Check if an array contains an element.
  1237. Args:
  1238. haystack: The array to check.
  1239. needle: The element to check for.
  1240. field: The field to check.
  1241. Returns:
  1242. The array contains operation.
  1243. """
  1244. return var_operation_return(
  1245. js_expression=f"{haystack}.some(obj => obj[{field}] === {needle})",
  1246. var_type=bool,
  1247. )
  1248. @var_operation
  1249. def array_contains_operation(
  1250. haystack: ArrayVar, needle: Any | Var
  1251. ) -> CustomVarOperationReturn[bool]:
  1252. """Check if an array contains an element.
  1253. Args:
  1254. haystack: The array to check.
  1255. needle: The element to check for.
  1256. Returns:
  1257. The array contains operation.
  1258. """
  1259. return var_operation_return(
  1260. js_expression=f"{haystack}.includes({needle})",
  1261. var_type=bool,
  1262. )
  1263. @var_operation
  1264. def repeat_array_operation(
  1265. array: ArrayVar[ARRAY_VAR_TYPE], count: NumberVar | int
  1266. ) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
  1267. """Repeat an array a number of times.
  1268. Args:
  1269. array: The array to repeat.
  1270. count: The number of times to repeat the array.
  1271. Returns:
  1272. The repeated array.
  1273. """
  1274. return var_operation_return(
  1275. js_expression=f"Array.from({{ length: {count} }}).flatMap(() => {array})",
  1276. var_type=array._var_type,
  1277. )
  1278. if TYPE_CHECKING:
  1279. from .function import FunctionVar
  1280. @var_operation
  1281. def map_array_operation(
  1282. array: ArrayVar[ARRAY_VAR_TYPE],
  1283. function: FunctionVar,
  1284. ) -> CustomVarOperationReturn[List[Any]]:
  1285. """Map a function over an array.
  1286. Args:
  1287. array: The array.
  1288. function: The function to map.
  1289. Returns:
  1290. The mapped array.
  1291. """
  1292. return var_operation_return(
  1293. js_expression=f"{array}.map({function})", var_type=List[Any]
  1294. )
  1295. @var_operation
  1296. def array_concat_operation(
  1297. lhs: ArrayVar[ARRAY_VAR_TYPE], rhs: ArrayVar[ARRAY_VAR_TYPE]
  1298. ) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
  1299. """Concatenate two arrays.
  1300. Args:
  1301. lhs: The left-hand side array.
  1302. rhs: The right-hand side array.
  1303. Returns:
  1304. The concatenated array.
  1305. """
  1306. return var_operation_return(
  1307. js_expression=f"[...{lhs}, ...{rhs}]",
  1308. var_type=Union[lhs._var_type, rhs._var_type], # pyright: ignore [reportArgumentType]
  1309. )
  1310. class ColorVar(StringVar[Color], python_types=Color):
  1311. """Base class for immutable color vars."""
  1312. @dataclasses.dataclass(
  1313. eq=False,
  1314. frozen=True,
  1315. slots=True,
  1316. )
  1317. class LiteralColorVar(CachedVarOperation, LiteralVar, ColorVar):
  1318. """Base class for immutable literal color vars."""
  1319. _var_value: Color = dataclasses.field(default_factory=lambda: Color(color="black"))
  1320. @classmethod
  1321. def create(
  1322. cls,
  1323. value: Color,
  1324. _var_type: Type[Color] | None = None,
  1325. _var_data: VarData | None = None,
  1326. ) -> ColorVar:
  1327. """Create a var from a string value.
  1328. Args:
  1329. value: The value to create the var from.
  1330. _var_type: The type of the var.
  1331. _var_data: Additional hooks and imports associated with the Var.
  1332. Returns:
  1333. The var.
  1334. """
  1335. return cls(
  1336. _js_expr="",
  1337. _var_type=_var_type or Color,
  1338. _var_data=_var_data,
  1339. _var_value=value,
  1340. )
  1341. def __hash__(self) -> int:
  1342. """Get the hash of the var.
  1343. Returns:
  1344. The hash of the var.
  1345. """
  1346. return hash(
  1347. (
  1348. self.__class__.__name__,
  1349. self._var_value.color,
  1350. self._var_value.alpha,
  1351. self._var_value.shade,
  1352. )
  1353. )
  1354. @cached_property_no_lock
  1355. def _cached_var_name(self) -> str:
  1356. """The name of the var.
  1357. Returns:
  1358. The name of the var.
  1359. """
  1360. alpha = self._var_value.alpha
  1361. alpha = (
  1362. ternary_operation(
  1363. alpha,
  1364. LiteralStringVar.create("a"),
  1365. LiteralStringVar.create(""),
  1366. )
  1367. if isinstance(alpha, Var)
  1368. else LiteralStringVar.create("a" if alpha else "")
  1369. )
  1370. shade = self._var_value.shade
  1371. shade = (
  1372. shade.to_string(use_json=False)
  1373. if isinstance(shade, Var)
  1374. else LiteralStringVar.create(str(shade))
  1375. )
  1376. return str(
  1377. ConcatVarOperation.create(
  1378. LiteralStringVar.create("var(--"),
  1379. self._var_value.color,
  1380. LiteralStringVar.create("-"),
  1381. alpha,
  1382. shade,
  1383. LiteralStringVar.create(")"),
  1384. )
  1385. )
  1386. @cached_property_no_lock
  1387. def _cached_get_all_var_data(self) -> VarData | None:
  1388. """Get all the var data.
  1389. Returns:
  1390. The var data.
  1391. """
  1392. return VarData.merge(
  1393. *[
  1394. LiteralVar.create(var)._get_all_var_data()
  1395. for var in (
  1396. self._var_value.color,
  1397. self._var_value.alpha,
  1398. self._var_value.shade,
  1399. )
  1400. ],
  1401. self._var_data,
  1402. )
  1403. def json(self) -> str:
  1404. """Get the JSON representation of the var.
  1405. Returns:
  1406. The JSON representation of the var.
  1407. Raises:
  1408. TypeError: If the color is not a valid color.
  1409. """
  1410. color, alpha, shade = map(
  1411. get_python_literal,
  1412. (self._var_value.color, self._var_value.alpha, self._var_value.shade),
  1413. )
  1414. if color is None or alpha is None or shade is None:
  1415. raise TypeError("Cannot serialize color that contains non-literal vars.")
  1416. if (
  1417. not isinstance(color, str)
  1418. or not isinstance(alpha, bool)
  1419. or not isinstance(shade, int)
  1420. ):
  1421. raise TypeError("Color is not a valid color.")
  1422. return f"var(--{color}-{'a' if alpha else ''}{shade})"