sequence.py 52 KB

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