Pārlūkot izejas kodu

use underscore suffix instead

Khaleel Al-Adhami 2 nedēļas atpakaļ
vecāks
revīzija
4fe0fe0bbe

+ 3 - 6
reflex/components/core/foreach.py

@@ -15,7 +15,7 @@ from reflex.constants import MemoizationMode
 from reflex.state import ComponentState
 from reflex.utils import types
 from reflex.utils.exceptions import UntypedVarError
-from reflex.vars.base import LiteralVar, Var, is_illegal_javascript_identifier
+from reflex.vars.base import LiteralVar, Var
 
 
 class ForeachVarError(TypeError):
@@ -130,14 +130,11 @@ class Foreach(Component):
 
         if len(params) >= 1:
             # Determine the arg var name based on the params accepted by render_fn.
-            name = params[0].name
-            if is_illegal_javascript_identifier(name):
-                name = f"arg_{name}"
-            props["arg_var_name"] = name
+            props["arg_var_name"] = params[0].name + "_rx_foreach_"
 
         if len(params) == 2:
             # Determine the index var name based on the params accepted by render_fn.
-            props["index_var_name"] = params[1].name
+            props["index_var_name"] = params[1].name + "_rx_foreach_"
         else:
             render_fn = self.render_fn
             # Otherwise, use a deterministic index, based on the render function bytecode.

+ 6 - 8
reflex/state.py

@@ -84,7 +84,6 @@ from reflex.vars.base import (
     dispatch,
     get_unique_variable_name,
     is_computed_var,
-    is_illegal_javascript_identifier,
 )
 
 if TYPE_CHECKING:
@@ -274,7 +273,7 @@ def _unwrap_field_type(type_: types.GenericType) -> type:
     return type_
 
 
-def get_var_for_field(cls: type[BaseState], f: ModelField):
+def get_var_for_field(cls: type[BaseState], f: ModelField) -> Var:
     """Get a Var instance for a Pydantic field.
 
     Args:
@@ -284,7 +283,9 @@ def get_var_for_field(cls: type[BaseState], f: ModelField):
     Returns:
         The Var instance.
     """
-    field_name = format.format_state_name(cls.get_full_name()) + "." + f.name
+    field_name = (
+        format.format_state_name(cls.get_full_name()) + "." + f.name + "_rx_state_"
+    )
 
     return dispatch(
         field_name=field_name,
@@ -1051,11 +1052,8 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
         var = Var(
             _js_expr=format.format_state_name(cls.get_full_name())
             + "."
-            + (
-                name
-                if not is_illegal_javascript_identifier(name)
-                else name + "_" + md5(name.encode()).hexdigest()
-            ),
+            + name
+            + "_rx_state_",
             _var_type=type_,
             _var_data=VarData.from_state(cls, name),
         ).guess_type()

+ 0 - 87
reflex/vars/base.py

@@ -89,93 +89,6 @@ SEQUENCE_TYPE = TypeVar("SEQUENCE_TYPE", bound=Sequence)
 
 warnings.filterwarnings("ignore", message="fields may not start with an underscore")
 
-ILLEGAL_JAVASCRIPT_NAMES = frozenset(
-    [
-        "abstract",
-        "arguments",
-        "as",
-        "async",
-        "await",
-        "boolean",
-        "break",
-        "byte",
-        "case",
-        "catch",
-        "char",
-        "class",
-        "const",
-        "continue",
-        "debugger",
-        "default",
-        "delete",
-        "do",
-        "double",
-        "else",
-        "enum",
-        "eval",
-        "export",
-        "extends",
-        "false",
-        "final",
-        "finally",
-        "float",
-        "for",
-        "from",
-        "function",
-        "get",
-        "goto",
-        "if",
-        "implements",
-        "import",
-        "in",
-        "instanceof",
-        "int",
-        "interface",
-        "let",
-        "long",
-        "native",
-        "new",
-        "null",
-        "of",
-        "package",
-        "private",
-        "protected",
-        "public",
-        "return",
-        "set",
-        "short",
-        "static",
-        "super",
-        "switch",
-        "synchronized",
-        "this",
-        "throw",
-        "throws",
-        "transient",
-        "true",
-        "try",
-        "typeof",
-        "var",
-        "void",
-        "volatile",
-        "while",
-        "with",
-        "yield",
-    ]
-)
-
-
-def is_illegal_javascript_identifier(name: str) -> bool:
-    """Check if the name is an illegal JavaScript identifier.
-
-    Args:
-        name: The name to check.
-
-    Returns:
-        True if the name is an illegal JavaScript identifier, False otherwise.
-    """
-    return name in ILLEGAL_JAVASCRIPT_NAMES
-
 
 @dataclasses.dataclass(
     eq=False,

+ 11 - 11
tests/units/components/core/test_colors.py

@@ -30,38 +30,38 @@ def create_color_var(color):
         (create_color_var(rx.color("mint", 3, True)), '"var(--mint-a3)"', Color),
         (
             create_color_var(rx.color(ColorState.color, ColorState.shade)),
-            f'("var(--"+{color_state_name!s}.color+"-"+(((__to_string) => __to_string.toString())({color_state_name!s}.shade))+")")',
+            f'("var(--"+{color_state_name!s}.color_rx_state_+"-"+(((__to_string) => __to_string.toString())({color_state_name!s}.shade_rx_state_))+")")',
             Color,
         ),
         (
             create_color_var(
                 rx.color(ColorState.color, ColorState.shade, ColorState.alpha)
             ),
-            f'("var(--"+{color_state_name!s}.color+"-"+({color_state_name!s}.alpha ? "a" : "")+(((__to_string) => __to_string.toString())({color_state_name!s}.shade))+")")',
+            f'("var(--"+{color_state_name!s}.color_rx_state_+"-"+({color_state_name!s}.alpha_rx_state_ ? "a" : "")+(((__to_string) => __to_string.toString())({color_state_name!s}.shade_rx_state_))+")")',
             Color,
         ),
         (
             create_color_var(rx.color(f"{ColorState.color}", f"{ColorState.shade}")),
-            f'("var(--"+{color_state_name!s}.color+"-"+{color_state_name!s}.shade+")")',
+            f'("var(--"+{color_state_name!s}.color_rx_state_+"-"+{color_state_name!s}.shade_rx_state_+")")',
             Color,
         ),
         (
             create_color_var(
                 rx.color(f"{ColorState.color_part}ato", f"{ColorState.shade}")
             ),
-            f'("var(--"+({color_state_name!s}.color_part+"ato")+"-"+{color_state_name!s}.shade+")")',
+            f'("var(--"+({color_state_name!s}.color_part_rx_state_+"ato")+"-"+{color_state_name!s}.shade_rx_state_+")")',
             Color,
         ),
         (
             create_color_var(f"{rx.color(ColorState.color, f'{ColorState.shade}')}"),
-            f'("var(--"+{color_state_name!s}.color+"-"+{color_state_name!s}.shade+")")',
+            f'("var(--"+{color_state_name!s}.color_rx_state_+"-"+{color_state_name!s}.shade_rx_state_+")")',
             str,
         ),
         (
             create_color_var(
                 f"{rx.color(f'{ColorState.color}', f'{ColorState.shade}')}"
             ),
-            f'("var(--"+{color_state_name!s}.color+"-"+{color_state_name!s}.shade+")")',
+            f'("var(--"+{color_state_name!s}.color_rx_state_+"-"+{color_state_name!s}.shade_rx_state_+")")',
             str,
         ),
     ],
@@ -80,7 +80,7 @@ def test_color(color, expected, expected_type: type[str] | type[Color]):
         ),
         (
             rx.cond(True, rx.color(ColorState.color), rx.color(ColorState.color, 5)),
-            f'(true ? ("var(--"+{color_state_name!s}.color+"-7)") : ("var(--"+{color_state_name!s}.color+"-5)"))',
+            f'(true ? ("var(--"+{color_state_name!s}.color_rx_state_+"-7)") : ("var(--"+{color_state_name!s}.color_rx_state_+"-5)"))',
         ),
         (
             rx.match(
@@ -91,7 +91,7 @@ def test_color(color, expected, expected_type: type[str] | type[Color]):
             ),
             '(() => { switch (JSON.stringify("condition")) {case JSON.stringify("first"):  return ("var(--mint-7)");'
             '  break;case JSON.stringify("second"):  return ("var(--tomato-5)");  break;default:  '
-            f'return (("var(--"+{color_state_name!s}.color+"-2)"));  break;}};}})()',
+            f'return (("var(--"+{color_state_name!s}.color_rx_state_+"-2)"));  break;}};}})()',
         ),
         (
             rx.match(
@@ -101,9 +101,9 @@ def test_color(color, expected, expected_type: type[str] | type[Color]):
                 rx.color(ColorState.color, 2),
             ),
             '(() => { switch (JSON.stringify("condition")) {case JSON.stringify("first"):  '
-            f'return (("var(--"+{color_state_name!s}.color+"-7)"));  break;case JSON.stringify("second"):  '
-            f'return (("var(--"+{color_state_name!s}.color+"-5)"));  break;default:  '
-            f'return (("var(--"+{color_state_name!s}.color+"-2)"));  break;}};}})()',
+            f'return (("var(--"+{color_state_name!s}.color_rx_state_+"-7)"));  break;case JSON.stringify("second"):  '
+            f'return (("var(--"+{color_state_name!s}.color_rx_state_+"-5)"));  break;default:  '
+            f'return (("var(--"+{color_state_name!s}.color_rx_state_+"-2)"));  break;}};}})()',
         ),
     ],
 )

+ 11 - 11
tests/units/components/core/test_foreach.py

@@ -150,77 +150,77 @@ seen_index_vars = set()
             ForEachState.colors_list,
             display_color,
             {
-                "iterable_state": f"{ForEachState.get_full_name()}.colors_list",
+                "iterable_state": f"{ForEachState.get_full_name()}.colors_list_rx_state_",
             },
         ),
         (
             ForEachState.colors_dict_list,
             display_color_name,
             {
-                "iterable_state": f"{ForEachState.get_full_name()}.colors_dict_list",
+                "iterable_state": f"{ForEachState.get_full_name()}.colors_dict_list_rx_state_",
             },
         ),
         (
             ForEachState.colors_nested_dict_list,
             display_shade,
             {
-                "iterable_state": f"{ForEachState.get_full_name()}.colors_nested_dict_list",
+                "iterable_state": f"{ForEachState.get_full_name()}.colors_nested_dict_list_rx_state_",
             },
         ),
         (
             ForEachState.primary_color,
             display_primary_colors,
             {
-                "iterable_state": f"Object.entries({ForEachState.get_full_name()}.primary_color)",
+                "iterable_state": f"Object.entries({ForEachState.get_full_name()}.primary_color_rx_state_)",
             },
         ),
         (
             ForEachState.color_with_shades,
             display_color_with_shades,
             {
-                "iterable_state": f"Object.entries({ForEachState.get_full_name()}.color_with_shades)",
+                "iterable_state": f"Object.entries({ForEachState.get_full_name()}.color_with_shades_rx_state_)",
             },
         ),
         (
             ForEachState.nested_colors_with_shades,
             display_nested_color_with_shades,
             {
-                "iterable_state": f"Object.entries({ForEachState.get_full_name()}.nested_colors_with_shades)",
+                "iterable_state": f"Object.entries({ForEachState.get_full_name()}.nested_colors_with_shades_rx_state_)",
             },
         ),
         (
             ForEachState.nested_colors_with_shades,
             display_nested_color_with_shades_v2,
             {
-                "iterable_state": f"Object.entries({ForEachState.get_full_name()}.nested_colors_with_shades)",
+                "iterable_state": f"Object.entries({ForEachState.get_full_name()}.nested_colors_with_shades_rx_state_)",
             },
         ),
         (
             ForEachState.color_tuple,
             display_color_tuple,
             {
-                "iterable_state": f"{ForEachState.get_full_name()}.color_tuple",
+                "iterable_state": f"{ForEachState.get_full_name()}.color_tuple_rx_state_",
             },
         ),
         (
             ForEachState.colors_set,
             display_colors_set,
             {
-                "iterable_state": f"{ForEachState.get_full_name()}.colors_set",
+                "iterable_state": f"{ForEachState.get_full_name()}.colors_set_rx_state_",
             },
         ),
         (
             ForEachState.nested_colors_list,
             lambda el, i: display_nested_list_element(el, i),
             {
-                "iterable_state": f"{ForEachState.get_full_name()}.nested_colors_list",
+                "iterable_state": f"{ForEachState.get_full_name()}.nested_colors_list_rx_state_",
             },
         ),
         (
             ForEachState.color_index_tuple,
             display_color_index_tuple,
             {
-                "iterable_state": f"{ForEachState.get_full_name()}.color_index_tuple",
+                "iterable_state": f"{ForEachState.get_full_name()}.color_index_tuple_rx_state_",
             },
         ),
     ],

+ 9 - 9
tests/units/components/core/test_match.py

@@ -38,7 +38,7 @@ def test_match_components():
     [match_child] = match_dict["children"]
 
     assert match_child["name"] == "match"
-    assert str(match_child["cond"]) == f"{MatchState.get_name()}.value"
+    assert str(match_child["cond"]) == f"{MatchState.get_name()}.value_rx_state_"
 
     match_cases = match_child["match_cases"]
     assert len(match_cases) == 6
@@ -75,7 +75,7 @@ def test_match_components():
     assert fifth_return_value_render["name"] == "RadixThemesText"
     assert fifth_return_value_render["children"][0]["contents"] == '{"fifth value"}'
 
-    assert match_cases[5][0]._js_expr == f"({MatchState.get_name()}.num + 1)"
+    assert match_cases[5][0]._js_expr == f"({MatchState.get_name()}.num_rx_state_ + 1)"
     assert match_cases[5][0]._var_type is int
     fifth_return_value_render = match_cases[5][1]
     assert fifth_return_value_render["name"] == "RadixThemesText"
@@ -102,11 +102,11 @@ def test_match_components():
                 (MatchState.string, f"{MatchState.value} - string"),
                 "default value",
             ),
-            f'(() => {{ switch (JSON.stringify({MatchState.get_name()}.value)) {{case JSON.stringify(1):  return ("first");  break;case JSON.stringify(2): case JSON.stringify(3):  return '
+            f'(() => {{ switch (JSON.stringify({MatchState.get_name()}.value_rx_state_)) {{case JSON.stringify(1):  return ("first");  break;case JSON.stringify(2): case JSON.stringify(3):  return '
             '("second value");  break;case JSON.stringify([1, 2]):  return ("third-value");  break;case JSON.stringify("random"):  '
             'return ("fourth_value");  break;case JSON.stringify(({ ["foo"] : "bar" })):  return ("fifth value");  '
-            f'break;case JSON.stringify(({MatchState.get_name()}.num + 1)):  return ("sixth value");  break;case JSON.stringify(({MatchState.get_name()}.value+" - string")):  '
-            f'return ({MatchState.get_name()}.string);  break;case JSON.stringify({MatchState.get_name()}.string):  return (({MatchState.get_name()}.value+" - string"));  break;default:  '
+            f'break;case JSON.stringify(({MatchState.get_name()}.num_rx_state_ + 1)):  return ("sixth value");  break;case JSON.stringify(({MatchState.get_name()}.value_rx_state_+" - string")):  '
+            f'return ({MatchState.get_name()}.string_rx_state_);  break;case JSON.stringify({MatchState.get_name()}.string_rx_state_):  return (({MatchState.get_name()}.value_rx_state_+" - string"));  break;default:  '
             'return ("default value");  break;};})()',
         ),
         (
@@ -121,12 +121,12 @@ def test_match_components():
                 (MatchState.string, f"{MatchState.value} - string"),
                 MatchState.string,
             ),
-            f'(() => {{ switch (JSON.stringify({MatchState.get_name()}.value)) {{case JSON.stringify(1):  return ("first");  break;case JSON.stringify(2): case JSON.stringify(3):  return '
+            f'(() => {{ switch (JSON.stringify({MatchState.get_name()}.value_rx_state_)) {{case JSON.stringify(1):  return ("first");  break;case JSON.stringify(2): case JSON.stringify(3):  return '
             '("second value");  break;case JSON.stringify([1, 2]):  return ("third-value");  break;case JSON.stringify("random"):  '
             'return ("fourth_value");  break;case JSON.stringify(({ ["foo"] : "bar" })):  return ("fifth value");  '
-            f'break;case JSON.stringify(({MatchState.get_name()}.num + 1)):  return ("sixth value");  break;case JSON.stringify(({MatchState.get_name()}.value+" - string")):  '
-            f'return ({MatchState.get_name()}.string);  break;case JSON.stringify({MatchState.get_name()}.string):  return (({MatchState.get_name()}.value+" - string"));  break;default:  '
-            f"return ({MatchState.get_name()}.string);  break;}};}})()",
+            f'break;case JSON.stringify(({MatchState.get_name()}.num_rx_state_ + 1)):  return ("sixth value");  break;case JSON.stringify(({MatchState.get_name()}.value_rx_state_+" - string")):  '
+            f'return ({MatchState.get_name()}.string_rx_state_);  break;case JSON.stringify({MatchState.get_name()}.string_rx_state_):  return (({MatchState.get_name()}.value_rx_state_+" - string"));  break;default:  '
+            f"return ({MatchState.get_name()}.string_rx_state_);  break;}};}})()",
         ),
     ],
 )

+ 12 - 3
tests/units/components/datadisplay/test_datatable.py

@@ -44,11 +44,20 @@ def test_validate_data_table(data_table_state: rx.State, expected):
 
     # prefix expected with state name
     state_name = data_table_state.get_name()
-    expected = f"{state_name}.{expected}" if expected else state_name
+    expected_columns = (
+        f"{state_name}.{expected}_rx_state_.columns"
+        if expected
+        else state_name + ".columns_rx_state_"
+    )
+    expected_data = (
+        f"{state_name}.{expected}_rx_state_.data"
+        if expected
+        else state_name + ".data_rx_state_"
+    )
 
     assert data_table_dict["props"] == [
-        f"columns={{{expected}.columns}}",
-        f"data={{{expected}.data}}",
+        "columns=" + f"{{{expected_columns}}}",
+        "data=" + f"{{{expected_data}}}",
     ]
 
 

+ 1 - 1
tests/units/components/test_component.py

@@ -2165,7 +2165,7 @@ def test_add_style_embedded_vars(test_state: BaseState):
     assert "useParent" in page._get_all_hooks_internal()
     assert (
         str(page).count(
-            f'css={{({{ ["fakeParent"] : "parent", ["color"] : "var(--plum-10)", ["fake"] : "text", ["margin"] : ({test_state.get_name()}.num+"%") }})}}'
+            f'css={{({{ ["fakeParent"] : "parent", ["color"] : "var(--plum-10)", ["fake"] : "text", ["margin"] : ({test_state.get_name()}.num_rx_state_+"%") }})}}'
         )
         == 1
     )

+ 10 - 6
tests/units/test_state.py

@@ -296,7 +296,7 @@ def test_base_class_vars(test_state):
             continue
         prop = getattr(cls, field)
         assert isinstance(prop, Var)
-        assert prop._js_expr.split(".")[-1] == field
+        assert prop._js_expr.split(".")[-1] == field + "_rx_state_"
 
     assert cls.num1._var_type is int
     assert cls.num2._var_type is float
@@ -425,27 +425,31 @@ def test_default_setters(test_state):
 def test_class_indexing_with_vars():
     """Test that we can index into a state var with another var."""
     prop = TestState.array[TestState.num1]  # pyright: ignore [reportCallIssue, reportArgumentType]
-    assert str(prop) == f"{TestState.get_name()}.array.at({TestState.get_name()}.num1)"
+    assert (
+        str(prop)
+        == f"{TestState.get_name()}.array_rx_state_.at({TestState.get_name()}.num1_rx_state_)"
+    )
 
     prop = TestState.mapping["a"][TestState.num1]  # pyright: ignore [reportCallIssue, reportArgumentType]
     assert (
         str(prop)
-        == f'{TestState.get_name()}.mapping["a"].at({TestState.get_name()}.num1)'
+        == f'{TestState.get_name()}.mapping_rx_state_["a"].at({TestState.get_name()}.num1_rx_state_)'
     )
 
     prop = TestState.mapping[TestState.map_key]
     assert (
-        str(prop) == f"{TestState.get_name()}.mapping[{TestState.get_name()}.map_key]"
+        str(prop)
+        == f"{TestState.get_name()}.mapping_rx_state_[{TestState.get_name()}.map_key_rx_state_]"
     )
 
 
 def test_class_attributes():
     """Test that we can get class attributes."""
     prop = TestState.obj.prop1
-    assert str(prop) == f'{TestState.get_name()}.obj["prop1"]'
+    assert str(prop) == f'{TestState.get_name()}.obj_rx_state_["prop1"]'
 
     prop = TestState.complex[1].prop1
-    assert str(prop) == f'{TestState.get_name()}.complex[1]["prop1"]'
+    assert str(prop) == f'{TestState.get_name()}.complex_rx_state_[1]["prop1"]'
 
 
 def test_get_parent_state():

+ 5 - 4
tests/units/test_var.py

@@ -1788,15 +1788,15 @@ def test_invalid_var_operations(operand1_var: Var, operand2_var, operators: list
         (LiteralVar.create({"foo": "bar"}), '({ ["foo"] : "bar" })'),
         (
             LiteralVar.create(ATestState.value),
-            f"{ATestState.get_full_name()}.value",
+            f"{ATestState.get_full_name()}.value_rx_state_",
         ),
         (
             LiteralVar.create(f"{ATestState.value} string"),
-            f'({ATestState.get_full_name()}.value+" string")',
+            f'({ATestState.get_full_name()}.value_rx_state_+" string")',
         ),
         (
             LiteralVar.create(ATestState.dict_val),
-            f"{ATestState.get_full_name()}.dict_val",
+            f"{ATestState.get_full_name()}.dict_val_rx_state_",
         ),
     ],
 )
@@ -1848,7 +1848,8 @@ def test_to_string_operation():
         email: Email = Email("test@reflex.dev")
 
     assert (
-        str(TestState.optional_email) == f"{TestState.get_full_name()}.optional_email"
+        str(TestState.optional_email)
+        == f"{TestState.get_full_name()}.optional_email_rx_state_"
     )
     my_state = TestState()
     assert my_state.optional_email is None

+ 2 - 2
tests/units/utils/test_format.py

@@ -326,8 +326,8 @@ def test_format_route(route: str, format_case: bool, expected: bool):
             ],
             LiteralVar.create("yellow"),
             '(() => { switch (JSON.stringify(state__state.value)) {case JSON.stringify(1):  return ("red");  break;case JSON.stringify(2): case JSON.stringify(3):  '
-            f'return ("blue");  break;case JSON.stringify({TestState.get_full_name()}.mapping):  return '
-            f'({TestState.get_full_name()}.num1);  break;case JSON.stringify(({TestState.get_full_name()}.map_key+"-key")):  return ("return-key");'
+            f'return ("blue");  break;case JSON.stringify({TestState.get_full_name()}.mapping_rx_state_):  return '
+            f'({TestState.get_full_name()}.num1_rx_state_);  break;case JSON.stringify(({TestState.get_full_name()}.map_key_rx_state_+"-key")):  return ("return-key");'
             '  break;default:  return ("yellow");  break;};})()',
         )
     ],