sequence.py 54 KB

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