Skip to content

Commit

Permalink
[ENG-4255] Code blocks lead to redefined const in web page (#4598)
Browse files Browse the repository at this point in the history
Instead of potentially defining `_LANGUAGE` constant twice in a component,
simply pass the language prop directly to the hook generator function.

If no language is passed, then it defaults to `_LANGUAGE`, which continues to
work for markdown component_map use case.
  • Loading branch information
masenf authored Jan 7, 2025
1 parent 5f169bc commit 93245ef
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions reflex/components/datadisplay/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,8 +502,8 @@ def _render(self):

theme = self.theme

out.add_props(style=theme).remove_props("theme", "code", "language").add_props(
children=self.code, language=_LANGUAGE
out.add_props(style=theme).remove_props("theme", "code").add_props(
children=self.code,
)

return out
Expand All @@ -512,20 +512,25 @@ def _exclude_props(self) -> list[str]:
return ["can_copy", "copy_button"]

@classmethod
def _get_language_registration_hook(cls) -> str:
def _get_language_registration_hook(cls, language_var: Var = _LANGUAGE) -> str:
"""Get the hook to register the language.
Args:
language_var: The const/literal Var of the language module to import.
For markdown, uses the default placeholder _LANGUAGE. For direct use,
a LiteralStringVar should be passed via the language prop.
Returns:
The hook to register the language.
"""
return f"""
if ({_LANGUAGE!s}) {{
if ({language_var!s}) {{
(async () => {{
try {{
const module = await import(`react-syntax-highlighter/dist/cjs/languages/prism/${{{_LANGUAGE!s}}}`);
SyntaxHighlighter.registerLanguage({_LANGUAGE!s}, module.default);
const module = await import(`react-syntax-highlighter/dist/cjs/languages/prism/${{{language_var!s}}}`);
SyntaxHighlighter.registerLanguage({language_var!s}, module.default);
}} catch (error) {{
console.error(`Error importing language module for ${{{_LANGUAGE!s}}}:`, error);
console.error(`Error importing language module for ${{{language_var!s}}}:`, error);
}}
}})();
}}
Expand All @@ -547,8 +552,7 @@ def add_hooks(self) -> list[str | Var]:
The hooks for the component.
"""
return [
f"const {_LANGUAGE!s} = {self.language!s}",
self._get_language_registration_hook(),
self._get_language_registration_hook(language_var=self.language),
]


Expand Down

0 comments on commit 93245ef

Please sign in to comment.