diff --git a/reflex/utils/format.py b/reflex/utils/format.py index 1d6671a0b..ea8ed1427 100644 --- a/reflex/utils/format.py +++ b/reflex/utils/format.py @@ -4,9 +4,8 @@ from __future__ import annotations import inspect import json -import os import re -from typing import TYPE_CHECKING, Any, List, Optional, Union +from typing import TYPE_CHECKING, Any, Optional, Union from reflex import constants from reflex.constants.state import FRONTEND_EVENT_STATE @@ -107,22 +106,6 @@ def wrap( return f"{open * num}{text}{close * num}" -def indent(text: str, indent_level: int = 2) -> str: - """Indent the given text by the given indent level. - - Args: - text: The text to indent. - indent_level: The indent level. - - Returns: - The indented text. - """ - lines = text.splitlines() - if len(lines) < 2: - return text - return os.linesep.join(f"{' ' * indent_level}{line}" for line in lines) + os.linesep - - def to_snake_case(text: str) -> str: """Convert a string to snake case. @@ -210,80 +193,6 @@ def make_default_page_title(app_name: str, route: str) -> str: return to_title_case(title) -def _escape_js_string(string: str) -> str: - """Escape the string for use as a JS string literal. - - Args: - string: The string to escape. - - Returns: - The escaped string. - """ - - # TODO: we may need to re-vist this logic after new Var API is implemented. - def escape_outside_segments(segment): - """Escape backticks in segments outside of `${}`. - - Args: - segment: The part of the string to escape. - - Returns: - The escaped or unescaped segment. - """ - if segment.startswith("${") and segment.endswith("}"): - # Return the `${}` segment unchanged - return segment - else: - # Escape backticks in the segment - segment = segment.replace(r"\`", "`") - segment = segment.replace("`", r"\`") - return segment - - # Split the string into parts, keeping the `${}` segments - parts = re.split(r"(\$\{.*?\})", string) - escaped_parts = [escape_outside_segments(part) for part in parts] - escaped_string = "".join(escaped_parts) - return escaped_string - - -def _wrap_js_string(string: str) -> str: - """Wrap string so it looks like {`string`}. - - Args: - string: The string to wrap. - - Returns: - The wrapped string. - """ - string = wrap(string, "`") - string = wrap(string, "{") - return string - - -def format_string(string: str) -> str: - """Format the given string as a JS string literal.. - - Args: - string: The string to format. - - Returns: - The formatted string. - """ - return _wrap_js_string(_escape_js_string(string)) - - -def format_var(var: Var) -> str: - """Format the given Var as a javascript value. - - Args: - var: The Var to format. - - Returns: - The formatted Var. - """ - return str(var) - - def format_route(route: str, format_case=True) -> str: """Format the given route. @@ -306,40 +215,6 @@ def format_route(route: str, format_case=True) -> str: return route -def format_match( - cond: str | Var, - match_cases: List[List[Var]], - default: Var, -) -> str: - """Format a match expression whose return type is a Var. - - Args: - cond: The condition. - match_cases: The list of cases to match. - default: The default case. - - Returns: - The formatted match expression - - """ - switch_code = f"(() => {{ switch (JSON.stringify({cond})) {{" - - for case in match_cases: - conditions = case[:-1] - return_value = case[-1] - - case_conditions = " ".join( - [f"case JSON.stringify({condition!s}):" for condition in conditions] - ) - case_code = f"{case_conditions} return ({return_value!s}); break;" - switch_code += case_code - - switch_code += f"default: return ({default!s}); break;" - switch_code += "};})()" - - return switch_code - - def format_prop( prop: Union[Var, EventChain, ComponentStyle, str], ) -> Union[int, float, str]: diff --git a/tests/units/utils/test_format.py b/tests/units/utils/test_format.py index 2a2aa8259..48281a119 100644 --- a/tests/units/utils/test_format.py +++ b/tests/units/utils/test_format.py @@ -2,7 +2,7 @@ from __future__ import annotations import datetime import json -from typing import Any, List +from typing import Any import plotly.graph_objects as go import pytest @@ -98,60 +98,6 @@ def test_wrap(text: str, open: str, expected: str, check_first: bool, num: int): assert format.wrap(text, open, check_first=check_first, num=num) == expected -@pytest.mark.parametrize( - "string,expected_output", - [ - ("This is a random string", "This is a random string"), - ( - "This is a random string with `backticks`", - "This is a random string with \\`backticks\\`", - ), - ( - "This is a random string with `backticks`", - "This is a random string with \\`backticks\\`", - ), - ( - "This is a string with ${someValue[`string interpolation`]} unescaped", - "This is a string with ${someValue[`string interpolation`]} unescaped", - ), - ( - "This is a string with `backticks` and ${someValue[`string interpolation`]} unescaped", - "This is a string with \\`backticks\\` and ${someValue[`string interpolation`]} unescaped", - ), - ( - "This is a string with `backticks`, ${someValue[`the first string interpolation`]} and ${someValue[`the second`]}", - "This is a string with \\`backticks\\`, ${someValue[`the first string interpolation`]} and ${someValue[`the second`]}", - ), - ], -) -def test_escape_js_string(string, expected_output): - assert format._escape_js_string(string) == expected_output - - -@pytest.mark.parametrize( - "text,indent_level,expected", - [ - ("", 2, ""), - ("hello", 2, "hello"), - ("hello\nworld", 2, " hello\n world\n"), - ("hello\nworld", 4, " hello\n world\n"), - (" hello\n world", 2, " hello\n world\n"), - ], -) -def test_indent(text: str, indent_level: int, expected: str, windows_platform: bool): - """Test indenting a string. - - Args: - text: The text to indent. - indent_level: The number of spaces to indent by. - expected: The expected output string. - windows_platform: Whether the system is windows. - """ - assert format.indent(text, indent_level) == ( - expected.replace("\n", "\r\n") if windows_platform else expected - ) - - @pytest.mark.parametrize( "input,output", [ @@ -252,25 +198,6 @@ def test_to_kebab_case(input: str, output: str): assert format.to_kebab_case(input) == output -@pytest.mark.parametrize( - "input,output", - [ - ("", "{``}"), - ("hello", "{`hello`}"), - ("hello world", "{`hello world`}"), - ("hello=`world`", "{`hello=\\`world\\``}"), - ], -) -def test_format_string(input: str, output: str): - """Test formatting the input as JS string literal. - - Args: - input: the input string. - output: the output string. - """ - assert format.format_string(input) == output - - @pytest.mark.parametrize( "input,output", [ @@ -310,45 +237,6 @@ def test_format_route(route: str, format_case: bool, expected: bool): assert format.format_route(route, format_case=format_case) == expected -@pytest.mark.parametrize( - "condition, match_cases, default,expected", - [ - ( - "state__state.value", - [ - [LiteralVar.create(1), LiteralVar.create("red")], - [LiteralVar.create(2), LiteralVar.create(3), LiteralVar.create("blue")], - [TestState.mapping, TestState.num1], - [ - LiteralVar.create(f"{TestState.map_key}-key"), - LiteralVar.create("return-key"), - ], - ], - 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");' - ' break;default: return ("yellow"); break;};})()', - ) - ], -) -def test_format_match( - condition: str, - match_cases: List[List[Var]], - default: Var, - expected: str, -): - """Test formatting a match statement. - - Args: - condition: The condition to match. - match_cases: List of match cases to be matched. - default: Catchall case for the match statement. - expected: The expected string output. - """ - assert format.format_match(condition, match_cases, default) == expected - - @pytest.mark.parametrize( "prop,formatted", [