From 270b227bc5e3f03f0dfa1689e604045b5bd802d5 Mon Sep 17 00:00:00 2001 From: Khaleel Al-Adhami Date: Tue, 15 Oct 2024 12:27:57 -0700 Subject: [PATCH] fix json --- reflex/vars/base.py | 24 +++++++++++++++++++++++- reflex/vars/sequence.py | 18 +++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/reflex/vars/base.py b/reflex/vars/base.py index d7ac83185..7ba04ed00 100644 --- a/reflex/vars/base.py +++ b/reflex/vars/base.py @@ -38,7 +38,13 @@ from typing import ( overload, ) -from typing_extensions import ParamSpec, TypeGuard, deprecated, get_type_hints, override +from typing_extensions import ( + ParamSpec, + TypeGuard, + deprecated, + get_type_hints, + override, +) from reflex import constants from reflex.base import Base @@ -1388,6 +1394,22 @@ def serialize_literal(value: LiteralVar): return value._var_value +def get_python_literal(value: Union[LiteralVar, Any]) -> Any | None: + """Get the Python literal value. + + Args: + value: The value to get the Python literal value of. + + Returns: + The Python literal value. + """ + if isinstance(value, LiteralVar): + return value._var_value + if isinstance(value, Var): + return None + return value + + P = ParamSpec("P") T = TypeVar("T") diff --git a/reflex/vars/sequence.py b/reflex/vars/sequence.py index e31f7ef61..6d36f06fa 100644 --- a/reflex/vars/sequence.py +++ b/reflex/vars/sequence.py @@ -39,6 +39,7 @@ from .base import ( _global_vars, cached_property_no_lock, figure_out_type, + get_python_literal, get_unique_variable_name, unionize, var_operation, @@ -1746,5 +1747,20 @@ class LiteralColorVar(CachedVarOperation, LiteralVar, ColorVar): Returns: The JSON representation of the var. + + Raises: + TypeError: If the color is not a valid color. """ - return json.dumps(f"{self._var_value}") + 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})"