From 860449f814436fd6f706ad1663e872beff9b9785 Mon Sep 17 00:00:00 2001 From: Elijah Date: Fri, 4 Oct 2024 09:56:04 +0000 Subject: [PATCH] strip transformer triggers --- .../datadisplay/shiki_code_block.py | 21 ++++++++++++++++++- reflex/vars/sequence.py | 20 ++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/reflex/components/datadisplay/shiki_code_block.py b/reflex/components/datadisplay/shiki_code_block.py index d57ee36b7..9b2be4beb 100644 --- a/reflex/components/datadisplay/shiki_code_block.py +++ b/reflex/components/datadisplay/shiki_code_block.py @@ -2,6 +2,7 @@ from __future__ import annotations +import re from collections import defaultdict from typing import Any, Literal, Optional, Union @@ -17,6 +18,7 @@ from reflex.style import Style from reflex.utils.imports import ImportVar from reflex.vars.base import LiteralVar, Var from reflex.vars.function import FunctionStringVar +from reflex.vars.sequence import StringVar, string_replace_operation def copy_script(id: str, code: str) -> Any: @@ -719,7 +721,9 @@ class ShikiHighLevelCodeBlock(ShikiCodeBlock): else Button.create( Icon.create(tag="copy", size=16, color=color("gray", 11)), id=button_id, - on_click=copy_script(button_id, code), + on_click=copy_script( + button_id, cls._strip_transformer_triggers(code) + ), style=Style( { "position": "absolute", @@ -768,6 +772,21 @@ class ShikiHighLevelCodeBlock(ShikiCodeBlock): return LANGUAGE_MAPPING[language] return language + @staticmethod + def _strip_transformer_triggers(code: str | Var) -> StringVar | str: + if not isinstance(code, (Var, str)): + raise ValueError( + f"code should be string literal or a Var type. Got {type(code)} instead." + ) + + if isinstance(code, Var): + return string_replace_operation( + code, StringVar(_js_expr=r"/\/\/ \[!code.*?\]/g", _var_type=str), "" + ) + if isinstance(code, str): + cleaned_code = re.sub(r"// \[!code.*?\]", "", code) + return cleaned_code + class TransformerNamespace(ComponentNamespace): """Namespace for the Transformers.""" diff --git a/reflex/vars/sequence.py b/reflex/vars/sequence.py index 149300028..39139ce3f 100644 --- a/reflex/vars/sequence.py +++ b/reflex/vars/sequence.py @@ -529,6 +529,26 @@ def array_join_operation(array: ArrayVar, sep: StringVar[Any] | str = ""): return var_operation_return(js_expression=f"{array}.join({sep})", var_type=str) +@var_operation +def string_replace_operation( + string: StringVar, search_value: StringVar | str, new_value: StringVar | 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}"