sequence.py 57 KB

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