sequence.py 54 KB

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