sequence.py 54 KB

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