sequence.py 51 KB

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