diff --git a/packages/reflex-components-core/news/+bare-string-form-deps.bugfix.md b/packages/reflex-components-core/news/+bare-string-form-deps.bugfix.md new file mode 100644 index 00000000000..8ba96b8282b --- /dev/null +++ b/packages/reflex-components-core/news/+bare-string-form-deps.bugfix.md @@ -0,0 +1 @@ +An object or boolean Var rendered as a child now brings along the hooks and imports of its `to_string()`, so a Var type with its own string form no longer breaks the page. diff --git a/packages/reflex-components-core/src/reflex_components_core/base/bare.py b/packages/reflex-components-core/src/reflex_components_core/base/bare.py index 058952c124a..3bfd1968438 100644 --- a/packages/reflex-components-core/src/reflex_components_core/base/bare.py +++ b/packages/reflex-components-core/src/reflex_components_core/base/bare.py @@ -2,6 +2,7 @@ from __future__ import annotations +import functools import logging from collections.abc import Iterator, Sequence from typing import Any @@ -11,7 +12,6 @@ from reflex_base.components.tags.tagless import Tagless from reflex_base.environment import PerformanceMode, environment from reflex_base.utils.decorator import once -from reflex_base.utils.imports import ParsedImportDict from reflex_base.vars import BooleanVar, ObjectVar, Var from reflex_base.vars.base import GLOBAL_CACHE, VarData from reflex_base.vars.sequence import LiteralStringVar @@ -86,9 +86,8 @@ def _get_all_hooks_internal(self) -> dict[str, VarData | None]: The hooks for the component. """ hooks = super()._get_all_hooks_internal() - if isinstance(self.contents, Var): - for component in _components_from_var(self.contents): - hooks |= component._get_all_hooks_internal() + for component in self._contents_components(): + hooks |= component._get_all_hooks_internal() return hooks def _get_all_hooks(self) -> dict[str, VarData | None]: @@ -98,51 +97,10 @@ def _get_all_hooks(self) -> dict[str, VarData | None]: The hooks for the component. """ hooks = super()._get_all_hooks() - if isinstance(self.contents, Var): - for component in _components_from_var(self.contents): - hooks |= component._get_all_hooks() + for component in self._contents_components(): + hooks |= component._get_all_hooks() return hooks - def _get_all_imports(self, collapse: bool = False) -> ParsedImportDict: - """Include the imports for the component. - - Args: - collapse: Whether to collapse the imports. - - Returns: - The imports for the component. - """ - imports = super()._get_all_imports(collapse=collapse) - if isinstance(self.contents, Var): - var_data = self.contents._get_all_var_data() - if var_data: - imports |= {k: list(v) for k, v in var_data.imports} - return imports - - def _get_all_dynamic_imports(self) -> set[str]: - """Get dynamic imports for the component. - - Returns: - The dynamic imports. - """ - dynamic_imports = super()._get_all_dynamic_imports() - if isinstance(self.contents, Var): - for component in _components_from_var(self.contents): - dynamic_imports |= component._get_all_dynamic_imports() - return dynamic_imports - - def _get_all_custom_code(self) -> dict[str, None]: - """Get custom code for the component. - - Returns: - The custom code. - """ - custom_code = super()._get_all_custom_code() - if isinstance(self.contents, Var): - for component in _components_from_var(self.contents): - custom_code |= component._get_all_custom_code() - return custom_code - def _get_all_app_wrap_components( self, *, ignore_ids: set[int] | None = None ) -> dict[tuple[int, str], Component]: @@ -158,37 +116,70 @@ def _get_all_app_wrap_components( app_wrap_components = super()._get_all_app_wrap_components( ignore_ids=ignore_ids ) - if isinstance(self.contents, Var): - for component in _components_from_var(self.contents): - component_id = id(component) - if isinstance(component, Component) and component_id not in ignore_ids: - ignore_ids.add(component_id) - app_wrap_components |= component._get_all_app_wrap_components( - ignore_ids=ignore_ids - ) + for component in self._contents_components(): + component_id = id(component) + if isinstance(component, Component) and component_id not in ignore_ids: + ignore_ids.add(component_id) + app_wrap_components |= component._get_all_app_wrap_components( + ignore_ids=ignore_ids + ) return app_wrap_components - def _get_all_refs(self) -> dict[str, None]: - """Get the refs for the children of the component. + @functools.cached_property + def _get_component_prop_property(self) -> Sequence[BaseComponent]: + """The components of the props and of the var rendered for the contents. + + The compiler and the import, custom code, dynamic import and ref collectors + follow this traversal, so components a custom ``to_string()`` brings count. + + Returns: + Each component of the props, then the rendered var's others. + """ + components = super()._get_component_prop_property + seen = {id(component) for component in components} + return [ + *components, + *(c for c in self._contents_components() if id(c) not in seen), + ] + + def _contents_vars(self) -> tuple[Var, ...]: + """The contents and, when it differs, the var rendered for them, built once. + + The rendered var shows booleans and objects as their string form. Returns: - The refs for the children. + The vars, the rendered one last. + """ + contents = self.contents + cached = self.__dict__.get("_vars_cache") + # The base class's vars cache, dropped with the other compile caches; + # keyed on the contents too, so reassigning them never renders stale. + if cached is not None and cached[0] is contents: + return cached + rendered = contents if isinstance(contents, Var) else Var.create(contents) + if isinstance(rendered, (BooleanVar, ObjectVar)): + rendered = rendered.to_string() + cached = (contents,) if rendered is contents else (contents, rendered) + self._vars_cache = cached + return cached + + def _contents_components(self) -> Iterator[BaseComponent]: + """The components carried by the contents and the var rendered for them. + + A custom ``to_string()`` can bring components the contents lack. + + Yields: + Each component once, those of the contents first. """ - refs = super()._get_all_refs() - if isinstance(self.contents, Var): - for component in _components_from_var(self.contents): - refs |= component._get_all_refs() - return refs + seen: set[int] = set() + for var in self._contents_vars(): + for component in _components_from_var(var): + if id(component) not in seen: + seen.add(id(component)) + yield component def _render(self) -> CommonTag: - contents = ( - Var.create(self.contents) - if not isinstance(self.contents, Var) - else self.contents - ) - if isinstance(contents, (BooleanVar, ObjectVar)): - return Tagless(contents=f"{contents.to_string()!s}") - return Tagless(contents=f"{contents!s}") + return Tagless(contents=f"{self._contents_vars()[-1]!s}") def render(self) -> dict: """Render the component as a dictionary. @@ -198,14 +189,7 @@ def render(self) -> dict: Returns: The rendered component. """ - contents = ( - Var.create(self.contents) - if not isinstance(self.contents, Var) - else self.contents - ) - if isinstance(contents, (BooleanVar, ObjectVar)): - return {"contents": f"{contents.to_string()!s}"} - return {"contents": f"{contents!s}"} + return {"contents": f"{self._contents_vars()[-1]!s}"} def _add_style_recursive( self, style: ComponentStyle, theme: Component | None = None @@ -223,11 +207,10 @@ def _add_style_recursive( are_components_touched = False - if isinstance(self.contents, Var): - for component in _components_from_var(self.contents): - if isinstance(component, Component): - component._add_style_recursive(style, theme) - are_components_touched = True + for component in self._contents_components(): + if isinstance(component, Component): + component._add_style_recursive(style, theme) + are_components_touched = True if are_components_touched: GLOBAL_CACHE.clear() @@ -244,6 +227,6 @@ def _get_vars( ignore_ids: The ids to ignore. Yields: - The contents if it is a Var, otherwise nothing. + The contents, and the var rendered for them when that differs. """ - yield self.contents + yield from self._contents_vars() diff --git a/tests/units/components/base/test_bare.py b/tests/units/components/base/test_bare.py index 30f3d9b233c..04c063715b6 100644 --- a/tests/units/components/base/test_bare.py +++ b/tests/units/components/base/test_bare.py @@ -1,5 +1,10 @@ import pytest -from reflex_base.vars.base import Var +from reflex_base.components.component import Component +from reflex_base.components.tags.tagless import Tagless +from reflex_base.utils.imports import ImportVar +from reflex_base.vars import ObjectVar +from reflex_base.vars.base import Var, VarData +from reflex_base.vars.sequence import StringVar from reflex_components_core.base.bare import Bare STATE_VAR = Var(_js_expr="default_state.name") @@ -23,3 +28,130 @@ def test_fstrings(contents, expected): """ comp = Bare.create(contents).render() assert comp["contents"] == expected + + +TEXTS_HOOK = "const texts = useTexts()" +PICK_HOOK = "const pick = usePick()" + + +class PickedVar(ObjectVar[dict]): + """An object var whose string form needs another hook from the same library.""" + + def to_string(self, use_json: bool = True) -> StringVar: + """Pick a text from the object with a hook. + + Args: + use_json: Unused. + + Returns: + The picked text. + """ + return Var( + _js_expr=f"pick({self!s})", + _var_data=VarData( + hooks={PICK_HOOK: None}, imports={"$/utils/i18n": ["usePick"]} + ), + ).to(str) + + +def test_rendered_string_form_brings_its_hooks_and_imports(): + """An object rendered through to_string carries that var's hooks and imports.""" + texts = PickedVar( + _js_expr="texts", + _var_type=dict, + _var_data=VarData( + hooks={TEXTS_HOOK: None}, imports={"$/utils/i18n": ["useTexts"]} + ), + ) + comp = Bare.create(texts) + + assert comp.render()["contents"] == "pick(texts)" + assert comp._get_all_hooks() == {TEXTS_HOOK: None, PICK_HOOK: None} + assert comp._get_all_imports(collapse=True) == { + "$/utils/i18n": [ImportVar(tag="useTexts"), ImportVar(tag="usePick")] + } + + +def test_string_form_is_built_once_per_contents(): + """The string form is built once per contents and shared by the vars and the render.""" + comp = Bare.create(Var(_js_expr="flag", _var_type=bool).guess_type()) + assert isinstance(comp, Bare) + contents, rendered = comp._get_vars() + + assert contents is comp.contents + assert tuple(map(id, comp._get_vars())) == (id(contents), id(rendered)) + assert str(rendered) == "(JSON.stringify(flag))" + assert comp.render() == {"contents": "(JSON.stringify(flag))"} + assert comp._render() == Tagless(contents="(JSON.stringify(flag))") + + comp.contents = Var(_js_expr="items", _var_type=dict).guess_type() + + assert comp.render() == {"contents": "(JSON.stringify(items))"} + assert [str(var) for var in comp._get_vars()] == [ + "items", + "(JSON.stringify(items))", + ] + + +BOX_HOOK = "const box = useBox()" +BOX_CODE = "const boxDefaults = {};" + + +class HookedBox(Component): + """A component with a hook and custom code of its own.""" + + tag = "HookedBox" + library = "hooked-box" + + def add_hooks(self) -> list[str]: + """Add the box hook. + + Returns: + The hooks. + """ + return [BOX_HOOK] + + def add_custom_code(self) -> list[str]: + """Add the box defaults. + + Returns: + The custom code. + """ + return [BOX_CODE] + + +class BoxedVar(ObjectVar[dict]): + """An object var whose string form renders through a component.""" + + def to_string(self, use_json: bool = True) -> StringVar: + """Render the object through a box component. + + Args: + use_json: Unused. + + Returns: + The boxed text. + """ + return Var( + _js_expr=f"box({self!s})", + _var_data=VarData(components=(HookedBox.create(id="box"),)), + ).to(str) + + +def test_rendered_string_form_brings_its_components(): + """Components carried by the string form count like those of the contents.""" + comp = Bare.create(BoxedVar(_js_expr="data", _var_type=dict)) + + assert comp.render()["contents"] == "box(data)" + assert comp._get_all_hooks() == { + 'const ref_box = useRegisteredRef("ref_box");': None, + BOX_HOOK: None, + } + assert comp._get_all_custom_code() == {BOX_CODE: None} + assert comp._get_all_refs() == {"ref_box": None} + # the compiler reaches the box's imports through the prop traversal too + assert [type(c) for c in comp._get_components_in_props()] == [HookedBox] + assert comp._get_all_imports(collapse=True) == { + "$/utils/state": [ImportVar(tag="useRegisteredRef")], + "hooked-box": [ImportVar(tag="HookedBox")], + }