1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873 |
- """Collection of string classes and utilities."""
- from __future__ import annotations
- import dataclasses
- import functools
- import inspect
- import json
- import re
- import sys
- import typing
- from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- Dict,
- List,
- Literal,
- NoReturn,
- Set,
- Tuple,
- Type,
- Union,
- cast,
- overload,
- )
- from typing_extensions import TypeAliasType, TypeVar
- from reflex import constants
- from reflex.constants.base import REFLEX_VAR_OPENING_TAG
- from reflex.constants.colors import Color
- from reflex.utils.exceptions import VarTypeError
- from reflex.utils.types import GenericType, get_origin
- from .base import (
- CachedVarOperation,
- CustomVarOperationReturn,
- LiteralVar,
- ReflexCallable,
- Var,
- VarData,
- _global_vars,
- cached_property_no_lock,
- figure_out_type,
- get_python_literal,
- get_unique_variable_name,
- nary_type_computer,
- passthrough_unary_type_computer,
- unionize,
- unwrap_reflex_callalbe,
- var_operation,
- var_operation_return,
- )
- from .number import (
- BooleanVar,
- LiteralNumberVar,
- NumberVar,
- raise_unsupported_operand_types,
- ternary_operation,
- )
- if TYPE_CHECKING:
- from .function import FunctionVar
- from .object import ObjectVar
- STRING_TYPE = TypeVar("STRING_TYPE", default=str)
- class StringVar(Var[STRING_TYPE], python_types=str):
- """Base class for immutable string vars."""
- @overload
- def __add__(self, other: StringVar | str) -> ConcatVarOperation: ...
- @overload
- def __add__(self, other: NoReturn) -> NoReturn: ...
- def __add__(self, other: Any) -> ConcatVarOperation:
- """Concatenate two strings.
- Args:
- other: The other string.
- Returns:
- The string concatenation operation.
- """
- if not isinstance(other, (StringVar, str)):
- raise_unsupported_operand_types("+", (type(self), type(other)))
- return ConcatVarOperation.create(self, other)
- @overload
- def __radd__(self, other: StringVar | str) -> ConcatVarOperation: ...
- @overload
- def __radd__(self, other: NoReturn) -> NoReturn: ...
- def __radd__(self, other: Any) -> ConcatVarOperation:
- """Concatenate two strings.
- Args:
- other: The other string.
- Returns:
- The string concatenation operation.
- """
- if not isinstance(other, (StringVar, str)):
- raise_unsupported_operand_types("+", (type(other), type(self)))
- return ConcatVarOperation.create(other, self)
- @overload
- def __mul__(self, other: NumberVar | int) -> StringVar: ...
- @overload
- def __mul__(self, other: NoReturn) -> NoReturn: ...
- def __mul__(self, other: Any) -> StringVar:
- """Multiply the sequence by a number or an integer.
- Args:
- other: The number or integer to multiply the sequence by.
- Returns:
- StringVar: The resulting sequence after multiplication.
- """
- if not isinstance(other, (NumberVar, int)):
- raise_unsupported_operand_types("*", (type(self), type(other)))
- return (self.split() * other).join()
- @overload
- def __rmul__(self, other: NumberVar | int) -> StringVar: ...
- @overload
- def __rmul__(self, other: NoReturn) -> NoReturn: ...
- def __rmul__(self, other: Any) -> StringVar:
- """Multiply the sequence by a number or an integer.
- Args:
- other: The number or integer to multiply the sequence by.
- Returns:
- StringVar: The resulting sequence after multiplication.
- """
- if not isinstance(other, (NumberVar, int)):
- raise_unsupported_operand_types("*", (type(other), type(self)))
- return (self.split() * other).join()
- @overload
- def __getitem__(self, i: slice) -> StringVar: ...
- @overload
- def __getitem__(self, i: int | NumberVar) -> StringVar: ...
- def __getitem__(self, i: Any) -> StringVar:
- """Get a slice of the string.
- Args:
- i: The slice.
- Returns:
- The string slice operation.
- """
- if isinstance(i, slice):
- return self.split()[i].join()
- if not isinstance(i, (int, NumberVar)) or (
- isinstance(i, NumberVar) and i._is_strict_float()
- ):
- raise_unsupported_operand_types("[]", (type(self), type(i)))
- return string_item_operation(self, i).guess_type()
- def length(self) -> NumberVar:
- """Get the length of the string.
- Returns:
- The string length operation.
- """
- return self.split().length()
- def lower(self) -> StringVar:
- """Convert the string to lowercase.
- Returns:
- The string lower operation.
- """
- return string_lower_operation(self).guess_type()
- def upper(self) -> StringVar:
- """Convert the string to uppercase.
- Returns:
- The string upper operation.
- """
- return string_upper_operation(self).guess_type()
- def strip(self) -> StringVar:
- """Strip the string.
- Returns:
- The string strip operation.
- """
- return string_strip_operation(self).guess_type()
- def reversed(self) -> StringVar:
- """Reverse the string.
- Returns:
- The string reverse operation.
- """
- return self.split().reverse().join()
- @overload
- def contains(
- self, other: StringVar | str, field: StringVar | str | None = None
- ) -> BooleanVar: ...
- @overload
- def contains(
- self, other: NoReturn, field: StringVar | str | None = None
- ) -> NoReturn: ...
- def contains(self, other: Any, field: Any = None) -> BooleanVar:
- """Check if the string contains another string.
- Args:
- other: The other string.
- field: The field to check.
- Returns:
- The string contains operation.
- """
- if not isinstance(other, (StringVar, str)):
- raise_unsupported_operand_types("contains", (type(self), type(other)))
- if field is not None:
- if not isinstance(field, (StringVar, str)):
- raise_unsupported_operand_types("contains", (type(self), type(field)))
- return string_contains_field_operation(self, other, field).guess_type()
- return string_contains_operation(self, other).guess_type()
- @overload
- def split(self, separator: StringVar | str = "") -> ArrayVar[List[str]]: ...
- @overload
- def split(self, separator: NoReturn) -> NoReturn: ...
- def split(self, separator: Any = "") -> ArrayVar[List[str]]:
- """Split the string.
- Args:
- separator: The separator.
- Returns:
- The string split operation.
- """
- if not isinstance(separator, (StringVar, str)):
- raise_unsupported_operand_types("split", (type(self), type(separator)))
- return string_split_operation(self, separator).guess_type()
- @overload
- def startswith(self, prefix: StringVar | str) -> BooleanVar: ...
- @overload
- def startswith(self, prefix: NoReturn) -> NoReturn: ...
- def startswith(self, prefix: Any) -> BooleanVar:
- """Check if the string starts with a prefix.
- Args:
- prefix: The prefix.
- Returns:
- The string starts with operation.
- """
- if not isinstance(prefix, (StringVar, str)):
- raise_unsupported_operand_types("startswith", (type(self), type(prefix)))
- return string_starts_with_operation(self, prefix).guess_type()
- @overload
- def __lt__(self, other: StringVar | str) -> BooleanVar: ...
- @overload
- def __lt__(self, other: NoReturn) -> NoReturn: ...
- def __lt__(self, other: Any):
- """Check if the string is less than another string.
- Args:
- other: The other string.
- Returns:
- The string less than operation.
- """
- if not isinstance(other, (StringVar, str)):
- raise_unsupported_operand_types("<", (type(self), type(other)))
- return string_lt_operation(self, other).guess_type()
- @overload
- def __gt__(self, other: StringVar | str) -> BooleanVar: ...
- @overload
- def __gt__(self, other: NoReturn) -> NoReturn: ...
- def __gt__(self, other: Any):
- """Check if the string is greater than another string.
- Args:
- other: The other string.
- Returns:
- The string greater than operation.
- """
- if not isinstance(other, (StringVar, str)):
- raise_unsupported_operand_types(">", (type(self), type(other)))
- return string_gt_operation(self, other).guess_type()
- @overload
- def __le__(self, other: StringVar | str) -> BooleanVar: ...
- @overload
- def __le__(self, other: NoReturn) -> NoReturn: ...
- def __le__(self, other: Any):
- """Check if the string is less than or equal to another string.
- Args:
- other: The other string.
- Returns:
- The string less than or equal operation.
- """
- if not isinstance(other, (StringVar, str)):
- raise_unsupported_operand_types("<=", (type(self), type(other)))
- return string_le_operation(self, other).guess_type()
- @overload
- def __ge__(self, other: StringVar | str) -> BooleanVar: ...
- @overload
- def __ge__(self, other: NoReturn) -> NoReturn: ...
- def __ge__(self, other: Any):
- """Check if the string is greater than or equal to another string.
- Args:
- other: The other string.
- Returns:
- The string greater than or equal operation.
- """
- if not isinstance(other, (StringVar, str)):
- raise_unsupported_operand_types(">=", (type(self), type(other)))
- return string_ge_operation(self, other).guess_type()
- @var_operation
- def string_lt_operation(lhs: Var[str], rhs: Var[str]):
- """Check if a string is less than another string.
- Args:
- lhs: The left-hand side string.
- rhs: The right-hand side string.
- Returns:
- The string less than operation.
- """
- return var_operation_return(js_expression=f"{lhs} < {rhs}", var_type=bool)
- @var_operation
- def string_gt_operation(lhs: Var[str], rhs: Var[str]):
- """Check if a string is greater than another string.
- Args:
- lhs: The left-hand side string.
- rhs: The right-hand side string.
- Returns:
- The string greater than operation.
- """
- return var_operation_return(js_expression=f"{lhs} > {rhs}", var_type=bool)
- @var_operation
- def string_le_operation(lhs: Var[str], rhs: Var[str]):
- """Check if a string is less than or equal to another string.
- Args:
- lhs: The left-hand side string.
- rhs: The right-hand side string.
- Returns:
- The string less than or equal operation.
- """
- return var_operation_return(js_expression=f"{lhs} <= {rhs}", var_type=bool)
- @var_operation
- def string_ge_operation(lhs: Var[str], rhs: Var[str]):
- """Check if a string is greater than or equal to another string.
- Args:
- lhs: The left-hand side string.
- rhs: The right-hand side string.
- Returns:
- The string greater than or equal operation.
- """
- return var_operation_return(js_expression=f"{lhs} >= {rhs}", var_type=bool)
- @var_operation
- def string_lower_operation(string: Var[str]):
- """Convert a string to lowercase.
- Args:
- string: The string to convert.
- Returns:
- The lowercase string.
- """
- return var_operation_return(js_expression=f"{string}.toLowerCase()", var_type=str)
- @var_operation
- def string_upper_operation(string: Var[str]):
- """Convert a string to uppercase.
- Args:
- string: The string to convert.
- Returns:
- The uppercase string.
- """
- return var_operation_return(js_expression=f"{string}.toUpperCase()", var_type=str)
- @var_operation
- def string_strip_operation(string: Var[str]):
- """Strip a string.
- Args:
- string: The string to strip.
- Returns:
- The stripped string.
- """
- return var_operation_return(js_expression=f"{string}.trim()", var_type=str)
- @var_operation
- def string_contains_field_operation(
- haystack: Var[str], needle: Var[str], field: Var[str]
- ):
- """Check if a string contains another string.
- Args:
- haystack: The haystack.
- needle: The needle.
- field: The field to check.
- Returns:
- The string contains operation.
- """
- return var_operation_return(
- js_expression=f"{haystack}.some(obj => obj[{field}] === {needle})",
- var_type=bool,
- )
- @var_operation
- def string_contains_operation(haystack: Var[str], needle: Var[str]):
- """Check if a string contains another string.
- Args:
- haystack: The haystack.
- needle: The needle.
- Returns:
- The string contains operation.
- """
- return var_operation_return(
- js_expression=f"{haystack}.includes({needle})", var_type=bool
- )
- @var_operation
- def string_starts_with_operation(full_string: Var[str], prefix: Var[str]):
- """Check if a string starts with a prefix.
- Args:
- full_string: The full string.
- prefix: The prefix.
- Returns:
- Whether the string starts with the prefix.
- """
- return var_operation_return(
- js_expression=f"{full_string}.startsWith({prefix})", var_type=bool
- )
- @var_operation
- def string_item_operation(string: Var[str], index: Var[int]):
- """Get an item from a string.
- Args:
- string: The string.
- index: The index of the item.
- Returns:
- The item from the string.
- """
- return var_operation_return(js_expression=f"{string}.at({index})", var_type=str)
- @var_operation
- def string_replace_operation(
- string: Var[str], search_value: Var[str], new_value: Var[str]
- ):
- """Replace a string with a value.
- Args:
- string: The string.
- search_value: The string to search.
- new_value: The value to be replaced with.
- Returns:
- The string replace operation.
- """
- return var_operation_return(
- js_expression=f"{string}.replace({search_value}, {new_value})",
- var_type=str,
- )
- # Compile regex for finding reflex var tags.
- _decode_var_pattern_re = (
- rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
- )
- _decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
- @dataclasses.dataclass(
- eq=False,
- frozen=True,
- **{"slots": True} if sys.version_info >= (3, 10) else {},
- )
- class LiteralStringVar(LiteralVar, StringVar[str]):
- """Base class for immutable literal string vars."""
- _var_value: str = dataclasses.field(default="")
- @classmethod
- def create(
- cls,
- value: str,
- _var_type: GenericType | None = None,
- _var_data: VarData | None = None,
- ) -> StringVar:
- """Create a var from a string value.
- Args:
- value: The value to create the var from.
- _var_type: The type of the var.
- _var_data: Additional hooks and imports associated with the Var.
- Returns:
- The var.
- """
- # Determine var type in case the value is inherited from str.
- _var_type = _var_type or type(value) or str
- if REFLEX_VAR_OPENING_TAG in value:
- strings_and_vals: list[Var | str] = []
- offset = 0
- # Find all tags
- while m := _decode_var_pattern.search(value):
- start, end = m.span()
- strings_and_vals.append(value[:start])
- serialized_data = m.group(1)
- if serialized_data.isnumeric() or (
- serialized_data[0] == "-" and serialized_data[1:].isnumeric()
- ):
- # This is a global immutable var.
- var = _global_vars[int(serialized_data)]
- strings_and_vals.append(var)
- value = value[(end + len(var._js_expr)) :]
- offset += end - start
- strings_and_vals.append(value)
- filtered_strings_and_vals = [
- s for s in strings_and_vals if isinstance(s, Var) or s
- ]
- if len(filtered_strings_and_vals) == 1:
- only_string = filtered_strings_and_vals[0]
- if isinstance(only_string, str):
- return LiteralVar.create(only_string).to(StringVar, _var_type)
- else:
- return only_string.to(StringVar, only_string._var_type)
- if len(
- literal_strings := [
- s
- for s in filtered_strings_and_vals
- if isinstance(s, (str, LiteralStringVar))
- ]
- ) == len(filtered_strings_and_vals):
- return LiteralStringVar.create(
- "".join(
- s._var_value if isinstance(s, LiteralStringVar) else s
- for s in literal_strings
- ),
- _var_type=_var_type,
- _var_data=VarData.merge(
- _var_data,
- *(
- s._get_all_var_data()
- for s in filtered_strings_and_vals
- if isinstance(s, Var)
- ),
- ),
- )
- concat_result = ConcatVarOperation.create(
- *filtered_strings_and_vals,
- _var_data=_var_data,
- )
- return (
- concat_result
- if _var_type is str
- else concat_result.to(StringVar, _var_type)
- )
- return LiteralStringVar(
- _js_expr=json.dumps(value),
- _var_type=_var_type,
- _var_data=_var_data,
- _var_value=value,
- )
- def __hash__(self) -> int:
- """Get the hash of the var.
- Returns:
- The hash of the var.
- """
- return hash((self.__class__.__name__, self._var_value))
- def json(self) -> str:
- """Get the JSON representation of the var.
- Returns:
- The JSON representation of the var.
- """
- return json.dumps(self._var_value)
- @dataclasses.dataclass(
- eq=False,
- frozen=True,
- **{"slots": True} if sys.version_info >= (3, 10) else {},
- )
- class ConcatVarOperation(CachedVarOperation, StringVar[str]):
- """Representing a concatenation of literal string vars."""
- _var_value: Tuple[Var, ...] = dataclasses.field(default_factory=tuple)
- @cached_property_no_lock
- def _cached_var_name(self) -> str:
- """The name of the var.
- Returns:
- The name of the var.
- """
- list_of_strs: List[Union[str, Var]] = []
- last_string = ""
- for var in self._var_value:
- if isinstance(var, LiteralStringVar):
- last_string += var._var_value
- else:
- if last_string:
- list_of_strs.append(last_string)
- last_string = ""
- list_of_strs.append(var)
- if last_string:
- list_of_strs.append(last_string)
- list_of_strs_filtered = [
- str(LiteralVar.create(s)) for s in list_of_strs if isinstance(s, Var) or s
- ]
- if len(list_of_strs_filtered) == 1:
- return list_of_strs_filtered[0]
- return "(" + "+".join(list_of_strs_filtered) + ")"
- @cached_property_no_lock
- def _cached_get_all_var_data(self) -> VarData | None:
- """Get all the VarData asVarDatae Var.
- Returns:
- The VarData associated with the Var.
- """
- return VarData.merge(
- *[
- var._get_all_var_data()
- for var in self._var_value
- if isinstance(var, Var)
- ],
- self._var_data,
- )
- @classmethod
- def create(
- cls,
- *value: Var | str,
- _var_data: VarData | None = None,
- ) -> ConcatVarOperation:
- """Create a var from a string value.
- Args:
- value: The values to concatenate.
- _var_data: Additional hooks and imports associated with the Var.
- Returns:
- The var.
- """
- return cls(
- _js_expr="",
- _var_type=str,
- _var_data=_var_data,
- _var_value=tuple(map(LiteralVar.create, value)),
- )
- ARRAY_VAR_TYPE = TypeVar("ARRAY_VAR_TYPE", bound=Union[List, Tuple, Set])
- OTHER_TUPLE = TypeVar("OTHER_TUPLE")
- INNER_ARRAY_VAR = TypeVar("INNER_ARRAY_VAR")
- ANOTHER_ARRAY_VAR = TypeVar("ANOTHER_ARRAY_VAR")
- KEY_TYPE = TypeVar("KEY_TYPE")
- VALUE_TYPE = TypeVar("VALUE_TYPE")
- class ArrayVar(Var[ARRAY_VAR_TYPE], python_types=(list, tuple, set)):
- """Base class for immutable array vars."""
- @overload
- def join(self, sep: StringVar | str = "") -> StringVar: ...
- @overload
- def join(self, sep: NoReturn) -> NoReturn: ...
- def join(self, sep: Any = "") -> StringVar:
- """Join the elements of the array.
- Args:
- sep: The separator between elements.
- Returns:
- The joined elements.
- """
- if not isinstance(sep, (StringVar, str)):
- raise_unsupported_operand_types("join", (type(self), type(sep)))
- if (
- isinstance(self, LiteralArrayVar)
- and (
- len(
- args := [
- x
- for x in self._var_value
- if isinstance(x, (LiteralStringVar, str))
- ]
- )
- == len(self._var_value)
- )
- and isinstance(sep, (LiteralStringVar, str))
- ):
- sep_str = sep._var_value if isinstance(sep, LiteralStringVar) else sep
- return LiteralStringVar.create(
- sep_str.join(
- i._var_value if isinstance(i, LiteralStringVar) else i for i in args
- )
- )
- return array_join_operation(self, sep).guess_type()
- def reverse(self) -> ArrayVar[ARRAY_VAR_TYPE]:
- """Reverse the array.
- Returns:
- The reversed array.
- """
- return array_reverse_operation(self).to(ArrayVar, self._var_type)
- @overload
- def __add__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> ArrayVar[ARRAY_VAR_TYPE]: ...
- @overload
- def __add__(self, other: NoReturn) -> NoReturn: ...
- def __add__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]:
- """Concatenate two arrays.
- Parameters:
- other: The other array to concatenate.
- Returns:
- ArrayConcatOperation: The concatenation of the two arrays.
- """
- if not isinstance(other, ArrayVar):
- raise_unsupported_operand_types("+", (type(self), type(other)))
- return array_concat_operation(self, other).to(
- ArrayVar, unionize(self._var_type, other._var_type)
- )
- @overload
- def __getitem__(self, i: slice) -> ArrayVar[ARRAY_VAR_TYPE]: ...
- @overload
- def __getitem__(
- self: (
- ArrayVar[Tuple[int, OTHER_TUPLE]]
- | ArrayVar[Tuple[float, OTHER_TUPLE]]
- | ArrayVar[Tuple[int | float, OTHER_TUPLE]]
- ),
- i: Literal[0, -2],
- ) -> NumberVar: ...
- @overload
- def __getitem__(
- self: (
- ArrayVar[Tuple[Any, int]]
- | ArrayVar[Tuple[Any, float]]
- | ArrayVar[Tuple[Any, int | float]]
- ),
- i: Literal[1, -1],
- ) -> NumberVar: ...
- @overload
- def __getitem__(
- self: ArrayVar[Tuple[str, Any]], i: Literal[0, -2]
- ) -> StringVar: ...
- @overload
- def __getitem__(
- self: ArrayVar[Tuple[Any, str]], i: Literal[1, -1]
- ) -> StringVar: ...
- @overload
- def __getitem__(
- self: ArrayVar[Tuple[bool, Any]], i: Literal[0, -2]
- ) -> BooleanVar: ...
- @overload
- def __getitem__(
- self: ArrayVar[Tuple[Any, bool]], i: Literal[1, -1]
- ) -> BooleanVar: ...
- @overload
- def __getitem__(
- self: (
- ARRAY_VAR_OF_LIST_ELEMENT[int]
- | ARRAY_VAR_OF_LIST_ELEMENT[float]
- | ARRAY_VAR_OF_LIST_ELEMENT[int | float]
- ),
- i: int | NumberVar,
- ) -> NumberVar: ...
- @overload
- def __getitem__(
- self: ARRAY_VAR_OF_LIST_ELEMENT[str], i: int | NumberVar
- ) -> StringVar: ...
- @overload
- def __getitem__(
- self: ARRAY_VAR_OF_LIST_ELEMENT[bool], i: int | NumberVar
- ) -> BooleanVar: ...
- @overload
- def __getitem__(
- self: ARRAY_VAR_OF_LIST_ELEMENT[List[INNER_ARRAY_VAR]],
- i: int | NumberVar,
- ) -> ArrayVar[List[INNER_ARRAY_VAR]]: ...
- @overload
- def __getitem__(
- self: ARRAY_VAR_OF_LIST_ELEMENT[Set[INNER_ARRAY_VAR]],
- i: int | NumberVar,
- ) -> ArrayVar[Set[INNER_ARRAY_VAR]]: ...
- @overload
- def __getitem__(
- self: ARRAY_VAR_OF_LIST_ELEMENT[Tuple[KEY_TYPE, VALUE_TYPE]],
- i: int | NumberVar,
- ) -> ArrayVar[Tuple[KEY_TYPE, VALUE_TYPE]]: ...
- @overload
- def __getitem__(
- self: ARRAY_VAR_OF_LIST_ELEMENT[Tuple[INNER_ARRAY_VAR, ...]],
- i: int | NumberVar,
- ) -> ArrayVar[Tuple[INNER_ARRAY_VAR, ...]]: ...
- @overload
- def __getitem__(
- self: ARRAY_VAR_OF_LIST_ELEMENT[Dict[KEY_TYPE, VALUE_TYPE]],
- i: int | NumberVar,
- ) -> ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]]: ...
- @overload
- def __getitem__(self, i: int | NumberVar) -> Var: ...
- def __getitem__(self, i: Any) -> ArrayVar[ARRAY_VAR_TYPE] | Var:
- """Get a slice of the array.
- Args:
- i: The slice.
- Returns:
- The array slice operation.
- """
- if isinstance(i, slice):
- return ArraySliceOperation.create(self, i)
- if not isinstance(i, (int, NumberVar)) or (
- isinstance(i, NumberVar) and i._is_strict_float()
- ):
- raise_unsupported_operand_types("[]", (type(self), type(i)))
- return array_item_operation(self, i).guess_type()
- def length(self) -> NumberVar:
- """Get the length of the array.
- Returns:
- The length of the array.
- """
- return array_length_operation(self).guess_type()
- @overload
- @classmethod
- def range(cls, stop: int | NumberVar, /) -> ArrayVar[List[int]]: ...
- @overload
- @classmethod
- def range(
- cls,
- start: int | NumberVar,
- end: int | NumberVar,
- step: int | NumberVar = 1,
- /,
- ) -> ArrayVar[List[int]]: ...
- @overload
- @classmethod
- def range(
- cls,
- first_endpoint: int | NumberVar,
- second_endpoint: int | NumberVar | None = None,
- step: int | NumberVar | None = None,
- ) -> ArrayVar[List[int]]: ...
- @classmethod
- def range(
- cls,
- first_endpoint: int | NumberVar,
- second_endpoint: int | NumberVar | None = None,
- step: int | NumberVar | None = None,
- ) -> ArrayVar[List[int]]:
- """Create a range of numbers.
- Args:
- first_endpoint: The end of the range if second_endpoint is not provided, otherwise the start of the range.
- second_endpoint: The end of the range.
- step: The step of the range.
- Returns:
- The range of numbers.
- """
- if any(
- not isinstance(i, (int, NumberVar))
- for i in (first_endpoint, second_endpoint, step)
- if i is not None
- ):
- raise_unsupported_operand_types(
- "range", (type(first_endpoint), type(second_endpoint), type(step))
- )
- if second_endpoint is None:
- start = 0
- end = first_endpoint
- else:
- start = first_endpoint
- end = second_endpoint
- return array_range_operation(start, end, step or 1).guess_type()
- @overload
- def contains(self, other: Any) -> BooleanVar: ...
- @overload
- def contains(self, other: Any, field: StringVar | str) -> BooleanVar: ...
- def contains(self, other: Any, field: Any = None) -> BooleanVar:
- """Check if the array contains an element.
- Args:
- other: The element to check for.
- field: The field to check.
- Returns:
- The array contains operation.
- """
- if field is not None:
- if not isinstance(field, (StringVar, str)):
- raise_unsupported_operand_types("contains", (type(self), type(field)))
- return array_contains_field_operation(self, other, field).guess_type()
- return array_contains_operation(self, other).guess_type()
- def pluck(self, field: StringVar | str) -> ArrayVar:
- """Pluck a field from the array.
- Args:
- field: The field to pluck from the array.
- Returns:
- The array pluck operation.
- """
- return array_pluck_operation(self, field).guess_type()
- @overload
- def __mul__(self, other: NumberVar | int) -> ArrayVar[ARRAY_VAR_TYPE]: ...
- @overload
- def __mul__(self, other: NoReturn) -> NoReturn: ...
- def __mul__(self, other: Any) -> ArrayVar[ARRAY_VAR_TYPE]:
- """Multiply the sequence by a number or integer.
- Parameters:
- other: The number or integer to multiply the sequence by.
- Returns:
- ArrayVar[ARRAY_VAR_TYPE]: The result of multiplying the sequence by the given number or integer.
- """
- if not isinstance(other, (NumberVar, int)) or (
- isinstance(other, NumberVar) and other._is_strict_float()
- ):
- raise_unsupported_operand_types("*", (type(self), type(other)))
- return repeat_array_operation(self, other).to(ArrayVar, self._var_type)
- __rmul__ = __mul__ # type: ignore
- @overload
- def __lt__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
- @overload
- def __lt__(self, other: list | tuple) -> BooleanVar: ...
- def __lt__(self, other: Any):
- """Check if the array is less than another array.
- Args:
- other: The other array.
- Returns:
- The array less than operation.
- """
- if not isinstance(other, (ArrayVar, list, tuple)):
- raise_unsupported_operand_types("<", (type(self), type(other)))
- return array_lt_operation(self, other).guess_type()
- @overload
- def __gt__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
- @overload
- def __gt__(self, other: list | tuple) -> BooleanVar: ...
- def __gt__(self, other: Any):
- """Check if the array is greater than another array.
- Args:
- other: The other array.
- Returns:
- The array greater than operation.
- """
- if not isinstance(other, (ArrayVar, list, tuple)):
- raise_unsupported_operand_types(">", (type(self), type(other)))
- return array_gt_operation(self, other).guess_type()
- @overload
- def __le__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
- @overload
- def __le__(self, other: list | tuple) -> BooleanVar: ...
- def __le__(self, other: Any):
- """Check if the array is less than or equal to another array.
- Args:
- other: The other array.
- Returns:
- The array less than or equal operation.
- """
- if not isinstance(other, (ArrayVar, list, tuple)):
- raise_unsupported_operand_types("<=", (type(self), type(other)))
- return array_le_operation(self, other).guess_type()
- @overload
- def __ge__(self, other: ArrayVar[ARRAY_VAR_TYPE]) -> BooleanVar: ...
- @overload
- def __ge__(self, other: list | tuple) -> BooleanVar: ...
- def __ge__(self, other: Any):
- """Check if the array is greater than or equal to another array.
- Args:
- other: The other array.
- Returns:
- The array greater than or equal operation.
- """
- if not isinstance(other, (ArrayVar, list, tuple)):
- raise_unsupported_operand_types(">=", (type(self), type(other)))
- return array_ge_operation(self, other).guess_type()
- def foreach(
- self: ARRAY_VAR_OF_LIST_ELEMENT[INNER_ARRAY_VAR],
- fn: Callable[[Var[INNER_ARRAY_VAR]], ANOTHER_ARRAY_VAR]
- | Callable[[], ANOTHER_ARRAY_VAR],
- ) -> ArrayVar[List[ANOTHER_ARRAY_VAR]]:
- """Apply a function to each element of the array.
- Args:
- fn: The function to apply.
- Returns:
- The array after applying the function.
- Raises:
- VarTypeError: If the function takes more than one argument.
- """
- from .function import ArgsFunctionOperation
- if not callable(fn):
- raise_unsupported_operand_types("foreach", (type(self), type(fn)))
- # get the number of arguments of the function
- num_args = len(inspect.signature(fn).parameters)
- if num_args > 1:
- raise VarTypeError(
- "The function passed to foreach should take at most one argument."
- )
- if num_args == 0:
- return_value = fn() # type: ignore
- simple_function_var: FunctionVar[ReflexCallable[[], ANOTHER_ARRAY_VAR]] = (
- ArgsFunctionOperation.create(tuple(), return_value)
- )
- return map_array_operation(self, simple_function_var).guess_type()
- # generic number var
- number_var = Var("").to(NumberVar, int)
- first_arg_type = self[number_var]._var_type
- arg_name = get_unique_variable_name()
- # get first argument type
- first_arg = cast(
- Var[Any],
- Var(
- _js_expr=arg_name,
- _var_type=first_arg_type,
- ).guess_type(),
- )
- function_var: FunctionVar[
- ReflexCallable[[INNER_ARRAY_VAR], ANOTHER_ARRAY_VAR]
- ] = ArgsFunctionOperation.create(
- (arg_name,),
- Var.create(fn(first_arg)), # type: ignore
- )
- return map_array_operation(self, function_var).guess_type()
- LIST_ELEMENT = TypeVar("LIST_ELEMENT")
- ARRAY_VAR_OF_LIST_ELEMENT = TypeAliasType(
- "ARRAY_VAR_OF_LIST_ELEMENT",
- Union[
- ArrayVar[List[LIST_ELEMENT]],
- ArrayVar[Tuple[LIST_ELEMENT, ...]],
- ArrayVar[Set[LIST_ELEMENT]],
- ],
- type_params=(LIST_ELEMENT,),
- )
- @dataclasses.dataclass(
- eq=False,
- frozen=True,
- **{"slots": True} if sys.version_info >= (3, 10) else {},
- )
- class LiteralArrayVar(CachedVarOperation, LiteralVar, ArrayVar[ARRAY_VAR_TYPE]):
- """Base class for immutable literal array vars."""
- _var_value: Union[
- List[Union[Var, Any]],
- Set[Union[Var, Any]],
- Tuple[Union[Var, Any], ...],
- ] = dataclasses.field(default_factory=list)
- @cached_property_no_lock
- def _cached_var_name(self) -> str:
- """The name of the var.
- Returns:
- The name of the var.
- """
- return (
- "["
- + ", ".join(
- [str(LiteralVar.create(element)) for element in self._var_value]
- )
- + "]"
- )
- @cached_property_no_lock
- def _cached_get_all_var_data(self) -> VarData | None:
- """Get all the VarData associated with the Var.
- Returns:
- The VarData associated with the Var.
- """
- return VarData.merge(
- *[
- LiteralVar.create(element)._get_all_var_data()
- for element in self._var_value
- ],
- self._var_data,
- )
- def __hash__(self) -> int:
- """Get the hash of the var.
- Returns:
- The hash of the var.
- """
- return hash((self.__class__.__name__, self._js_expr))
- def json(self) -> str:
- """Get the JSON representation of the var.
- Returns:
- The JSON representation of the var.
- """
- return (
- "["
- + ", ".join(
- [LiteralVar.create(element).json() for element in self._var_value]
- )
- + "]"
- )
- @classmethod
- def create(
- cls,
- value: ARRAY_VAR_TYPE,
- _var_type: Type[ARRAY_VAR_TYPE] | None = None,
- _var_data: VarData | None = None,
- ) -> LiteralArrayVar[ARRAY_VAR_TYPE]:
- """Create a var from a string value.
- Args:
- value: The value to create the var from.
- _var_data: Additional hooks and imports associated with the Var.
- Returns:
- The var.
- """
- return cls(
- _js_expr="",
- _var_type=figure_out_type(value) if _var_type is None else _var_type,
- _var_data=_var_data,
- _var_value=value,
- )
- @var_operation
- def string_split_operation(string: Var[str], sep: Var[str]):
- """Split a string.
- Args:
- string: The string to split.
- sep: The separator.
- Returns:
- The split string.
- """
- return var_operation_return(
- js_expression=f"{string}.split({sep})", var_type=List[str]
- )
- @dataclasses.dataclass(
- eq=False,
- frozen=True,
- **{"slots": True} if sys.version_info >= (3, 10) else {},
- )
- class ArraySliceOperation(CachedVarOperation, ArrayVar):
- """Base class for immutable string vars that are the result of a string slice operation."""
- _array: ArrayVar = dataclasses.field(
- default_factory=lambda: LiteralArrayVar.create([])
- )
- _start: NumberVar | int = dataclasses.field(default_factory=lambda: 0)
- _stop: NumberVar | int = dataclasses.field(default_factory=lambda: 0)
- _step: NumberVar | int = dataclasses.field(default_factory=lambda: 1)
- @cached_property_no_lock
- def _cached_var_name(self) -> str:
- """The name of the var.
- Returns:
- The name of the var.
- Raises:
- ValueError: If the slice step is zero.
- """
- start, end, step = self._start, self._stop, self._step
- normalized_start = (
- LiteralVar.create(start) if start is not None else Var(_js_expr="undefined")
- )
- normalized_end = (
- LiteralVar.create(end) if end is not None else Var(_js_expr="undefined")
- )
- if step is None:
- return f"{str(self._array)}.slice({str(normalized_start)}, {str(normalized_end)})"
- if not isinstance(step, Var):
- if step < 0:
- actual_start = end + 1 if end is not None else 0
- actual_end = start + 1 if start is not None else self._array.length()
- return str(self._array[actual_start:actual_end].reverse()[::-step])
- if step == 0:
- raise ValueError("slice step cannot be zero")
- return f"{str(self._array)}.slice({str(normalized_start)}, {str(normalized_end)}).filter((_, i) => i % {str(step)} === 0)"
- actual_start_reverse = end + 1 if end is not None else 0
- actual_end_reverse = start + 1 if start is not None else self._array.length()
- 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)"
- @classmethod
- def create(
- cls,
- array: ArrayVar,
- slice: slice,
- _var_data: VarData | None = None,
- ) -> ArraySliceOperation:
- """Create a var from a string value.
- Args:
- array: The array.
- slice: The slice.
- _var_data: Additional hooks and imports associated with the Var.
- Returns:
- The var.
- """
- return cls(
- _js_expr="",
- _var_type=array._var_type,
- _var_data=_var_data,
- _array=array,
- _start=slice.start,
- _stop=slice.stop,
- _step=slice.step,
- )
- @var_operation
- def array_pluck_operation(
- array: Var[ARRAY_VAR_TYPE],
- field: Var[str],
- ) -> CustomVarOperationReturn[List]:
- """Pluck a field from an array of objects.
- Args:
- array: The array to pluck from.
- field: The field to pluck from the objects in the array.
- Returns:
- The reversed array.
- """
- return var_operation_return(
- js_expression=f"{array}.map(e=>e?.[{field}])",
- var_type=List[Any],
- )
- @var_operation
- def array_join_operation(array: Var[ARRAY_VAR_TYPE], sep: Var[str]):
- """Join the elements of an array.
- Args:
- array: The array.
- sep: The separator.
- Returns:
- The joined elements.
- """
- return var_operation_return(js_expression=f"{array}.join({sep})", var_type=str)
- @var_operation
- def array_reverse_operation(
- array: Var[ARRAY_VAR_TYPE],
- ) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
- """Reverse an array.
- Args:
- array: The array to reverse.
- Returns:
- The reversed array.
- """
- return var_operation_return(
- js_expression=f"{array}.slice().reverse()",
- type_computer=passthrough_unary_type_computer(ReflexCallable[[List], List]),
- )
- @var_operation
- def array_lt_operation(lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]):
- """Check if an array is less than another array.
- Args:
- lhs: The left-hand side array.
- rhs: The right-hand side array.
- Returns:
- The array less than operation.
- """
- return var_operation_return(js_expression=f"{lhs} < {rhs}", var_type=bool)
- @var_operation
- def array_gt_operation(lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]):
- """Check if an array is greater than another array.
- Args:
- lhs: The left-hand side array.
- rhs: The right-hand side array.
- Returns:
- The array greater than operation.
- """
- return var_operation_return(js_expression=f"{lhs} > {rhs}", var_type=bool)
- @var_operation
- def array_le_operation(lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]):
- """Check if an array is less than or equal to another array.
- Args:
- lhs: The left-hand side array.
- rhs: The right-hand side array.
- Returns:
- The array less than or equal operation.
- """
- return var_operation_return(js_expression=f"{lhs} <= {rhs}", var_type=bool)
- @var_operation
- def array_ge_operation(lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]):
- """Check if an array is greater than or equal to another array.
- Args:
- lhs: The left-hand side array.
- rhs: The right-hand side array.
- Returns:
- The array greater than or equal operation.
- """
- return var_operation_return(js_expression=f"{lhs} >= {rhs}", var_type=bool)
- @var_operation
- def array_length_operation(array: Var[ARRAY_VAR_TYPE]):
- """Get the length of an array.
- Args:
- array: The array.
- Returns:
- The length of the array.
- """
- return var_operation_return(
- js_expression=f"{array}.length",
- var_type=int,
- )
- def is_tuple_type(t: GenericType) -> bool:
- """Check if a type is a tuple type.
- Args:
- t: The type to check.
- Returns:
- Whether the type is a tuple type.
- """
- if inspect.isclass(t):
- return issubclass(t, tuple)
- return get_origin(t) is tuple
- @var_operation
- def array_item_operation(array: Var[ARRAY_VAR_TYPE], index: Var[int]):
- """Get an item from an array.
- Args:
- array: The array.
- index: The index of the item.
- Returns:
- The item from the array.
- """
- def type_computer(*args):
- if len(args) == 0:
- return (
- ReflexCallable[[List[Any], int], Any],
- functools.partial(type_computer, *args),
- )
- array = args[0]
- array_args = typing.get_args(array._var_type)
- if len(args) == 1:
- return (
- ReflexCallable[[int], unionize(*array_args)],
- functools.partial(type_computer, *args),
- )
- index = args[1]
- if (
- array_args
- and isinstance(index, LiteralNumberVar)
- and is_tuple_type(array._var_type)
- ):
- index_value = int(index._var_value)
- element_type = array_args[index_value % len(array_args)]
- else:
- element_type = unionize(*array_args)
- return (ReflexCallable[[], element_type], None)
- return var_operation_return(
- js_expression=f"{str(array)}.at({str(index)})",
- type_computer=type_computer,
- )
- @var_operation
- def array_range_operation(start: Var[int], stop: Var[int], step: Var[int]):
- """Create a range of numbers.
- Args:
- start: The start of the range.
- stop: The end of the range.
- step: The step of the range.
- Returns:
- The range of numbers.
- """
- return var_operation_return(
- js_expression=f"Array.from({{ length: ({str(stop)} - {str(start)}) / {str(step)} }}, (_, i) => {str(start)} + i * {str(step)})",
- var_type=List[int],
- )
- @var_operation
- def array_contains_field_operation(
- haystack: Var[ARRAY_VAR_TYPE], needle: Var, field: Var[str]
- ):
- """Check if an array contains an element.
- Args:
- haystack: The array to check.
- needle: The element to check for.
- field: The field to check.
- Returns:
- The array contains operation.
- """
- return var_operation_return(
- js_expression=f"{haystack}.some(obj => obj[{field}] === {needle})",
- var_type=bool,
- )
- @var_operation
- def array_contains_operation(haystack: Var[ARRAY_VAR_TYPE], needle: Var):
- """Check if an array contains an element.
- Args:
- haystack: The array to check.
- needle: The element to check for.
- Returns:
- The array contains operation.
- """
- return var_operation_return(
- js_expression=f"{haystack}.includes({needle})",
- var_type=bool,
- )
- @var_operation
- def repeat_array_operation(
- array: Var[ARRAY_VAR_TYPE], count: Var[int]
- ) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
- """Repeat an array a number of times.
- Args:
- array: The array to repeat.
- count: The number of times to repeat the array.
- Returns:
- The repeated array.
- """
- def type_computer(*args: Var):
- if not args:
- return (
- ReflexCallable[[List[Any], int], List[Any]],
- type_computer,
- )
- if len(args) == 1:
- return (
- ReflexCallable[[int], args[0]._var_type],
- functools.partial(type_computer, *args),
- )
- return (ReflexCallable[[], args[0]._var_type], None)
- return var_operation_return(
- js_expression=f"Array.from({{ length: {count} }}).flatMap(() => {array})",
- type_computer=type_computer,
- )
- if TYPE_CHECKING:
- pass
- @var_operation
- def map_array_operation(
- array: Var[ARRAY_VAR_OF_LIST_ELEMENT[INNER_ARRAY_VAR]],
- function: Var[ReflexCallable[[INNER_ARRAY_VAR], ANOTHER_ARRAY_VAR]],
- ) -> CustomVarOperationReturn[List[ANOTHER_ARRAY_VAR]]:
- """Map a function over an array.
- Args:
- array: The array.
- function: The function to map.
- Returns:
- The mapped array.
- """
- def type_computer(*args: Var):
- if not args:
- return (
- ReflexCallable[[List[Any], ReflexCallable], List[Any]],
- type_computer,
- )
- if len(args) == 1:
- return (
- ReflexCallable[[ReflexCallable], List[Any]],
- functools.partial(type_computer, *args),
- )
- return (ReflexCallable[[], List[args[0]._var_type]], None)
- return var_operation_return(
- js_expression=f"{array}.map({function})",
- type_computer=nary_type_computer(
- ReflexCallable[[List[Any], ReflexCallable], List[Any]],
- ReflexCallable[[ReflexCallable], List[Any]],
- computer=lambda args: List[unwrap_reflex_callalbe(args[1]._var_type)[1]], # type: ignore
- ),
- )
- @var_operation
- def array_concat_operation(
- lhs: Var[ARRAY_VAR_TYPE], rhs: Var[ARRAY_VAR_TYPE]
- ) -> CustomVarOperationReturn[ARRAY_VAR_TYPE]:
- """Concatenate two arrays.
- Args:
- lhs: The left-hand side array.
- rhs: The right-hand side array.
- Returns:
- The concatenated array.
- """
- return var_operation_return(
- js_expression=f"[...{lhs}, ...{rhs}]",
- type_computer=nary_type_computer(
- ReflexCallable[[List[Any], List[Any]], List[Any]],
- ReflexCallable[[List[Any]], List[Any]],
- computer=lambda args: unionize(args[0]._var_type, args[1]._var_type),
- ),
- )
- class ColorVar(StringVar[Color], python_types=Color):
- """Base class for immutable color vars."""
- @dataclasses.dataclass(
- eq=False,
- frozen=True,
- **{"slots": True} if sys.version_info >= (3, 10) else {},
- )
- class LiteralColorVar(CachedVarOperation, LiteralVar, ColorVar):
- """Base class for immutable literal color vars."""
- _var_value: Color = dataclasses.field(default_factory=lambda: Color(color="black"))
- @classmethod
- def create(
- cls,
- value: Color,
- _var_type: Type[Color] | None = None,
- _var_data: VarData | None = None,
- ) -> ColorVar:
- """Create a var from a string value.
- Args:
- value: The value to create the var from.
- _var_type: The type of the var.
- _var_data: Additional hooks and imports associated with the Var.
- Returns:
- The var.
- """
- return cls(
- _js_expr="",
- _var_type=_var_type or Color,
- _var_data=_var_data,
- _var_value=value,
- )
- def __hash__(self) -> int:
- """Get the hash of the var.
- Returns:
- The hash of the var.
- """
- return hash(
- (
- self.__class__.__name__,
- self._var_value.color,
- self._var_value.alpha,
- self._var_value.shade,
- )
- )
- @cached_property_no_lock
- def _cached_var_name(self) -> str:
- """The name of the var.
- Returns:
- The name of the var.
- """
- alpha = self._var_value.alpha
- alpha = (
- ternary_operation(
- alpha,
- LiteralStringVar.create("a"),
- LiteralStringVar.create(""),
- )
- if isinstance(alpha, Var)
- else LiteralStringVar.create("a" if alpha else "")
- )
- shade = self._var_value.shade
- shade = (
- shade.to_string(use_json=False)
- if isinstance(shade, Var)
- else LiteralStringVar.create(str(shade))
- )
- return str(
- ConcatVarOperation.create(
- LiteralStringVar.create("var(--"),
- self._var_value.color,
- LiteralStringVar.create("-"),
- alpha,
- shade,
- LiteralStringVar.create(")"),
- )
- )
- @cached_property_no_lock
- def _cached_get_all_var_data(self) -> VarData | None:
- """Get all the var data.
- Returns:
- The var data.
- """
- return VarData.merge(
- *[
- LiteralVar.create(var)._get_all_var_data()
- for var in (
- self._var_value.color,
- self._var_value.alpha,
- self._var_value.shade,
- )
- ],
- self._var_data,
- )
- def json(self) -> str:
- """Get the JSON representation of the var.
- Returns:
- The JSON representation of the var.
- Raises:
- TypeError: If the color is not a valid color.
- """
- color, alpha, shade = map(
- get_python_literal,
- (self._var_value.color, self._var_value.alpha, self._var_value.shade),
- )
- if color is None or alpha is None or shade is None:
- raise TypeError("Cannot serialize color that contains non-literal vars.")
- if (
- not isinstance(color, str)
- or not isinstance(alpha, bool)
- or not isinstance(shade, int)
- ):
- raise TypeError("Color is not a valid color.")
- return f"var(--{color}-{'a' if alpha else ''}{shade})"
|