sequence.py 51 KB

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