strip transformer triggers

This commit is contained in:
Elijah 2024-10-04 09:56:04 +00:00
parent e6cb4185b2
commit 860449f814
2 changed files with 40 additions and 1 deletions

View File

@ -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."""

View File

@ -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}"