sequence.py 50 KB

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