sequence.py 50 KB

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